From 9ad93583c5ae2b3b22c3b4caddd853438161efd0 Mon Sep 17 00:00:00 2001 From: Zac Walker <181544+ZacWalk@users.noreply.github.com> Date: Sun, 29 Nov 2026 06:43:24 +0100 Subject: [PATCH] Build a Debian package, use the libraries' agent session, JSON writer, completion, HDR, keyboard and render counter code, and test ARM64 in CI --- .gitattributes | 4 + .github/instructions/docs.instructions.md | 3 + .github/instructions/platform.instructions.md | 18 +- .github/workflows/linux.yml | 22 +- .gitignore | 3 + AGENTS.md | 12 +- CITATION.cff | 28 + CMakeLists.txt | 9 +- README.md | 5 +- cmake/DiffractorCompilerPolicy.cmake | 26 +- cmake/DiffractorLib64.cmake | 2 +- cmake/DiffractorLibdesktop.cmake | 2 +- cmake/DiffractorLibfiles.cmake | 2 +- cmake/DiffractorLibmug.cmake | 2 +- cmake/DiffractorLinuxInstall.cmake | 79 + cmake/vendored/FFmpeg.cmake | 30 +- cmake/vendored/archive-linux/config_linux.h | 3 +- cmake/vendored/ffmpeg-config-divergence.txt | 17 +- cmake/vendored/minizip-linux/mz_config.h | 32 + cmake/vendored/minizip.local.cmake | 3 + dd.ps1 | 44 +- docs/agents.md | 202 +-- docs/crash.md | 155 +- docs/design.md | 27 +- docs/file-io.md | 1 + docs/implementation.md | 36 +- docs/linux.md | 198 ++- docs/metadata.md | 4 +- docs/mission.md | 412 +++++ docs/movie.md | 45 +- docs/rendering.md | 3 +- docs/testing.md | 31 +- docs/third-party.md | 44 +- docs/v-1.27.5.md | 164 ++ docs/zoom.md | 3 +- exe/AppxManifest.xml | 2 +- exe/languages/cs.po | 113 +- exe/languages/de.po | 112 +- exe/languages/es.po | 110 ++ exe/languages/fr.po | 118 +- exe/languages/it.po | 112 +- exe/languages/ja.po | 110 ++ exe/languages/ko.po | 110 ++ exe/languages/pl.po | 113 +- exe/languages/pt.po | 110 ++ exe/languages/ru.po | 113 +- exe/languages/tr.po | 110 ++ exe/languages/uk.po | 111 ++ exe/languages/zh.po | 110 ++ installer/diff.nsi | 6 +- packaging/flatpak/README.md | 30 + .../flatpak/com.diffractor.Diffractor.yml | 107 ++ .../com.diffractor.Diffractor.desktop.in | 12 + .../com.diffractor.Diffractor.metainfo.xml | 53 + .../apps/com.diffractor.Diffractor.png | Bin 0 -> 8825 bytes .../apps/com.diffractor.Diffractor.png | Bin 0 -> 18210 bytes .../64x64/apps/com.diffractor.Diffractor.png | Bin 0 -> 4298 bytes src/app.cpp | 324 ++-- src/app.h | 55 +- src/app_command_line.h | 14 +- src/app_commands.cpp | 22 +- src/app_commands.h | 2 +- src/app_crash_report.cpp | 374 ++++ src/app_crash_report.h | 103 ++ src/app_dialogs.cpp | 16 +- src/app_dialogs.h | 2 +- src/app_gen_docs.cpp | 89 +- src/app_mcp.cpp | 1570 +++++------------ src/app_mcp.h | 297 +--- src/app_mcp_controls.cpp | 1458 --------------- src/app_mcp_faces.cpp | 58 +- src/app_mcp_json.h | 130 -- src/app_mcp_tools.cpp | 177 +- src/app_mcp_ui.cpp | 1466 ++------------- src/app_movie_batch.cpp | 117 +- src/app_perf.cpp | 104 +- src/app_perf.h | 4 +- src/app_record.cpp | 573 ++++++ src/app_record.h | 108 +- src/app_resources.h | 5 - src/app_search.cpp | 2 +- src/app_search.h | 127 +- src/app_settings.cpp | 12 +- src/app_settings.h | 4 +- src/app_text.cpp | 75 +- src/app_text.h | 22 +- src/app_toolbar.cpp | 149 +- src/app_tutorial.cpp | 85 +- src/app_tutorial.h | 3 - src/app_util.cpp | 16 +- src/app_util.h | 4 + src/app_version.h | 21 + src/av_c64.cpp | 188 +- src/av_c64.h | 32 +- src/av_format.cpp | 64 +- src/av_movie_writer.cpp | 899 ++++++++++ src/av_movie_writer.h | 32 + src/av_sid.cpp | 56 +- src/av_sid.h | 7 +- src/av_sound.h | 4 +- src/crypto_md5.cpp | 10 +- src/crypto_md5.h | 2 +- src/files.cpp | 276 +-- src/files.h | 12 +- src/files_heif.cpp | 37 +- src/files_jxl.cpp | 30 +- src/media_edit.cpp | 7 +- src/metadata.cpp | 115 +- src/model.cpp | 5 +- src/model_db.cpp | 1 + src/model_faces.cpp | 43 +- src/model_faces_search.cpp | 5 +- src/model_index.cpp | 4 +- src/model_index.h | 4 +- src/model_index_summary.cpp | 2 +- src/model_items.cpp | 5 - src/model_locations.cpp | 1 + src/model_search.cpp | 28 +- src/model_search.h | 30 +- src/platform_linux_app.cpp | 46 +- src/platform_win.manifest | 2 +- src/platform_win_av.cpp | 17 +- src/platform_win_record.cpp | 203 +-- src/platform_win_res.rc | 8 +- src/render_globe.cpp | 15 +- src/test.h | 11 +- src/test_app.cpp | 858 ++++++--- src/test_av.cpp | 56 +- src/test_faces.cpp | 65 +- src/test_files.cpp | 569 ++---- src/test_fixtures.cpp | 2 +- src/test_index.cpp | 17 +- src/test_media_edit.cpp | 26 +- src/test_metadata.cpp | 46 +- src/test_platform_linux.cpp | 1283 ++++++++++++++ src/test_platform_win.cpp | 60 +- src/test_render.cpp | 89 +- src/test_runner.h | 1 + src/test_search.cpp | 61 +- src/test_util.cpp | 38 +- src/test_view.cpp | 7 +- src/ui_c64.cpp | 14 +- src/ui_c64.h | 6 +- src/ui_dialog.h | 3 +- src/ui_music.cpp | 1 + src/ui_view.h | 26 +- src/util_crash_files_db.h | 90 +- src/util_spell.h | 2 +- src/view_batch.cpp | 4 +- src/view_edit.cpp | 2 +- src/view_explore.cpp | 1 + src/view_faces.cpp | 8 +- src/view_faces_actions.cpp | 16 +- src/view_import.cpp | 11 +- src/view_movie.cpp | 5 +- src/view_options.cpp | 11 +- src/view_sync.cpp | 8 +- tools/check_translations.py | 49 +- tools/compare_ffmpeg_config.py | 78 +- tools/dd.py | 235 ++- tools/generate_icon.py | 3 + tools/sweep_mcp.py | 30 +- tools/test_check_translations.py | 33 +- tools/test_mcp_session.py | 36 +- 164 files changed, 9771 insertions(+), 7201 deletions(-) create mode 100644 CITATION.cff create mode 100644 cmake/DiffractorLinuxInstall.cmake create mode 100644 cmake/vendored/minizip-linux/mz_config.h create mode 100644 docs/mission.md create mode 100644 docs/v-1.27.5.md create mode 100644 packaging/flatpak/README.md create mode 100644 packaging/flatpak/com.diffractor.Diffractor.yml create mode 100644 packaging/linux/com.diffractor.Diffractor.desktop.in create mode 100644 packaging/linux/com.diffractor.Diffractor.metainfo.xml create mode 100644 packaging/linux/icons/hicolor/128x128/apps/com.diffractor.Diffractor.png create mode 100644 packaging/linux/icons/hicolor/256x256/apps/com.diffractor.Diffractor.png create mode 100644 packaging/linux/icons/hicolor/64x64/apps/com.diffractor.Diffractor.png create mode 100644 src/app_crash_report.cpp create mode 100644 src/app_crash_report.h delete mode 100644 src/app_mcp_controls.cpp delete mode 100644 src/app_mcp_json.h create mode 100644 src/app_record.cpp create mode 100644 src/av_movie_writer.cpp create mode 100644 src/av_movie_writer.h create mode 100644 src/test_platform_linux.cpp diff --git a/.gitattributes b/.gitattributes index ae401d53..d0c6e7cd 100644 --- a/.gitattributes +++ b/.gitattributes @@ -17,3 +17,7 @@ dd text eol=lf /src/Res/logo.png -text /src/Res/logo15.png -text /src/Res/logo30.png -text + +# Read on Linux, where a desktop entry whose lines end in a carriage return is invalid. +/packaging/** text eol=lf +/packaging/linux/icons/** -text diff --git a/.github/instructions/docs.instructions.md b/.github/instructions/docs.instructions.md index b1e298a8..8d3caa2a 100644 --- a/.github/instructions/docs.instructions.md +++ b/.github/instructions/docs.instructions.md @@ -14,6 +14,9 @@ owning document. two documents come to disagree, and an agent reading the wrong one cannot tell. - **GitHub issues and releases own work, status, discussion, follow-up, and release history.** Repository documents describe current behavior and constraints, not how they evolved. +- **The one exception is the next release's plan, `docs/v-.md`.** It tracks that release's + work until it ships; its user-facing changes then become the GitHub release notes, and the next + release's plan replaces it. - **Source owns exact APIs, enums, signatures and file lists.** Documents name files and stable symbols so a reader can route; they do not restate a signature that the compiler already checks. - Unfinished ideas, alternatives, open questions, validation transcripts, and rejected designs do diff --git a/.github/instructions/platform.instructions.md b/.github/instructions/platform.instructions.md index 98d7d95a..e1db7263 100644 --- a/.github/instructions/platform.instructions.md +++ b/.github/instructions/platform.instructions.md @@ -13,8 +13,9 @@ Owning documents: [implementation](../../docs/implementation.md) for the boundar System headers, Windows API calls and OS handle types (`HWND`, `LRESULT`, `WPARAM`, `LPARAM`, ``, `d3d11`, `dxgi`, `dwrite`, `shlobj`, `shellapi`, `wincodec`) appear **only** in `platform*` files, apart from the entry points in `app.cpp`. The lint enforces this. `test_platform_win.cpp` is -the single test file permitted system headers, and keeping those tests there is what lets every other -test file stay free of them. +the single test file permitted Windows system headers, and keeping those tests there is what lets every other +test file stay free of them; `test_platform_linux.cpp` is the Linux counterpart, whose subject is what only +Linux builds. ## Adding to the abstraction @@ -26,16 +27,17 @@ even though it compiles. A service only the window layer can implement is declar [render.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/render.h) or [ui.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/ui.h) instead, and implemented by its render backends (`src/render/win`, `src/render/linux`), also in libdesktop. What stays here is the -application's own: its side of FFmpeg's hardware decoding (`platform_win_av.cpp`), the screen recorder -(`platform_win_record.cpp`), its resource script and Linux glue (`platform_linux_app.cpp`). -`src/app.cpp` owns the Windows `wWinMain` and Linux `main`, and both call `platform::run`. +application's own: its side of FFmpeg's hardware decoding (`platform_win_av.cpp`), which writer writes a movie +- the system's on Windows, FFmpeg's own on Linux - behind `df::create_movie_writer` (`av_movie_writer.h`), the +screen recorder (`platform_win_record.cpp`), its resource script and Linux glue (`platform_linux_app.cpp`). +`src/app.cpp` owns `main`, the same on both systems, which calls `platform::run`. Every new platform capability needs a Linux implementation or an explicit unavailable answer. libdesktop's [Linux backend](https://github.com/ZacWalk/libdesktop/blob/main/docs/platform.md#the-linux-backend) lists what it answers as unavailable, and [linux.md](../../docs/linux.md) what that removes from -Diffractor. `platform_linux_app.cpp` supplies the Linux hardware-decode, screen-recorder and platform-test -answers; it is built instead of the Windows-only `platform_win_av.cpp`, `platform_win_record.cpp` and -`test_platform_win.cpp`. +Diffractor. `platform_linux_app.cpp` supplies the Linux hardware-decode, movie-writer and screen-recorder +answers and registers the Linux platform tests, `test_platform_linux.cpp`; it is built instead of the +Windows-only `platform_win_av.cpp`, `platform_win_record.cpp` and `test_platform_win.cpp`. ## Capability is answered at run time diff --git a/.github/workflows/linux.yml b/.github/workflows/linux.yml index f9b3f985..f6aed1e4 100644 --- a/.github/workflows/linux.yml +++ b/.github/workflows/linux.yml @@ -18,12 +18,16 @@ permissions: jobs: build: - runs-on: ubuntu-24.04 + # The x64 legs keep their names; the legs on Arm's runner add arm64, and there FFmpeg's configure + # chooses its aarch64 assembly and nasm goes unused. + name: build (${{ matrix.config }}${{ matrix.os == 'ubuntu-24.04-arm' && ', arm64' || '' }}) + runs-on: ${{ matrix.os }} strategy: fail-fast: false matrix: config: [ Debug, Release ] + os: [ ubuntu-24.04, ubuntu-24.04-arm ] steps: - uses: actions/checkout@v4 @@ -33,7 +37,10 @@ jobs: # The vendored build is the default (DIFFRACTOR_PREFER_SYSTEM is OFF), so these are the # toolchain rather than the dependencies. FFmpeg is driven by its own configure and make. # libdesktop-render's window layer sets text with Pango and drives X11 and Wayland through SDL3, - # which it builds from its pin, so it needs their development packages. + # which it builds from its pin, so it needs their development packages. libdesktop-platform's + # web client is the system's libcurl and its JPEG decoder the system's libjpeg-turbo; SDL3 builds + # its PulseAudio, ALSA and PipeWire audio backends only where their development packages are + # installed; and a phone or camera is reached over MTP through libmtp, which speaks USB through libusb. - name: Install toolchain run: | sudo apt-get update @@ -41,18 +48,21 @@ jobs: libpango1.0-dev libfontconfig-dev libfreetype-dev \ libx11-dev libxext-dev libxrandr-dev libxcursor-dev libxfixes-dev libxi-dev libxss-dev libxtst-dev \ libxkbcommon-dev libwayland-dev wayland-protocols libegl-dev libgl-dev libgles-dev libdrm-dev \ - libgbm-dev libdecor-0-dev libdbus-1-dev libudev-dev + libgbm-dev libdecor-0-dev libdbus-1-dev libudev-dev \ + libcurl4-openssl-dev libjpeg-dev libpulse-dev libasound2-dev libpipewire-0.3-dev libmtp-dev \ + libusb-1.0-0-dev # FFmpeg and the 25 vendored CMake modules are most of the build time and change rarely. # CCACHE_DIR is set rather than assumed: ccache 4.x defaults to ~/.cache/ccache, not ~/.ccache, - # so caching the older path would silently cache nothing. + # so caching the older path would silently cache nothing. An ARM64 leg's key names its + # architecture, so neither architecture restores the other's objects. - name: Cache compiler output uses: actions/cache@v4 with: path: ~/.cache/ccache - key: ccache-${{ runner.os }}-${{ matrix.config }}-${{ github.sha }} + key: ccache-${{ runner.os }}${{ runner.arch == 'ARM64' && '-ARM64' || '' }}-${{ matrix.config }}-${{ github.sha }} restore-keys: | - ccache-${{ runner.os }}-${{ matrix.config }}- + ccache-${{ runner.os }}${{ runner.arch == 'ARM64' && '-ARM64' || '' }}-${{ matrix.config }}- # bash ./dd rather than ./dd: the launcher is checked in from Windows and carries no # executable bit. It prefers pwsh and falls back to tools/dd.py, which is what runs here. diff --git a/.gitignore b/.gitignore index cc08e942..87594aa7 100644 --- a/.gitignore +++ b/.gitignore @@ -57,5 +57,8 @@ exe/tiles/*.png /search_*.ps1 *.msixupload *.appxsym +# Debian packages from `dd deb`, and their debug information. +/*.deb +/*.debug # Store artwork from running tools/generate_store_assets.py by hand; packaging writes its own to dist/. /exe/Assets/ diff --git a/AGENTS.md b/AGENTS.md index 24e3ab4f..694095dc 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -30,8 +30,8 @@ open the listed source, and run the listed check. Do not read unrelated document | Edit: a photo's adjustments, a video's or sound file's lossless trim, sound removal and turn | [design](docs/design.md#metadata-editing-and-files); writing is [file I/O](docs/file-io.md#writing)'s | [view_edit.cpp](src/view_edit.cpp), [media_edit.cpp](src/media_edit.cpp), [av_format.cpp](src/av_format.cpp)'s `av_remux` | `/test:*edit*`, `/test:*trim*` | | SID tunes and their length, tracker modules, the Commodore 64 | [design](docs/design.md#selection-and-viewing) | [av_sid.cpp](src/av_sid.cpp), [ui_sid.cpp](src/ui_sid.cpp), [av_tracker.cpp](src/av_tracker.cpp), [ui_tracker.cpp](src/ui_tracker.cpp), [av_c64.cpp](src/av_c64.cpp), [ui_c64.cpp](src/ui_c64.cpp) | `/test:*SID tune*`, `/test:*monitor*`, `/test:*tracker*`, `/test:*Commodore*` | | A guided operation: Rename, Import, Sync, Convert, Metadata, Date | [design](docs/design.md#guided-operations) | [view_rename.cpp](src/view_rename.cpp), [view_import.cpp](src/view_import.cpp), [view_sync.cpp](src/view_sync.cpp), [view_batch.cpp](src/view_batch.cpp) | `/test:*rename*`, `/test:*import*`, `/test:*sync*` | -| Movie mixer: the timeline, project files, rendering, YouTube Shorts, checking and rendering without the window | [movie](docs/movie.md) | [model_movie.cpp](src/model_movie.cpp), [view_movie.cpp](src/view_movie.cpp), [view_movie_audio.cpp](src/view_movie_audio.cpp), [app_movie_batch.cpp](src/app_movie_batch.cpp) | `/test:*movie*`, `/test:*YouTube*` | -| An agent session over MCP, its tools, `-tool:`, screenshots, recording and tutorial scripts | [agents](docs/agents.md) | [app_mcp.cpp](src/app_mcp.cpp), [app_mcp_tools.cpp](src/app_mcp_tools.cpp), [app_mcp_ui.cpp](src/app_mcp_ui.cpp), [app_mcp_controls.cpp](src/app_mcp_controls.cpp), [app_mcp_faces.cpp](src/app_mcp_faces.cpp), [app_tutorial.cpp](src/app_tutorial.cpp) | `/test:*agent*`, `/test:*tool call*`, `python tools/test_mcp_session.py exe/diffractor64-d.exe`, `python tools/sweep_mcp.py exe/diffractor64.exe` | +| Movie mixer: the timeline, project files, rendering, YouTube Shorts, checking and rendering without the window | [movie](docs/movie.md) | [model_movie.cpp](src/model_movie.cpp), [view_movie.cpp](src/view_movie.cpp), [view_movie_audio.cpp](src/view_movie_audio.cpp), [app_movie_batch.cpp](src/app_movie_batch.cpp), [av_movie_writer.cpp](src/av_movie_writer.cpp) | `/test:*movie*`, `/test:*YouTube*` | +| An agent session over MCP, its tools, `-tool:`, screenshots, recording and tutorial scripts | [agents](docs/agents.md) | [app_mcp.cpp](src/app_mcp.cpp), [app_mcp_tools.cpp](src/app_mcp_tools.cpp), [app_mcp_ui.cpp](src/app_mcp_ui.cpp), [app_mcp_faces.cpp](src/app_mcp_faces.cpp), [app_tutorial.cpp](src/app_tutorial.cpp), [app_record.cpp](src/app_record.cpp) | `/test:*agent*`, `/test:*shows work*`, `/test:*recording*`, `python tools/test_mcp_session.py exe/diffractor64-d.exe`, `python tools/sweep_mcp.py exe/diffractor64.exe` | | Faces: names read from and written into face regions, face search's scan of pictures and videos' key frames, the store and its comparisons, the face book and its database, people and groups, face terms, the Faces view, and faces on a picture or video | [faces](docs/faces.md) | [model_faces.cpp](src/model_faces.cpp), [model_faces_search.cpp](src/model_faces_search.cpp), [model_faces_book.cpp](src/model_faces_book.cpp), [model_db_faces.cpp](src/model_db_faces.cpp), [model_faces_groups.cpp](src/model_faces_groups.cpp), [view_faces.cpp](src/view_faces.cpp), [view_faces_actions.cpp](src/view_faces_actions.cpp), [ui_elements.cpp](src/ui_elements.cpp)'s `picture_faces`, [av_format.cpp](src/av_format.cpp)'s `read_key_frame` and `av_decode_key_frame`, [metadata.cpp](src/metadata.cpp)'s `apply_face_names` | `/test:*face*`, `python tools/test_mcp_session.py exe/diffractor64-d.exe` (its faces sessions) | | A crash report, dump, or symbolization | [crash investigation](docs/crash.md) | [app.cpp](src/app.cpp)'s `app_frame::crash`, libdesktop's [process.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/process.cpp), [util_crash_files_db.h](src/util_crash_files_db.h) | see [crash](docs/crash.md) | | Where a test belongs, or why the suite is arranged this way | [testing](docs/testing.md) | `src/test_*.cpp` | `.\dd.ps1 test` | @@ -43,10 +43,11 @@ open the listed source, and run the listed check. Do not read unrelated document ## Information ownership -GitHub issues and releases own work, status, discussion, follow-up, and release history. Source owns exact APIs, enums, and file lists. Every other subject has exactly one owning document: +GitHub issues and releases own work, status, discussion, follow-up, and release history, apart from the next release's plan, which its own document tracks until that release ships. Source owns exact APIs, enums, and file lists. Every other subject has exactly one owning document: | Document | Owns | |---|---| +| [mission](docs/mission.md) | Why Diffractor exists: whom it serves, the experience it promises them, what it will not become, and the order of the bets that follow | | [design](docs/design.md) | Durable user concepts and behavior: the user mental model, targeting and command availability, and view, mode, and presentation naming | | [implementation](docs/implementation.md) | Architecture and source organization, data flow, threading, ownership, invalidation, index/search internals | | [crash investigation](docs/crash.md) | Crash report contents, symbol store and debugger setup, dump symbolization, attributing a fault to a cause | @@ -63,6 +64,7 @@ GitHub issues and releases own work, status, discussion, follow-up, and release | [faces](docs/faces.md) | Faces: the people files name, face search - finding, embedding and comparing faces - the face book of what the user says of them, people and groups, the Faces view, and saving names to files | | [third-party](docs/third-party.md) | Fetched dependencies and their pins, the outbound licence they constrain, the upgrade procedure, and the integration constraints an upgrade must keep | | [Linux port](docs/linux.md) | Current Linux support, the platform boundary, unsupported surfaces, and build behavior | +| [next release](docs/v-1.27.5.md) | The plan for 1.27.5 until it ships: the changes in the tree, the planned work, the release tasks, and how the release is verified | | [README](README.md) | Product overview, build prerequisites, command line, and the licence Diffractor is released under | Move information to its owner; link rather than duplicate volatile detail. `tools/lint_repo.ps1` fails when a document has no owner row, when a link does not resolve, or when a `src/` path a document names no longer exists. @@ -82,7 +84,7 @@ Diffractor's `df::` and `str::` are its own types. Four sibling libraries supply - **libdesktop** ([DiffractorLibdesktop.cmake](cmake/DiffractorLibdesktop.cmake)): the `core::` vocabulary in `libdesktop/core.h`; OS services and the application loop in `platform::`/`libdesktop/platform.h`; drawing backends and counters in `render::`/`libdesktop/render.h`; frames, controls, menus and text views in `ui::`/`libdesktop/ui.h`, with headless fakes in `libdesktop/ui/test_support.h` and syntax highlighters in `libdesktop/ui/syntax.h`. - **libfiles** ([DiffractorLibfiles.cmake](cmake/DiffractorLibfiles.cmake)): scanning, decoding and encoding stills, scanning audio and video containers, and reading and writing EXIF, IPTC and XMP. `files.cpp` and `metadata.cpp` are Diffractor's side of it. -- **lib64** ([DiffractorLib64.cmake](cmake/DiffractorLib64.cmake)): the Commodore 64 emulator. It plays SID tunes, through `av_sid.cpp`, and runs a disk's, tape's, cartridge's or program file's program in the media pane, through `av_c64.cpp`. +- **lib64** ([DiffractorLib64.cmake](cmake/DiffractorLib64.cmake)): the Commodore 64 emulator and its media, through `lib64/*.h`. It plays SID tunes, through `av_sid.cpp`; lists what a disk, tape, cartridge or program file holds, through `files.cpp` and `ui_c64.cpp`; and runs its program in the media pane, through `av_c64.cpp`. - **libmug** ([DiffractorLibmug.cmake](cmake/DiffractorLibmug.cmake)): face detection and recognition, on libfiles' Highway. `model_faces.cpp` is Diffractor's side of it, and `model_faces_search.cpp` runs it over the collection. A sibling checkout at `..\libdesktop`, `..\libfiles`, `..\lib64` or `..\libmug` is built instead of the pin whenever it exists, so a local edit there reaches this build at once while isolated CI builds the pin. A change to one of them is made in that repository, under its own AGENTS.md. Before release, follow the [pinned build check](docs/third-party.md#upgrade-procedure): a green sibling build does not validate a release pin. @@ -96,7 +98,7 @@ Four recurring workflows are `.github/prompts/` slash commands rather than proce - Build and validate with `.\dd.ps1 test --label headless`: it runs `tools/lint_repo.ps1`, the release-tool and headless command-line checks, rebuilds `exe\diffractor64.exe` (Release) when a source file under `src/` is newer than it, then runs the unit tests, both translation validators and the MCP session test. It does not look at the sibling libraries, so after editing one, build first with `python tools\dd.py build --config Release`. - Build with `tools/dd.py`: `python tools\dd.py build` for Debug (`exe\diffractor64-d.exe`), `--config Release` for Release. `.\dd.ps1 build` also bumps the build number in `src/app.cpp`, `installer/diff.nsi` and `exe/AppxManifest.xml`; use it only to cut a build. CMake is the only description of the build on both platforms. App source belongs in `src/`; temporary output belongs in `tmp/`. - Style: C and C++ follow the repository's `.clang-format` (tabs, Allman braces, 120 columns); `.\dd.ps1` has no format command, so run the `clang-format` Visual Studio installs in `VC\Tools\Llvm\x64\bin`. `.clang-format-ignore` lists the generated files it skips, and hand-aligned tables sit between `// clang-format off` and `// clang-format on`. Diffractor's own code builds without a warning at `/W4` and at GCC's `-Wall`, in Debug and Release - fix a warning rather than suppress it - while vendored targets build at `/W0` (`-w`). `.clang-tidy` holds the static-analysis checks; where a finding is wrong, a `// NOLINTNEXTLINE(check)` says why. -- System, OS, Windows API, and other platform-specific implementation code MUST exist only in `platform*.*` files or in libdesktop; the one exception is the entry points, `wWinMain` and `main`, in `app.cpp`. Other modules use platform abstractions. +- System, OS, Windows API, and other platform-specific implementation code MUST exist only in `platform*.*` files or in libdesktop. Other modules use platform abstractions; the entry point, `main` in `app.cpp`, is the same on every platform. - Keep `// Purpose:` comments accurate in modified `src/*.h` and `src/*.cpp` files. - Preserve [product design](docs/design.md), especially targeting, recovery, navigation restoration, and preview-before-run. diff --git a/CITATION.cff b/CITATION.cff new file mode 100644 index 00000000..1e911bc7 --- /dev/null +++ b/CITATION.cff @@ -0,0 +1,28 @@ +cff-version: 1.2.0 +title: "Diffractor" +message: "If you use this software, please cite it using the metadata from this file." +type: software +authors: + - given-names: "Zac" + family-names: "Walker" + alias: "ZacWalk" + website: "https://github.com/ZacWalk" +repository-code: "https://github.com/ZacWalk/diffractor" +url: "https://diffractor.com/" +abstract: >- + Diffractor is a free, high-performance photo, video and audio organizer for + Windows, optimized for speed and local file control, with no cloud storage or + subscriptions required. It indexes a collection locally for instant metadata + search, reads and writes XMP, IPTC, EXIF and ID3, places photos and videos by + GPS, finds duplicates and faces on the computer itself, edits photos, trims + videos and sound files losslessly, and joins them into movies. +keywords: + - "photo management" + - "media organizer" + - "video" + - "audio" + - "metadata" + - "XMP" + - "EXIF" + - "face recognition" +license: MPL-2.0 diff --git a/CMakeLists.txt b/CMakeLists.txt index 9667b973..80cee65d 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -250,15 +250,16 @@ set(DIFFRACTOR_PORTABLE_SOURCES src/ui_controls.cpp src/ui_document.cpp src/app_commands.cpp + src/app_crash_report.cpp src/app_dialogs.cpp src/app.cpp src/app_dup_report.cpp src/app_mcp.cpp - src/app_mcp_controls.cpp src/app_mcp_faces.cpp src/app_mcp_tools.cpp src/app_mcp_ui.cpp src/app_movie_batch.cpp + src/app_record.cpp src/app_search.cpp src/app_toolbar.cpp src/app_tutorial.cpp @@ -286,6 +287,7 @@ list(APPEND DIFFRACTOR_PORTABLE_SOURCES src/av_c64.cpp src/av_deinterlace.cpp src/av_format.cpp + src/av_movie_writer.cpp src/av_pcm.cpp src/av_sid.cpp src/av_tracker.cpp @@ -398,6 +400,8 @@ if (WIN32) "${_generated_resources}" ) else () + list(APPEND DIFFRACTOR_TEST_SOURCES src/test_platform_linux.cpp) + set(DIFFRACTOR_PLATFORM_SOURCES src/platform_linux_app.cpp "${_generated_resources}" @@ -421,8 +425,7 @@ if (NOT WIN32) VERBATIM) target_sources(diffractor PRIVATE "${_app_icon_cpp}") set_source_files_properties("${_app_icon_cpp}" PROPERTIES SKIP_PRECOMPILE_HEADERS ON) - file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/diffractor.desktop" - CONTENT "[Desktop Entry]\nType=Application\nName=Diffractor\nExec=\"$\" %F\nIcon=${CMAKE_CURRENT_SOURCE_DIR}/src/Res/app.png\nTerminal=false\nCategories=Graphics;Photography;\n") + include(DiffractorLinuxInstall) endif () target_include_directories(diffractor PRIVATE diff --git a/README.md b/README.md index e56b2e13..079a8d51 100644 --- a/README.md +++ b/README.md @@ -2,8 +2,8 @@ [![CI](https://github.com/ZacWalk/diffractor/actions/workflows/windows.yml/badge.svg)](https://github.com/ZacWalk/diffractor/actions/workflows/windows.yml) Free, high-performance photo, video and audio organizer for Windows. Optimized for speed and local -file control—no cloud storage or subscriptions required. A Linux build runs but is not distributed; -see [docs/linux.md](docs/linux.md). +file control—no cloud storage or subscriptions required. A Linux beta is built as a Flatpak and as a Debian +package; see [docs/linux.md](docs/linux.md). ![Diffractor screenshot](screenshot.webp) @@ -45,6 +45,7 @@ python tools/dd.py build --config Release # Release x64: exe\diff python tools/dd.py build --config Release --arch x86 # the 32-bit desktop binary python tools/dd.py build --winstore # the Store binary .\dd.ps1 linux # build the Linux binary in WSL and run it +.\dd.ps1 deb # package the Linux Release as a .deb, in WSL .\dd.ps1 vs # debug the Debug build in Visual Studio ``` diff --git a/cmake/DiffractorCompilerPolicy.cmake b/cmake/DiffractorCompilerPolicy.cmake index afe3069d..8f791c0c 100644 --- a/cmake/DiffractorCompilerPolicy.cmake +++ b/cmake/DiffractorCompilerPolicy.cmake @@ -110,6 +110,10 @@ else () # the C compiler rejects the option rather than ignoring it. $<$:-Wno-changes-meaning> ) + + # A Debug build checks what MSVC's Debug library checks - an index past the end, a clamp whose bounds have + # crossed - as the Flatpak SDK's flags make the shipped build check it, where such a slip ends the process. + add_compile_definitions($<$:_GLIBCXX_ASSERTIONS>) endif () # Diffractor's own code. Warnings are on, and the precompiled header is applied where it works. @@ -142,15 +146,31 @@ function(diffractor_apply_app_policy target) # case-insensitive filesystem and reports every declaration in it as a redefinition. target_precompile_headers(${target} PRIVATE "${CMAKE_SOURCE_DIR}/src/pch.h") - # SubSystem Windows. The entry point is Diffractor's wWinMain in src/app.cpp; the explicit CRT - # startup option keeps the Windows subsystem entrypoint unambiguous. + # SubSystem Windows. The entry point is Diffractor's main in src/app.cpp, as it is on Linux; the explicit CRT + # startup option keeps a Windows-subsystem program from looking for WinMain. set_target_properties(${target} PROPERTIES WIN32_EXECUTABLE ON) - target_link_options(${target} PRIVATE /ENTRY:wWinMainCRTStartup) + target_link_options(${target} PRIVATE /ENTRY:mainCRTStartup) # GenerateManifest false. platform_win_res.rc embeds platform_win.manifest itself, and a # linker-generated one collides with it rather than being ignored. target_link_options(${target} PRIVATE /MANIFEST:NO) endif () + + # The binary links libpng, zlib, bzip2 and Brotli statically, and the FreeType, libcurl and GLib it links + # dynamically name the same functions. GNU ld exports what a regular object defines and a shared library + # references, so each of those libraries would bind to Diffractor's copy at run time, and libdecor's GTK plugin, + # which brings GTK's own libpng into the process, is refused while "png_free" is defined twice. Nothing looks a + # symbol up in the executable, so no archive exports one. + if (CMAKE_SYSTEM_NAME STREQUAL "Linux") + target_link_options(${target} PRIVATE LINKER:--exclude-libs,ALL) + endif () + + # The Store and a Flatpak are updated by their package manager, and a Linux build from source by its checkout - + # the published installer is a Windows program - so none of them offers an update of its own: no check, offer or + # installer, and no setting for them. WINSTORE also takes out crash reports, which Linux keeps. + if (DIFFRACTOR_WINSTORE OR NOT WIN32) + target_compile_definitions(${target} PRIVATE DIFFRACTOR_PACKAGE_UPDATES) + endif () endfunction() # Vendored code. It is not ours to make warning-clean, and the noise would bury our own. diff --git a/cmake/DiffractorLib64.cmake b/cmake/DiffractorLib64.cmake index 52b3460e..912b6424 100644 --- a/cmake/DiffractorLib64.cmake +++ b/cmake/DiffractorLib64.cmake @@ -9,7 +9,7 @@ include_guard(GLOBAL) include(FetchContent) -set(DIFFRACTOR_LIB64_REVISION f08de54b2f31c7750a2600d3ebefd2dd191fadad) +set(DIFFRACTOR_LIB64_REVISION c6259a4fe419ded975f3482172b5db8858b10335) if (NOT DEFINED FETCHCONTENT_SOURCE_DIR_LIB64 AND EXISTS "${CMAKE_SOURCE_DIR}/../lib64/CMakeLists.txt") set(FETCHCONTENT_SOURCE_DIR_LIB64 "${CMAKE_SOURCE_DIR}/../lib64" CACHE PATH diff --git a/cmake/DiffractorLibdesktop.cmake b/cmake/DiffractorLibdesktop.cmake index a1e697fc..47e3f7ac 100644 --- a/cmake/DiffractorLibdesktop.cmake +++ b/cmake/DiffractorLibdesktop.cmake @@ -11,7 +11,7 @@ include_guard(GLOBAL) include(FetchContent) -set(DIFFRACTOR_LIBDESKTOP_REVISION 368d34ff21f943fe1d77e2fb6615ccd0bf14ae68) +set(DIFFRACTOR_LIBDESKTOP_REVISION f933bba51df5064dfb639df7cbfc2aebef11cb24) if (NOT DEFINED FETCHCONTENT_SOURCE_DIR_LIBDESKTOP AND EXISTS "${CMAKE_SOURCE_DIR}/../libdesktop/CMakeLists.txt") set(FETCHCONTENT_SOURCE_DIR_LIBDESKTOP "${CMAKE_SOURCE_DIR}/../libdesktop" CACHE PATH diff --git a/cmake/DiffractorLibfiles.cmake b/cmake/DiffractorLibfiles.cmake index 8585490b..c05dae66 100644 --- a/cmake/DiffractorLibfiles.cmake +++ b/cmake/DiffractorLibfiles.cmake @@ -9,7 +9,7 @@ include_guard(GLOBAL) include(FetchContent) -set(DIFFRACTOR_LIBFILES_REVISION 749c7f46d4ee67f34d9125c7733905a55995f4d0) +set(DIFFRACTOR_LIBFILES_REVISION fa4c23e1665398ec77f11f88c8d58abfc8486a2d) if (NOT DEFINED FETCHCONTENT_SOURCE_DIR_LIBFILES AND EXISTS "${CMAKE_SOURCE_DIR}/../libfiles/CMakeLists.txt") set(FETCHCONTENT_SOURCE_DIR_LIBFILES "${CMAKE_SOURCE_DIR}/../libfiles" CACHE PATH diff --git a/cmake/DiffractorLibmug.cmake b/cmake/DiffractorLibmug.cmake index fc660b29..722fd144 100644 --- a/cmake/DiffractorLibmug.cmake +++ b/cmake/DiffractorLibmug.cmake @@ -10,7 +10,7 @@ include_guard(GLOBAL) include(FetchContent) -set(DIFFRACTOR_LIBMUG_REVISION fd94430daf52949ed719acaa4d7a8a072464178e) +set(DIFFRACTOR_LIBMUG_REVISION 944a1174a6129d20f44c11bbf08ae9f70ae8ab97) if (NOT DEFINED FETCHCONTENT_SOURCE_DIR_LIBMUG AND EXISTS "${CMAKE_SOURCE_DIR}/../libmug/CMakeLists.txt") set(FETCHCONTENT_SOURCE_DIR_LIBMUG "${CMAKE_SOURCE_DIR}/../libmug" CACHE PATH diff --git a/cmake/DiffractorLinuxInstall.cmake b/cmake/DiffractorLinuxInstall.cmake new file mode 100644 index 00000000..229a24ea --- /dev/null +++ b/cmake/DiffractorLinuxInstall.cmake @@ -0,0 +1,79 @@ +# This file is part of the Diffractor photo and video organizer +# Copyright 2026 Zac Walker +# +# Purpose: What a Linux package of Diffractor installs and where, and the launcher a local build writes beside its +# binary. A distribution package and the Flatpak in packaging/flatpak, which installs to /app, share these rules. +# +# Diffractor reads its catalogs, dictionaries and place data from the folder of the running binary +# (platform::known_folder::running_app_folder, from /proc/self/exe), so they install beside it in lib/diffractor, and +# bin/diffractor is a link to it: the kernel answers /proc/self/exe with the link's target. + +include_guard(GLOBAL) + +# The window's application ID, which Wayland and X11 find the launcher and its icon by: also the launcher's, the +# AppStream metadata's and the icons' file names. src/app.cpp sets the same one, and the Flatpak manifest names it. +set(DIFFRACTOR_APP_ID com.diffractor.Diffractor) +set(_app_dir lib/diffractor) +set(_launcher_template "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/${DIFFRACTOR_APP_ID}.desktop.in") + +# One launcher, two sets of values. The local build's names its binary and icon by path, so a copy in +# $XDG_DATA_HOME/applications finds them where they are; the installed one names them as a package puts them. +set(DIFFRACTOR_DESKTOP_EXEC "\"$\"") +set(DIFFRACTOR_DESKTOP_ICON "${CMAKE_CURRENT_SOURCE_DIR}/src/Res/app.png") +configure_file("${_launcher_template}" "${CMAKE_CURRENT_BINARY_DIR}/launcher/${DIFFRACTOR_APP_ID}.desktop.in" @ONLY) +file(GENERATE OUTPUT "${CMAKE_CURRENT_BINARY_DIR}/${DIFFRACTOR_APP_ID}.desktop" + INPUT "${CMAKE_CURRENT_BINARY_DIR}/launcher/${DIFFRACTOR_APP_ID}.desktop.in") + +set(DIFFRACTOR_DESKTOP_EXEC diffractor) +set(DIFFRACTOR_DESKTOP_ICON "${DIFFRACTOR_APP_ID}") +configure_file("${_launcher_template}" "${CMAKE_CURRENT_BINARY_DIR}/install/${DIFFRACTOR_APP_ID}.desktop" @ONLY) + +install(TARGETS diffractor RUNTIME DESTINATION ${_app_dir}) +install(DIRECTORY "${CMAKE_CURRENT_SOURCE_DIR}/exe/languages" "${CMAKE_CURRENT_SOURCE_DIR}/exe/dictionaries" + DESTINATION ${_app_dir}) +install(FILES + "${CMAKE_CURRENT_SOURCE_DIR}/exe/location-countries.txt" + "${CMAKE_CURRENT_SOURCE_DIR}/exe/location-places.txt" + "${CMAKE_CURRENT_SOURCE_DIR}/exe/location-states.txt" + DESTINATION ${_app_dir}) + +# Relative, so a staged tree (DESTDIR) and a prefix that is moved afterwards both keep a working link. +install(CODE " + file(MAKE_DIRECTORY \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin\") + file(CREATE_LINK \"../${_app_dir}/diffractor\" \"\$ENV{DESTDIR}\${CMAKE_INSTALL_PREFIX}/bin/diffractor\" SYMBOLIC) +") + +install(FILES "${CMAKE_CURRENT_BINARY_DIR}/install/${DIFFRACTOR_APP_ID}.desktop" DESTINATION share/applications) +install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/${DIFFRACTOR_APP_ID}.metainfo.xml" + DESTINATION share/metainfo) + +# tools/generate_icon.py draws these from the same vectors as the Windows icon, and its --check keeps them current; +# the 512 is src/Res/app.png itself. +foreach (_size IN ITEMS 64 128 256) + install(FILES + "${CMAKE_CURRENT_SOURCE_DIR}/packaging/linux/icons/hicolor/${_size}x${_size}/apps/${DIFFRACTOR_APP_ID}.png" + DESTINATION share/icons/hicolor/${_size}x${_size}/apps) +endforeach () + +install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/src/Res/app.png" + DESTINATION share/icons/hicolor/512x512/apps RENAME ${DIFFRACTOR_APP_ID}.png) + +# The eight licence texts every release package carries beside the binary, under the names dd.ps1 gives them: the +# binary links LGPL libraries statically, and libaom, the libfacedetection weights and SFace ask for theirs (README). +set(_licence_dir share/licenses/${DIFFRACTOR_APP_ID}) +install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/LICENSE" DESTINATION ${_licence_dir} RENAME LICENSE.txt) + +foreach (_licence IN ITEMS + LGPL-3.0.txt:COPYING.LGPLv3.txt + GPL-3.0.txt:COPYING.GPLv3.txt + LGPL-2.1.txt:COPYING.LGPLv2.1.txt + libaom-BSD-2-Clause.txt:LICENSE.libaom.txt + AOM-Patent-License-1.0.txt:PATENTS.libaom.txt + libfacedetection-BSD-3-Clause.txt:LICENSE.libfacedetection.txt + Apache-2.0.txt:LICENSE.sface.txt) + string(REPLACE ":" ";" _licence "${_licence}") + list(GET _licence 0 _licence_file) + list(GET _licence 1 _licence_name) + install(FILES "${CMAKE_CURRENT_SOURCE_DIR}/licences/${_licence_file}" DESTINATION ${_licence_dir} + RENAME ${_licence_name}) +endforeach () diff --git a/cmake/vendored/FFmpeg.cmake b/cmake/vendored/FFmpeg.cmake index b21a5777..1c7e38e2 100644 --- a/cmake/vendored/FFmpeg.cmake +++ b/cmake/vendored/FFmpeg.cmake @@ -89,6 +89,22 @@ if (TARGET libfiles-dav1d) "$, -I>" "-lpthread -lm") endif () +# Movies are written here, not by the platform as on Windows (src/av_movie_writer.cpp): AV1 by the libaom +# libfiles already builds for AVIF, and AAC by FFmpeg's own encoder, which needs nothing external. Only the +# encoder is wanted of libaom: libfiles builds it without its decoder, so FFmpeg's libaom decoder - which would +# be configured with the library, and reference a decoder interface the archive does not have - is turned +# off, and libdav1d stays the software AV1 decoder. The 3.15.1 is libfiles' pin; configure asks for 2.0.0. +set(_ff_encoders "") + +if (TARGET libfiles-aom) + set(_ff_encoders + --enable-libaom + --enable-encoder=aac,libaom_av1 + --disable-decoder=libaom_av1) + _ff_describe_vendored(aom libfiles-aom 3.15.1 + "$, -I>" "-lpthread -lm") +endif () + # bzlib and lzma have no pkg-config path in configure at all -- it probes them with a hard coded # -lbz2 and -llzma -- so the vendored archives are staged under the names it looks for. Naming the # system copies instead would put a second bzip2 and a second lzma in a binary that already links @@ -127,11 +143,12 @@ endif () # organizer opens a socket, and it removes the RTP, RTSP, SAP and SDP demuxers from the attack # surface along with the protocol layer beneath them. # -# Diffractor is a broad-support reader: every decoder and demuxer is wanted, and no encoder is. The -# encoder, muxer, filter, device and protocol switches below are the Windows configure line from -# docs/third-party.md, which this had not been matching -- the whole encoder and muxer set was being -# compiled in here. file is the one intentional protocol. The muxers named are the containers Edit's -# lossless audio and video edits copy a file back into, packets as they are; no other is built. +# Diffractor is a broad-support reader: every decoder and demuxer is wanted, and no encoder is but the two +# above that write a movie on Linux. The encoder, muxer, filter, device and protocol switches below are the +# Windows configure line from docs/third-party.md, which this had not been matching -- the whole encoder and +# muxer set was being compiled in here. file is the one intentional protocol. The muxers named are the +# containers Edit's lossless audio and video edits copy a file back into, packets as they are, and the movie +# writer's MP4; no other is built. # # --enable-small is deliberately absent. It buys a smaller binary by stripping codec and profile # names and by sending H.264 macroblocks, MPEG motion compensation and swscale output down their @@ -149,6 +166,7 @@ ExternalProject_Add(ffmpeg_external --disable-autodetect --disable-network --disable-encoders + ${_ff_encoders} --disable-muxers --enable-muxer=mov,mp4,ipod,tgp,tg2,matroska,webm,mpegts,avi,asf,flv,mp3,flac,ogg,oga,opus,wav,aiff,adts --disable-devices @@ -195,7 +213,7 @@ set_property(GLOBAL PROPERTY DIFFRACTOR_GROUPED_ARCHIVES "${_ff_archives}") # configure links a probe against the archives named in the .pc files, so they have to be on disk # before the external project starts rather than merely before the application links. -foreach (_ff_dep IN ITEMS diffractor_openmpt libfiles-zlib libfiles-dav1d ffmpeg_compression_libs) +foreach (_ff_dep IN ITEMS diffractor_openmpt libfiles-zlib libfiles-dav1d libfiles-aom ffmpeg_compression_libs) if (TARGET ${_ff_dep}) add_dependencies(ffmpeg_external ${_ff_dep}) endif () diff --git a/cmake/vendored/archive-linux/config_linux.h b/cmake/vendored/archive-linux/config_linux.h index ebf9950f..63f6c994 100644 --- a/cmake/vendored/archive-linux/config_linux.h +++ b/cmake/vendored/archive-linux/config_linux.h @@ -90,7 +90,8 @@ #define HAVE_FTRUNCATE 1 #define HAVE_FUTIMENS 1 #define HAVE_FUTIMES 1 -#define HAVE_FUTIMESAT 1 +/* No HAVE_FUTIMESAT: glibc declares it only under _GNU_SOURCE, and GCC 14 refuses the implicit declaration that GCC 13 + let pass. futimens and utimensat do its work. */ #define HAVE_GETEUID 1 #define HAVE_GETGRGID_R 1 #define HAVE_GETGRNAM_R 1 diff --git a/cmake/vendored/ffmpeg-config-divergence.txt b/cmake/vendored/ffmpeg-config-divergence.txt index affdd44e..4a7a7ed0 100644 --- a/cmake/vendored/ffmpeg-config-divergence.txt +++ b/cmake/vendored/ffmpeg-config-divergence.txt @@ -3,8 +3,9 @@ # Generated by tools/compare_ffmpeg_config.py --update. Each line names the platform that # enables a switch the other does not. Read every line before re-recording: each should be # platform by nature -- the hardware accelerators, Media Foundation and SChannel on the -# Windows side, glibc's iconv on the Linux side. A decoder, demuxer, encoder or muxer here is -# a defect rather than a divergence, and so is anything that is merely a choice one side made. +# Windows side, glibc's iconv on the Linux side -- or the movie writer's, below. A decoder, +# demuxer, encoder or muxer anywhere else is a defect rather than a divergence, which the tool +# refuses to record, and so is anything that is merely a choice one side made. # # See docs/third-party.md, 'FFmpeg Configuration And Upgrade Checklist'. @@ -27,3 +28,15 @@ WINDOWS CONFIG_VP9_D3D11VA_HWACCEL WINDOWS CONFIG_WMV3_D3D11VA2_HWACCEL WINDOWS CONFIG_WMV3_D3D11VA_HWACCEL LINUX CONFIG_ICONV + +# The movie writer. Linux writes movies with FFmpeg's own encoders - AV1 by libaom, AAC by +# its native encoder - where Windows asks Media Foundation, whose encoders are the system's +# and not FFmpeg's. Each line is an encoder, libaom, or what the encoders are made of. +# docs/movie.md and docs/third-party.md say why. +LINUX CONFIG_AAC_ENCODER +LINUX CONFIG_AUDIO_FRAME_QUEUE +LINUX CONFIG_ENCODERS +LINUX CONFIG_FRAME_THREAD_ENCODER +LINUX CONFIG_LIBAOM +LINUX CONFIG_LIBAOM_AV1_ENCODER +LINUX CONFIG_LPC diff --git a/cmake/vendored/minizip-linux/mz_config.h b/cmake/vendored/minizip-linux/mz_config.h new file mode 100644 index 00000000..300f53f7 --- /dev/null +++ b/cmake/vendored/minizip-linux/mz_config.h @@ -0,0 +1,32 @@ +#ifndef MZ_CONFIG_H +#define MZ_CONFIG_H + +/* Diffractor's Linux configuration for minizip-ng: the answers its own configure finds on glibc + (mz_config.h.cmakein). The Windows one beside it denies , so mz_os_posix.c is left with no declaration of + opendir, readdir or closedir, which GCC 14 refuses and GCC 13 took as calls to functions returning int. */ + +/* Define to 1 if you have the header file. */ +#define HAVE_DIRENT_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_SYS_DIRENT_H 0 + +/* Define to 1 if you have the header file. */ +#define HAVE_INTTYPES_H 1 + +/* Define to 1 if you have the header file. */ +#define HAVE_STDINT_H 1 + +/* Define to 1 if DIR* is defined. */ +#define HAVE_PDIR 1 + +/* Define to 1 if fseeko() is defined. */ +#define HAVE_FSEEKO 1 + +/* Define to 1 if symlink() is defined. */ +#define HAVE_SYMLINK 1 + +/* Define to 1 if readlink() is defined. */ +#define HAVE_READLINK 1 + +#endif diff --git a/cmake/vendored/minizip.local.cmake b/cmake/vendored/minizip.local.cmake index 6ef84d57..feb00441 100644 --- a/cmake/vendored/minizip.local.cmake +++ b/cmake/vendored/minizip.local.cmake @@ -16,5 +16,8 @@ if (NOT WIN32) "${minizip_SOURCE_DIR}/mz_strm_os_posix.c" "${minizip_SOURCE_DIR}/mz_crypt_openssl.c") + # Ahead of the Windows mz_config.h: it denies and the rest, which these sources need. + target_include_directories(diffractor_minizip BEFORE PUBLIC "${CMAKE_CURRENT_LIST_DIR}/minizip-linux") + target_link_libraries(diffractor_minizip PRIVATE crypto) endif () diff --git a/dd.ps1 b/dd.ps1 index b5fb166a..52682ca6 100644 --- a/dd.ps1 +++ b/dd.ps1 @@ -67,7 +67,7 @@ param( [Parameter(Position = 0)] - [ValidateSet("desktop", "store", "run", "run32", "cpu", "linux", "test", "bean", "build", "bump-build", "bump-ver", "deploy", "release", "loc", "code", "vs", "clear-cache", "setup", "configure", "clean", "info", "help", "")] + [ValidateSet("desktop", "store", "run", "run32", "cpu", "linux", "deb", "test", "bean", "build", "bump-build", "bump-ver", "deploy", "release", "loc", "code", "vs", "clear-cache", "setup", "configure", "clean", "info", "help", "")] [string]$Command = "", # Package the version already in the tree: for desktop and store builds of one release, or for rebuilding a @@ -127,15 +127,17 @@ function Get-CurrentVersion { # Read version from app.cpp as the source of truth $content = Get-Content $AppCppFile -Raw - # Extract version: const std::string_view s_app_version = "126.2"; - if ($content -match 'const std::string_view s_app_version = "(\d+)\.(\d+)";') { - $majorMinor = $Matches[1] # e.g., "126" - $patch = $Matches[2] # e.g., "2" - - # Parse majorMinor: first digit is major, rest is minor - $major = [int]$majorMinor.Substring(0, 1) - $minor = [int]$majorMinor.Substring(1) - $patchNum = [int]$patch + # Extract version: const std::string_view s_app_version = "1.27.4"; + if ($content -match 'const std::string_view s_app_version = "(\d+)\.(\d+)\.(\d+)";') { + $major = [int]$Matches[1] + $minor = [int]$Matches[2] + $patchNum = [int]$Matches[3] + } + # Builds up to 1.27.4.1316 wrote the two-part form, the major folded into the minor: "127.4" + elseif ($content -match 'const std::string_view s_app_version = "(\d)(\d+)\.(\d+)";') { + $major = [int]$Matches[1] + $minor = [int]$Matches[2] + $patchNum = [int]$Matches[3] } else { Write-Host "Error: Could not parse version from app.cpp" -ForegroundColor Red @@ -156,10 +158,10 @@ function Get-CurrentVersion { Minor = $minor Patch = $patchNum Build = $build - VersionString = "$major.$minor.$patchNum" # e.g., "1.26.2" - AppVersion = "$major$minor.$patchNum" # e.g., "126.2" - FileVersion = "$major.$minor.$patchNum.$build" # e.g., "1.26.2.1187" - CommaVersion = "$major, $minor, $patchNum, $build" # e.g., "1, 26, 2, 1187" + VersionString = "$major.$minor.$patchNum" # e.g., "1.27.4" + AppVersion = "$major.$minor.$patchNum" # e.g., "1.27.4" + FileVersion = "$major.$minor.$patchNum.$build" # e.g., "1.27.4.1316" + CommaVersion = "$major, $minor, $patchNum, $build" # e.g., "1, 27, 4, 1316" } } @@ -171,10 +173,10 @@ function Update-AllVersionFiles { [int]$Build ) - $appVersion = "$Major$Minor.$Patch" # e.g., "126.2" - $fileVersion = "$Major.$Minor.$Patch.$Build" # e.g., "1.26.2.1187" - $commaVersion = "$Major, $Minor, $Patch, $Build" # e.g., "1, 26, 2, 1187" - $productVersion = "$Major$Minor.$Patch" # e.g., "126.2" + $appVersion = "$Major.$Minor.$Patch" # e.g., "1.27.4" + $fileVersion = "$Major.$Minor.$Patch.$Build" # e.g., "1.27.4.1316" + $commaVersion = "$Major, $Minor, $Patch, $Build" # e.g., "1, 27, 4, 1316" + $productVersion = "$Major.$Minor.$Patch" # e.g., "1.27.4" Write-Host "" Write-Host "Updating version to: $fileVersion" -ForegroundColor Cyan @@ -185,7 +187,7 @@ function Update-AllVersionFiles { # Update app.cpp Write-Host "Updating $AppCppFile..." -ForegroundColor Yellow $content = Get-Content $AppCppFile -Raw - $content = $content -replace 'const std::string_view s_app_version = "\d+\.\d+";', "const std::string_view s_app_version = `"$appVersion`";" + $content = $content -replace 'const std::string_view s_app_version = "\d+(\.\d+){1,2}";', "const std::string_view s_app_version = `"$appVersion`";" $content = $content -replace 'const std::string_view g_app_build = "\d+";', "const std::string_view g_app_build = `"$Build`";" Set-Content $AppCppFile $content -NoNewline @@ -193,7 +195,7 @@ function Update-AllVersionFiles { Write-Host "Updating $NsiFile..." -ForegroundColor Yellow $content = Get-Content $NsiFile -Raw $content = $content -replace '!define BUILD_NUM "\d+"', "!define BUILD_NUM `"$Build`"" - $content = $content -replace '!define PRODUCT_VERSION "\d+\.\d+"', "!define PRODUCT_VERSION `"$productVersion`"" + $content = $content -replace '!define PRODUCT_VERSION "\d+(\.\d+){1,2}"', "!define PRODUCT_VERSION `"$productVersion`"" $content = $content -replace '!define FILE_VERSION "\d+\.\d+\.\d+\.\$\{BUILD_NUM\}"', "!define FILE_VERSION `"$Major.$Minor.$Patch.`${BUILD_NUM}`"" Set-Content $NsiFile $content -NoNewline @@ -307,6 +309,7 @@ function Show-Usage { Write-Host " clean Remove the CMake build directory" Write-Host " info Report host, build directory and detected tooling" Write-Host " linux Build the Linux application and run it - from Windows in WSL, shown through WSLg" + Write-Host " deb Build the Linux Release and package it as a .deb in the repository root - from Windows in WSL" Write-Host "" Write-Host " build / test / run use CMake and Ninja on both hosts." Write-Host "" @@ -1604,6 +1607,7 @@ switch ($Command) { "clean" { Invoke-DdPython -Action "clean" -Arguments $Rest } "info" { Invoke-DdPython -Action "info" -Arguments $Rest } "linux" { Invoke-DdPython -Action "linux" -Arguments $Rest } + "deb" { Invoke-DdPython -Action "deb" -Arguments $Rest } "build" { if ($IsLinuxHost) { Invoke-DdPython -Action "build" -Arguments $Rest } diff --git a/docs/agents.md b/docs/agents.md index a8fede14..09055877 100644 --- a/docs/agents.md +++ b/docs/agents.md @@ -6,8 +6,12 @@ render Movie projects, drive the window - commands, tasks, dialogs, selection an record the window, play tutorial scripts and run the developer's checks. `-tool:` calls one of them once from the command line. -This document owns the session: starting it, what it may do, its window, long work and dialogs, the tools and the -tasks they work. The other switches are the [README](../README.md#command-line)'s; the `.dfv` format is +libdesktop's [agent mode](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md) serves the session: the +switches, the tiers and how they hold, the window made out of sight, jobs and waiting, dialogs and menus, the tools +any window answers - `ui_state`, `ui_controls`, `ui_act`, `command_run`, `dialog_respond`, `screenshot` and the rest +- `-tool:`, and the Python client that drives a session. This document owns what is Diffractor's: what its +session may do and keeps to itself, its window and index, its own tools, the tasks they work, tutorials and +recordings. The other switches are the [README](../README.md#command-line)'s; the `.dfv` format is [movie](movie.md#6-project-files)'s, as is what the Movie tools check and report, YouTube Shorts included ([movie](movie.md#9-checking-and-rendering-without-the-window)); faces are [faces](faces.md)'s; and the tutorial script grammar is in [app_tutorial.h](../src/app_tutorial.h). @@ -31,26 +35,13 @@ Copilot - in VS Code and the Copilot CLI - reads its servers from `%USERPROFILE% ``` A workspace's `.vscode/mcp.json` takes the same entry under `servers`; Claude Desktop's -`claude_desktop_config.json` and Cursor's `mcp.json` take its `command` and `args` under `mcpServers`. Grant -tiers (section 2) in `args` only as the work needs them. - -| Switch | Effect | -|--------|--------| -| `-mcp` | Serves the tools on stdin and stdout; the end of input ends the session | -| `-mcp-ui:none`, `offscreen` or `visible` | Where the window is: made by the first tool that needs it, out of sight (the default); made at once, out of sight; or made at once, on the desktop | -| `-mcp-allow:` | What beyond reading the session may do, comma-separated: `write`, `capture`, `network`, `dev`, `launch` (section 2) | - +`claude_desktop_config.json` and Cursor's `mcp.json` take its `command` and `args` under `mcpServers`. `-mcp-ui` +says where the window is and `-mcp-allow` grants tiers (section 2), in `args` only as the work needs them. `-profile:` and `-collection:` ([README](../README.md#command-line)) keep a session's settings, index and collection apart from the user's. -Both protocol revisions in use are spoken: 2026-07-28, whose requests carry their revision in `_meta` and which -`server/discover` describes, and the `initialize` handshake of 2025-11-25, 2025-06-18 and 2025-03-26. The server -offers tools only. A call that asks for progress hears it; a call the client cancels is stopped and answered with -nothing. Nothing but the protocol is written to stdout: Diffractor's log goes to its log file, and what it says to -the client is on stderr. - -Start with `status`, which says what the session was started with, and `help`, which explains the search -language, the `.dfv` and `.dft` formats and the tiers. +Start with `status`, which says what the session was started with and how the index stands, and `help`, which +explains the search language, the `.dfv` and `.dft` formats and the tiers. ## 2. What a session may do @@ -65,13 +56,13 @@ A session reads by default; the client's configuration, which is the user's, gra | `dev` | The developer's tools: `run_tests`, `validate_translations`, `generate_docs`, `duplicate_report`, and in a Debug build `debug_action` | | `launch` | Opening another program, a folder or a web page on the user's desktop: the help, a file's folder, a map, Open with, and the links that open a web page | -A tool the session may not use is not offered; `status` names each one withheld and the tier that would allow -it. `command_list` marks each command that needs a tier, and `command_run` refuses those the session may not -run, `exit` - closing the input ends the session - and those that work through the system's own windows. A -command that opens a menu opens it, and what is chosen from it needs what its own command needs. The tiers hold -however a command is reached - a key, a toolbar's button, a menu row, a step of `ui_input` or `tutorial_run` - -and the log says what was not run; steps that would run a refused command are refused before any is played. -The window's own Close is left to whoever watches a visible session. +The tiers hold however a command is reached, as libdesktop's agent mode +[says](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md#what-a-session-may-do). Diffractor's commands +need what [app_mcp.cpp](../src/app_mcp.cpp)'s `rule_of` says: those that change files, the face book, the +clipboard or the system need `write`, and those that open the help, a file's folder or a map need `launch`. +`command_run` refuses `exit` - closing the input ends the session - and the commands that work through the +system's own windows or install another version. Steps of `ui_input` or `tutorial_run` that would run a refused +command are refused before any is played. The window's own Close is left to whoever watches a visible session. The session uses the user's own profile unless started with `-profile`, and changes nothing the user's next start finds: settings it changes last only as long as it runs. It shares the user's index, so it refuses to make its @@ -87,42 +78,33 @@ report, even if its Options page asks for them. ## 3. The window The tools that need the window - the library's, the window's and the face tools, `window` and `debug_action` - -make it and load the index when the first of them is called; the others do not. A window out of sight is never -shown on the desktop or the taskbar - on Windows it is cloaked - yet it is drawn, laid out and captured as one on -the desktop is, by the software renderer, and plays nothing aloud. `window` sizes it; screenshots and recordings -are made at its size. +make it and load the index when the first of them is called; the others do not. A window out of sight is drawn by +the software renderer and plays nothing aloud. `window` sizes it; screenshots and recordings are made at its size. A recording films the window as the screen shows it, so it needs `-mcp-ui:visible`. While it records, the window -is held above the others; keep the screen unlocked. +is held above the others; keep the screen unlocked. On Linux there is no desktop to ask for what the screen shows, +so a recording is the window's own pixels, as its software renderer draws them: a menu or a bubble, which is a +window of its own there, is not in it, the system's pointer is drawn as an arrow whatever its shape, and the window +is not held above the others. A script's pointer and clicks are drawn in on both. ## 4. Long work, waiting and dialogs -A call that starts long work - a render, the test suite, a tutorial, a command - answers within `wait_s` seconds, -50 unless the call says otherwise: with its result, or with its job and how far it has got. `job_wait` waits for -the job again and answers with its result once it has finished; `job_cancel` stops it, and a render stopped leaves -no movie behind. - -A dialog that asks - a confirmation, a question, a report waiting on Close - or a menu that opens stops the input -behind it, and a call waiting on work it interrupts is answered at once with the dialog: its title, text, buttons, -check boxes and fields, and as `rows` a list a search fills - Copy to folder's folders, the people naming a face -offers - the chosen row marked. Work that holds the window while it runs is waited out, whether nothing shows or a -dialog shows it under way - a rating written, a batch's progress, an edit being saved - and a command that starts -it is answered once it has finished; work that ends with files it could not change leaves its report of them -waiting on Close, which is a dialog like any other. `ui_state` shows the dialog in front, or the open menu's rows. - -`dialog_respond` answers the dialog in front: it fills fields by their label, a date as `yyyy-mm-dd hh:mm:ss`, and -sets check boxes and radio buttons by their text, then presses a button by its text, or cancels the dialog as -Escape does; `choose` picks a row by its text, as a click does, then presses the button named, or else the default -one. It answers once the dialog has closed or another has opened. A session without `write` can only cancel. -`menu_respond` chooses from a menu - a row by its text, or by its path from the first level, `Sort by > Name` - or -cancels it. - -A dialog Windows shows itself while work waits on it is listed last, as the one in front, and marked `system`: its -title, text and buttons are read as a screen reader reads them, and it has no fields or check boxes to set. -Diffractor asks what it can before calling Windows - a delete on a network share is confirmed once, as permanent, -and Windows is not asked again - but Windows still asks where only it knows, as when another program holds a file -open or a delete cannot use the Recycle Bin after all. A call waiting on the work is answered with it, `ui_state` -counts it among what is busy, and `dialog_respond` presses its buttons by their text or cancels it. +Long work - a render, the test suite, a tutorial, a command - runs as a job, and a dialog or a menu that opens +interrupts the call waiting on it, as libdesktop's agent mode +[says](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md#long-work-waiting-and-dialogs). A render that +`job_cancel` stops leaves no movie behind. Work that holds the window while it runs is waited out - a rating +written, a batch's progress, an edit being saved - and work that ends with files it could not change leaves its +report of them waiting on Close, which is a dialog like any other. A dialog's `rows` are the list a search fills +in it: Copy to folder's folders, and the people naming a face offers. + +A dialog the system shows itself while work waits on it - Windows does; on Linux the system puts up none - is +listed last, as the one in front, and marked `system`: its title, text and buttons are read as a screen reader +reads them, and it has no fields or check boxes to set. Diffractor asks what it can before calling the system - a +delete of what the Recycle Bin or Trash cannot take, as on a network share, is confirmed once, as permanent, and +the system is not asked again - but Windows still asks where only it knows, as when another program holds a file +open or a delete cannot use the Recycle Bin after all. Linux has no one to ask: what the Trash cannot take stays +where it is and its delete fails. A call waiting on the work is answered with it, `ui_state` counts it among what +is busy, and `dialog_respond` presses its buttons by their text or cancels it. `wait_until_idle` waits until the index has loaded and nothing is scanning, searching, indexing, making thumbnails, loading media - from when the window asks for it until it has it - acting out steps, running a task, @@ -131,19 +113,25 @@ settles until it is answered. Call it before a screenshot, or after starting wor ## 5. The tools +Diffractor offers libdesktop's [tools](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md#the-tools) +and its own: + | Area | Tools | |------|-------| -| The session | `help`, `status`, `wait_until_idle`, `diagnostics` (the version, system, graphics, memory, the index's counts and the session's performance counters), `log_read` (the latest log lines, or those since a mark), `job_wait`, `job_cancel`, `window` | | The library | `search` (the address box's language, without changing the window: each file's dates and rating, the set of copies it belongs to, and its metadata where asked, in order of path, of when each was taken or of its set of copies), `item_info` (what Diffractor reads from one file: from the index once it has read the file, otherwise from the file itself), `location_suggest` (section 6) | -| The window | `ui_state`, `command_list`, `command_run`, `navigate` (a folder or a search, as the address box opens it), `select` (by file name, or by full path where a search across folders shows two of a name), `dialog_respond`, `menu_respond`, `ui_input`, `ui_controls`, `ui_act`, `coverage` | +| The window | `navigate` (a folder or a search, as the address box opens it), `select` (by file name, or by full path where a search across folders shows two of a name), `ui_input` (a tutorial script's steps) | | Tasks | `task_state`, `task_set` (section 6) | | Faces | `faces_state`, `faces_select`, `faces_data` | -| Pictures | `screenshot`, `record_start`, `record_mark`, `record_stop`, `tutorial_run` | +| Pictures | `record_start`, `record_mark`, `record_stop`, `tutorial_run` | | Movie | `movie_check`, `movie_render` | | The developer's | `run_tests`, `validate_translations`, `generate_docs`, `duplicate_report`, and in a Debug build `debug_action` | -Each tool's description and input schema, from `tools/list`, are its reference. Paths are full paths. A result -is text for the model and, where it has structure, the same as JSON in `structuredContent`. +Each tool's description and input schema, from `tools/list`, are its reference. Paths are full paths. Of +libdesktop's tools, `status` adds the profile, the cache folder, the collection and how the index stands; +`diagnostics` the index's counts and timings and the session's queries, database, files and thumbnails; `ui_state`, +`command_run` and the tools that act the view, the search, how many items it finds and shows, the first of them +and of the selection, and the media shown - where it is, whether it plays, and the parts of a video where faces the +search found it by are seen; and `help` the topics `search`, `dfv` and `dft`. `ui_input` acts out steps in the window as a user would, in a tutorial script's scene language: `point tile 'IMG_1.jpg'`, `click`, `double-click`, `right-click`, `drag at 0.5 0.5`, `wheel down 3`, `type 'beach'`, @@ -152,16 +140,14 @@ own input, so they reach what a user's would, and the pointer it draws shows whe own pointer and keyboard are not used. Each call starts with the pointer hidden, so a click follows a point in the same call. A dialog or menu that opens ends the steps. -`ui_controls` lists everything the window offers now, each with an id: the bars' buttons, boxes and slider, the -view's links and parts, its panel's controls, the view itself and the strip, the dialog in front and the open -menu's rows - `status/button/Rotate clockwise`, `panel/edit/Folder`, `menu/item/Sort by > Name`. `ui_act` works -one by its id - a press, a double or right click, a hover, a drag, the wheel, typed text or a key - as the -platform's own input to its window, so through whatever is in front, and answers once the window has caught up or -as soon as a dialog or menu opens. One scrolled out of sight is scrolled into view first, and a key is pressed -with the keyboard taken to it, as Tab takes it there; `view/content/…` takes it to the view. `coverage` counts -each command run and menu opened, from wherever, and which listed controls have been used, so a sweep that -presses every button knows what it has missed; [sweep_mcp.py](../tools/sweep_mcp.py) is one -([testing](testing.md#the-sweep)). +`ui_controls` lists the bars' buttons, boxes and sliders - the address box is `title/edit/address`, and the +filter, the item size, the people filter and the face size are called so - the logo, which opens the help, the +view's regions - `sidebar`, `view`, `listing`, `media` and the task's `panel` - with their links and parts, the view +itself and the strip, then the dialog in front and the open menu's rows: `status/button/Rotate clockwise`, +`panel/edit/Folder`, `menu/item/Sort by > Name`. A key `ui_act` presses on a part is pressed with the keyboard on +that part, as Tab takes it there, and `view/content/…` takes it to the view. `coverage` counts what has been +exercised, so a sweep that presses every button knows what it has missed; [sweep_mcp.py](../tools/sweep_mcp.py) is +one ([testing](testing.md#the-sweep)). The face tools work [faces](faces.md) as a user does. `faces_state` says whether face search is on, for photos and for videos, and how far it has read - the files that could not be read and those waiting for their drive @@ -224,35 +210,36 @@ rehearses, naming each beat as it starts, as progress too. A step that finds not named in the answer. A dialog or menu that opens is waited out, for a script cannot answer one, and the player says so. -`record_start`, `record_mark` and `record_stop` film the window for any other purpose, on Windows, at 30 frames a +`record_start`, `record_mark` and `record_stop` film the window for any other purpose, at 30 frames a second - a rate Movie renders at, so a recording joins a movie with no frame repeated or dropped unevenly - and -`record_mark`'s names are written to the markers file in the same way. +`record_mark`'s names are written to the markers file in the same way. Windows writes the film as H.264 through +Media Foundation, and Linux as AV1 with FFmpeg's own encoder, both in an MP4 ([movie](movie.md#7-rendering)). A tutorial made with a collection of its own is the same on every machine: `-collection:` with the pictures it shows, and `-profile:` for its settings. ## 8. Screenshots -`screenshot` takes a picture of the window, or of the dialog in front, as it is drawn - on the desktop or out of -sight - once the window has settled, waiting up to `settle_s` seconds (10 by default). It is saved where `path` -says, as PNG, JPEG, WebP, JPEG XL or AVIF by the path's extension, and returned as a PNG unless it was saved and -`image` is false. `max_size` bounds its longer side: 1600 pixels for a picture returned, none for one only saved. -Pictures for the documentation take a session with `-mcp-allow:capture` - and `write`, for `ui_input` - a -collection and profile of its own, `window` to set the size, then `navigate`, `select`, `command_run` and -`ui_input` to set the scene. +`screenshot` is libdesktop's +([screenshots](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md#screenshots)); Diffractor saves one as +JPEG, WebP, JPEG XL or AVIF as well as PNG, by the path's extension, with libfiles' encoders. Pictures for the +documentation take a session with `-mcp-allow:capture` - and `write`, for `ui_input` - a collection and profile of +its own, `window` to set the size, then `navigate`, `select`, `command_run` and `ui_input` to set the scene; +libdesktop's `mcp_client.py` saves them compressed. ## 9. Testing and diagnostics `run_tests` runs the test suite, or the tests a filter names, in a copy of the program, and answers with how -many passed and why each failure failed; `validate_translations` checks the catalogs. `diagnostics` and -`log_read` say what Diffractor is doing and what it costs: ask before and after an action to see what changed. -The suite and its taxonomy are [testing](testing.md)'s. +many passed and why each failure failed, its progress counted as each test reports; `validate_translations` +checks the catalogs. `diagnostics` and `log_read` say what Diffractor is doing and what it costs: ask before and +after an action to see what changed. The suite and its taxonomy are [testing](testing.md)'s. `.\dd.ps1 test` drives sessions end to end with [test_mcp_session.py](../tools/test_mcp_session.py), each in a profile and collection of its own. The first, which may capture, covers both handshakes, the tools withheld, a Movie project checked without a window, the window made out of sight by a search, its controls listed and a menu -opened, read and cancelled, a screenshot, task panels filled in - fields a check box shows or enables among them - -analyzed and refused a run, a place suggested and proposed by Locate, and the end of input ending the session. +opened, read and cancelled, a screenshot and the paints `diagnostics` counts, task panels filled in - fields a check +box shows or enables among them - analyzed and refused a run, a place suggested and proposed by Locate, and the end +of input ending the session. The second, which may write, types a search into the address box as a user does, finds the window busy while a large photo is read and decoded, reads back from the file what Convert has just written, and on Windows meets the dialog Windows shows when Delete finds a file another program holds open: listed with the dialogs, ending a wait @@ -266,12 +253,10 @@ others were skipped, where the session test checks specific outcomes. ## 10. A single call from the command line -`-tool: name=value ...` calls one tool once, without a session, and exits. Each value is read as the -tool's input schema types it: a number, `true` or `false`, a list split at commas, an object as JSON, or text; -quote a pair whose value has a space. What the tool reports as it works goes to stderr and its result to stdout - -its structured content as JSON where it has some, otherwise its text. The exit code is 0 for a result, 1 for an -error the tool reports and 2 for a call that could not be made. A call from the command line may use every tier, -as it does only what it names; the tools that need the window need a session. +`-tool: name=value ...` calls one tool once, without a session, and exits, as libdesktop's agent mode +[says](https://github.com/ZacWalk/libdesktop/blob/main/docs/agent.md#a-single-call-from-the-command-line): its +result on stdout, what it reports on stderr, and an exit code of 0 for a result, 1 for the tool's error and 2 for a +call that could not be made. The tools that need the window need a session. ```powershell & .\exe\diffractor64.exe -tool:movie_check projects=D:\Projects 2>&1 | Out-Host @@ -282,31 +267,32 @@ Piping into `Out-Host` makes PowerShell wait for this GUI-subsystem executable a ## Where this lives -- [app_mcp.h](../src/app_mcp.h) and [app_mcp.cpp](../src/app_mcp.cpp): the session's host - its options and - tiers, jobs and the calls waiting on them, the window made when a tool needs it, the log lines it keeps, the - session's own tools, and `-tool:`. [app_mcp_json.h](../src/app_mcp_json.h): the JSON results are written with. +- [app_mcp.h](../src/app_mcp.h) and [app_mcp.cpp](../src/app_mcp.cpp): what Diffractor tells libdesktop's agent + host - its guidance and help topics, its window and index made when a tool needs them, each command's tier, + what keeps it busy, what status and diagnostics add, what its bars and views offer `ui_controls`, its own + elements and dialogs, and the picture types a screenshot is saved as. - [app_mcp_tools.cpp](../src/app_mcp_tools.cpp): the Movie, developer's and library tools, and the `agent` queue long work runs on; `location_suggest` groups what `index_state::dated_locations` and `suggest_locations` in - [model_index_summary.cpp](../src/model_index_summary.cpp) answer. [app_mcp_ui.cpp](../src/app_mcp_ui.cpp): the - window's tools, dialogs, task views, screenshots and recordings. [app_mcp_controls.cpp](../src/app_mcp_controls.cpp): - `ui_controls`, `ui_act`, `menu_respond` and `coverage`, the open menu described, and the counts of what has run; - libdesktop's `ui::send_pointer` and its kin give the input, as the platform's own. + [model_index_summary.cpp](../src/model_index_summary.cpp) answer. [app_mcp_ui.cpp](../src/app_mcp_ui.cpp): + navigation and selection, `ui_input` and tutorials, task views and recordings. [app_mcp_faces.cpp](../src/app_mcp_faces.cpp): `faces_state`, `faces_select` and `faces_data`. - [app.cpp](../src/app.cpp): the switches, read into [app_command_line.h](../src/app_command_line.h); the session made in `parse_command_line`, its window in `start_window`, and the run settings a session applies. [app_settings.cpp](../src/app_settings.cpp): the settings a session keeps to itself, and `-profile`. - [app_tutorial.h](../src/app_tutorial.h) and [app_tutorial.cpp](../src/app_tutorial.cpp): tutorial scripts and the player that acts them and `ui_input`'s steps out; [app_record.h](../src/app_record.h) and - [platform_win_record.cpp](../src/platform_win_record.cpp): the recorder. + [app_record.cpp](../src/app_record.cpp): the recorder's request, the pointer, click ring and markers a script + makes the same on both platforms, and the recorder of a window's own pixels; + [platform_win_record.cpp](../src/platform_win_record.cpp) and + [platform_linux_app.cpp](../src/platform_linux_app.cpp): capturing the window, on Windows and on Linux. - [app_movie_batch.cpp](../src/app_movie_batch.cpp), [app_dup_report.cpp](../src/app_dup_report.cpp) and [app_gen_docs.cpp](../src/app_gen_docs.cpp): the work the Movie and developer's tools run. [app_commands.cpp](../src/app_commands.cpp): every command's name. [ui_dialog.h](../src/ui_dialog.h): the - dialogs showing, which the tools describe and answer. -- libdesktop's [core/mcp.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/mcp.h): the - protocol, the tools' schemas and results; its [agent session](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/agent.cpp) - serves it on stdin and stdout from `platform::run`, and keeps system dialogs from being shown; its - [system prompts](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/system_prompts.cpp) read and - answer the dialogs Windows shows itself, which [app_mcp_ui.cpp](../src/app_mcp_ui.cpp) lists with Diffractor's. -- Tests: [test_app.cpp](../src/test_app.cpp) for the tools' arguments, the session's options and settings, the - commands' names and the Movie report; [test_util.cpp](../src/test_util.cpp) for the switches; and + dialogs showing, which the host describes and answers. +- libdesktop's [ui/agent.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/ui/agent.h): the + host - the session's options and tiers, its jobs, the tools any window answers and `-tool:` - over + [core/mcp.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/mcp.h), the protocol, served + on stdin and stdout from `platform::run`; its system prompts read and answer the dialogs Windows shows itself. +- Tests: [test_app.cpp](../src/test_app.cpp) for the dialogs a session waits out, its settings, the commands' + names and the Movie report; [test_util.cpp](../src/test_util.cpp) for the switches; and [test_mcp_session.py](../tools/test_mcp_session.py) for a session end to end. diff --git a/docs/crash.md b/docs/crash.md index 3f5ab382..e5b5e4f2 100644 --- a/docs/crash.md +++ b/docs/crash.md @@ -1,20 +1,35 @@ # Crash investigation This document owns turning a Diffractor crash report into an attributed defect: what a report contains, -where symbols come from, how to make a minidump resolve, and how to tell the faulting frame from the -cause. What the code does belongs to [implementation.md](implementation.md) and the owning subject +where symbols come from, how to make a minidump or a Linux report resolve, and how to tell the faulting frame +from the cause. What the code does belongs to [implementation.md](implementation.md) and the owning subject document. ## 1. What a report contains -libdesktop's exception filter calls `app_frame::crash` ([app.cpp](../src/app.cpp)), which posts a -`crash.zip` to diffractor.com under the subject `Diffractor CRASH report`, beside form fields carrying -`calc_app_info` - the block the logo's tooltip shows with debug info on. The zip holds: +On Windows libdesktop's exception filter calls `app_frame::crash` ([app.cpp](../src/app.cpp)) in the crashing +process, which posts a `crash.zip` to diffractor.com under the subject `Diffractor CRASH report`, beside form +fields carrying `calc_app_info` - the block the logo's tooltip shows with debug info on. The zip holds: - `Diffractor----.dmp` (UTC) — a user minidump. - `diffractor.log` — the crashing session. - `diffractor.previous.log` — the session before it. +On Linux nothing of Diffractor's runs in the process that crashes: libdesktop's signal handler writes a report +file and the process ends with its signal, and **the next start** sends the report through the same post +(`df::post_crash_report`, [app_crash_report.cpp](../src/app_crash_report.cpp)), under the same subject and with +the same form fields. The `message` is what the crashed run told its report at startup (`Release`, `Build`, +`Version`, `Windows`, `Id`), then `Crash`, `Thread`, `Running`, `Build id`, `Reported: by the start after the +crash`, and `Open file in ` for each file open, as a crash in process logs them. The `diffractor` +and `build` fields name the release and build that crashed, not the one that sends, and say `unknown` for a crash +before the run could say. The zip holds: + +- `Diffractor----.crash.txt` (UTC) — the report ([section 8](#8-linux-reports)), + where the dump would be. +- `diffractor.log` — the crashing session, when the file the restart rotated to `diffractor.previous.log` is that + session's: its last write falls between the run's start and its end. The session before it is not kept, since + this start's log took the name, and a log a later run has written since is not sent as the crash's. + **Support** (`send_info`, [app_dialogs.cpp](../src/app_dialogs.cpp)) posts the same block and logs to the same endpoint as `logs.zip` under `Diffractor LOG`, with no dump. Read the subject first: a `LOG` report is a user asking for help, not a fault. @@ -22,17 +37,36 @@ a user asking for help, not a fault. The dump is the part most likely to be missing: writing it needs `dbghelp` and a writable temp file, and without either the logs go alone, the log saying `no minidump was written - reporting logs only`. A report with no `.dmp` is therefore a real crash, not a truncated upload. Both temp files are deleted once the -attempt ends, so nothing is left on the user's machine to ask for. +attempt ends, so nothing is left on the user's machine to ask for. On Linux the report stays in the data folder +until it is sent or dropped. One thread claims the handler (`df::handling_crash`), so a report never duplicates a second fault inside -the first. Before anything else, and whether or not it reports, the handler adds the files the faulting -thread had open to the skip list ([crash-loop protection](implementation.md#crash-loop-protection)). No -report comes from the Store build, which compiles the filter out (`WINSTORE`) - its crashes reach Partner -Center's health reports through the `.appxsym` symbols in the upload `.\dd.ps1 store` builds - nor with +the first; on Linux libdesktop's handler claims it, and a thread that faults meanwhile waits for that report. +Before anything else, and whether or not it reports, the handler adds the files the faulting thread had open to the +skip list ([crash-loop protection](implementation.md#crash-loop-protection)); on Linux the next start does, +from the report's work, before anything scans (`app_frame::init`), for a report of its own release line. No report +comes from the Store build, which compiles the filter and the post out (`WINSTORE`) - its crashes reach +Partner Center's health reports through the `.appxsym` symbols in the upload `.\dd.ps1 store` builds - nor with `setting.send_crash_dumps` off, from a run with `-profile:`, or from an agent session without `network` -(`app_frame::apply_run_settings`). When Windows ends a hung or crashing process, in either build, its -recovery callback (`save_recovery_state`) logs `*** recover callback ***` and `Open file in ` -for each open file, and adds them to the skip list. +(`app_frame::apply_run_settings`); Linux packages, Flatpak among them, report as any build does. When Windows ends +a hung or crashing process, in either build, its recovery callback (`save_recovery_state`) logs +`*** recover callback ***` and `Open file in ` for each open file, and adds them to the skip list. + +A Linux start decides each report it finds (`df::decide_crash_report_fate`), and the settings that count are the +ones Windows asks, asked of both runs: + +| Report | Fate | +|---|---| +| The run that crashed said `Reports: no` — a `-profile:` run, or a session without `network` | removed, unsent | +| This run has `-profile:`, or is a session without `network` | kept for a run that may send it | +| `Send crash reports` is off | removed, unsent | +| There is no network | kept | +| The server answers 2xx, or 4xx | sent, or refused: removed | +| The transfer fails, or the server answers 5xx | kept, and sent again at the next start | + +A report is sent from the web queue once the window is up, so a start that never makes one - an agent session with +no window - leaves it for the next. libdesktop keeps the sixteen newest, so a crash at every start cannot fill the +folder. ## 2. Read the logs before the dump @@ -52,13 +86,26 @@ account name as `%user%`. Take: left unscanned in this session. - **The previous log** — if it shows the same anomaly, the crash is reproducible on that machine and the anomaly is a lead rather than a coincidence. +- **`perf results`** — what a run that ended normally cost, as one table: Diffractor's own areas, and painting, + Direct3D and the software renderer in the rows libdesktop gives (`render::counter_rows`), whose own lines at the + end Diffractor turns off so each fact is logged once. A log that reaches 4 MiB says `*** log truncated ...` and then keeps only `main` and `perf` lines, so its crash tail is missing. Anything a `__try`/`__except` or `catch` swallowed appears here and nowhere else; a swallowed fault minutes before the crash is a suspect, not a footnote. +A Linux log has no such tail, for the crashing process cannot log from its handler and the file's own buffer is +lost with it. The report's `-- log` section holds the last 16 KiB the log was given, lines the file never got +included, and the `Open file` lines are in the message and the report's work. The start that sends the report logs +what it found - ` crash report(s) were left by earlier runs, and file(s) they had open are skipped`, then +`Add file type to crash list ` for each - and what became of each (`crash report was sent (200)`, `is +kept for a run that can send it`, `is not sent: ...`). + ## 3. Symbols +On Linux a report is a text file and its addresses resolve against the binary's debug information, which a +release build has none of: see [section 8](#8-linux-reports). What follows is Windows'. + `dd.ps1`'s `Add-ToSymbolStore` publishes with `symstore add /r /f /s c:\code\symbols /t Diffractor /compress`, run from the Windows SDK's `Windows Kits\10\Debuggers\x64`: its **Debugging Tools for Windows**, without which desktop and Store @@ -160,22 +207,98 @@ In order, and stopping as soon as the answer is unambiguous: - **Deliberate crashes.** A Debug build's `debug_action` tool ([agents](agents.md)) crashes on purpose: `crash` writes through a null pointer in `app_frame::run_test_action`, and `send-crash-report` sends a report whose "dump" is the fixture `Test.jpg`. A crash with `run_console_tests` on its stack and an - uptime of seconds is a `/test` console run, not a user session. + uptime of seconds is a `/test` console run, not a user session. `run_test_action` is compiled under MSVC's + `_DEBUG`, which GCC never defines, so a Linux build has neither; to see the Linux path, signal the process: + `kill -SEGV ` writes a report whose code is `SI_USER` and whose thread is the one the kernel chose, and + `tgkill` names a thread. A Linux `/test` run installs the reporter like any other, so its crash leaves a + report for the next start. An attributed crash needs three things that agree: the faulting instruction, a mechanism in our code that produces it, and something in the log or the dump's globals that says this configuration took that path. Two out of three is a hypothesis. +## 8. Linux reports + +libdesktop's handler for SIGSEGV, SIGBUS, SIGILL, SIGFPE, SIGABRT and SIGSYS writes one text file per crash into +the application's data folder - `$XDG_DATA_HOME/diffractor`, which is `~/.local/share/diffractor`, or +`~/.var/app//data/diffractor` in a Flatpak - as `diffractor-crash---.txt` (UTC). It +is written as `.part` and renamed once whole, and the handler then lets the signal end the process, so the exit +status and any core dump are the system's. Only calls a signal handler may make are used in it, on a stack of its +own, so a stack overflow is reported too; a report that takes ten seconds is given up, and the signal ends the +process anyway. + +``` +libdesktop crash report 1 +application: Diffractor +executable: /app/bin/diffractor +build-id: 8c7d00112233445566778899aabbccddeeff0011 +load-base: 0x55d0c0000000 +signal: 11 SIGSEGV +code: 1 SEGV_MAPERR +address: 0x0000000000000008 +thread: 4243 +thread-name: thumbnail_decod +pc: 0x000055d0c1e0a5c0 +-- text 118 +Release: 1.27.5 +... +``` + +The header says what ended the process and where, and `-- text` what Diffractor told its report at startup +(`df::crash_report_text`: release, build, whether the run reports, and the lines the logo's tooltip starts with), +set again once the command line says whether the run reports. The rest are sections: + +| Section | Holds | +|---|---| +| `-- work` | One per file a worker had open, with the thread that had it and the stage: `crash_files_db` keeps the list where the handler reads it without a lock. These paths stay on the machine | +| `-- backtrace` | The faulting thread's frames, as `(+)[
]`: the first are the handler's own, up to libc's signal trampoline (`libc.so.6(+0x...)`), and the frame after it is where the fault was | +| `-- log` | The last 16 KiB the log was given, whether or not its file kept them | +| `-- status` | `/proc/self/status`: `VmRSS` and `VmPeak` say whether the process ran out of memory | +| `-- maps` | `/proc/self/maps`: what was mapped where, which with `load-base` turns an address into an offset in a binary | + +What is sent is the report without its work, with only programs and libraries named in the memory map (a decoder's +mapped photo is the user's), and with the account name in a path replaced by `%user%`, as the log does. The files +that were open go in the message by type and stage, as a crash in process logs them. + +**Symbolizing.** A Release build from source is compiled without `-g`, so its report resolves to function names +from the binary's symbol table, and to lines only against debug information of the same build; the Flatpak is +compiled with `-g`, and keeps that information apart, in its `.Debug` extension: + +1. Find the binary by `build-id`: `readelf -n diffractor | grep 'Build ID'`. A rebuild of the same commit has + another one - the build date is in the binary - so keep the debug file of every build that ships. A Flatpak's + is in its `.Debug` extension, which the bundle leaves out and the repository it was built in keeps + ([packaging](../packaging/flatpak/README.md)), as `lib/diffractor/diffractor.debug`; its build id is the + binary's. +2. `pc` less `load-base` is where the fault is in the binary; a frame's `(+0x)` is already relative, and a + frame with only `[
]` less `load-base` is. A caller's address is where the call returns to, so one less + points into the call: + + ```bash + addr2line -f -C -i -p -e diffractor.debug 0x1e0a5c0 # pc - load-base: the faulting instruction + addr2line -f -C -i -p -e diffractor.debug 0x1e0a41f # a caller: its offset - 1 + eu-addr2line -f -C -i -e diffractor 0x1e0a41f --debuginfo-path= + ``` + +3. A frame in a library - `libc.so.6(+0x...)` - is resolved against that library's own debug information, which + the distribution ships as a `-dbgsym` package. When `load-base` is not at hand, the executable's first line in + `-- maps` (offset `00000000`) is it. + +Read the `thread-name` first: a worker named for its queue (`thumbnail_decod`, `scan_folder`) names the stage that +faulted, and the `Open file` lines say which type of file it had open. The faulting frame is no more the culprit +here than on Windows ([section 7](#7-attribution)). + ## Where this lives | Crash-handling subject | Source | |---|---| -| Report contents and posting | `app_frame::crash` and `calc_app_info` in [app.cpp](../src/app.cpp); `send_info` in [app_dialogs.cpp](../src/app_dialogs.cpp) | +| Report contents and posting | `app_frame::crash` and `calc_app_info` in [app.cpp](../src/app.cpp); `df::post_crash_report` in [app_crash_report.cpp](../src/app_crash_report.cpp); `send_info` in [app_dialogs.cpp](../src/app_dialogs.cpp) | | Exception filter, minidump writing, and restart and recovery registration | libdesktop's [process.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/process.cpp) | +| A Linux report: the signal handler, the file, the text and work it keeps, and the stacks it runs on | libdesktop's [posix/crash.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/posix/crash.cpp), [linux/crash.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/linux/crash.cpp) and [crash.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/platform/crash.h) | +| What a run tells its Linux report, and what the next start does with one: skip list, send, drop or keep | [app_crash_report.cpp](../src/app_crash_report.cpp), called from `app_frame::pre_init`, `parse_command_line` and `init`, and `check_for_updates_and_location` in [app.cpp](../src/app.cpp) | | The open-file list a fault records, and its bounds | [util_crash_files_db.h](../src/util_crash_files_db.h); `app_frame::save_recovery_state` in [app.cpp](../src/app.cpp) | | The graphics crash guard and hardware-acceleration fallback | libdesktop's [settings.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/settings.cpp) keeps the guards; `apply_gpu_crash_guard` in [app.cpp](../src/app.cpp) falls back from them | | The safe start after two unsettled launches | `app_frame::load_settings` in [app.cpp](../src/app.cpp), `decide_startup` in [app_settings.h](../src/app_settings.h), `reset_presentation` in [app_settings.cpp](../src/app_settings.cpp) | -| Diagnostic log and session counters | libdesktop's [core/log.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/log.h), [core/util.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/util.h) and [platform/services.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/platform/services.h); [app_perf.h](../src/app_perf.h) | +| Diagnostic log and session counters | libdesktop's [core/log.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/log.h), [core/util.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/util.h), [platform/app.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/platform/app.h) and [render/counters.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/render/counters.h); `df::log_perf_summary` in [app_perf.cpp](../src/app_perf.cpp) and [app_perf.h](../src/app_perf.h) | | SDK symbol-store discovery and publishing | `Get-SymStore` and `Add-ToSymbolStore` in [dd.ps1](../dd.ps1), checked by [test_release_tools.ps1](../tools/test_release_tools.ps1) | | Debugging a reproducible crash in Visual Studio (`dd.ps1 vs`) | `Open-VisualStudio` in [dd.ps1](../dd.ps1) | | Deliberate crashes in a Debug build | `app_frame::run_test_action` in [app_commands.cpp](../src/app_commands.cpp) | diff --git a/docs/design.md b/docs/design.md index 0db03c25..399633fe 100644 --- a/docs/design.md +++ b/docs/design.md @@ -17,7 +17,7 @@ must not introduce avoidable blocking or unbounded work. ## Product Promise Diffractor is a private organizer for photos, video, and audio on storage the user controls. It is -released for Windows; a [Linux](linux.md) build runs but is not distributed. It finds, views, +released for Windows; a [Linux](linux.md) build is in beta, as a Flatpak. It finds, views, compares, describes, edits, and manages media without making its rebuildable index the authority for user files or metadata. @@ -448,7 +448,8 @@ store's drawing of its waveform ([metadata](metadata.md#audio-and-video-metadata alone, and a cover still on its way leaves its place empty rather than grey. A Commodore 64 disk (D64, D71, D81), tape (T64) or program file (PRG, P00) shows its listing in the -C64's blue where media shows, above the item's panel. Clicking a program's row - any row of a tape - +C64's blue and its own characters, a directory's graphics among them, where media shows, above the item's +panel. Clicking a program's row - any row of a tape - runs it on an emulated Commodore 64, and a program file also has Start under its listing. A cartridge (CRT) is drawn as Commodore's own: a black shell in the original's proportions, standing as it goes in, with its grip ridges, its title on a silver label and the board's gold contacts, and Start under it. The @@ -595,11 +596,14 @@ and kept until the next share, since the receiving app may read them later, and format Diffractor does not write goes as a JPEG. Sources are never changed. Collisions use Replace, Skip, Auto-rename, or Block Run; two plan rows claiming one destination are a -collision. Delete distinguishes recoverable Recycle from confirmed permanent delete, and asks first only -when its confirmation option is on - except on a network share, or a drive mapped to one, which has no -Recycle Bin: there Delete always asks, once, saying the items will be permanently deleted, and Windows, -recycling what it can, does not ask again. When a requested Recycle would destroy an item, Windows asks -before removing it, and Windows' own Recycle Bin confirmation, if on, may confirm ordinary recycles too. +collision. Delete distinguishes recoverable Recycle - to the Recycle Bin on Windows, the desktop's Trash on +Linux - from confirmed permanent delete, and asks first only when its confirmation option is on - except where +an item cannot be recycled: a network share, or a drive mapped to one, has no Recycle Bin, and on Linux a +network mount, a Windows drive under WSL or a memory file system has no Trash. There Delete always asks, once, +saying the items will be permanently deleted, and the system, recycling what it can, does not ask again. When +a requested Recycle would destroy an item, Windows asks before removing it, and Windows' own Recycle Bin +confirmation, if on, may confirm ordinary recycles too; Linux has no one to ask, so an item the Trash cannot +take stays where it is and its delete fails, as an error says. What Delete or Move takes away leaves the listing at once, the rest keeping its place; when the selection went, the cursor lands on the item that followed it, or the one before at the listing's end. @@ -689,7 +693,9 @@ cancelled Analyze stages nothing. Import copies from a device whatever Move says copies once a run, leaving Import or choosing another source is done with them. Each running Diffractor stages in a folder of its own, and opening Import clears what instances since ended left there. A device offering nothing - locked, or asking whether to allow the computer in - is said to be so, with a request -to unlock it. Only Windows reaches such devices. +to unlock it. A device that will not open at all - on Linux, most often a phone the file manager has +mounted - carries the platform's sentence for why under its check box, and Analyze shows it rather than +finding nothing. Windows reaches such devices through Windows Portable Devices, Linux through libmtp. ### Name templates @@ -744,8 +750,9 @@ disable control. Aggregate feature-use diagnostics contain no stable user ID or `default_keyboard_accelerators`: each command's availability, disabled reason and keys; [app_commands.cpp](../src/app_commands.cpp) and [app_commands.h](../src/app_commands.h): the commands, their targets, handlers and menus; `bubble_delay` in [ui_view.h](../src/ui_view.h): how long bubbles wait. -- [app_search.h](../src/app_search.h), [model_search.cpp](../src/model_search.cpp), and - [model_tokenizer.h](../src/model_tokenizer.h): address editing, parsing, and matching. +- [app_search.cpp](../src/app_search.cpp), with libdesktop's `ui::completion_session`, + [model_search.cpp](../src/model_search.cpp), and [model_tokenizer.h](../src/model_tokenizer.h): address + editing, parsing, and matching. - [view_items.cpp](../src/view_items.cpp), [view_items.h](../src/view_items.h), and [view_media.h](../src/view_media.h): Items, selection presentation, and Fullscreen; the region drawn on a picture is `view_state::drawn_region` in [model.h](../src/model.h), drawn by `photo_control` in diff --git a/docs/file-io.md b/docs/file-io.md index ae9f2e2e..110575c8 100644 --- a/docs/file-io.md +++ b/docs/file-io.md @@ -250,6 +250,7 @@ folder comparison and treated conservatively, because their effect is unknown. | Media replacement fails | Destination remains unchanged | | Sidecar replacement fails | Media is restored from its rollback copy, or removed when it is new | | In-place patch fails | One retry while the file is untouched, then a reported failure and rescan; no full rollback promise | +| The packet refuses the edit: libfiles rejected it whole as it read it, or cannot read or make a field the edit touches - a value where the packet holds an array, a region in a form its path cannot name | The edit fails with libfiles' reason, and nothing is written, the sidecar included | Cancellation stops future items in a batch and reports completed, failed, skipped and cancelled items separately. It does not claim to undo completed writes. diff --git a/docs/implementation.md b/docs/implementation.md index d9b2ba90..6cd77570 100644 --- a/docs/implementation.md +++ b/docs/implementation.md @@ -11,7 +11,7 @@ rebuildable index and thumbnail cache; media files and sidecars stay authoritati file, reads and writes its metadata, and decodes and encodes most still formats. FFmpeg decodes audio, video and the stills libfiles is not built to decode here - GIF and TIFF among them - and copies a video's or sound file's packets into a new file for Edit's lossless edits. lib64 emulates the Commodore 64 that -plays SID tunes and runs disks, tapes, cartridges and programs. libmug finds faces and makes each a vector +plays SID tunes and runs disks, tapes, cartridges and programs, and lists what each holds. libmug finds faces and makes each a vector for [face search](faces.md). Diffractor's own `platform*` files hold only what is the application's: its side of hardware decoding, the screen recorder, its resource identifiers and its Linux stand-ins. @@ -91,11 +91,11 @@ client-relative. Native child-window bounds are parent-relative, not a desktop o menu at its bounds converted through its frame's `client_to_screen`; a right-click, which arrives as a screen point, reaches the view by the view surface's screen origin. -A bubble shows once the pointer has dwelt for its target's delay (`bubble_delay`; half a second for help), -observed after input and queued UI work in monotonic milliseconds (`pointer_dwell`). The dwell allows four -logical pixels of jitter round where it started, not round the last sample, so slow drift restarts it; -sidebar and scroll-bar entries follow the pointer instead. Idle ticks complete a dwell without another -mouse event, and refreshed content keeps its target's timer. +A bubble shows once the pointer has dwelt for its target's delay (`bubble_delay`; half a second for help), observed +after input and queued UI work in monotonic milliseconds (libdesktop's `ui::pointer_dwell`). The dwell allows four +logical pixels of jitter round where it started, not round the last sample, so slow drift restarts it; sidebar and +scroll-bar entries follow the pointer instead. Idle ticks complete a dwell without another mouse event, and refreshed +content keeps its target's timer. ## View Invalidation @@ -399,7 +399,8 @@ as a user would; the boot and the load run unpaced and silent, then a PAL frame sound device, or by the clock without one. `update_for_present` uploads each newer picture to the texture [ui_c64.cpp](../src/ui_c64.cpp) draws, so the scene is presented again rather than rebuilt; starting, failing and the first picture rebuild it. Keys reach the machine through `view_state::c64_key_down` ahead of -the application's own, and are let go when polling finds them up, since key-ups are not delivered. +the application's own - `c64_key` chooses the C64 key a host key stands for, and lib64's `keyboard.h` where +that key sits in its matrix - and are let go when polling finds them up, since key-ups are not delivered. Subtitles ride the playing session ([av_subtitle.cpp](../src/av_subtitle.cpp)). The read thread decodes the chosen embedded stream's packets as it demuxes them, or a sidecar whole when the session opens, into events @@ -419,14 +420,23 @@ capabilities over libdesktop's web client. Application settings decide whether e `df::network_allowed`, which an agent session clears unless allowed `network`, withholds them all. Feature-use and performance counters are relaxed aggregate diagnostics and never control behavior. +A build that something other than Diffractor updates - the Microsoft Store's (`WINSTORE`), the Flatpak +([packaging](../packaging/flatpak/README.md)) and any Linux build, whose source checkout updates it and for which +the published installer, a Windows program, means nothing - offers no update of its own: each compiles out the +update check, its dialog, commands and setting (`DIFFRACTOR_PACKAGE_UPDATES`, which CMake defines for all of +them). Only the Store build also compiles out crash reports. + ## Crash-Loop Protection Graphics crash guards disable only the risky capability whose durable marker survived a crash ([Rendering](rendering.md#resilience)). `crash_files_db` records the files the faulting thread had open during a scan, thumbnail read or picture hash - or every open file when that thread had none, as in Windows' -recovery callback, which runs on its own - and skips them for the rest of the release line (the major -version) during unattended indexing, thumbnailing and duplicate hashing. Explicit user opens are still -attempted. +recovery callback, which runs on its own - and skips them for the rest of the release line (major and minor: +1.27.4 and 1.27.5 are one line) during unattended indexing, thumbnailing and duplicate hashing. Explicit user +opens are still attempted. A process that crashes on Windows records them itself; one that dies of a signal on +Linux cannot, so the list also keeps what is open where libdesktop's handler reads it +(`platform::add_crash_work`), the report it writes carries it, and the next start records it before any work +starts - for a report of its own release line only, so that the release tag keeps meaning what it does. Two unsettled starts in a row make the next a safe start: it resets presentation settings and turns off GPU rendering and hardware decode before the first window, so that window can explain the recovery. @@ -469,10 +479,10 @@ none and leaves the graphics crash guards alone. Crash report contents and symbo [view_list.h](../src/view_list.h): the document panel adapters and task-table policy over libdesktop's document views, table elements and shared column layout. - [app_mcp.cpp](../src/app_mcp.cpp), [app_mcp_tools.cpp](../src/app_mcp_tools.cpp), - [app_mcp_ui.cpp](../src/app_mcp_ui.cpp), [app_mcp_controls.cpp](../src/app_mcp_controls.cpp) and - [app_mcp_faces.cpp](../src/app_mcp_faces.cpp): the agent session and its tools, which [agents](agents.md) - owns. + [app_mcp_ui.cpp](../src/app_mcp_ui.cpp) and [app_mcp_faces.cpp](../src/app_mcp_faces.cpp): what Diffractor tells + libdesktop's agent host, and its own tools, which [agents](agents.md) owns. - [util_crash_files_db.h](../src/util_crash_files_db.h): media crash-loop protection; + [app_crash_report.cpp](../src/app_crash_report.cpp): the crash post, and the reports a crashed Linux run left; [app_settings.h](../src/app_settings.h) and [app_settings.cpp](../src/app_settings.cpp): when a start is safe, and the settings it resets. - libdesktop's [core.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core.h): diff --git a/docs/linux.md b/docs/linux.md index 96564e1e..4303edfd 100644 --- a/docs/linux.md +++ b/docs/linux.md @@ -1,33 +1,72 @@ # Linux Port This document owns Diffractor's Linux support: what runs, the platform boundary, what is unavailable, -and how it builds. [Implementation](implementation.md) owns architecture and [Design](design.md) user -behavior; libdesktop's +and how it builds and installs. [Implementation](implementation.md) owns architecture and +[Design](design.md) user behavior; libdesktop's [Linux backend](https://github.com/ZacWalk/libdesktop/blob/main/docs/platform.md#the-linux-backend) owns the platform services beneath it. ## Current Support -The application builds with CMake and GCC and runs on libdesktop's Linux window layer: SDL3 windows on -Wayland or X11, drawn by the software renderer, with Pango setting the text. Frames, controls, menus and -dialogs are the ones Windows shows, since libdesktop draws them itself on both platforms, and the picture -keeps the software renderer's contract ([rendering](rendering.md#backends)). Indexing, search, metadata, -image and media decode, face search, collections, locations and file operations share Windows' model and -tests. The embedded suite runs headless in Debug and Release; `_DEBUG` is an MSVC definition, so Linux runs -the Release-only tests (`#ifndef _DEBUG`) in both. An agent session without a display gets SDL's offscreen -windows. - -The Linux build is not distributed: it has no audio output, GPU backend or hardware video decode, and -much of the desktop integration is unavailable. +Linux runs the whole application apart from what [Unavailable On Linux](#unavailable-on-linux) lists. +It builds with CMake and GCC and runs on libdesktop's Linux window layer: SDL3 windows on Wayland or X11, +drawn by the software renderer into one buffer the size of the window and presented once a frame, with +Pango setting the text. The title bar, view and status bar are regions of that one window rather than +windows of their own. Frames, controls, menus, dialogs and the file and folder pickers are the ones +Windows shows, since libdesktop draws them itself on both platforms, and the picture keeps the software +renderer's contract ([rendering](rendering.md#backends)). Indexing, search, metadata, image and media +decode, face search, collections, locations and file operations share Windows' model and tests. + +What the desktop provides, Diffractor uses: + +- **Sound** plays through SDL3's audio: PipeWire, PulseAudio or ALSA. +- **Movies** - Movie Render, and the recording of the window for an agent or a tutorial - are MP4 files + of AV1 (libaom, in real-time mode) and AAC, written by Diffractor's own FFmpeg build + ([av_movie_writer.cpp](../src/av_movie_writer.cpp)), since the system has no encoder to ask. +- **The network** is libcurl's: map tiles, spelling dictionaries, and crash and Support reports. +- **Delete** moves items to the desktop's Trash. Where a drive has none - a network share, a Windows + drive under WSL, a memory file system - Diffractor says so and deletes permanently only once the user + agrees, as on Windows when the Recycle Bin cannot take something. +- **The clipboard** carries files, pictures and text in the forms the file managers use - Nautilus, Dolphin, + Nemo, Caja and Thunar's. Files dropped on the window arrive as on Windows. +- **Import** lists mounted drives and cards, and phones and cameras connected over MTP (libmtp). +- **Links, files and folders** open in the desktop's handler (`xdg-open`); Open in file browser opens + the item's folder, with nothing selected. +- **A second launch** hands its files to the running window, as on Windows. + +The embedded suite runs headless in Debug and Release; `_DEBUG` is an MSVC definition, so Linux runs the +Release-only tests (`#ifndef _DEBUG`) in both. A Linux Debug build defines `_GLIBCXX_ASSERTIONS`, so the +suite checks the standard library's preconditions - an index past the end, a clamp whose bounds have +crossed - as MSVC's Debug library does, and as the Flatpak, built with the SDK's flags, checks them where +a slip ends the process. An agent session's window, and its menus and dialogs, are +never shown on a display, yet are laid out, drawn and hit as a shown window is, and the agent-session +checks in [testing](testing.md) run on Linux as on Windows. Without a display - or under SDL's offscreen +video driver - a session gets SDL's offscreen windows, which have no popups: its menus do not open. ### Desktop icon -On X11 the window carries the embedded `app-icon.bmp`. Wayland finds icons through the application ID -instead: CMake writes a `diffractor.desktop` launcher into the build directory, naming that build's binary -and `src/Res/app.png`. Copy it to `$XDG_DATA_HOME/applications/diffractor.desktop` (normally -`~/.local/share/applications/`), keeping its file name and the checkout's paths; the name matches the -window's application ID, `diffractor`, which libdesktop makes from the registered name in lower case. It is -a launcher for a local build, not a distribution package. +On X11 the window carries the embedded `app-icon.bmp`. Wayland and X11 desktops find the launcher and +icon through the application ID, `com.diffractor.Diffractor`, which [app.cpp](../src/app.cpp) sets with +`core::set_app_id` and which names the `.desktop` file; X11's `WM_CLASS` class carries it too. CMake +writes a `com.diffractor.Diffractor.desktop` launcher into the build directory, naming that build's +binary and `src/Res/app.png` by path. Copy it to +`$XDG_DATA_HOME/applications/com.diffractor.Diffractor.desktop` (normally `~/.local/share/applications/`), +keeping its file name and the checkout's paths. It is a launcher for a local build; a package installs its +own ([Install](#install)). + +### Crashes + +A Linux run that dies of a fatal signal ends with it, as the system's default would, after libdesktop's +handler has written a report into `$XDG_DATA_HOME/diffractor`. The next start adds the files the faulting +thread had open to the skip list before anything scans, and sends the report as Windows sends a crash - +the same setting and exclusions, from the web queue. [crash.md](crash.md#8-linux-reports) owns what a +report holds and how to resolve one. A Release build from source compiles Diffractor's own code without +`-g`, so a report resolves to function names from the binary's symbol table, and to source lines only +against debug information of the same build. The Debian package keeps that information in a `.debug` file +beside it ([Debian package](#debian-package)), and the Flatpak is compiled with it and keeps it in its +`.Debug` extension ([packaging](../packaging/flatpak/README.md)). `debug_action`'s `crash` and `send-crash-report` +are compiled under MSVC's `_DEBUG`, which GCC never defines, so a Linux build has neither: signal the +process instead. ## Platform Boundary @@ -37,21 +76,23 @@ operating-system services, and on its [render.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/render.h) and [ui.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/ui.h) for the window layer. Operating-system headers, handles and system calls stay in libdesktop and Diffractor's own `platform*` -files, apart from the entry points in [app.cpp](../src/app.cpp), `wWinMain` and `main`, which both call +files; the entry point, `main` in [app.cpp](../src/app.cpp), is the same on both and calls `platform::run`. Repository lint enforces what source text shows of this boundary and allows OS headers in any `platform*` file; only `platform_win_av.cpp`, the screen recorder `platform_win_record.cpp` and the Windows platform tests use them. [platform_linux_app.cpp](../src/platform_linux_app.cpp) is built in their -place: it answers that there is no hardware video decode and nothing to record the window with, and -registers no platform tests. +place: it answers that there is no hardware video decode, makes the movie writer, records the window from +its own pixels, and registers the Linux platform tests, +[test_platform_linux.cpp](../src/test_platform_linux.cpp). Portable code expresses the intended operation rather than mirroring a Win32 API shape. A Linux stand-in may support headless tests, but never reports success for a user-visible operation it did not perform. Path identity follows the filesystem: case-insensitive on Windows, case-sensitive on Linux. Case-folded -comparison suits media types, tags and other vocabulary, not path-keyed containers. Property ratios and -search terms are read with `_snscanf_s` (in `model_property.cpp` and `model_search.cpp`), which libdesktop -shims on Linux and which can read damaged text differently there; dates, and the numbers in a photo's -metadata, parse by one rule on both platforms - libdesktop's and libfiles'. +comparison suits media types, tags and other vocabulary, not path-keyed containers; a Linux drive is named +by its mount point, so the drive a folder is on is the one whose path holds it. Property ratios and search +terms are read with `_snscanf_s` (in `model_property.cpp` and `model_search.cpp`), which libdesktop shims +on Linux and which can read damaged text differently there; dates, and the numbers in a photo's metadata, +parse by one rule on both platforms - libdesktop's and libfiles'. ## Unavailable On Linux @@ -60,31 +101,36 @@ that answers false keeps its command out of the interface; libdesktop's [list](https://github.com/ZacWalk/libdesktop/blob/main/docs/platform.md#the-linux-backend) is the complete one. In Diffractor that means no: -- drag and drop, or files and images on the clipboard - text works; -- GPU backend, audio output, or hardware video decode; -- network, so no map tiles beyond the built-in map, update check, crash or Support report, or spelling - dictionary download; -- movie writer, so no Movie Render and no recording of the window for an agent or a tutorial; -- Recycle Bin, so Delete is permanent; -- Import from a phone or camera connected as a device rather than a drive; -- folder pickers, opening a file or link in another program or the file browser, external tools, - printing, the desktop background, disc burning or sharing; -- Windows Shell features such as associations, properties, Explorer thumbnails, device eject and taskbar - progress; -- update, installer, Store or desktop packaging workflows. +- GPU backend or hardware video decode; +- dragging items out to another program - SDL cannot start a drag; +- Print, Desktop background, Properties, Scan, Share or Email, Burn or Eject - each is absent from the + interface; +- opening an item with a program of the user's choosing: Open with lists Diffractor's own tools; +- Windows Shell features such as associations, Explorer thumbnails and taskbar progress; +- update check or installer: a Flatpak is updated by Flatpak and a build from source by its checkout, so + every Linux build compiles them out ([implementation](implementation.md)). ## Build CMake is the only build description. Linux builds the same fetched dependencies, upstream FFmpeg through -its own configure and make, and libfiles, libdesktop, lib64 and libmug at their pins - or sibling -`../libfiles`, `../libdesktop`, `../lib64` and `../libmug` checkouts. The binary stays in the build -directory, with the runtime fixtures, catalogs, dictionaries and location data linked beside it. +its own configure and make - with libfiles' libaom and FFmpeg's AAC encoder for the movie writer - and +libfiles, libdesktop, lib64 and libmug at their pins, or sibling `../libfiles`, `../libdesktop`, +`../lib64` and `../libmug` checkouts. The system supplies the window layer's libraries, libcurl, libjpeg-turbo, +the audio backends' development packages and libmtp. The binary stays in the build directory, with the runtime +fixtures, catalogs, dictionaries and location data linked beside it. + +The executable exports none of its static libraries' symbols. It links libpng, zlib, bzip2 and Brotli, and +the FreeType, libcurl and GLib it loads name the same functions, so GNU ld would export Diffractor's copies +for them to bind to - and libdecor's GTK plugin, which brings GTK's libpng, is refused while `png_free` is +defined twice. The link passes `--exclude-libs,ALL`, and a Linux platform test reads the binary's own +dynamic symbol table to keep it so. ```bash bash ./dd setup # install the packages the build needs; uses sudo bash ./dd build # Debug; --config Release for the other bash ./dd test # the embedded suite, as CI runs it bash ./dd run +bash ./dd deb # a Debian package of the Release build (Install, below) ``` `./dd` runs `dd.ps1` under PowerShell, or `tools/dd.py` without it; it is checked in without an @@ -92,8 +138,8 @@ executable bit, hence `bash`. The build goes to `tmp/linux-build/`, or - for a c where a tree is slow and FetchContent cannot rename the directories it extracts - to `~/.cache/diffractor//linux-build` (`$XDG_CACHE_HOME` where set); `./dd info` names it. A leading `/` starts a path on Linux, so switches take `-` or `--` there. -[linux.yml](../.github/workflows/linux.yml) is authoritative for the compiler and packages, and `./dd setup` -installs the same window-layer list. +[linux.yml](../.github/workflows/linux.yml) is authoritative for the compiler and packages, and +`./dd setup` installs the same list. From Windows, `.\dd.ps1 linux` builds Release in WSL and starts it on WSLg's display (`--config Debug` builds the other; further arguments reach Diffractor). It stops first if a package the build needs is @@ -107,18 +153,74 @@ description can drift from CMake. A fetched dependency's own build system never Diffractor's CMake modules decide how each joins the build, FFmpeg's configure and make on Linux among them. +## Install + +`cmake --install` (Linux only) lays out `lib/diffractor/` - the binary, `languages/`, `dictionaries/` and +`location-*.txt`, which Diffractor reads from the folder of the running binary - `bin/diffractor` (a +relative link to it), `share/applications/com.diffractor.Diffractor.desktop`, +`share/metainfo/com.diffractor.Diffractor.metainfo.xml`, +`share/icons/hicolor/{64,128,256,512}/apps/com.diffractor.Diffractor.png` and +`share/licenses/com.diffractor.Diffractor/`. + +### Debian package + +`./dd deb` - `.\dd.ps1 deb` from Windows, which builds in WSL - builds Release and packages what +`cmake --install --prefix /usr` lays out as `diffractor__.deb` in the repository +root, with the version the application reports. It installs on the release it was built on and later ones: +built on Ubuntu 24.04, the floor CI builds on, it serves Ubuntu 24.04 and later, while Debian names some of +its libraries otherwise. `sudo apt install ./diffractor__amd64.deb` installs it, with what it +depends on, and `sudo apt remove diffractor` removes it. + +- Its dependencies are the libraries dpkg-shlibdeps finds the binary linked against, and those it loads + while it runs, which [tools/dd.py](../tools/dd.py) names: SDL's X11, Wayland, EGL and ALSA backends and + libjpeg-turbo are dependencies, its PulseAudio, PipeWire, libdecor, D-Bus and XTest ones recommendations. +- The packaged binary keeps its symbol table but none of the debug information vendored libraries are built + with: that goes to `diffractor__.debug` beside the package, which shares the + binary's build id and resolves a tester's crash report to source lines. + +### Flatpak + +[packaging/flatpak](../packaging/flatpak) builds `com.diffractor.Diffractor` on +`org.freedesktop.Platform//26.08` from the sibling checkouts, with libmtp as its only module - libusb is the +runtime's; its README has the commands. Its permissions: + +- `--share=ipc`, `--socket=wayland` and `--socket=fallback-x11`: the window; +- `--socket=pulseaudio`: sound; +- `--share=network`: map tiles, spelling dictionaries and crash and Support reports; +- `--filesystem=host`: the user's whole collection, removable drives included, and the host Trash that + Delete uses; +- `--device=all`: phones and cameras over USB (MTP). + +Settings, the log (`diffractor.log`, and the run before as `diffractor.previous.log`), crash reports and the +people database are in `~/.var/app/com.diffractor.Diffractor/data/diffractor/`, and the index and map tiles +in `~/.var/app/com.diffractor.Diffractor/cache/diffractor/`; the instance lock files are in +`$XDG_RUNTIME_DIR/app/com.diffractor.Diffractor/`. Outside a Flatpak the same files are in +`$XDG_DATA_HOME/diffractor` and `$XDG_CACHE_HOME/diffractor`, except that a binary in a folder it can write - +a build directory - keeps its log beside itself. + ## Where this lives - libdesktop's [platform.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/platform.h) and [render.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/render.h): the abstraction required from each platform. -- libdesktop's [Linux backend](https://github.com/ZacWalk/libdesktop/tree/main/src/platform/linux), - [Linux window layer](https://github.com/ZacWalk/libdesktop/blob/main/src/render/linux/window_device.cpp) - and [platform_linux_app.cpp](../src/platform_linux_app.cpp): the Linux implementation. +- libdesktop's [SDL](https://github.com/ZacWalk/libdesktop/tree/main/src/platform/sdl), + [POSIX](https://github.com/ZacWalk/libdesktop/tree/main/src/platform/posix) and + [Linux](https://github.com/ZacWalk/libdesktop/tree/main/src/platform/linux) backends, its + [SDL window layer](https://github.com/ZacWalk/libdesktop/blob/main/src/render/sdl/window_device.cpp) + and [Pango text](https://github.com/ZacWalk/libdesktop/blob/main/src/render/pango/text.cpp), and + [platform_linux_app.cpp](../src/platform_linux_app.cpp): the Linux implementation. +- [av_movie_writer.cpp](../src/av_movie_writer.cpp): movies written with FFmpeg's own encoders. +- [app_crash_report.cpp](../src/app_crash_report.cpp) and libdesktop's + [posix/crash.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/posix/crash.cpp) and + [linux/crash.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/linux/crash.cpp): the Linux + crash report. +- [test_platform_linux.cpp](../src/test_platform_linux.cpp): the Linux platform tests. - libdesktop's [dialect.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/dialect.h): cross-platform compatibility helpers, `_snscanf_s` among them. - [CMakeLists.txt](../CMakeLists.txt) and the `cmake/` modules: the build description, the Linux sources, - the runtime links and the `.desktop` launcher. -- [dd](../dd), [dd.ps1](../dd.ps1) and [tools/dd.py](../tools/dd.py): the drivers - `setup`, `linux` and + the runtime links, the `.desktop` launcher and the install rules + ([DiffractorLinuxInstall.cmake](../cmake/DiffractorLinuxInstall.cmake)). +- [packaging/](../packaging): the launcher template, metadata, icons and the Flatpak manifest. +- [dd](../dd), [dd.ps1](../dd.ps1) and [tools/dd.py](../tools/dd.py): the drivers - `setup`, `linux`, `deb` and the build directory. - [linux.yml](../.github/workflows/linux.yml): the Debug and Release builds and suites CI runs. diff --git a/docs/metadata.md b/docs/metadata.md index 23daba87..acfcaeb7 100644 --- a/docs/metadata.md +++ b/docs/metadata.md @@ -128,6 +128,8 @@ format's fields and where they go. A tag edit on a packet without `dc:subject` s item shows, legacy keywords included. A conversion writes the source's packet - or, for a file libfiles cannot update, such as a camera raw without a sidecar, the packet its scan finds - and fills what the packet lacks from what the item shows, since the new format may have no place for the source's IPTC. +A packet libfiles rejects whole, or one in which it cannot read or make what the edit touches, is never +written ([File I/O](file-io.md#failure-and-recovery)). ## Audio And Video Metadata @@ -251,7 +253,7 @@ shape instead: anything shown at least twice as wide as it is tall, declared or with `list_iptc`. - [model_dates.h](../src/model_dates.h): date sources, their ranking (`date_sources`), and the date pack. - libdesktop's [win/platform.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/platform.cpp) - and [linux/platform.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/linux/platform.cpp): + and [posix/platform.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/posix/platform.cpp): date-sensitive conversion between UTC and local wall time. - [files.cpp](../src/files.cpp)'s `scan_media_file` and `file_scan_result::parse_media_properties`: an audio or video file as libfiles' media scan reads it, in Diffractor's own terms; and diff --git a/docs/mission.md b/docs/mission.md new file mode 100644 index 00000000..fd423f20 --- /dev/null +++ b/docs/mission.md @@ -0,0 +1,412 @@ +# Diffractor's Mission + +This document owns why Diffractor exists: whom it serves, the experience it promises them, the principles that +decide what it will and will not become, and the direction that follows from them. [Design](design.md) owns how it +behaves, the subject documents in [AGENTS.md](../AGENTS.md#information-ownership) own their details, and GitHub +issues own the work. + +## 1. The mission + +**Diffractor is the fastest way to organize photos and videos on your PC.** + +Organizing is the means. The end is the moment someone sees a face again, hears a voice in an old video, or turns +to the person beside them and asks "do you remember this?". Diffractor exists so people can enjoy a lifetime of +their own photos, videos and music - reliving, showing, watching, listening and rediscovering - on a big screen, at +once, from storage they own. Everything else it does serves that moment: organizing finds it and gives it its +context, the files keep it for decades, speed keeps it from waiting, privacy keeps it theirs, and an AI agent can +take on the chores so that more of the time goes on looking. + +The site, the Store listing and release notes say it in this order, speed first: + +- The fastest way to organize photos and videos on your PC. +- Everything opens and plays at once. +- Your people, places and years on the big screen, a key away. +- Your photos stay in your folders, in files any program can read. +- Private by design: no account, no cloud, and AI that runs on your PC. +- Works with your AI agent, and nothing changes until you say so. + +## 2. What a collection is for + +People keep photos, videos and music to live with them again. What research has found about that is what +Diffractor has to do: + +| Finding | What it asks of Diffractor | +|---|---| +| Recalling good memories, with or without photos to hand, raised how often people felt happy over the following week ([Bryant et al. 2005](https://link.springer.com/article/10.1007/s10902-005-3889-4)). Nostalgia builds connection to others, continuity with one's past, and meaning ([Van Tilburg et al. 2019](https://www.southampton.ac.uk/~crsi/Van%20Tilburg,%20Sedikides,%20Wildschut,%20&%20Vingerhoets,%202019,%20EJSP.pdf)) | The time spent reliving is the value, so it comes first | +| Families named sharing photos in person the most common and enjoyable thing they do with them, and the conversation mattered more than the pictures ([Frohlich et al. 2002](https://www.academia.edu/1455833/Requirements_for_photoware)) | Made to be shown: a big screen, paced by whoever tells the story, ready for its tangents | +| People reminisce most about people - more than about things, places or experiences ([Pensieve, CHI 2010](https://www.cs.cornell.edu/~danco/research/papers/peesapati-pensieve-chi2010.pdf)) | Who is in a picture is the first way in, and a person over the years the first story | +| 85% of those sent reminders to reminisce kept them coming, and said their mood was better for it (Pensieve); but memories pushed unasked can wound ([Meyer 2014](https://meyerweb.com/eric/thoughts/2014/12/24/inadvertent-algorithmic-cruelty/)), and 47% avoid photos from some period of their lives ([Popsa 2026](https://popsa.com/perspectives/memory-economy-2026-photo-trends-report/)) | Rediscovery offered, never pushed, with the people and periods someone would rather not meet kept out of it | +| 70% of phone photos are never looked at again (Popsa 2026), and parents could not find 39% of the photos of important family events they looked for ([Whittaker et al. 2010](https://link.springer.com/article/10.1007/s00779-009-0218-7)) | Organizing is how pictures come back to life: context to find them by, ways in to start from, clutter out of the way | +| Talking memories through with children helps them build a coherent sense of themselves and of others ([Fivush 2007](https://link.springer.com/article/10.1007/s10615-006-0065-1)); reminiscence brings people with dementia small but real benefits ([Cochrane 2018](https://www.cochrane.org/evidence/CD001120_reminiscence-therapy-dementia)) | Usable by every generation: big pictures, simple keys, captions that can be read from the sofa | + +Popsa makes photo books, and its figures come from its own survey of 8,000 people; the others are peer-reviewed. + +## 3. What spoils it + +- **Waiting.** A spinner where a picture should be. The wish to look lasts seconds. +- **Clutter.** The good pictures buried under ten frames of the same burst, three copies of each, screenshots, + receipts and memes. +- **Lost context.** No date on a scan, the wrong date on a messaging app's copy, no place, nobody named - so + nothing can be found, and no story told. +- **Unfaithful pictures.** Colours clipped, HDR flattened, a video stretched or turned, a cloud's compressed copy in + place of the original. +- **Scattered media.** Photos in one app, home video in another, music in a third, spread across phones, drives, + clouds and a NAS. +- **Things in the way.** Toolbars, prompts, badges and upsells between the person and the picture. +- **Feeds that choose.** Somebody else's algorithm deciding what to show, and when - including what hurts. +- **Fear.** Of losing everything, of an edit that cannot be undone, of a company studying the family's faces. +- **Software that goes.** Picasa was retired in 2016, and Windows Photos dropped face grouping and tag search + ([Microsoft](https://support.microsoft.com/en-us/windows/apps/photos/changes-in-the-new-photos-app)); a catalog or + a cloud can take years of work with it. + +## 4. The moments that matter + +1. **A quiet evening alone.** A name or a year typed, then wandering: from a picture to the rest of its day, to the + trip, to the same people ten years on. +2. **The family on the sofa.** The TV shows only the picture while the PC steers; the teller jumps when the story + jumps, and a caption appears when someone asks who that was. +3. **A birthday, a wedding, a funeral.** A life's pictures of one person gathered, put in order and played as a + slideshow or a movie with music - in an evening, not a week. +4. **Rediscovery.** This day in other years, a trip from long ago, a shuffle through the favorites - when the person + asks for it. +5. **In the background.** A second screen or an idle TV showing favorite pictures, quietly. +6. **Films, series and music.** Picking up where it stopped, the next episode, subtitles in one's own language, a + SID tune's three voices. +7. **Making something.** A photo brought to its best, a video trimmed to its moment, a short movie for the family. +8. **Handing it down.** Names and stories written down while someone still remembers them, in files that will + outlast the software. + +## 5. A good experience + +Ten principles. Each holds wherever the collection is looked at - Items, Fullscreen, Explore, Faces, a slideshow +or a movie. + +| Principle | Means | Diffractor today | Still missing | +|---|---|---|---| +| **Instant** | Opening, the next picture, zooming and playing never wait | Native decoding and drawing, thumbnails kept in the index, video previewed under the pointer | - | +| **Faithful** | Shown as it was captured | Colour profiles, orientation and aspect honoured; RAW, HEIC, JPEG XL, panoramas and 360° photos; video with its subtitles | HDR and wide-gamut colour are shown in SDR and sRGB even on screens that can show more ([rendering](rendering.md#hdr-stills)); a motion photo's moment is not played | +| **Immersive** | The window steps back | Fullscreen, whose panels and pointer leave a picture or a playing video alone after a few idle seconds; no advertising or notifications | - | +| **Connected** | Every picture leads on to its day, its trip, its people and its place | [Related items](design.md#related-items), faces, places from GPS, [Explore](design.md#explore)'s globe and timeline | One place across the years | +| **Uncluttered** | The good pictures are not buried | Ratings, labels, filters, graded duplicates | Copies and bursts collapsing to one while looking; screenshots and documents stepping aside | +| **Many ways in** | Nobody faces 100,000 thumbnails with nowhere to start | Search, the calendar, Explore, Faces, `@inprogress` for what was being watched | This day in other years | +| **Together** | Made to be shown | Fullscreen, Slideshow, shuffle, media keys | A TV or second screen showing only the picture while the PC steers; music under a slideshow | +| **Gentle** | Nothing pushed, and what hurts kept away on request | Nothing is pushed | People, periods and folders kept out of rediscovery and the background | +| **For everyone** | Grandparents and children look without being taught | Large type, the keyboard throughout, media keys, fourteen languages | A touch-friendly mode ([#38](https://github.com/ZacWalk/diffractor/issues/38)) | +| **Lasting** | What people add outlives the software | Names, places, dates and captions written into the files | The story in the teller's own voice; a copy to hand down | + +## 6. Organizing serves the experience + +Every chore pays out in a moment of looking: + +| Chore | What it gives | +|---|---| +| Dates set right | The timeline, this day in other years, a story in the right order | +| Places | The globe, [trips](locations.md#trips-and-a-years-places), one place across the years | +| Names | A person through the years - what people reminisce about most | +| Ratings and favorites | A best-of worth watching, and what the background shows | +| Copies and bursts set aside | A slideshow without ten of the same | +| Captions | The story on screen tonight, and in thirty years | +| Backups and sync | The calm of knowing it is safe | + +People look at their collection all the time and organize it in bursts: after a trip, at the year's end, before a +wedding, birthday or funeral, when storage fills, on a new PC, or when a service changes its terms. Diffractor has +to be a pleasure every day and at its best in those bursts, and every chore an agent takes is time given back to +looking. + +## 7. Agents: stagehands, not the audience + +An agent can find, sort, fix and draft. It cannot remember, enjoy or tell the story; those are the person's, and +they are why the collection exists. So an agent works for the experience in two ways: + +- **Before, preparing an occasion.** "Get Christmas 2019 ready to show Grandma" becomes the photos and videos found, + copies and bursts set aside, missing dates, places and names proposed, captions drafted, and a running order laid + out as a slideshow or a `.dfv` movie ([movie](movie.md#6-project-files)) - all checked by the person before the + evening. +- **During, as a remote that understands.** "The beach from that trip", "the video where Ava first walks", "back to + the one with the dog" - spoken or typed, and shown in the person's window, on the big screen. + +| | Is good at | +|---|---| +| A person | Looking, remembering and enjoying; taste - which shot; meaning - who and what mattered; consent - what to show, change or delete; memories the files do not hold | +| An agent | Labour at scale, consistency, cross-referencing, first drafts, and reports of what is missing | +| Diffractor | Seeing - every format, faces, places, copies; speed; and changing files safely, with staging, sidecars, rollback and a result for every item | + +The contract between them: + +1. The agent sees through Diffractor: the index, the search language and the evidence grades a person sees. +2. Reading is free; changing needs a grant ([tiers](agents.md#2-what-a-session-may-do)). +3. Large changes are reviewed: the agent prepares, the person checks on the big screen, and the run reports each + item. +4. Nothing is deleted, chosen as the keeper, shown unasked or published on the person's behalf. +5. What an agent did stays in sight: [Recent changes](design.md#recent-changes), each run's results, the log. +6. The person chooses the agent, cloud or local, and the tiers say what it may see. + +What the mixture still lacks: + +- **One window for both.** An agent session refuses its window while the person's own Diffractor has the same + profile open, and its own window is out of sight by default, so what an agent finds reaches the person as a list + of paths rather than as pictures on their screen. +- **Delete is a write like any other.** A session granted `write` can run Delete and answer its confirmation + ([app_mcp_ui.cpp](../src/app_mcp_ui.cpp)'s `rule_of`), so deletion is not yet reserved to the person. +- **Proposals as files.** A `.dfv` movie is a plain-text plan an agent writes and a person opens, checks and + renders. Tags, ratings, captions, dates, places, names, renames and moves deserve the same: a plan file that opens + in the matching review and needs no `write` grant. +- **Eyes for the agent.** No tool returns an item's picture, so an agent that would caption or judge one must + screenshot the window. +- **A small tool set.** About thirty tools, many of them driving the window, crowd a small local model's context; + task-level tools and ready-made recipes would let one do real work. + +## 8. Who it is for + +| Person | Enjoys | Needs | Comes looking because | +|---|---|---|---| +| Family storyteller | Showing the family its own story: the children growing up, the people who have gone | Names, dates and places right; a big screen; a copy to hand down | Picasa was retired, Windows Photos dropped faces and tags, and cloud storage keeps costing | +| Enthusiast | Their best work as it was shot | Fidelity, fast culling and comparison, metadata other tools read | Subscriptions, catalogs and slow browsing | +| Household with a NAS | Evenings on the TV with years of family photos and video | A viewer and player over the NAS's folders, and sync it can review | Phone and web galleries are poor on a TV and at work in bulk | +| Cloud leaver | Their memories back, whole | Dates, places, captions and people back in the files, and no duplicates | A price, a locked account, AI terms, or principle | +| Collector | Films, series, music, Commodore 64 tunes and games | Everything playing in one place | A drawer of single-purpose players | +| Agent user | More time looking, less time sorting | Chores delegated, results reviewed, answers shown on their screen | Cloud agents read the whole library, and there is no local one to point an agent at | + +Diffractor is not for a phone-only library happily kept in a cloud gallery, a studio needing a shared multi-user +catalog, or RAW development, which it hands to the editor its user prefers. + +## 9. Why now + +The big photo services decide more and more of what people see, and now run agents over the libraries they hold. +Since September 2026 Google's Gemini Spark curates, edits, shares and runs scheduled automations over a Google +Photos library for paying AI subscribers +([TechCrunch](https://techcrunch.com/2026/09/04/googles-gemini-spark-can-now-manage-your-google-photos-library/)), +beside the Memories feed that already chooses what to show. Microsoft Photos searches local pictures by +description only on Copilot+ PCs +([release notes](https://learn.microsoft.com/en-us/windows-insider/release-notes/apps/photos)). Lightroom's catalog +comes with a subscription, $19.99 a month for new subscribers since Adobe closed its cheaper plan in January 2025 +([comparison](https://www.photographytalk.com/lightroom-alternatives-2026/)), and Google Takeout returns photos with +their dates, places and captions split off into JSON files beside them +([explainer](https://www.foliosort.app/google-photos/takeout-json-files)). + +Meanwhile more people keep their own. In a 2025 survey 60% had run out of cloud space in the previous six months +and 35% found it ever more expensive, while 45% used an external drive and 19% a NAS +([Western Digital](https://www.westerndigital.com/en-au/company/newsroom/press-releases/2025/2025-03-25-western-digital-world-backup-day)). +Immich, a self-hosted Google Photos, has passed 100,000 GitHub stars since its stable release in October 2025 +([review](https://www.gappsy.com/tools/immich/)). Models that call tools run at home: LM Studio hosts MCP servers +and a 20-billion-parameter model fits in 16 GB ([guide](https://localaimaster.com/blog/lm-studio-mcp-setup)), and +llama.cpp's own interface hosts them too ([setup](https://vdf.ai/blog/mcp-ollama-lm-studio-setup/)). + +Four shifts give Diffractor its place: + +1. **What is left is the looking.** An agent can find, sort and fix; it cannot remember a face, laugh at a video or + choose the picture for a funeral. As agents take the chores, what remains is what people kept the collection + for, and it happens on a screen in front of them. +2. **Agents favor open collections.** An agent works best on plain folders, standard metadata and plain-text + plans, which is how Diffractor has always kept a collection. A catalog only its vendor's agent can work is the + new lock-in; files any agent can read are the way out. +3. **Review becomes the bottleneck.** An agent can propose five thousand changes in a minute. What is scarce is a + person's attention to check them, and checking pictures is big-screen work - thumbnails at speed, side by side, + in context. Diffractor's analyze, review and run grammar ([guided operations](design.md#guided-operations)) is + that review already. +4. **AI no longer needs the cloud.** Face search runs on the CPU inside Diffractor today, and a local model can + drive Diffractor. A collection can have AI help without leaving the house. + +The cloud services offer a feed to look at the library they hold and an agent to run it. **Diffractor is where you +enjoy the library you hold, with the agent you choose keeping it in order.** + +## 10. The promise + +Five commitments, the first above the rest. Every feature serves at least one and breaks none. + +### 10.1 The experience comes first + +A collection is kept to be looked at, played and shown, and every view is judged by the principles of +[§5](#5-a-good-experience). **Never:** a view that waits on an agent, a window given over to a chat, or a feed that +chooses what the person sees. + +### 10.2 Your collection, where it already is + +A [collection](collections.md) is a short declaration of folders, not an accumulation: the file system stays the +organizing tool, nothing is imported into a catalog, there is no library file, and a detached drive or NAS stays +known by its label. **Never:** a proprietary library, an "add to library" step, or copies of the user's files in +Diffractor's own storage. + +### 10.3 Your files and your privacy + +The tags, ratings, captions, places, dates and names a user gives are written into the files or their sidecars, +in XMP, EXIF, IPTC and ID3 ([metadata](metadata.md)); the index is a rebuildable cache, and the one store of +Diffractor's own, the face book, exports to a file. Diffractor reads the tags and face names Lightroom, digiKam, +Picasa and Windows wrote into the files, so arriving from them costs nothing, and leaving costs nothing either. +Nothing leaves the PC unless the user turns it on: place names come from a gazetteer Diffractor carries +([locations](locations.md#place-data)), face search uses no network ([faces](faces.md#11-privacy-and-recovery)), +and each network use - updates, reports, dictionaries, map tiles - is disclosed and switched separately +([implementation](implementation.md#persistence-and-network)). **Never:** an account, a required cloud, +diagnostics carrying an identity or file information, or a description of the user's media that only Diffractor +can read. + +The same truth is told about agents: an agent sees what its tiers allow, a cloud model's provider sees what the +agent sees, and a local model keeps everything on the PC. + +### 10.4 Fast, lean and native + +Diffractor starts and responds quickly at any collection size, is one program carrying everything it needs, and +runs on the PC people already have, its installer edition reaching back to Windows 7 and 32-bit PCs. Speed is a +product requirement, not a feature ([design drivers](design.md#primary-design-drivers)). **Never:** a feature that +slows starting, opening, playing, browsing or searching, or a runtime, service or GPU the user must install. + +### 10.5 Agents decided by people + +The MCP server is built in ([agents](agents.md)). An agent uses the search, commands and reviews a person uses; +reading is the default, and changing needs a grant in the agent's configuration, which is the user's. An agent's +answer is often a view rather than a change, shown where the person is looking. Plans are reviewed before they run, +and deleting - and so choosing which copy to keep - is the person's alone. **Never:** autonomous deletion, keeper +choice or bulk resolution of duplicates ([collections](collections.md#74-what-redundancy-reporting-will-not-do)). + +## 11. C++ as an advantage + +Native code is how the experience is kept, and AI makes it matter more, not less: + +1. **Latency is feeling.** A picture that opens at once, a video that starts at once and thumbnails that keep up + with the scroll are most of what makes looking a pleasure. The same speed keeps review honest: slow review + becomes rubber-stamping. +2. **Fidelity needs the whole pipeline.** Diffractor owns its decoders (libfiles, and FFmpeg built from source), + its colour mapping and its renderer (libdesktop's Direct3D 11 and software backends), so showing HDR and wide + gamut on screens that can is its own work to do, not a wait on a platform framework. +3. **Small enough for the PC by the TV.** One executable under 70 MB - 53 MB for 32-bit - carries FFmpeg and the + photo decoders, SQLite, the face networks and a Commodore 64, with its place names and translations as text + files beside it. There is no runtime, service, container or database server, so an old laptop or a small PC + beside the TV runs it, which matters to the many left behind by Windows 10's end. +4. **AI without a runtime.** [libmug](https://github.com/ZacWalk/libmug) runs face detection and recognition on + the CPU in its own SIMD kernels, with weights pinned and quantized at build time: no Python, no ONNX Runtime, no + GPU or NPU. The same route can bring search by what a picture shows to every PC, not only Copilot+ PCs. +5. **The agent is the app.** The MCP server is the program itself, so an agent passes through the same targets, + availability rules and previews as the window, and its answers come straight from the loaded index - cheap + enough for a small local model to call often. +6. **Headless, deterministic and owned.** The software renderer draws, captures and records a window nobody sees, + so agents, tests and tutorial videos run unattended. libdesktop, libfiles, lib64 and libmug are Diffractor's + own, so no platform framework's churn can take features away, and Linux is a port rather than a rewrite. The + line has run since ImageWalker in 2000. + +The price is memory safety. Media from anywhere is hostile input, and agents will bring more of it. A warning-free +build, static analysis, crash-loop protection and the test suite are the floor; fuzzing the decoders and metadata +readers, and sanitizer builds, are the next step. Coding agents have narrowed C++'s old cost of development, and +the routing documents, the headless gate and the [sweep](testing.md#the-sweep) are what let them work here safely. + +## 12. Keeping faith with existing users + +The people already using Diffractor chose it for speed, for files that stay theirs, and for asking nothing of +them. Growth must not cost them that: + +1. **Free stays free.** No account, advertising or subscription, and nothing free today goes behind a payment. +2. **Nothing new is on uninvited.** AI features are opt-in, local, bounded and pausable, as face search is, and + named by what they do rather than as AI. Agent support stays invisible until an agent is connected. +3. **Speed is a release gate.** No release makes starting, opening, playing, browsing or searching slower on the + same collection. +4. **Habits stay.** Keys, defaults and workflows stay; a change of behavior arrives as an option whose default is + today's, as the plan for [#269](https://github.com/ZacWalk/diffractor/issues/269) does. +5. **Both editions, and old PCs, stay welcome.** The Store and installer editions both continue; the installer + keeps 32-bit and Windows 7 for as long as the toolchain allows, and the end is announced, not discovered. +6. **Few new words.** Every visible string costs thirteen volunteer translators; agent-facing text is English and + costs them nothing. +7. **Safety and viewing before novelty.** Data-safety bugs, and bugs in how pictures and video show, close before + new surface ships. +8. **The delights stay.** SID tunes, tracker modules and the Commodore 64 are part of the craft people come for. + +## 13. What Diffractor will not become + +- A cloud, an account or a subscription. +- A feed: it shows what the person asks to see, and never decides that for them. +- A phone app or phone backup service: it imports from phones, and works alongside Immich, Syncthing or the phone's + own backup. +- A RAW developer or layered editor: it opens files in darktable, Affinity, Lightroom or whatever the user prefers. +- A generator: edits correct a picture and never invent what was not there. +- An autonomous organizer: no unattended deletion, keeper choice or bulk resolution. +- A multi-user catalog for a team. +- A chatbot, or a back end for agents: agents connect from outside, and the window stays the person's. + +## 14. Direction + +Every release keeps looking instant and faithful, and fixes how pictures and video show before it adds surface. +Beyond that, in order, each step keeping every promise above. A step becomes GitHub issues when it is taken up and +leaves this list once it ships; this section states intent, not status. + +### 14.1 First: the experience + +1. **The big screen.** A TV or second monitor shows only the picture, the slideshow or the movie while the PC + steers, and an idle one can show favorites in the background + ([#94](https://github.com/ZacWalk/diffractor/issues/94)). +2. **Faithful on modern screens.** HDR photos and video, and wide-gamut colour, shown as such on displays that can + show them, as edits already keep them; a motion photo's moment played from its still. +3. **Play anything.** Any search, trip, person, year or day played as a slideshow, with music under it and its pace + chosen; and playback that keeps up - a few seconds back or on + ([#31](https://github.com/ZacWalk/diffractor/issues/31)), and playing on while browsing + ([#73](https://github.com/ZacWalk/diffractor/issues/73)). +4. **Out of the way.** Copies and bursts collapse to one while looking, and screenshots and documents step aside - + a way of viewing, with nothing deleted. +5. **Rediscovery, gently.** This day in other years, a trip from long ago, a person then and now, one place across + the years - opened by the person, with the people, periods and folders they choose kept out of it. +6. **The listing people asked for.** Names under thumbnails + ([#223](https://github.com/ZacWalk/diffractor/issues/223)), a compact view + ([#112](https://github.com/ZacWalk/diffractor/issues/112)), custom shortcuts + ([#237](https://github.com/ZacWalk/diffractor/issues/237)), moving on after a rating + ([#136](https://github.com/ZacWalk/diffractor/issues/136)) and a touch-friendly mode + ([#38](https://github.com/ZacWalk/diffractor/issues/38)). + +### 14.2 Next: agents as stagehands + +7. **Attach to the running window.** An agent session joins the person's open Diffractor - one index, one window, + an indicator while it works and a way to stop it - so that what it finds is shown where the person is looking, + and a spoken or typed request can steer the big screen. +8. **Deletion stays the person's.** An agent marks what it would remove, or puts it in a plan; only the person + deletes, from the window. +9. **Plans as files.** A plain-text change plan, written by any agent or script, opens in the matching review, + where the person runs it or not. It needs no `write` grant and leaves a record. +10. **Pictures for agents.** A `capture` tool returns an item's picture, a video's frames, or a contact sheet of + many items, at a size a model can afford. +11. **A lean tool set and recipes.** Task-level tools by default, the window-driving and developer's tools on + request, and recipes offered as MCP prompts and tested end to end with a local model: get an occasion ready, + a person through the years, the year in three minutes, show me a person, place or time, organize an import, + place what is unplaced, check the backups. +12. **Leave the cloud cleanly.** Import reads Google Takeout's JSON sidecars and writes their dates, places, + captions, favorites and people into the files, keeps a Live Photo's still and motion together, and skips what + presence says is already held. + +### 14.3 Then: see more + +13. **Search by what a picture shows, on any PC:** compact image and text embeddings run as libmug runs faces - + on the CPU, with permissively licensed weights pinned at build time - built in the background as face search + is, combined with who, where and when, and "more like this" from any item. +14. **Evidence of clutter and quality** - screenshots, documents, receipts, blur, darkness, closed eyes - for + viewing to set aside and reviews to group, never as actions. +15. **Bursts as a review:** each burst on one screen, the person picking its keepers, an agent free to rank them + first. + +### 14.4 Later: lasting and reach + +16. **Stories in their own voice:** a spoken story recorded beside a picture, in a file of its own, and played as + the picture shows. +17. **A copy to hand down:** a chosen set as plain folders, captions and a page to browse them by, readable without + Diffractor. +18. **A portable edition** ([#13](https://github.com/ZacWalk/diffractor/issues/13)), its settings and index beside + the program, for a collection carried on a drive. +19. **Hardening:** fuzzing and sanitizer builds for the decoders and metadata readers. +20. **A Linux edition** for people leaving Windows 10 behind, once it costs Windows nothing. + +## 15. How we will know + +- **Looking stays instant:** the time to the first picture, to the next, to playback, and scrolling a large + collection - measured each release with starting and indexing - are never worse. +- **Pictures stay faithful:** colour, orientation, aspect and HDR fixtures pass on every renderer. +- **People look more than they fix:** where people allow aggregate feature counts, Fullscreen, Slideshow, Explore + and playback grow against the tasks. +- **Reviews talk about memories:** what people write about Diffractor names their family, trips and films, not + only its tools. +- **Trust holds:** no data-loss issue is open at release, and crash reports fall. +- **The mixture works:** the recipes complete end to end with a local model as well as a cloud one. +- **Existing users stay:** installer-edition updates keep pace, and long-time reporters keep reporting. + +## Where this lives + +| Promise | Owned by | Source | +|---|---|---| +| The experience | [design](design.md#selection-and-viewing), [zoom](zoom.md), [rendering](rendering.md), [locations](locations.md), [faces](faces.md) | [view_media.h](../src/view_media.h), [view_items.cpp](../src/view_items.cpp), [view_explore.cpp](../src/view_explore.cpp), [model_related.h](../src/model_related.h) | +| The collection | [collections](collections.md) | [app_settings.cpp](../src/app_settings.cpp), [model_index.cpp](../src/model_index.cpp) | +| Files and privacy | [metadata](metadata.md), [file I/O](file-io.md), [faces](faces.md#11-privacy-and-recovery), [implementation](implementation.md#persistence-and-network) | [files.cpp](../src/files.cpp), [metadata.cpp](../src/metadata.cpp) | +| Fast, lean and native | [implementation](implementation.md), [rendering](rendering.md), [third-party](third-party.md) | [model.h](../src/model.h)'s `async_strategy`, [model_faces.cpp](../src/model_faces.cpp) | +| Agents | [agents](agents.md), [movie](movie.md#6-project-files) | [app_mcp.cpp](../src/app_mcp.cpp), [app_mcp_tools.cpp](../src/app_mcp_tools.cpp), [app_mcp_ui.cpp](../src/app_mcp_ui.cpp)'s `rule_of` | diff --git a/docs/movie.md b/docs/movie.md index e968bd51..8b9970ee 100644 --- a/docs/movie.md +++ b/docs/movie.md @@ -327,9 +327,31 @@ Output is derived without asking for codec settings: Windows writes H.264 video and AAC audio in MP4 through Media Foundation. The codec is the system's to supply rather than Diffractor's to ship: H.264 and AAC carry patent licences that a vendored encoder would oblige Diffractor to hold, and the outbound licence in [third-party](third-party.md) -is chosen on the assumption it does not. This is why `platform::can_write_movies` exists at all, why -the FFmpeg build is configured without encoders on both platforms, and why Render is absent rather -than dimmed where the platform has no writer. +is chosen on the assumption it does not. This is why `df::can_write_movies` exists at all, why +Windows' FFmpeg is configured without encoders, and why Render is absent rather than dimmed where there +is no writer. + +Linux has no system encoder to ask, so its own FFmpeg writes the movie: AV1 from libaom - the encoder libfiles +builds for AVIF, whose licence and royalty-free patent grant [third-party](third-party.md#licensing) states - and +AAC from FFmpeg's own encoder, in an MP4. Render is offered because that FFmpeg has both, which the probe finds by +asking it. Both platforms are written through one seam, `df::create_movie_writer`, so nothing above it knows which +writer it has, and each keeps libdesktop's `platform::movie_writer` contract: a movie is at its path only once `close` +has finished it, a writer abandoned or let go unfinished leaves none, a failure's reason is in `last_error`, and a +frame is shown from its time until the next. + +Linux's writer makes 8-bit 4:2:0 AV1 from the frame's RGB, converted as BT.709 limited range and tagged so, at the +bitrate the output asks for - Movie's own 0.10 bits a pixel a frame where a request asks for none - with a key frame +at least every two seconds. libaom runs in its real-time usage, one pass and no lookahead, so a frame is out as it +goes in and a render is the size its panel said. Its speed follows the pixels a second, 7 up to 720p30, 8 up to +1080p30, 9 up to 1080 x 1920 at 60 and 10 above, across at most 16 threads, with row-based threading and tile columns +as the threads and the width allow. The conversion is on the caller's thread and the encoding on a worker of the +writer's own, which the caller may run up to four pictures ahead of: the next frame is composed while libaom encodes +the last, a render's memory is the same whichever of the two is slower, and a failure the worker finds is the answer +of the next write, or of `close`. Sound is AAC-LC at the audio bitrate asked, from the 16-bit samples, in the +frames of 1024 the encoder takes. The MP4 has its index first, so it plays while it is still being uploaded. The times +a caller gives are kept: a frame later than the next shows what came before it until then, and a gap in the sound is +silence, as the Windows sink writes them; a time that is not after the last is refused. The screen recorder +([agents](agents.md#7-tutorial-videos)) writes through the same seam. The render worker receives an immutable project snapshot, precomputes item timing once, walks frames in order and uses CPU surfaces @@ -393,9 +415,9 @@ only as screens on near black and a caption on each clip, in one style with no a music or narration track under several clips - an audio file is a clip of its own, with its picture, and a clip's sound file plays only while that clip shows - no sound file set from the panel, no speed control, no per-clip volume, no pan-and-zoom, no color grading, no stabilization yet, no setting but YouTube -Short, no redo, no output larger than HD, nothing faster than 30 fps but a Short, which goes to 60, and no HEVC or -AV1 output. Rendering is -unavailable where the platform reports no movie writer. +Short, no redo, no output larger than HD, nothing faster than 30 fps but a Short, which goes to 60, and no choice +of codec: H.264 on Windows and AV1 on Linux, in an MP4 either way. Rendering is +unavailable where the system has no movie writer. ## 9. Checking and rendering without the window @@ -448,9 +470,14 @@ Frame and audio extraction are in [av_format.h](../src/av_format.h), [av_format.cpp](../src/av_format.cpp) and [av_player.h](../src/av_player.h). The audio endpoint the preview mixes into and the platform writer contract are in libdesktop's [platform/media.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/platform/media.h), with the Windows implementations in libdesktop's [sound.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/sound.cpp) and -[movie_writer.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/movie_writer.cpp) and the unavailable-platform answers in -libdesktop's [Linux backend](https://github.com/ZacWalk/libdesktop/tree/main/src/platform/linux). +[movie_writer.cpp](https://github.com/ZacWalk/libdesktop/blob/main/src/platform/win/movie_writer.cpp). The seam every +render and recording is written through, and the FFmpeg writer behind it on Linux, are in +[av_movie_writer.h](../src/av_movie_writer.h) and [av_movie_writer.cpp](../src/av_movie_writer.cpp), with each +platform's answer in [platform_win_av.cpp](../src/platform_win_av.cpp) and +[platform_linux_app.cpp](../src/platform_linux_app.cpp); the encoders are configured in +[FFmpeg.cmake](../cmake/vendored/FFmpeg.cmake). Tests are in [test_movie.cpp](../src/test_movie.cpp), [test_view.cpp](../src/test_view.cpp), -[test_av.cpp](../src/test_av.cpp), [test_platform_win.cpp](../src/test_platform_win.cpp) and, for +[test_av.cpp](../src/test_av.cpp), [test_platform_win.cpp](../src/test_platform_win.cpp) for the system's writer, +[test_platform_linux.cpp](../src/test_platform_linux.cpp) for FFmpeg's and, for checking and rendering without the window and its report, [test_app.cpp](../src/test_app.cpp). diff --git a/docs/rendering.md b/docs/rendering.md index 884cc6b7..e5431128 100644 --- a/docs/rendering.md +++ b/docs/rendering.md @@ -239,7 +239,8 @@ device and survive it, and repeated failure never loops device creation. subtitles over the picture. - [av_format.cpp](../src/av_format.cpp): video decode, hardware decode selection, decode-thread picture preparation, the matrix an untagged picture is assumed to have and where its chroma lies, - the HDR mapping, and hardware-frame publication. + the HDR mapping - by the PQ and BT.2390 functions of libfiles' `hdr.h`, which show HDR stills - and + hardware-frame publication. - [av_deinterlace.cpp](../src/av_deinterlace.cpp): the deinterlacer that makes each field of an interlaced frame a whole picture. - [platform_win_av.cpp](../src/platform_win_av.cpp): the D3D11VA decoder the renderer presents from, diff --git a/docs/testing.md b/docs/testing.md index 88c52f57..f4a2f59f 100644 --- a/docs/testing.md +++ b/docs/testing.md @@ -36,7 +36,8 @@ The decoder robustness sweeps and the closest-location lookup register only unde Windows Debug run leaves them out; [Linux](linux.md#current-support) runs them in both configurations. `check_translations.py` also checks that `app_text` registers libdesktop's shared messages, read from the -sibling `..\libdesktop` or the one copy fetched under `tmp`, or else from the `services.h` passed with +sibling `..\libdesktop` or the one copy fetched under `tmp` - `platform/messages.h`, or `platform/services.h` +in a libdesktop from before that header was split - or else from the header passed with `--platform-text-header`; its tests prove that omitted, duplicated, unknown and wrongly typed shared messages fail. Outside the gate, `python tools\test_generate_icon.py` holds the logo to `tools/logo.html`, desktop and Store artwork to the same vectors, tile margins, and placement that keeps alpha; the @@ -54,15 +55,16 @@ One file per subject, matching the `src/` prefixes in [implementation](implement | [test_files.cpp](../src/test_files.cpp) | `register_files_tests` | `files*`: codecs, format detection, container parsing, folder art and `.nfo` files, the write path (staging, replacement, originals, collisions, rollback), decoder robustness | | [test_metadata.cpp](../src/test_metadata.cpp) | `register_metadata_tests` | `metadata*`, `model_property`, `model_dates`, `model_tags`: EXIF, IPTC, XMP, ICC, per-format metadata scanning, the date pack and its authority table, the panorama declaration, sidecars, tag sets, property presentation, face names written into their regions | | [test_media_edit.cpp](../src/test_media_edit.cpp) | `register_media_edit_tests` | The metadata write path and the image editing model: in-place and staged edits, Windows shell tags, orientation, crop, perspective, temperature, a wide-gamut photo's colours, and the metadata a lossless video or sound edit keeps | -| [test_faces.cpp](../src/test_faces.cpp) | `register_faces_tests` | `model_faces*`, `model_db_faces`, `view_faces*`: face regions files name; pictures handed to libmug in every orientation, packed or planar, reduced, with nobody in them, or in formats libmug cannot read (libmug's own suite holds its networks); a video's faces read from its key frames; face hashes, records and the store; the scan and its share of the disk; face terms; the face book, its database and CSV - a later release's database, two windows, a failed write, marks following their pictures; suggestions and the overview; the Faces view's pages. See [faces](faces.md) | +| [test_faces.cpp](../src/test_faces.cpp) | `register_faces_tests` | `model_faces*`, `model_db_faces`, `view_faces*`: face regions files name; pictures handed to libmug in every orientation, packed or planar, reduced, with nobody in them, or in formats libmug cannot read (libmug's own suite holds its networks); a video's faces read from its key frames; face hashes, records and the store; the scan, its passes and its share of the disk; face terms; the face book, its database and CSV - a later release's database, two windows, a failed write, marks following their pictures; suggestions and the overview; the Faces view's pages. See [faces](faces.md) | | [test_av.cpp](../src/test_av.cpp) | `register_av_tests` | `av*`: probing, seeking, read-ahead bounds, hover preview, audio buffers, the visualizer, SID tunes and where they end, tracker modules, the Commodore 64 the media pane runs and its keyboard, subtitles, session lifetime, a picture's matrix, chroma siting and fields, Edit's lossless copy, a video's key frames read and decoded alone for face search, and an MP4's index moved before its media | | [test_index.cpp](../src/test_index.cpp) | `register_index_tests` | `model_index`, `model_db`, `model_postings`, `model_search_index`: indexing, the inverted and trigram indexes, the search index and its agreement with a scan, the database, the thumbnail pipeline, duplicates and presence, stale-result discarding, hydration; face records restamped across a metadata write and none written once face search was turned off since, regrouping only on change, an import's face suggestions, the upgrade to people named in pictures, and face-book names found through the search index | | [test_search.cpp](../src/test_search.cpp) | `register_search_tests` | `model_search`, `model_related`, `app_match`: query parsing, term matching, person terms, scopes, negation, exclusion, related items, prediction | | [test_locations.cpp](../src/test_locations.cpp) | `register_location_tests` | `model_locations`, `model_visits`, `model_explore`, `ui_map*`, `ui_globe`, `model_tile_cache`: the gazetteer, place naming, map areas and geometry, the globe's projection, framing and zoom, visits, the timeline, Explore's counts, trips and clusters, the map tile cache. See [locations](locations.md) | | [test_movie.cpp](../src/test_movie.cpp) | `register_movie_tests` | `model_movie`: the Movie document - output geometry and YouTube Shorts, crossfade and duration arithmetic, when captions show and how loud each sound plays, timeline edits and undo, entering Movie with a timeline, the `.dfv` project file. See [movie](movie.md) | | [test_view.cpp](../src/test_view.cpp) | `register_view_tests` | `view*`, `ui*`, `model_zoom`: the zoom model, the panorama camera and its field-of-view ladder, the item selector, the scroller, flex layout, tile geometry, detail rows, the task list's run highlight and scrolling keys, Explore's timeline, keyboard reach and hit testing among drawn elements, the media stack, the SID and tracker monitors and Movie's audio-clip frames, the Commodore 64 listing, cartridge and screen, a picture's people and the face actions on it, the Faces toolbar, text editing. Its scroller, flex and hit-test tests repeat libdesktop's `ui` suite through the application's element tree | -| [test_app.cpp](../src/test_app.cpp) | `register_app_tests` | `app*`: selection and command enablement, Tab order and the keys a focused control keeps, settings and the Options view, rename, import, sync and convert planning, external tools, history, the safe start and crash records, an agent session's options and its tools' arguments; the Faces commands, status text and sidebar button, face marks an import moves, and face-book names predicted in the address bar | -| [test_platform_win.cpp](../src/test_platform_win.cpp) | `register_platform_tests` | `platform_win*`: extended paths, DXGI device loss, adapter classification and texture budgets, the decode device's adapter, texture recycling, the GPU recovery session, the font stack, the registry store, the shell data object, the window chrome. The only test file that may include system headers | +| [test_app.cpp](../src/test_app.cpp) | `register_app_tests` | `app*`: selection and command enablement, Tab order and the keys a focused control keeps, settings and the Options view, rename, import, sync and convert planning, external tools, history, the safe start and crash records, the dialogs an agent session waits out; the screen recorder's script - where its pointer glides, the ring a click spreads, the moments it names and the markers file; the Faces commands, status text and sidebar button, face marks an import moves, and face-book names predicted in the address bar | +| [test_platform_win.cpp](../src/test_platform_win.cpp) | `register_platform_tests` | `platform_win*`: extended paths, DXGI device loss, adapter classification and texture budgets, the decode device's adapter, texture recycling, the GPU recovery session, the font stack, the registry store, the shell data object, the window chrome, the software renderer's window-sized buffer and the Recycle Bin's words. The only test file that may include Windows headers | +| [test_platform_linux.cpp](../src/test_platform_linux.cpp) | `register_platform_linux_tests`, called by `register_platform_tests` in [platform_linux_app.cpp](../src/platform_linux_app.cpp) | What Diffractor says, offers and builds on Linux alone, the counterpart of `test_platform_win.cpp`: the Trash's words where Delete goes to the Trash, no command whose service is a stand-in - Eject, Print, Scan and the like - a folder's drive found by its mount point and a medium Import lists once, an executable that exports none of its static libraries' symbols; the file operations and INI settings saves libdesktop makes on Linux - collisions, symlinks, permissions, raced names and failed writes, some staged through its Linux test seams (`libdesktop/platform/linux.h`); and, since only Linux builds FFmpeg's encoders, the movie writer - AV1 and AAC in an MP4, read back through the application's own media reader and FFmpeg's, a movie abandoned, held through a hole in its times, a render cancelled - and the recorder of a window's own pixels, run over frames the test draws, with the test as the UI thread | [test.h](../src/test.h) holds the assertion helpers, [test_fixtures.h](../src/test_fixtures.h) and [test_fixtures.cpp](../src/test_fixtures.cpp) the shared fixtures, and [test_runner.cpp](../src/test_runner.cpp) @@ -89,7 +91,7 @@ Ask what the test constrains, not what prompted it. - **Persist user state.** A test that appends to a real dictionary, settings key or collection passes once, then fails, and edits a file the user owns. Write to `test_temps` instead. - **Depend on another test.** One `shared_test_context` carries the loaded index, and one gazetteer is loaded per run, because loading either per test is not affordable; nothing else carries between tests. -- **Depend on ordering, wall-clock timing, or the machine's fonts and DPI.** Layout tests measure through stub measure contexts for this reason. Ordering includes the order a folder lists in: NTFS lists names sorted and ext4 does not, and a Linux build of a checkout under WSL's `/mnt/c` reaches `exe/` through links that list as NTFS does, so only CI shows the dependency; the record tests sort what they collect (`scan_parity::add_folder` in [test_files.cpp](../src/test_files.cpp)). The processor matters where a codec picks its kernels at run time: dav1d decodes a damaged stream differently with each set, so the HEIF sweep pins its SSE4.1 kernels. +- **Depend on ordering, wall-clock timing, or the machine's fonts and DPI.** Layout tests measure through stub measure contexts for this reason. Ordering includes the order a folder lists in: NTFS lists names sorted and ext4 does not, and a Linux build of a checkout under WSL's `/mnt/c` reaches `exe/` through links that list as NTFS does, so only CI shows the dependency; the record tests sort what they collect (`scan_parity::add_folder` in [test_files.cpp](../src/test_files.cpp)). The processor matters where a codec picks its kernels at run time - dav1d decodes a damaged stream differently with each set, so the HEIF sweep pins its SSE4.1 kernels on x86 - and where GCC fuses a multiply and an add into one instruction, rounding once, which it does wherever the processor has one, as aarch64 does and x86-64's baseline does not. The records were taken on x86, in builds that fuse none: elsewhere the HEIF and raw sweeps, whose outcomes those change, check what their records were taken over and log the record. On aarch64 the JPEG and WebP sweeps differ in pixels alone - libjpeg-turbo's NEON kernels treat the coefficients a corrupted byte makes their own way, and libwebp's NEON rescaler rounds its own way - so every 64-bit build holds each outcome's shape, whether it decoded and its size, format, orientation and colour, and the JPEG sweep every whole file's pixels, while x86 holds the records whole. The other records hold on aarch64, as they do for an x86-64 build with fused multiply-adds and an unsigned `char`, as aarch64's is. - **Add files to `exe/test`.** That folder is indexed recursively and its file count is asserted by `expected_cached_item_count` and every search-count test. Fixtures loaded by path go in `exe/test/excluded1`, which indexing skips. ## Proving a test is worth having @@ -130,7 +132,7 @@ a window. These are pure functions for that reason: |---|---| | `should_resume_at` / `position_to_save` ([av_player.h](../src/av_player.h)) | the resume window and what a close saves | | `calc_playback_advance` ([util_interfaces.h](../src/util_interfaces.h)) | slideshow, repeat and continue-with-next, and how they interact | -| `search_edit_session` ([app_search.h](../src/app_search.h)) | the address box editing session: draft, preview, two-stage Escape, Tab, Enter | +| libdesktop's `ui::completion_session`, which [app_search.cpp](../src/app_search.cpp) drives | the address box editing session: draft, preview, two-stage Escape, Tab, Enter | | `make_search_auto_complete` ([app_search.h](../src/app_search.h)) | the address bar's completion results: content, counts, ranking, de-duplication, the cap, latest-wins | | `default_keyboard_accelerators` ([app_commands.h](../src/app_commands.h)) | the shipped key bindings, so a collision can be seen | @@ -144,16 +146,17 @@ latest-wins test publish two passes out of order; running the pass inline trips The unit suite and the session test check what is written down; [sweep_mcp.py](../tools/sweep_mcp.py) presses every button. It starts a session out of sight, allowed to write, on a collection and profile it makes and throws away. In each state it reaches - Items with nothing, one photo and everything selected; a photo, a tune -and a document full screen; Explore; Faces; each task - it runs each command, presses each row of each -command's menu and each control, link and part `ui_controls` lists, and puts the window back between presses, -checking each time that the process lives, the window settles and still draws, the log shows no new error, and -a dialog or menu that opened is described, then cancelled. +and a document full screen; Explore; Faces; each task - it runs each command the state does not hide, presses each +row of each command's menu and each control, link and part `ui_controls` lists, and puts the window back between +presses, checking each time that the process lives, the window settles and still draws, the log shows no new error, +and a dialog or menu that opened is described, then cancelled. Without `launch`, what would open another program, folder or web page is skipped and listed; what acts outside -the window - the desktop background, printing, the clipboard, the network - and the sidebar's drive rows, which -browse outside the fixture collection, are not pressed. Putting the window back restores what it shows, not the -Back and Forward history, so a menu row an earlier press disabled - Forward, once something new has opened - is -skipped and listed. It ends with `coverage`: what ran, what was used, and what never was, with why. +the window - the desktop background, printing, the clipboard, the network, an import into the Pictures folder - +and the sidebar's drive rows, which browse outside the fixture collection, are not pressed. Putting the window back +restores what it shows, not the Back and Forward history, so a menu row an earlier press disabled - Forward, once +something new has opened - is skipped and listed. It ends with `coverage`: what ran, what was used, and what never +was, with why. ```powershell python tools\sweep_mcp.py exe\diffractor64.exe diff --git a/docs/third-party.md b/docs/third-party.md index 55a8d595..1ae6352c 100644 --- a/docs/third-party.md +++ b/docs/third-party.md @@ -18,6 +18,12 @@ root and out of a top-level `LICENSES` folder, where GitHub would read them as D FFmpeg is configured without GPL, version-3, or LGPL-v3-only components, so it remains usable under LGPL 2.1. Enabling a GPL component changes the outbound licence of the combined binary and is not an ordinary build option. +Linux's FFmpeg also carries two encoders, for the movies Linux writes ([movie](movie.md#7-rendering)): libaom's AV1, +BSD-2-Clause with the Alliance for Open Media Patent License 1.0, whose texts every release package carries from +[licences](../licences), and FFmpeg's own AAC, which is LGPL like the rest of it. Neither is a GPL, version-3 or +nonfree component. AAC is the one of the two whose patents are licensed rather than granted royalty free, so the +Linux build settles that before it is published. The Flatpak also ships libmtp, LGPL-2.1-or-later, as a shared +library its manifest builds from the release archive; everything else it loads is the Flatpak runtime's. A dependency or model with non-commercial terms, no redistribution grant, or incompatible additional restrictions cannot ship. Every dependency keeps the licence and notices its exact upstream version requires; the licence file @@ -60,24 +66,25 @@ tests that link it. Archives are pinned by SHA-256. | FFmpeg | `d35e13b9e05cc20f48373f88e399c8ef0c16fc61`, upstream `master` of 2026-11-16 | Fetched | Upstream commit archive | [FFmpeg/FFmpeg](https://github.com/FFmpeg/FFmpeg). [FFmpeg.cmake](../cmake/vendored/FFmpeg.cmake) drives its configure and make on Linux, and [ffmpeg_msvc.cmake](../cmake/vendored/ffmpeg_msvc.cmake) builds it on Windows with the configuration its configure generated, kept in `cmake/vendored/ffmpeg-windows/` ([FFmpeg](#ffmpeg)) | | Highway | 1.4.0 | libfiles | Release archive | [google/highway releases](https://github.com/google/highway/releases), which libjxl and libmug use | | Hunspell | 1.7.6 | Fetched | Release archive | [Hunspell releases](https://github.com/hunspell/hunspell/releases); [hunspell.cmake](../cmake/vendored/hunspell.cmake) builds its `src/hunspell/` unchanged, the version and visibility headers included | -| lib64 | `DIFFRACTOR_LIB64_REVISION` in [DiffractorLib64.cmake](../cmake/DiffractorLib64.cmake) | Sibling | Commit, MIT | [ZacWalk/lib64](https://github.com/ZacWalk/lib64), its emulator core only. Its Commodore 64 plays SID tunes, which need no ROM, and shows the chip's registers for [av_sid.cpp](../src/av_sid.cpp), checks a tune's header for [files.cpp](../src/files.cpp), and runs a disk's, tape's, cartridge's or program file's program on the KERNAL, BASIC and character ROMs it carries for [av_c64.cpp](../src/av_c64.cpp) | -| libaom | 3.15.1 | libfiles | Release archive | [AOMedia releases](https://storage.googleapis.com/aom-releases/), signed with AOMedia's release key; BSD-2-Clause with the Alliance for Open Media Patent License 1.0, whose texts every release package carries from [licences](../licences). Its encoder alone, with the configuration its own CMake generated, in libfiles' `cmake/aom/` ([libaom](#libaom)): libheif's AV1 encoder, which libfiles writes AVIF with | +| lib64 | `DIFFRACTOR_LIB64_REVISION` in [DiffractorLib64.cmake](../cmake/DiffractorLib64.cmake) | Sibling | Commit, MIT | [ZacWalk/lib64](https://github.com/ZacWalk/lib64), its emulator core only. Its Commodore 64 plays SID tunes, which need no ROM, and shows the chip's registers for [av_sid.cpp](../src/av_sid.cpp), checks a tune's header and lists a disk's, tape's, cartridge's or program file's contents for [files.cpp](../src/files.cpp) and [ui_c64.cpp](../src/ui_c64.cpp), and runs their programs on the KERNAL, BASIC and character ROMs it carries for [av_c64.cpp](../src/av_c64.cpp) | +| libaom | 3.15.1 | libfiles | Release archive | [AOMedia releases](https://storage.googleapis.com/aom-releases/), signed with AOMedia's release key; BSD-2-Clause with the Alliance for Open Media Patent License 1.0, whose texts every release package carries from [licences](../licences). Its encoder alone, with the configuration its own CMake generated, in libfiles' `cmake/aom/` ([libaom](#libaom)): libheif's AV1 encoder, which libfiles writes AVIF with, and on Linux FFmpeg's, which writes the movies Render and the recorder make | | libarchive | 3.8.11 | Fetched | Release archive | [libarchive releases](https://github.com/libarchive/libarchive/releases); [archive.cmake](../cmake/vendored/archive.cmake) builds it unchanged, its CRC32 and umask helpers included, with the configuration its configure produced for Windows and for Linux kept in `cmake/vendored/archive-windows/` and `archive-linux/` | | libde265 | 1.1.3 | libfiles | Release archive | [strukturag/libde265 releases](https://github.com/strukturag/libde265/releases), with the `config.h` and `de265-version.h` its own build generates: libheif's HEVC decoder where FFmpeg's is not named | | libdesktop | `DIFFRACTOR_LIBDESKTOP_REVISION` in [DiffractorLibdesktop.cmake](../cmake/DiffractorLibdesktop.cmake) | Sibling | Commit, MPL-2.0 | [ZacWalk/libdesktop](https://github.com/ZacWalk/libdesktop), its four static layers: Diffractor links `libdesktop::ui`, which brings `libdesktop::core`, `libdesktop::platform` and `libdesktop::render`; [AGENTS.md](../AGENTS.md#source-directory-map) says what each supplies | | libfacedetection | `acf7b254121927e7dced30e233a2e03119f28ea2`, upstream `master` of 2026-06-28 | libmug | Commit archive | [ShiqiYu/libfacedetection](https://github.com/ShiqiYu/libfacedetection), BSD-3-Clause, whose text every release package carries from [licences](../licences). libmug compiles in its YuNet weights, converted, and runs the network on its own kernels; nothing else of it is built. Its sample photographs are the face tests' ([Faces](#faces)) | -| libfiles | `DIFFRACTOR_LIBFILES_REVISION` in [DiffractorLibfiles.cmake](../cmake/DiffractorLibfiles.cmake) | Sibling | Commit, MPL-2.0; its files ported from libexif and libiptcdata are LGPL-2.1-or-later | [ZacWalk/libfiles](https://github.com/ZacWalk/libfiles), shared with ImageWalker: format identification, still-image and audio/video scans, reconciled properties, XMP/EXIF/IPTC, the ICC profile listing, metadata updates, still-image decoding and encoding, camera raw loading, and the Commodore 64 listing. Diffractor supplies streams and pixel storage, and builds it without its GIF and TIFF documents (`LIBFILES_GIF`, `LIBFILES_TIFF`), so giflib and libtiff are not built; libheif is called here only to register its FFmpeg decoder plugin, and libjxl only by the DNG SDK | +| libfiles | `DIFFRACTOR_LIBFILES_REVISION` in [DiffractorLibfiles.cmake](../cmake/DiffractorLibfiles.cmake) | Sibling | Commit, MPL-2.0; its files ported from libexif and libiptcdata are LGPL-2.1-or-later | [ZacWalk/libfiles](https://github.com/ZacWalk/libfiles), shared with ImageWalker: format identification, still-image and audio/video scans, reconciled properties, XMP/EXIF/IPTC, the ICC profile listing, metadata updates, still-image decoding and encoding, and camera raw loading. Diffractor supplies streams and pixel storage, and builds it without its GIF and TIFF documents (`LIBFILES_GIF`, `LIBFILES_TIFF`), so giflib and libtiff are not built; libheif is called here only to register its FFmpeg decoder plugin, and libjxl only by the DNG SDK | | libheif | 1.23.7 | libfiles | Release archive | [strukturag/libheif releases](https://github.com/strukturag/libheif/releases): its library with the JPEG, libde265, dav1d and uncompressed decoders and the libaom and uncompressed encoders, for libfiles' HEIF decoder and AVIF encoder. Its FFmpeg decoder plugin is built here from that tree by [DiffractorHeif.cmake](../cmake/DiffractorHeif.cmake) and registered by [files_heif.cpp](../src/files_heif.cpp), which names it to libfiles for HEVC images | | libjpeg-turbo | 3.2.1 | libfiles | Release archive | [libjpeg-turbo releases](https://github.com/libjpeg-turbo/libjpeg-turbo/releases): libfiles decodes, encodes and losslessly turns JPEGs with it, and the codecs that read JPEG data and the tests link it | | libjxl | 0.13.0 | libfiles | Release archive | [libjxl releases](https://github.com/libjxl/libjxl/releases): its decoder, encoder, colour management and thread runners, with the version and export headers its own build generates, optimised like the rest; libfiles decodes and encodes JPEG XL with it, and the DNG SDK links it | | XZ / liblzma | 5.8.4 | Fetched | Release archive | [XZ releases](https://github.com/tukaani-project/xz/releases); [lzma.cmake](../cmake/vendored/lzma.cmake) builds `src/liblzma/` and `src/common/` unchanged, not the command-line tools, with the `config.h` kept in `cmake/vendored/lzma/` | +| libmtp | 1.1.23 | The Flatpak's manifest | Release archive | [libmtp releases](https://github.com/libmtp/libmtp/releases), LGPL-2.1-or-later: libdesktop reads phones and cameras through it on Linux. [The manifest](../packaging/flatpak/com.diffractor.Diffractor.yml) builds it as a shared library over the runtime's libusb and the Flatpak ships it; a build from source links the system's | | libmug | `DIFFRACTOR_LIBMUG_REVISION` in [DiffractorLibmug.cmake](../cmake/DiffractorLibmug.cmake) | Sibling | Commit, MIT | [ZacWalk/libmug](https://github.com/ZacWalk/libmug): finds faces and makes each a vector for [faces](faces.md), YuNet and SFace on its own SIMD kernels over libfiles' Highway (`LIBMUG_HIGHWAY_TARGET`), both networks' weights compiled in ([Faces](#faces)) | | libopenmpt | 0.8.10 | Fetched | Release archive | [libopenmpt downloads](https://lib.openmpt.org/libopenmpt/download/), the `.autotools` source release; [openmpt.cmake](../cmake/vendored/openmpt.cmake) builds it unchanged, with the release's own `svn_version.h` ([libopenmpt](#libopenmpt)) | | libpng | 1.6.59 | libfiles | Release archive | [libpng](https://www.libpng.org/pub/png/libpng.html), [upstream tags](https://github.com/pnggroup/libpng/tags): built in C alone, with the `pnglibconf.h` kept in libfiles' `cmake/`; libfiles decodes and encodes PNGs with it, and the tests link it | | LibRaw | 0.22.3 | libfiles | Release archive | [LibRaw releases](https://github.com/LibRaw/LibRaw/releases): its library, with the DNG SDK and libjpeg. libfiles loads raw files with it - their preview, or their raw data developed - and scans them: their metadata, the info pane's listing and a thumbnail. Diffractor links it for libfiles without calling it | | libwebp | 1.6.0 | libfiles | Release archive | [libwebp tags](https://github.com/webmproject/libwebp/tags): its decoder, encoder, sharpyuv, mux and demux as one library; libfiles decodes still WebPs and encodes WebPs with it, and the tests link it | -| minizip-ng | 4.2.2 | Fetched | Tag archive | [minizip-ng releases](https://github.com/zlib-ng/minizip-ng/releases); [minizip.cmake](../cmake/vendored/minizip.cmake) builds it unchanged, the `compat/` API included, with the `mz_config.h` kept in `cmake/vendored/minizip/` | -| RapidJSON | `297637bc0a0f00dc504dbc1a47ebdaa577f8ae19` | libdesktop | Commit archive | [Tencent/rapidjson](https://github.com/Tencent/rapidjson): headers only, which libdesktop gives `libdesktop::core`'s consumers; the agent tools and the Movie report read and write JSON with them ([app_mcp_json.h](../src/app_mcp_json.h), [app_movie_batch.cpp](../src/app_movie_batch.cpp)), and nothing of it is built | +| minizip-ng | 4.2.2 | Fetched | Tag archive | [minizip-ng releases](https://github.com/zlib-ng/minizip-ng/releases); [minizip.cmake](../cmake/vendored/minizip.cmake) builds it unchanged, the `compat/` API included, with the `mz_config.h` kept in `cmake/vendored/minizip/`, and on Linux the one in `cmake/vendored/minizip-linux/` ahead of it | +| RapidJSON | `297637bc0a0f00dc504dbc1a47ebdaa577f8ae19` | libdesktop | Commit archive | [Tencent/rapidjson](https://github.com/Tencent/rapidjson): headers only, which libdesktop gives `libdesktop::core`'s consumers; the agent tools and the Movie report read and write JSON with them ([app_mcp_tools.cpp](../src/app_mcp_tools.cpp), [app_movie_batch.cpp](../src/app_movie_batch.cpp)), and nothing of it is built | | SDL3 | 3.4.20 | libdesktop, on Linux | Release archive | [libsdl-org/SDL releases](https://github.com/libsdl-org/SDL/releases), linked statically into libdesktop's Linux platform and render backends; the Windows build does not use it | | SFace | OpenCV Zoo `ba91a3b91d00d76e86540d4013f944bd6b514e39`, `face_recognition_sface_2021dec.onnx` | libmug | Model file | [opencv/opencv_zoo](https://github.com/opencv/opencv_zoo/tree/main/models/face_recognition_sface), Apache-2.0, whose text every release package carries from [licences](../licences). libmug converts it as the build runs into the quantized weights it compiles in ([Faces](#faces)) | | skcms | `074a8d439d75df5bff2746458306f7760ee74dd8` | libfiles | Git commit | [Skia upstream](https://skia.googlesource.com/skcms/). It makes no releases, and Skia's generated archives differ from one download to the next, so libfiles clones the commit; its baseline, Haswell and Skylake units serve libjxl's colour management | @@ -134,15 +141,20 @@ FFmpeg is upstream [FFmpeg](https://github.com/FFmpeg/FFmpeg), fetched at the co [dd-dependencies.json](../cmake/dd-dependencies.json) pins and built unpatched: an upgrade is a new pin and a regenerated Windows configuration. Diffractor uses it to decode - playback, thumbnails, frame extraction, audio for the waveform and the movie encoder's sources - to describe the streams of a file libfiles' media scan cannot -describe whole, and to copy a video's or a sound file's packets into a new file of its own format, or an MP4, for -Edit's lossless edits. Every other audio and video read - the container's streams, duration, tags, XMP packet and +describe whole, to copy a video's or a sound file's packets into a new file of its own format, or an MP4, for +Edit's lossless edits, and on Linux to write the movies Render and the recorder make. Every other audio and video +read - the container's streams, duration, tags, XMP packet and cover art - is libfiles' ([metadata](metadata.md)). Its configuration controls the available demuxers, muxers, decoders, parsers and hardware acceleration. It builds no end-user programs and enables no network protocols. It is configured for decode speed rather than size, which also keeps codec profile names; it decodes software AV1 through libdav1d, built against libfiles' dav1d; D3D11VA, -on Windows, is its only hardware acceleration; its only muxers write the formats Edit copies a file into; and it -has no encoders or devices. It is configured LGPL 2.1: no GPL, version-3 or nonfree component. +on Windows, is its only hardware acceleration; its only muxers write the formats Edit copies a file into, and the +MP4 a movie is written in; and it has no devices. It has no encoders on Windows, where Media Foundation writes the +movies, and two on Linux: libaom's AV1 and its own AAC. libaom is libfiles' build, which configure is shown through +a generated `aom.pc` as it is shown libfiles' dav1d, and which has no decoder, so FFmpeg's libaom decoder is +switched off and libdav1d stays the software AV1 decoder. It is configured LGPL 2.1: no GPL, version-3 or +nonfree component. [av_format.cpp](../src/av_format.cpp) owns what FFmpeg's answers become: codec names in Diffractor's short form, a pixel format as chroma and depth, the coded sample type, and iTunes' `rtng` advisory kept out of the rating; its @@ -194,6 +206,13 @@ snapshot. - Compare the Windows/Linux component sets with `tools/compare_ffmpeg_config.py`. Explain any intentional platform difference in `cmake/vendored/ffmpeg-config-divergence.txt`; do not simply accept a changed baseline. A working Windows build does not verify the Linux configuration. +- Linux's configure line is the Windows one with the movie writer added: `--enable-libaom`, against the `aom.pc` + [FFmpeg.cmake](../cmake/vendored/FFmpeg.cmake) makes from libfiles' libaom, `--enable-encoder=aac,libaom_av1` + after `--disable-encoders`, and `--disable-decoder=libaom_av1`, because libfiles builds libaom's encoder alone and + a libaom decoder in libavcodec would call a decoder interface that archive does not have. The two encoders, and + what they select, are `MOVIE_WRITER` in `tools/compare_ffmpeg_config.py`, which refuses to record any other + encoder, decoder, demuxer or muxer as a difference. The Windows configuration keeps no encoder. An upgrade proves + the writer with `*movie*` and `*recording*` tests on Linux ([testing](testing.md)). - Prove decoding and the metadata probe through the application wrapper tests. Run the metadata, video, audio and format tests, then the complete suite. Do not replace a missing assembly implementation with an empty symbol or drop a decoder to make the link pass. @@ -222,7 +241,7 @@ comment records it. | libjxl / Highway / Brotli | Upgraded in libfiles: a new archive pin, with the version and export headers libjxl's own build generates, in libfiles' `cmake/jxl/include/`, brought up to the release. Use the upstream source lists to identify added or removed units, and preserve libjxl's Highway, Brotli and skcms dependencies. An upgrade runs the JPEG XL tests in Release, optimised: "Should scan jxl metadata" is where an MSVC miscompile that decodes a JPEG XL to an empty image would show. | | liblzma | A new archive pin. Keep `cmake/vendored/lzma/config.h` and the Linux POSIX-thread override, and build the library and common subset, not the differently licensed command-line scripts and tools. | | libarchive | A new archive pin. Keep `cmake/vendored/archive-windows/config_windows.h` and `archive-linux/config_linux.h`, which `PLATFORM_CONFIG_H` names, and bring them up to the release's configure output for each platform. Retain the CRC32 and umask sources, the Windows `ARCHIVE_CRYPTO_WIN` switch as well as its per-digest switches, and Linux's `HAVE_WAITPID`; otherwise encryption or external-filter process handling can silently disappear. Windows leaves `HAVE_FCNTL` undefined, as upstream's Windows configuration does: it has no `fcntl()`, and 3.8.11 calls one. Its XAR reader is built without an XML parser, so nothing needs Expat. | -| minizip-ng | A new archive pin. Keep `cmake/vendored/minizip/mz_config.h`, the configuration Windows and Linux both build with, and bring it up to the release's `mz_config.h.cmakein`. Its zlib-style compatibility API lives in `compat/`; retain it and the platform-specific crypto selection. | +| minizip-ng | A new archive pin. Keep `cmake/vendored/minizip/mz_config.h`, Windows's configuration, and `cmake/vendored/minizip-linux/mz_config.h`, which Linux builds with in its place, and bring each up to the release's `mz_config.h.cmakein`. Its zlib-style compatibility API lives in `compat/`; retain it and the platform-specific crypto selection. | | Hunspell | A new archive pin. Keep the static-library configuration. The source list includes `hunspelltrace.cxx`; dropping it leaves the trace hooks unresolved. | | LibRaw / DNG SDK | Upgraded in libfiles: a new archive pin each, with the SDK's `RawEnvironment.h`, in libfiles' `cmake/dng/`, kept. Preserve the LibRaw wrapper boundary. Build only the SDK's `dng_sdk/source/`, not Adobe's bundled copies of libraries libfiles owns. The SDK's `dng_xmp_sdk.cpp` is not built: libfiles' [dng_xmp_sdk.cpp](https://github.com/ZacWalk/libfiles/blob/main/src/dng_xmp_sdk.cpp) implements the SDK's `dng_xmp_sdk.h` over libfiles' XMP model in its place, so an upgrade that changes `dng_xmp_sdk.h` or `dng_xmp_sdk.cpp` must carry the change there - the namespaces `InitializeSDK` registers, which faults each call reports, swallows or throws, and the toolkit utilities it reproduces. The SDK is built with `qDNGXMPFiles=0`, and document-history support remains disabled, because that backend has neither XMPFiles nor `SXMPDocOps`. | | skcms | Upgraded in libfiles: a new commit pin. Keep the baseline, Haswell and Skylake transform units and their compiler-specific instruction-set flags. Validate ICC transforms, not only compilation. | @@ -245,7 +264,10 @@ generate both again with the release's own CMake, as libfiles' lists with the release's. Verify the new archive's signature against AOMedia's release key, and bring the licence and patent texts in [licences](../licences) up to the release's `LICENSE` and `PATENTS`. An upgrade runs libfiles' AVIF tests and the `*AVIF*` tests here, in Release, on x64 and x86: the x86-64 -build takes libaom's SIMD and the 32-bit one its C alone. +build takes libaom's SIMD and the 32-bit one its C alone. On Linux the same archive is FFmpeg's AV1 encoder for +the movie writer: an upgrade runs the `*movie*` tests there too, and moves the version [FFmpeg.cmake](../cmake/vendored/FFmpeg.cmake) +gives configure's `aom.pc` with libfiles' pin. The writer uses libaom's real-time usage and its speeds to 12, which +libfiles' build, not realtime-only, provides. ### libopenmpt diff --git a/docs/v-1.27.5.md b/docs/v-1.27.5.md new file mode 100644 index 00000000..6b27fc7b --- /dev/null +++ b/docs/v-1.27.5.md @@ -0,0 +1,164 @@ +# Diffractor 1.27.5 + +Baseline: 1.27.4, build 1316. **Status: planning.** The tree is stamped 1.27.5.1317. + +This is the plan for 1.27.5. Work moves out of [Planned](#planned) into [Changes](#changes) when it lands in the +tree, and the release is done when every [release task](#release-tasks) is ticked and [Verification](#verification) +is filled in. GitHub issues own issue state, and the linked documents own the behavior that ships. Once 1.27.5 +ships, its user-facing changes become the GitHub release notes and the next release's plan replaces this file. + +## Changes + +### Versions are named major.minor.patch + +The app names itself `1.27.5`, as releases, tags and the Store do. Builds up to 1.27.4.1316 named themselves in +two parts, the major folded into the minor - `127.4` - and `df::app_version` reads both forms as one version: + +- The update check compares an offer in either form, and shows it as `1.27.5`. +- The crash skip list keeps its tag: 1.27.4 and 1.27.5 are both line `127`, so a file 1.27.4 skipped stays + skipped until 1.28 ([crash-loop protection](implementation.md#crash-loop-protection)). +- The installer's Add/Remove Programs entry, the About box, crash dump names, the MCP server's version and the + map tile user agent all name it `1.27.5`. +- `.\dd.ps1 bump-ver` reads either form and writes the new one. + +diffractor.com's `/ver` still answers in two parts, because builds up to 1.27.4.1316 compare major.minor alone. +Later builds read either form, so the protocol does not change. + +> **Start here.** [app_version.h](../src/app_version.h) states the scheme and [app.cpp](../src/app.cpp) parses it. +> The comparisons are in [app_dialogs.cpp](../src/app_dialogs.cpp) and [app_toolbar.cpp](../src/app_toolbar.cpp), +> and the skip list's tag in [util_crash_files_db.h](../src/util_crash_files_db.h). `Should compare versions` and +> `Should record crashes` pin it. + +### The generated format list names every format + +`generate_docs` ([agents](agents.md#5-the-tools)) writes the format tables the wiki's Formats and Codecs page is +made from. Each extension is now listed once, under the type it opens as; types with one description share a row; +tracker modules are listed as such; and Commodore 64 files and archives have sections of their own. Descriptions +that were wrong or missing are corrected, among them IVF, PSP, RealMedia, Ogg, MOV, WebP, JPEG 2000 and Matroska +audio. + +> **Start here.** The descriptions are `build_file_types` in [files.cpp](../src/files.cpp), and the tables are +> written by [app_gen_docs.cpp](../src/app_gen_docs.cpp). + +### Linux runs every feature its platform offers, as a beta Flatpak + +Linux passes the same embedded suite, agent-session test and sweep as Windows, and is built into a Flatpak, +`com.diffractor.Diffractor`, for beta testers. + +- The software renderer draws a window into one buffer of the window's size and presents it once a frame, on + both platforms, so it no longer tears; on Linux the title bar, view and status bar are regions of one window. +- Sound plays through SDL3; movies - Render and the window's recording - are MP4s of AV1 and AAC written by + Diffractor's own FFmpeg; map tiles, dictionaries and crash and Support reports use libcurl; Delete moves items + to the freedesktop Trash; files and pictures go on the clipboard as the file managers use them and arrive by + drop; the file and folder pickers are drawn; Import reads phones and cameras over MTP; a second launch hands + its files to the running window; and a fatal signal leaves a crash report, sent at the next start. +- Print, Desktop background, Properties, Scan, Share or Email, Burn and Eject, whose services Linux lacks, are + absent rather than doing nothing, and every Linux build leaves out the update check, which installs a Windows + program. + +> **Start here.** [linux.md](linux.md) owns what runs, what is unavailable and how it builds and installs, and +> [packaging/flatpak](../packaging/flatpak/README.md) the bundle; libdesktop's +> [Linux backend](https://github.com/ZacWalk/libdesktop/blob/main/docs/platform.md#the-linux-backend) owns the +> services beneath it. [test_platform_linux.cpp](../src/test_platform_linux.cpp) pins what Linux alone says and +> offers. + +## Planned + +### Search words that are read as something else + +**Owned by [design](design.md#navigation-and-search).** Scope: Search. + +Three ways a query is accepted and quietly answers a different question, found while writing the wiki's search +reference. Each needs a case in [test_search.cpp](../src/test_search.cpp) that fails before its fix. + +- **The one-letter shortcuts never work.** `c:` (original date), `m:` (modified), `y:` (year) and `x:` (latitude) + are registered by `build_properties_by_name` in [model_property.cpp](../src/model_property.cpp), but + [model_tokenizer.h](../src/model_tokenizer.h) keeps one character before a colon as text, so that `c:\photos` + stays a drive path, and `y:2020` is searched for as text. The answer owed: drop the shortcuts, or read a letter + and colon as a scope unless a path separator follows. [locations](locations.md) lists `x:` and `y:` as working, + and changes with the answer. +- **A minus before a folder path is dropped.** `parse_parts` in [model_search.cpp](../src/model_search.cpp) makes + a path the search's folder without reading its modifier, so `-c:\photos\2019` searches that folder instead of + leaving it out. +- **A numeric month is not a date.** `2022-may` is read as a month and `2022-05` is not: `year_and_month` takes + only a month name, which is all `core::month` reads. + +### A SID tune's measured length reaches the index + +**Owned by [design](design.md#selection-and-viewing).** Scope: SID tunes. + +A SID file does not say how long it plays, so `files::scan_sid` in [files.cpp](../src/files.cpp) records every +tune as `sid_tune_seconds`, three minutes. Playback measures the real length - `find_sid_tune_length` in +[av_sid.cpp](../src/av_sid.cpp), cached in memory - but the index never learns it, so the details list, sorting by +duration and `duration:` searches all see 3:00. The answer owed: scan at index time, which costs up to about ten +seconds of a worker for a tune whose end the scan never finds, or write the length back once a tune has been +played and measured. + +### Stop at the ends when stepping through items (#269) + +**Owned by [design](design.md#selection-and-viewing).** Scope: keyboard and mouse wheel navigation. + +`view_state::next_item` in [model.cpp](../src/model.cpp) wraps from the last item to the first and back, and +[#269](https://github.com/ZacWalk/diffractor/issues/269) asks for an option to stop at the ends, so the end of a +long run of videos is noticed rather than started again. The option belongs on the [Options](design.md#options) +page, with wrapping as the default so nobody who leaves it alone sees a change. + +### Shared libraries + +- **libdesktop: publish the Linux backend and the window-sized software buffer, then move the pin.** Diffractor + builds against the sibling checkout until `DIFFRACTOR_LIBDESKTOP_REVISION` in + [DiffractorLibdesktop.cmake](../cmake/DiffractorLibdesktop.cmake) names the commit + ([upgrade procedure](third-party.md#upgrade-procedure)). +- **libdesktop: remove `core::version`.** Nothing uses it now that `df::app_version` replaced it + ([util.h](https://github.com/ZacWalk/libdesktop/blob/main/include/libdesktop/core/util.h)). A libdesktop + commit, then a pin move here ([upgrade procedure](third-party.md#upgrade-procedure)). +- **libdesktop: declare `supportedOS` in `tests/tests.manifest`.** Without it Windows reports an older release to + libdesktop's own tests, so its caption probe test never takes the Windows 11 path that Diffractor's manifest + selects. + +### Test coverage + +- **Give [the sweep](testing.md#the-sweep) a face.** Its collection - `make_collection` in + [sweep_mcp.py](../tools/sweep_mcp.py) - holds generated pictures with no faces, so the sweep presses the Faces + view's buttons only in its empty state. + +### Considered, not planned + +- The face strip loses its hover when the media view rebuilds its picture under the pointer; judged rare. +- Tracker modules and plain audio could fill a YouTube Short as the SID monitor does. + +## Release tasks + +- [ ] **winget.** `winget install Diffractor.Diffractor` fails today: winget ranks 126.0 above every 1.x version, + and 126.0's installer was under the `v126.0` tag, which became `v1.26.0` on 2026-11-26. A pull request to + [winget-pkgs](https://github.com/microsoft/winget-pkgs/tree/master/manifests/d/Diffractor/Diffractor) removes + 126.0 and adds the new release, mapping its `DisplayVersion` as the 1.27.2 entry maps `127.2`: `127.4` for + 1.27.4, and `1.27.5` from 1.27.5 on. It does not wait for the release. +- [ ] **Builds.** `.\dd.ps1 desktop -NoBump` and `.\dd.ps1 store -NoBump` ship the tree's stamp, as 1.27.4 shipped + 1.27.4.1316; without `-NoBump` each raises the build number. `.\dd.ps1 release` then publishes the GitHub release + as `v1.27.5`. +- [ ] **Site.** diffractor-site's release procedure, `.github/prompts/release.prompt.md`: refresh `releases.json`, + upload the binaries, move the test pins, then promote `/ver` about a day later. Promoted, `/ver` answers `127.5`, + which 1.27.4 installs compare as newer. +- [ ] **Wiki.** Regenerate the Formats and Codecs page with `generate_docs`, and change "1.27.4" on it and on Home. +- [ ] **Store.** New release notes for the listing; remove the old en-us screenshot 8 in Partner Center if it is + still there. +- [ ] **Linux beta.** Settle the AAC encoder's patent position and confirm the AppStream metadata - developer, + `CC0-1.0` metadata licence, release date - before the bundle goes beyond testers. Build it with + [packaging/flatpak](../packaging/flatpak/README.md) from the published checkouts, keep its `.Debug` bundle for + crash reports, and hand the bundle to testers. + +## Verification + +On completion this section records: + +- `.\dd.ps1 test --label headless` on the Release build: lint, the unit test count, both translation validators + and the agent session, all passing. +- On Linux: the embedded suite in Debug and Release, `--validate-po`, and the agent session and the sweep against + the installed Flatpak, all passing. +- Version stamps agreeing at 1.27.5 in [app.cpp](../src/app.cpp), [platform_win_res.rc](../src/platform_win_res.rc), + [platform_win.manifest](../src/platform_win.manifest), [diff.nsi](../installer/diff.nsi) and + [AppxManifest.xml](../exe/AppxManifest.xml). +- A 1.27.4 install offered 1.27.5 once `/ver` is promoted, and upgraded by it: Add/Remove Programs then shows + 1.27.5, and a file the 1.27.4 crash list skipped is still skipped. +- Each planned item's test named, and shown to fail without its fix. diff --git a/docs/zoom.md b/docs/zoom.md index b1f8495f..28cc18a0 100644 --- a/docs/zoom.md +++ b/docs/zoom.md @@ -47,7 +47,8 @@ fullscreen commands; commands whose target or effect is not visible are suppress ## Rendering Tiers GPU and software backends consume the same zoom geometry and sampler choice. The GPU scales, translates and fades -a retained texture; the software backend samples only the clipped viewport, a bounded tile at a time. Interactive +a retained texture; the software backend samples only the clipped viewport, into the window's own buffer, a +cache-sized band at a time. Interactive input uses the affordable path for its backend; settled output may use higher-quality downsampling. Alpha transitions run only when the rendering animation gate is open, and disabling them changes no anchoring, final geometry or image quality. diff --git a/exe/AppxManifest.xml b/exe/AppxManifest.xml index ff77b578..89680114 100644 --- a/exe/AppxManifest.xml +++ b/exe/AppxManifest.xml @@ -23,7 +23,7 @@ "; @@ -44,10 +53,9 @@ namespace // Note placed at the top of each generated block. constexpr std::string_view k_generated_note = - "\n\n"; + "\n\n"; std::string read_text_file(const core::file_path path) { @@ -97,31 +105,66 @@ namespace return saved; } - // Emits a markdown table of file types belonging to the given group, with an - // optional raw-trait filter, including only types with a description. + // Emits a markdown table of the file types in the given group, with an optional raw-trait filter: one row per + // description, in the order of the row's first extension. void write_format_table(std::string& md, const std::string_view section_title, const std::vector& types, const file_group_ref group, const bool require_raw, const bool exclude_raw) { - md += "## "; - md += section_title; - md += "\n\n"; - md += "| Extensions | Description |\n"; - md += "| --- | --- |\n"; + struct row + { + std::string_view description; + std::vector extensions; + }; + + std::vector rows; for (const auto* ft : types) { if (ft->group != group) continue; - if (ft->text.empty()) continue; const bool is_raw = ft->has_trait(file_traits::raw); if (require_raw && !is_raw) continue; if (exclude_raw && is_raw) continue; - md += "| "; - md += format_extensions(ft->extension); + auto extensions = own_extensions(ft); + if (extensions.empty()) continue; + + const auto description = format_description(ft, extensions.front()); + if (description.empty()) continue; + + const auto found = std::ranges::find(rows, description, &row::description); + + if (found == rows.end()) + { + rows.push_back({description, std::move(extensions)}); + } + else + { + found->extensions.insert(found->extensions.end(), extensions.begin(), extensions.end()); + } + } + + std::ranges::sort(rows, {}, [](const row& r) -> const std::string& { return r.extensions.front(); }); + + md += "## "; + md += section_title; + md += "\n\n"; + md += "| Extensions | Description |\n"; + md += "| --- | --- |\n"; + + for (const auto& r : rows) + { + md += "|"; + + for (const auto& extension : r.extensions) + { + md += &extension == &r.extensions.front() ? " " : ", "; + md += extension; + } + md += " | "; - md += ft->text; + md += r.description; md += " |\n"; } @@ -161,6 +204,8 @@ namespace write_format_table(block, "Raw Photo Formats", types, &file_group::photo, true, false); write_format_table(block, "Video and Container Formats", types, &file_group::video, false, false); write_format_table(block, "Audio Formats", types, &file_group::audio, false, false); + write_format_table(block, "Commodore 64 Formats", types, &file_group::commodore, false, false); + write_format_table(block, "Archive Formats", types, &file_group::archive, false, false); write_codec_list(block, "Video Codecs", codecs, av_codec_media_type::video); write_codec_list(block, "Audio Codecs", codecs, av_codec_media_type::audio); diff --git a/src/app_mcp.cpp b/src/app_mcp.cpp index 9d6fd9b2..d2c0640b 100644 --- a/src/app_mcp.cpp +++ b/src/app_mcp.cpp @@ -5,58 +5,28 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The agent session's host (app_mcp.h): its options, the jobs long work runs as and the calls that wait on -// them, the window it makes when a tool first needs one, the copies of itself it runs work in, the log lines it keeps, -// the session's own tools - help, status, waiting, diagnostics, the log, jobs and the window - and a single tool called -// from the command line (-tool:). +// Purpose: What Diffractor tells libdesktop's agent host of itself (app_mcp.h): its name and guidance and help's topics, +// its window - made when a tool first needs it, with the index - what each command needs of the session, what keeps +// the window busy, what status and diagnostics add, what the window offers - its bars, the view's regions and parts, +// the strip - and what its own elements and dialogs are, and the picture types a screenshot is saved as beside PNG. #include "pch.h" #include "app_mcp.h" -#include "app_mcp_json.h" #include "app_text.h" #include "app_perf.h" +#include "files.h" #include "model_db.h" #include "model_index.h" #include "model.h" +#include "ui_view.h" #include "ui_dialog.h" +#include "ui_controls.h" #include "app_command_line.h" #include "app.h" -#include - namespace { - // The latest lines the log was written, numbered so a caller can ask for those since a mark. - struct log_ring - { - std::mutex mutex; - std::deque> lines; - uint64_t next = 1; - }; - - constexpr size_t kept_log_lines = 4000; - - log_ring& ring() - { - static log_ring r; - return r; - } - - void observe_log(const std::string_view line) - { - auto text = std::string(line); - while (!text.empty() && (text.back() == '\n' || text.back() == '\r')) text.pop_back(); - - auto& r = ring(); - std::lock_guard lock(r.mutex); - r.lines.emplace_back(r.next++, std::move(text)); - while (r.lines.size() > kept_log_lines) r.lines.pop_front(); - } - - // A job's output is kept to this much: enough for a test run's report, bounded for a render's. - constexpr size_t kept_output_bytes = 256 * 1024; - constexpr std::string_view instructions = "Diffractor organizes the photos, videos and audio on the user's own disks; this session offers its tools. " "Start with status: what the session may do, where its window is, and how the index stands. The library " @@ -74,152 +44,234 @@ namespace "taken nearest in time, which Locate proposes. help explains the search language, the .dfv movie and .dft " "script formats, and what each -mcp-allow tier allows."; - std::string help_text(const std::string_view topic) + std::string search_help() { - if (topic == "search") - { - std::string scopes; - - for (const auto& s : prop::search_scopes()) - { - if (s.scope == "any") continue; - scopes += (scopes.empty() ? "" : ", ") + s.scope; - } - - return std::format( - "The search language is the address box's. Words, and \"quoted phrases\", match names and metadata; " - "scope:value narrows a word to one property, as tag:holiday or camera:canon; @photo, @video, @audio " - "and @commodore ask for a kind of file; @raw, @hdr, @animated, @transparent, @panorama, @wide, " - "@portrait, @landscape, @square and @slowmo for how a picture or video was made; and @duplicates for " - "the files the collection holds more than one copy " - "of; a number or a date after < or > compares, as rating:>3 or created:>2019, and a date alone, as " - "2019-07-13, asks for that day; ! or - before a term leaves out what it matches; and, or and " - "parentheses combine terms; with: and without: ask whether an item has one, as " - "without:location. A full folder path searches that folder, and ending it with ** searches its " - "subfolders too. search runs a query without changing the window, in order of path, of when each " - "item was taken, or of its set of copies; navigate shows it there.\n\nScopes: {}", - scopes); - } + std::string scopes; - if (topic == "dfv") + for (const auto& s : prop::search_scopes()) { - return "A Movie project is a .dfv file: UTF-8 text, one item per line, in the order they play. " - "# starts a comment line.\n" - " t [''] a screen of text on black for seconds\n" - " c [''] [!] a clip of the file\n" - " s [''] [!] the same, marked to be stabilized\n" - "A part is - in seconds (83.5), minutes and seconds (1:23.5) or hours (1:01:23.5); " - "either end may be left out, and - alone is the whole file. A photo shows for the part's length: " - "-6 is six seconds. # after a part plays tune n of a SID file. A file is a full path or one " - "relative to the project's folder. 'single quotes' read \\n as a new line; \"double quotes\" take " - "a path as it stands. !sound.wav plays that file in place of the clip's own sound. Check a " - "project with movie_check, which names each line it cannot read, and make it with movie_render. " - "docs/movie.md has the whole format."; + if (s.scope == "any") continue; + scopes += (scopes.empty() ? "" : ", ") + s.scope; } - if (topic == "dft") - { - return "A tutorial script is a .dft file, one step a line; # starts a comment. Steps before the first say " - "set the scene; say '' starts a beat, whose steps run while it is spoken. " - "ui_input's steps are a script's steps, with no say.\n" - " cue | wait | settle | hide | list | tooltips on|off\n" - " point [] the drawn pointer glides there\n" - " click [ctrl] [shift] | double-click | right-click on what the pointer is on\n" - " drag [] pressed where the pointer is, let go at the anchor\n" - " wheel up|down [] turned where the pointer is\n" - " type '' into the address box\n" - " text '' into whatever has the keyboard\n" - " key ctrl+, shift+, alt+ before a letter, digit or enter, escape, space, " - "tab, backspace, delete, insert, left, right, up, down, home, end, page-up, page-down, plus, minus, " - "apps, f1 to f12\n" - " command a command, by the name command_list gives\n" - " open [''] | select '' [ctrl]\n" - "Anchors: address, sidebar, types, map, calendar, month -, items, preview, view, " - "button , tile '' [ ], at - x and y are fractions from the top " - "left. The pointer and keys are given to the window as its own input, reaching what a user's " - "would. A script cannot work a dialog or a menu: dialog_respond and menu_respond answer them."; - } + return std::format( + "The search language is the address box's. Words, and \"quoted phrases\", match names and metadata; " + "scope:value narrows a word to one property, as tag:holiday or camera:canon; @photo, @video, @audio " + "and @commodore ask for a kind of file; @raw, @hdr, @animated, @transparent, @panorama, @wide, " + "@portrait, @landscape, @square and @slowmo for how a picture or video was made; and @duplicates for " + "the files the collection holds more than one copy " + "of; a number or a date after < or > compares, as rating:>3 or created:>2019, and a date alone, as " + "2019-07-13, asks for that day; ! or - before a term leaves out what it matches; and, or and " + "parentheses combine terms; with: and without: ask whether an item has one, as " + "without:location. A full folder path searches that folder, and ending it with ** searches its " + "subfolders too. search runs a query without changing the window, in order of path, of when each " + "item was taken, or of its set of copies; navigate shows it there.\n\nScopes: {}", + scopes); + } + + constexpr std::string_view dfv_help = + "A Movie project is a .dfv file: UTF-8 text, one item per line, in the order they play. " + "# starts a comment line.\n" + " t [''] a screen of text on black for seconds\n" + " c [''] [!] a clip of the file\n" + " s [''] [!] the same, marked to be stabilized\n" + "A part is - in seconds (83.5), minutes and seconds (1:23.5) or hours (1:01:23.5); " + "either end may be left out, and - alone is the whole file. A photo shows for the part's length: " + "-6 is six seconds. # after a part plays tune n of a SID file. A file is a full path or one " + "relative to the project's folder. 'single quotes' read \\n as a new line; \"double quotes\" take " + "a path as it stands. !sound.wav plays that file in place of the clip's own sound. Check a " + "project with movie_check, which names each line it cannot read, and make it with movie_render. " + "docs/movie.md has the whole format."; + + constexpr std::string_view dft_help = + "A tutorial script is a .dft file, one step a line; # starts a comment. Steps before the first say " + "set the scene; say '' starts a beat, whose steps run while it is spoken. " + "ui_input's steps are a script's steps, with no say.\n" + " cue | wait | settle | hide | list | tooltips on|off\n" + " point [] the drawn pointer glides there\n" + " click [ctrl] [shift] | double-click | right-click on what the pointer is on\n" + " drag [] pressed where the pointer is, let go at the anchor\n" + " wheel up|down [] turned where the pointer is\n" + " type '' into the address box\n" + " text '' into whatever has the keyboard\n" + " key ctrl+, shift+, alt+ before a letter, digit or enter, escape, space, " + "tab, backspace, delete, insert, left, right, up, down, home, end, page-up, page-down, plus, minus, " + "apps, f1 to f12\n" + " command a command, by the name command_list gives\n" + " open [''] | select '' [ctrl]\n" + "Anchors: address, sidebar, types, map, calendar, month -, items, preview, view, " + "button , tile '' [ ], at - x and y are fractions from the top " + "left. The pointer and keys are given to the window as its own input, reaching what a user's " + "would. A script cannot work a dialog or a menu: dialog_respond and menu_respond answer them."; + + constexpr std::string_view tiers_help = + "A session reads by default. The client's configuration starts it with -mcp-allow: to allow more, " + "comma-separated:\n" + " write change files: movie_render, ui_input, ui_act, tutorial_run, and commands, dialog " + "buttons and menu rows that change files\n" + " capture pictures of the screen and of the user's media: screenshot, record_*, tutorial_run\n" + " network work that reaches the network: update checks, crash reports, map tiles\n" + " dev the developer's tools: run_tests, validate_translations, generate_docs, " + "duplicate_report\n" + " launch opening another program, a folder or a web page on the user's desktop: the help, a " + "file's folder, a map, Open with. Without it, each is skipped and logged.\n" + "-mcp-ui:offscreen or visible makes the window at once, out of sight or on the desktop; a " + "recording needs it visible. -profile: keeps settings and the index apart from the user's, " + "and -collection: makes one folder the whole collection. status says what this session " + "was started with."; - if (topic == "tiers") - { - return "A session reads by default. The client's configuration starts it with -mcp-allow: to allow more, " - "comma-separated:\n" - " write change files: movie_render, ui_input, ui_act, tutorial_run, and commands, dialog " - "buttons and menu rows that change files\n" - " capture pictures of the screen and of the user's media: screenshot, record_*, tutorial_run\n" - " network work that reaches the network: update checks, crash reports, map tiles\n" - " dev the developer's tools: run_tests, validate_translations, generate_docs, " - "duplicate_report\n" - " launch opening another program, a folder or a web page on the user's desktop: the help, a " - "file's folder, a map, Open with. Without it, each is skipped and logged.\n" - "-mcp-ui:offscreen or visible makes the window at once, out of sight or on the desktop; a " - "recording needs it visible. -profile: keeps settings and the index apart from the user's, " - "and -collection: makes one folder the whole collection. status says what this session " - "was started with."; - } - - return std::string(instructions) + "\n\nTopics: search, dfv, dft, tiers."; + // A task that is analyzing or running. + bool task_running(const app_frame& app) + { + return app._view && app._view->progress().active; } - std::string_view presence_name(const agent_presence p) + // A task whose review is still being worked out, which its run waits for. + bool task_reviewing(const app_frame& app) { - switch (p) - { - case agent_presence::offscreen: return "offscreen"; - case agent_presence::visible: return "visible"; - case agent_presence::none: break; - } - return "none"; + return app._view && app._view->reviewing(); } - std::string_view view_name(const view_type v) + struct command_rule { - switch (v) + ui::agent_tier need = ui::agent_tier::read; + std::string_view why; + }; + + // What a command needs of the session beyond reading: one that changes files, the clipboard or the system needs + // write; one that opens another program, a folder or a web page on the user's desktop needs launch; one that ends + // the session is not run. One that opens a menu needs nothing: what is chosen from it needs what its own command + // needs. + command_rule rule_of(const commands id) + { + using enum ui::agent_tier; + constexpr std::string_view changes = "changes files, the clipboard or the system"; + constexpr std::string_view opens = "opens another program, a folder or a web page on the user's desktop"; + + switch (id) { - case view_type::items: return "items"; - case view_type::media: return "media"; - case view_type::edit: return "edit"; - case view_type::movie: return "movie"; - case view_type::rename: return "rename"; - case view_type::batch: return "batch"; - case view_type::import: return "import"; - case view_type::sync: return "sync"; - case view_type::locate: return "locate"; - case view_type::tags: return "tags"; - case view_type::explore: return "explore"; - case view_type::faces: return "faces"; - case view_type::options: return "options"; - case view_type::none: break; + case commands::exit: return {refused, "ends the session: close the session's input instead"}; + case commands::tool_scan: return {refused, "works a scanner through the system's own windows"}; +#ifndef DIFFRACTOR_PACKAGE_UPDATES + case commands::info_new_version: return {refused, "installs another version of Diffractor"}; + case commands::info_check_for_updates: return {network, "asks diffractor.com for a newer version"}; +#endif + + case commands::browse_open_containingfolder: + case commands::browse_open_googlemap: + case commands::browse_open_in_file_browser: + case commands::options_help: + case commands::tool_open_with: + case commands::view_help: return {launch, opens}; + + case commands::edit_copy: + case commands::edit_copy_item_path: + case commands::edit_cut: + case commands::edit_item_save: + case commands::edit_item_save_and_next: + case commands::edit_item_save_and_prev: + case commands::edit_item_save_as: + case commands::edit_paste: + case commands::import_run: + case commands::label_approved: + case commands::label_none: + case commands::label_review: + case commands::label_second: + case commands::label_select: + case commands::label_to_do: + case commands::locate_run: + case commands::print: + case commands::rate_1: + case commands::rate_2: + case commands::rate_3: + case commands::rate_4: + case commands::rate_5: + case commands::rate_none: + case commands::rate_rejected: + case commands::sync_run: + case commands::tags_run: + case commands::tool_burn: + case commands::tool_copy_to_folder: + case commands::tool_delete: + case commands::tool_desktop_background: + case commands::tool_edit_description: + case commands::tool_eject: + case commands::tool_file_properties: + case commands::tool_move_to_folder: + case commands::tool_movie_render: + case commands::tool_movie_save: + case commands::tool_new_folder: + case commands::tool_rotate_anticlockwise: + case commands::tool_rotate_clockwise: + case commands::tool_rotate_reset: + case commands::tool_run: + case commands::tool_save_current_video_frame: + case commands::tool_share: return {write, changes}; + + // docs/faces.md#6-the-face-book: what the user tells Diffractor about faces is theirs, as their files are. + case commands::face_confirm: + case commands::face_hide: + case commands::face_import: + case commands::face_name: + case commands::face_name_picture: + case commands::face_reject: + case commands::face_rename_person: + case commands::face_undo_placement: + case commands::face_show_again: return {write, "changes the user's face book"}; + case commands::face_export: + case commands::face_save_names: return {write, changes}; + + default: return {}; } - return "none"; } - // A task that is analyzing or running. - bool task_running(const app_frame& app) + std::optional command_of(const ui::command_ptr& c) { - return app._view && app._view->progress().active; + if (!c) return {}; + if (const auto* const id = std::any_cast(&c->opaque)) return *id; + return {}; } - // A task whose review is still being worked out, which its run waits for. - bool task_reviewing(const app_frame& app) + std::string_view area_name(const keyboard_area area) { - return app._view && app._view->reviewing(); + switch (area) + { + case keyboard_area::sidebar: return "sidebar"; + case keyboard_area::listing: return "listing"; + case keyboard_area::media: return "media"; + case keyboard_area::panel: return "panel"; + case keyboard_area::view: break; + } + + return "view"; } } std::string_view agent_view_name(const view_type v) { - return view_name(v); + switch (v) + { + case view_type::items: return "items"; + case view_type::media: return "media"; + case view_type::edit: return "edit"; + case view_type::movie: return "movie"; + case view_type::rename: return "rename"; + case view_type::batch: return "batch"; + case view_type::import: return "import"; + case view_type::sync: return "sync"; + case view_type::locate: return "locate"; + case view_type::tags: return "tags"; + case view_type::explore: return "explore"; + case view_type::faces: return "faces"; + case view_type::options: return "options"; + case view_type::none: break; + } + return "none"; } -bool agent_window_settled(const app_frame& app) +bool agent_window_caught_up(const app_frame& app) { - if (!app._window_started) return true; - const auto& index = app._item_index; - return index.is_init_complete() && index.scanning_items == 0 && index.searching == 0 && index.indexing == 0 && - index.thumbnailing_items == 0 && df::loading_media == 0 && app._invalids.load() == view_invalid::none && - !app._tutorial && !task_running(app) && !task_reviewing(app) && dialogs_showing_work().empty() && - !platform::system_prompt_shown(); + return app._invalids.load() == view_invalid::none && !task_reviewing(app); } std::vector agent_window_busy(const app_frame& app) @@ -243,1105 +295,369 @@ std::vector agent_window_busy(const app_frame& app) } if (task_reviewing(app)) busy.emplace_back("working out the review"); - for (auto& work : dialogs_showing_work()) busy.push_back(std::move(work)); - // Something Windows asks while a call into it waits, which ui_state shows and dialog_respond answers. - if (platform::system_prompt_shown()) busy.emplace_back("waiting on a dialog Windows shows"); - return busy; } -agent_options parse_agent_options(const std::string_view ui, const std::string_view allow) -{ - agent_options result; - - if (ui.empty() || ui == "none") result.presence = agent_presence::none; - else if (ui == "offscreen") result.presence = agent_presence::offscreen; - else if (ui == "visible") result.presence = agent_presence::visible; - else result.problems.emplace_back(std::format("-mcp-ui:{} is not none, offscreen or visible", ui)); - - for (const auto part : core::split(allow, false, [](const char c) { return c == ','; })) - { - const auto tier = core::trim(part); - if (tier.empty()) continue; - if (tier == "write") result.allow.write = true; - else if (tier == "capture") result.allow.capture = true; - else if (tier == "network") result.allow.network = true; - else if (tier == "dev") result.allow.dev = true; - else if (tier == "launch") result.allow.launch = true; - else - result.problems.emplace_back( - std::format("-mcp-allow:{} is not write, capture, network, dev or launch", tier)); - } - - return result; -} - -agent_job::agent_job(std::string id, std::string tool) : - _id(std::move(id)), _tool(std::move(tool)), _started(core::now()) -{ -} - -void agent_job::progress(const double fraction, const std::string_view message) -{ - std::lock_guard lock(_mutex); - _fraction = fraction; - if (!message.empty()) _message = message; -} - -void agent_job::output(const std::string_view line) +ui::agent_command agent_command_of(const app_frame& app, const commands id) { - std::lock_guard lock(_mutex); - if (_output_bytes > kept_output_bytes) return; - _lines.emplace_back(line); - _output_bytes += line.size() + 1; - if (_output_bytes > kept_output_bytes) _lines.emplace_back("(the rest of the output is not kept)"); + const auto rule = rule_of(id); + // Exit stays the watching user's way to close the window: the session's own tools refuse it. + return {.name = std::string(command_name(id)), + .command = app.find_command(id), + .need = rule.need, + .why = std::string(rule.why), + .user_may_run = id == commands::exit}; } -void agent_job::complete(core::mcp::tool_result result) -{ - std::lock_guard lock(_mutex); - if (_done) return; - _done = true; - _result = std::move(result); - _cancel = {}; -} +/////////////////////////////////////////////////////////////////////////////////////////////////// +// What the host asks of Diffractor +/////////////////////////////////////////////////////////////////////////////////////////////////// -void agent_job::on_cancel(std::function cancel) +core::mcp::server_info diffractor_agent::agent_info() { - std::lock_guard lock(_mutex); - if (!_done) _cancel = std::move(cancel); + return {.name = "Diffractor", .version = df::format_version(true), .instructions = std::string(instructions)}; } -void agent_job::cancel() +ui::frame_ptr diffractor_agent::agent_window() { - std::function cancel; - { - std::lock_guard lock(_mutex); - if (_done || _cancelled) return; - _cancelled = true; - cancel = _cancel; - } - - if (cancel) cancel(); - else complete(core::mcp::tool_result::error(std::format("{} was cancelled", _tool))); + return _app._window_started ? _app._app_frame : nullptr; } -bool agent_job::is_done() const +ui::frame_host* diffractor_agent::agent_window_host() { - std::lock_guard lock(_mutex); - return _done; + return &_app; } -core::mcp::tool_result agent_job::result() const +bool diffractor_agent::make_agent_window(std::string& why) { - std::lock_guard lock(_mutex); - return _result; + if (!_app.start_window(why)) return false; + // The platform shows the windows init made; this one comes later, and out of sight, so it is shown here. + _app._app_frame->show(true); + return true; } -double agent_job::fraction() const +std::vector> diffractor_agent::agent_help() { - std::lock_guard lock(_mutex); - return _fraction; + return {{"search", search_help()}, + {"dfv", std::string(dfv_help)}, + {"dft", std::string(dft_help)}, + {"tiers", std::string(tiers_help)}}; } -std::string agent_job::message() const +std::vector diffractor_agent::agent_commands() { - std::lock_guard lock(_mutex); - return _message; -} + std::vector result; + if (_app._commands.empty()) return result; -std::string agent_job::recent_output(const size_t lines) const -{ - std::lock_guard lock(_mutex); - std::string result; - const auto first = _lines.size() > lines ? _lines.size() - lines : 0; + const auto& ids = all_commands(); + result.reserve(ids.size()); - for (auto i = first; i < _lines.size(); ++i) + for (const auto id : ids) { - result += _lines[i]; - result += '\n'; + auto c = agent_command_of(_app, id); + if (c.command) result.push_back(std::move(c)); } return result; } -std::string agent_job::all_output() const +void diffractor_agent::agent_run(const ui::agent_command& c) { - return recent_output(SIZE_MAX); + if (const auto id = command_of(c.command)) _app.invoke(*id); + else ui::agent_app::agent_run(c); } -double agent_job::seconds() const +void diffractor_agent::agent_open_menu(const ui::command_ptr& c) { - return core::now() - _started; + const auto& view = _app._view_frame; + if (!c || !c->menu || !view) return; + const auto middle = view->frame()->client_to_screen(view->_view_bounds.center()); + _app.track_menu(view->frame(), recti(middle, sizei{}), c->menu()); } -mcp_host::mcp_host(app_frame& app, agent_options options, const bool console) : - _app(app), _options(std::move(options)), _console(console) +std::vector diffractor_agent::agent_busy() { - _server = std::make_shared(core::mcp::server_info{ - .name = "Diffractor", - .version = df::format_version(true), - .instructions = std::string(instructions), - }); - - if (!_console) core::set_log_observer(&observe_log); - // Another program, a folder or a web page would open on the user's desktop, beyond the session. - platform::allow_agent_to_open(_options.allow.launch); - - add_session_tools(*this); - add_engine_tools(*this); - add_library_tools(*this); - add_ui_tools(*this); + return agent_window_busy(_app); } -void mcp_host::add(core::mcp::tool tool, const tool_tier tier, const bool needs_window) +bool diffractor_agent::agent_caught_up() { - const auto& allow = _options.allow; - const auto allowed = tier == tool_tier::read || (tier == tool_tier::write && allow.write) || - (tier == tool_tier::capture && allow.capture) || (tier == tool_tier::dev && allow.dev); - - if (!allowed) - { - const auto* const needs = tier == tool_tier::write ? "write" : tier == tool_tier::capture ? "capture" : "dev"; - _withheld.emplace_back(tool.name, std::format("-mcp-allow:{}", needs)); - return; - } - - _schemas[tool.name] = tool.input_schema; - auto handler = std::move(tool.handler); - - tool.handler = [this, handler, needs_window, name = tool.name](const core::mcp::call_ptr& call) - { - if (needs_window) - { - if (_console) - { - call->finish(core::mcp::tool_result::error( - std::format("{} works in a session, with the window: start Diffractor with -mcp", name))); - return; - } - - std::string why; - - if (!ensure_window(why)) - { - call->finish(core::mcp::tool_result::error(why)); - return; - } - } - - handler(call); - }; - - _server->add_tool(std::move(tool)); + return agent_window_caught_up(_app); } -std::string mcp_host::input_schema(const std::string_view tool) const +void diffractor_agent::agent_update() { - const auto found = _schemas.find(std::string(tool)); - return found == _schemas.end() ? std::string{} : found->second; + _app.update_button_state(false); } -bool mcp_host::ensure_window(std::string& why) +std::string diffractor_agent::agent_status(core::json::writer& json) { - if (!_app._window_started) - { - if (_console) - { - why = "This needs a session, with the window: start Diffractor with -mcp"; - return false; - } + const auto& index = _app._item_index; + const auto started = _app._window_started; - core::log(__FUNCTION__, "A tool needs the window: making it"); + json.text("profile", command_line.profile_folder.empty() ? "the user's own" : command_line.profile_folder); + json.text("cache_folder", app_cache_folder().text().sv()); + json.key("collection").array(); + for (const auto& folder : index_folders(setting.collection).folders) json.text(folder.text().sv()); + json.end_array(); + json.boolean("settings_saved", false); - if (!_app.start_window(why)) - { - if (why.empty()) why = "The window could not be made"; - return false; - } - - // The platform shows the windows init made; this one comes later, and out of sight, so it is shown here. - _app._app_frame->show(true); - track_command_use(_app); - } - - return true; -} + json.key("index").object(); + json.boolean("started", started); + json.boolean("ready", started && index.is_init_complete()); + json.integer("items", static_cast(index.stats.index_item_count)); + json.integer("folders", static_cast(index.stats.index_folder_count)); + json.key("busy").array(); + for (const auto& b : agent_window_busy(_app)) json.text(b); + json.end_array(); + json.end_object(); -bool mcp_host::modal_ui_open() const -{ - return (_app._app_frame && !_app._app_frame->is_enabled()) || ui::menu_active > 0 || !open_dialogs().empty(); + if (!started) return "index not loaded until a tool needs it"; + return index.is_init_complete() ? std::format("index ready, {} items", index.stats.index_item_count) + : "index loading"s; } -bool mcp_host::answerable_ui_open() const +void diffractor_agent::agent_window_status(core::json::writer& json) { - return ui::menu_active > 0 || dialog_awaits_answer(); + json.text("view", agent_view_name(_app._state.view_mode())); + json.text("search", _app._state.search().text()); } -agent_job_ptr mcp_host::start_job(const std::string_view tool) +std::string diffractor_agent::agent_view(core::json::writer& json, const size_t listed) { - std::lock_guard lock(_jobs_mutex); - auto job = std::make_shared(std::format("job-{}", _next_job++), std::string(tool)); - _jobs.emplace(job->id(), job); - - // Finished jobs are kept for a while, for a job_wait that comes late; the oldest go first. - constexpr size_t kept_jobs = 64; - - while (_jobs.size() > kept_jobs) - { - const auto oldest = std::ranges::find_if(_jobs, [](const auto& entry) { return entry.second->is_done(); }); - if (oldest == _jobs.end()) break; - _jobs.erase(oldest); - } - - return job; + write_agent_view(json, _app, listed); + json.boolean("acting", _app._tutorial != nullptr); + if (_app._recording) json.key("recording").object().number("seconds", _app._recording->elapsed()).end_object(); + return agent_view_text(_app, listed); } -agent_job_ptr mcp_host::find_job(const std::string_view id) const +std::vector> diffractor_agent::agent_facts() { - std::lock_guard lock(_jobs_mutex); - const auto found = _jobs.find(id); - return found == _jobs.end() ? nullptr : found->second; -} - -std::vector mcp_host::jobs() const -{ - std::lock_guard lock(_jobs_mutex); - std::vector result; - for (const auto& [id, job] : _jobs) result.push_back(job); + std::vector> result; + for (const auto& [name, value] : calc_app_info(_app._item_index, true)) result.emplace_back(name, value); return result; } -double mcp_host::wait_seconds(const core::mcp::call& call) +std::vector> diffractor_agent::agent_counters() { - const auto asked = call.number("wait_s"); - if (!asked) return default_wait_seconds; - return std::clamp(*asked, 0.0, longest_wait_seconds); -} - -void mcp_host::wait(const core::mcp::call_ptr& call, const agent_job_ptr& job, const double wait_s, - const bool interruptible) -{ - if (job->is_done()) + const auto& q = df::query_perf; + const auto& f = df::file_perf; + const auto& d = df::db_perf; + const auto& th = df::thumbnail_perf; + const auto count = [](const uint64_t n) { - call->finish(job->result()); - return; - } - - waiter w; - w.call = call; - w.job = job; - w.deadline = core::now() + wait_s; - w.interruptible = interruptible; - _waiters.push_back(std::move(w)); - - // A single call from the command line has no frame ticks of its own: it is answered here. - if (_console) - { - while (!call->is_finished()) - { - platform::pump_ui_tasks(20); - tick(); - } - } -} - -void mcp_host::when(std::function ready, const double quiet_seconds, const double timeout_seconds, - std::function then) -{ - _conditions.push_back({std::move(ready), std::move(then), quiet_seconds, -1.0, core::now() + timeout_seconds}); -} - -void mcp_host::wait_until(const core::mcp::call_ptr& call, const std::string_view tool, std::function settled, - const double quiet_seconds, const double timeout_seconds, - std::function answer) -{ - const auto job = start_job(tool); - when(std::move(settled), quiet_seconds, timeout_seconds, - [job, answer = std::move(answer)](const bool met) { job->complete(answer(met)); }); - wait(call, job, timeout_seconds + 1.0, false); -} - -void mcp_host::release(waiter& w, const std::string_view why) -{ - const auto& job = w.job; - const auto dialog = why == "dialog"; - const auto fraction = job->fraction(); - const auto recent = job->recent_output(12); - - json_writer json; - json.object(); - json.text("job", job->id()); - json.text("state", dialog ? "waiting_for_dialog" : "running"); - if (fraction >= 0.0) json.number("progress", fraction); - json.text("message", job->message()); - json.number("seconds", job->seconds()); - if (dialog) - { - json.key("dialogs").raw(describe_dialogs_json(_app)); - json.key("menu").raw(describe_menu_json()); - } - json.end_object(); - - auto text = dialog ? std::format("{} is waiting on a dialog or menu that opened. Answer a dialog with " - "dialog_respond or a menu with menu_respond, then job_wait for {}.{}{}", - job->tool(), job->id(), describe_dialogs_text(_app), describe_menu_text()) - : std::format("{} is still running after {:.0f} s. job_wait waits for {}; job_cancel stops it.", - job->tool(), job->seconds(), job->id()); - if (!recent.empty()) text += "\n\nLatest output:\n" + recent; + return static_cast(n); + }; - w.call->finish(structured_result(std::move(text), json.str())); + return { + {"queries", count(q.queries.load())}, + {"query_ms", count(q.query_us.load() / 1000)}, + {"query_max_ms", count(q.query_max_us.load() / 1000)}, + {"file_scans", count(f.scans.load())}, + {"file_loads", count(f.loads.load())}, + {"file_load_max_ms", count(f.load_max_us.load() / 1000)}, + {"decodes", count(f.decodes.load())}, + {"metadata_errors", count(f.metadata_errors.load())}, + {"db_items_written", count(d.items_written.load())}, + {"db_thumbs_written", count(d.thumbs_written.load())}, + {"thumbnail_plans", count(th.plans.load())}, + {"thumbnail_load_failures", count(th.load_failures.load())}, + }; } -void mcp_host::tick() +void diffractor_agent::agent_targets(ui::agent_walk& walk) { - const auto now = core::now(); + auto& app = _app; - // A condition is met once it has held for its quiet time, or given up on at its limit. What follows runs once the - // list is settled, since it may add to it. - std::vector, bool>> due; - - for (auto i = _conditions.begin(); i != _conditions.end();) + // The bars' controls, the boxes and the slider each called by what it is for. + const auto walk_bar = [&app, &walk](const std::shared_ptr& bar, const std::string_view scope) { - auto& c = *i; + if (!bar || !app._show_bars) return; + const ui::agent_region region{.scope = std::string(scope), .frame = bar->frame()}; - if (c.ready()) - { - if (c.since < 0.0) c.since = now; - } - else + for (const auto& c : bar->_controls) { - c.since = -1.0; + const auto* const name = c == app._search_edit ? "address" + : c == app._filter_edit ? "filter" + : c == app._item_size ? "item size" + : c == app._face_filter_edit ? "people filter" + : c == app._face_size ? "face size" + : ""; + walk.control(region, c, name); } + }; - const auto met = c.since >= 0.0 && now - c.since >= c.quiet_seconds; - - if (met || now >= c.deadline) - { - due.emplace_back(std::move(c.then), met); - i = _conditions.erase(i); - continue; - } + walk_bar(app._title_bar, "title"); - ++i; + // The logo beside the title, which opens the help. + if (app._show_bars && app._app_logo && !app._title_bounds.is_empty()) + { + ui::agent_target logo; + logo.kind = "link"; + logo.label = "logo"; + logo.bounds = app._title_bounds; + logo.command = app.find_command(commands::view_help); + walk.target({.scope = "title", .frame = app._title_bar->frame()}, std::move(logo)); } - for (const auto& [then, met] : due) then(met); - - // A waiting call is answered with what it waits behind only once there is something to answer: a dialog that shows, - // or a menu. Work holding the window for a moment, a rating written say, is waited out. - const auto modal = answerable_ui_open(); - - for (auto i = _waiters.begin(); i != _waiters.end();) + if (const auto& view = app._view_frame) { - auto& w = *i; - - if (w.call->is_cancelled() || w.call->is_finished()) + for (auto& region : view->keyboard_regions()) { - if (w.call->is_cancelled()) w.job->cancel(); - i = _waiters.erase(i); - continue; - } - - if (w.job->is_done()) - { - w.call->finish(w.job->result()); - i = _waiters.erase(i); - continue; - } - - const auto fraction = w.job->fraction(); - const auto message = w.job->message(); + const auto area = region.area; + const ui::agent_region walked{.scope = std::string(area_name(area)), + .frame = view->frame(), + .visible = region.clip, + .reveal = region.reveal, + .focus = + [view, area](const ui::element_ptr& e, const int part, const recti bounds) + { + const keyboard_part focused{e, part, bounds}; + view->keyboard_to(area, &focused); + }}; - if (fraction != w.last_fraction || message != w.last_message) - { - w.last_fraction = fraction; - w.last_message = message; - // Progress must rise with each notification: a fraction where there is one, otherwise the seconds spent. - if (fraction >= 0.0) w.call->progress(fraction * 100.0, 100.0, message); - else w.call->progress(w.job->seconds(), 0.0, message); + for (const auto& root : region.roots) walk.elements(walked, root, region.offset); } - if (w.interruptible && modal) + if (!view->_view_bounds.is_empty()) { - release(w, "dialog"); - i = _waiters.erase(i); - continue; + ui::agent_target content; + content.kind = "content"; + content.label = agent_view_name(app._state.view_mode()); + content.bounds = view->_view_bounds; + content.focus = [&app] + { + app.focus_view(); + }; + walk.target({.scope = "view", .frame = view->frame()}, std::move(content)); } - if (now >= w.deadline) + if (view->_strip->is_visible() && app._selector_frame && !app._selector_frame->_view_bounds.is_empty()) { - release(w, "deadline"); - i = _waiters.erase(i); - continue; + ui::agent_target strip; + strip.kind = "content"; + strip.label = "strip"; + strip.bounds = app._selector_frame->_view_bounds; + walk.target({.scope = "strip", .frame = app._selector_frame->frame()}, std::move(strip)); } - - ++i; } + + walk_bar(app._status_bar, "status"); } -void mcp_host::run_child( - const core::mcp::call_ptr& call, const std::string_view tool, std::vector arguments, - std::function answer) +bool diffractor_agent::agent_describe(const ui::element_ptr& e, ui::agent_element& description) { - const auto job = start_job(tool); - const auto out = std::make_shared(); - const auto tests = std::make_shared>(0, 0); - - platform::child_process_callbacks callbacks; - - callbacks.on_stdout_line = [out, job, tests](const std::string_view line) - { - *out += line; - *out += '\n'; - - // A test run says how many tests it runs, then one line a test. - if (line.starts_with("Running ") && line.ends_with(" tests...")) - { - tests->first = parse_int(line.substr(8)); - } - else if ((line.starts_with(" PASS") || line.starts_with(" FAIL")) && tests->first > 0) - { - ++tests->second; - job->progress(static_cast(tests->second) / tests->first, - std::format("{} of {} tests", tests->second, tests->first)); - } - }; - - callbacks.on_stderr_line = [job](const std::string_view line) - { - job->output(line); - - // A render says how far it has got as a percentage. - if (const auto percent = line.find('%'); percent != std::string_view::npos && percent > 0) - { - auto digits = percent; - while (digits > 0 && line[digits - 1] >= '0' && line[digits - 1] <= '9') --digits; - if (digits < percent) - job->progress(parse_int(line.substr(digits, percent - digits)) / 100.0, core::trim(line)); - } - }; + auto known = true; - callbacks.on_exit = [out, job, answer](const int exit_code) + if (const auto* const title = dynamic_cast(e.get())) { - job->complete(answer ? answer(exit_code, *out, *job) : core::mcp::tool_result::error("No answer")); - }; - - const auto exe = platform::running_app_path(); - auto child = platform::spawn_child_process(exe, arguments, {}, std::move(callbacks)); - - if (!child) - { - job->complete(core::mcp::tool_result::error(std::format("{} could not start a copy of Diffractor", tool))); - call->finish(job->result()); - return; + description.title = title->text(); } - - core::log(__FUNCTION__, std::format("{} runs as {}", tool, job->id())); - - const std::shared_ptr running(std::move(child)); - job->on_cancel([running, job] + else if (const auto* const title2 = dynamic_cast(e.get())) { - running->terminate(); - job->complete(core::mcp::tool_result::error(std::format("{} was cancelled", job->tool()))); - }); - - // The process lives as long as the job: its callbacks belong to it. - std::erase_if(_children, [](const auto& c) { return c.first->is_done(); }); - _children.emplace_back(job, running); - - wait(call, job, wait_seconds(*call), false); -} - -void mcp_host::started() -{ - if (_console) return; - - for (const auto& problem : _options.problems) core::log(__FUNCTION__, problem); - core::log(__FUNCTION__, - std::format("Agent session: window {}, allowing {}{}{}{}{}", presence_name(_options.presence), - _options.allow.write ? "write " : "", _options.allow.capture ? "capture " : "", - _options.allow.network ? "network " : "", _options.allow.dev ? "dev " : "", - _options.allow.launch ? "launch" : "")); - if (_app._window_started) track_command_use(_app); -} - -uint64_t mcp_host::log_mark() const -{ - auto& r = ring(); - std::lock_guard lock(r.mutex); - return r.next; -} - -std::vector mcp_host::log_since(const uint64_t mark, const size_t most) const -{ - auto& r = ring(); - std::lock_guard lock(r.mutex); - std::vector result; - - for (const auto& [number, line] : r.lines) - if (number >= mark) result.push_back(line); - - if (result.size() > most) result.erase(result.begin(), result.end() - static_cast(most)); - return result; -} - -/////////////////////////////////////////////////////////////////////////////////////////////////// -// The session's own tools -/////////////////////////////////////////////////////////////////////////////////////////////////// - -namespace -{ - void add_status(mcp_host& host) + description.title = title2->title(); + description.text = title2->details(); + } + else if (const auto* const busy = dynamic_cast(e.get())) { - core::mcp::tool t; - t.name = "status"; - t.title = "Session status"; - t.description = "What this session is: Diffractor's version, the profile and collection it uses, where its " - "window is and what it shows, how the index stands, what the session may do and the tools it " - "withholds, and its jobs. Start here."; - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto& options = host.options(); - const auto& index = app._item_index; - - json_writer json; - json.object(); - json.text("version", df::format_version(true)); -#ifdef _DEBUG - json.text("build", "debug"); -#else - json.text("build", "release"); -#endif - json.text("platform", platform::OS()); - json.text("profile", command_line.profile_folder.empty() ? "the user's own" : command_line.profile_folder); - json.text("cache_folder", app_cache_folder().text().sv()); - json.key("collection").array(); - for (const auto& folder : index_folders(setting.collection).folders) json.text(folder.text().sv()); - json.end_array(); - json.boolean("settings_saved", false); - - json.key("window").object(); - json.text("presence", presence_name(options.presence)); - json.boolean("made", app._window_started); - - if (app._window_started && app._app_frame) - { - const auto bounds = app._app_frame->window_bounds(); - json.integer("width", bounds.width()); - json.integer("height", bounds.height()); - json.text("view", view_name(app._state.view_mode())); - json.text("search", app._state.search().text()); - } - - json.end_object(); - - json.key("index").object(); - json.boolean("started", app._window_started); - json.boolean("ready", app._window_started && index.is_init_complete()); - json.integer("items", static_cast(index.stats.index_item_count)); - json.integer("folders", static_cast(index.stats.index_folder_count)); - json.key("busy").array(); - for (const auto& b : agent_window_busy(app)) json.text(b); - json.end_array(); - json.end_object(); - - json.key("allow").object(); - json.boolean("write", options.allow.write); - json.boolean("capture", options.allow.capture); - json.boolean("network", options.allow.network); - json.boolean("dev", options.allow.dev); - json.boolean("launch", options.allow.launch); - json.end_object(); - - json.key("withheld").array(); - - for (const auto& [name, needs] : host.withheld()) - { - json.object().text("tool", name).text("needs", needs).end_object(); - } - - json.end_array(); - json.key("jobs").array(); - - for (const auto& job : host.jobs()) - { - json.object().text("job", job->id()).text("tool", job->tool()); - json.text("state", job->is_done() ? "done" : "running").end_object(); - } - - json.end_array(); - json.key("problems").array(); - for (const auto& problem : options.problems) json.text(problem); - json.end_array(); - json.end_object(); - - const auto summary = std::format("Diffractor {} - window {}{}; index {}; {} tools withheld", - df::format_version(true), presence_name(options.presence), - app._window_started ? " (made)" : " (not made yet)", - !app._window_started ? "not loaded until a tool needs it" - : index.is_init_complete() - ? std::format("ready, {} items", index.stats.index_item_count) - : "loading"s, - host.withheld().size()); - call->finish(structured_result(summary, json.str())); - }; - host.add(std::move(t), tool_tier::read, false); + description.text = busy->text(); } - - void add_help(mcp_host& host) + else if (const auto* const labelled = dynamic_cast(e.get())) { - core::mcp::tool t; - t.name = "help"; - t.title = "How to use Diffractor's tools"; - t.description = "Guidance: overview (the default), search (the query language), dfv (the Movie project " - "format), dft (tutorial scripts, and ui_input's steps), tiers (what -mcp-allow allows)."; - t.input_schema = - R"({"type":"object","properties":{"topic":{"type":"string","enum":["overview","search","dfv","dft","tiers"]}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [](const core::mcp::call_ptr& call) - { - call->finish(core::mcp::tool_result::text(help_text(call->text("topic", "overview")))); - }; - host.add(std::move(t), tool_tier::read, false); + description.label = labelled->label(); } - - void add_wait_until_idle(mcp_host& host) + else if (const auto* const row = dynamic_cast(e.get())) { - core::mcp::tool t; - t.name = "wait_until_idle"; - t.title = "Wait until Diffractor is idle"; - t.description = - "Waits until the index has loaded and nothing is scanning, searching, indexing, making " - "thumbnails, loading media, acting out steps, running a task - a Sync or Import analyzing " - "or running, say - or showing work under way, an edit being saved, and the window has caught " - "up - quiet for quiet_ms - or until timeout_s. Says what is still busy if it gives up. A dialog " - "Windows shows ends the wait at once, since nothing settles until it is answered: ui_state shows " - "it and dialog_respond answers it. Before a screenshot, or after starting work whose effects you " - "want to read."; - t.input_schema = - R"({"type":"object","properties":{"timeout_s":{"type":"number","minimum":0,"maximum":600},"quiet_ms":{"type":"integer","minimum":0,"maximum":10000}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto timeout = call->number("timeout_s").value_or(60.0); - const auto quiet = call->number("quiet_ms").value_or(500.0) / 1000.0; - const auto started = core::now(); - - host.wait_until(call, "wait_until_idle", - [&app] { return agent_window_settled(app) || platform::system_prompt_shown(); }, quiet, - timeout, [&app, started](const bool met) - { - const auto asking = platform::system_prompt_shown(); - const auto settled = met && !asking; - json_writer json; - json.object().boolean("idle", settled).number("waited_s", core::now() - started); - json.key("busy").array(); - const auto busy = agent_window_busy(app); - for (const auto& b : busy) json.text(b); - json.end_array(); - if (asking) json.key("dialogs").raw(describe_dialogs_json(app)); - json.end_object(); - const auto text = settled ? std::format("Idle after {:.1f} s", core::now() - started) - : asking - ? std::format("Waiting on a dialog Windows shows, after {:.1f} s: dialog_respond " - "answers it.{}", - core::now() - started, describe_dialogs_text(app)) - : std::format("Still busy after {:.1f} s: {}", core::now() - started, - join_text(busy, ", ")); - return structured_result(text, json.str()); - }); - }; - host.add(std::move(t), tool_tier::read, false); + description.label = row->row_label(); } - - void add_diagnostics(mcp_host& host) + else if (const auto list = std::dynamic_pointer_cast(e)) { - core::mcp::tool t; - t.name = "diagnostics"; - t.title = "Diagnostics"; - t.description = "What Diffractor knows of itself: the version, the system and graphics, memory, the " - "index's counts and timings, what is running, and the session's performance counters - " - "queries, the database, files, thumbnails and painting - since it started. Ask before and " - "after an action to see what it cost."; - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + // A list a search fills - Copy to folder's folders, the people naming a face offers - each row chosen as a + // click chooses it. + for (const auto& r : list->_results) { - auto& app = host.app(); - json_writer json; - json.object(); - json.key("app").object(); - std::string text; - - for (const auto& [name, value] : calc_app_info(app._item_index, true)) - { - auto key = core::trim(name); - if (key.ends_with(':')) key.remove_suffix(1); - json.text(core::trim(key), value); - text += std::format("{} {}\n", name, value); - } - - json.end_object(); - - const auto& q = df::query_perf; - const auto& f = df::file_perf; - const auto& d = df::db_perf; - const auto& th = df::thumbnail_perf; - const auto& ui = render::ui_perf; - - json.key("counters").object(); - json.integer("queries", static_cast(q.queries.load())); - json.integer("query_ms", static_cast(q.query_us.load() / 1000)); - json.integer("query_max_ms", static_cast(q.query_max_us.load() / 1000)); - json.integer("file_scans", static_cast(f.scans.load())); - json.integer("file_loads", static_cast(f.loads.load())); - json.integer("file_load_max_ms", static_cast(f.load_max_us.load() / 1000)); - json.integer("decodes", static_cast(f.decodes.load())); - json.integer("metadata_errors", static_cast(f.metadata_errors.load())); - json.integer("db_items_written", static_cast(d.items_written.load())); - json.integer("db_thumbs_written", static_cast(d.thumbs_written.load())); - json.integer("thumbnail_plans", static_cast(th.plans.load())); - json.integer("thumbnail_load_failures", static_cast(th.load_failures.load())); - json.integer("paints", static_cast(ui.paints.load())); - json.integer("paint_ms", static_cast(ui.paint_us.load() / 1000)); - json.integer("paint_max_ms", static_cast(ui.paint_max_us.load() / 1000)); - json.integer("frame_prepares", static_cast(ui.frame_prepares.load())); - json.integer("invalidates", static_cast(ui.invalidates.load())); - json.end_object(); - json.end_object(); - - call->finish(structured_result(text, json.str())); - }; - host.add(std::move(t), tool_tier::read, false); + if (!r) continue; + const auto selected = list->_completes && list->_completes->selected() == r; + description.rows.push_back({r->edit_text(), selected, + [list, r] { list->selected(r, ui::complete_strategy_t::select_type::click); }}); + } } - - void add_log_read(mcp_host& host) + else if (const auto link = std::dynamic_pointer_cast(e)) { - core::mcp::tool t; - t.name = "log_read"; - t.title = "Read the log"; - t.description = "The latest lines Diffractor wrote to its log - most, 200 by default - optionally only those " - "containing some text, or only those since a mark an earlier call returned. Returns a mark " - "to read on from."; - t.input_schema = - R"({"type":"object","properties":{"lines":{"type":"integer","minimum":1,"maximum":4000},"contains":{"type":"string"},"since":{"type":"integer","minimum":0}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - const auto most = static_cast(call->number("lines").value_or(200)); - const auto since = static_cast(call->number("since").value_or(0)); - const auto contains = call->text("contains"); - const auto mark = host.log_mark(); - auto lines = host.log_since(since, kept_log_lines); - - if (!contains.empty()) - { - std::erase_if(lines, [&contains](const std::string& l) - { return core::ifind(l, contains) == std::string::npos; }); - } - - if (lines.size() > most) lines.erase(lines.begin(), lines.end() - static_cast(most)); - - json_writer json; - json.object() - .integer("mark", static_cast(mark)) - .integer("lines", static_cast(lines.size())); - json.end_object(); - - auto text = join_text(lines, "\n"); - if (text.empty()) text = "(no lines)"; - call->finish(structured_result(std::format("{}\n\nmark {}", text, mark), json.str())); - }; - host.add(std::move(t), tool_tier::read, false); + description.command = link->command(); } - - void add_jobs(mcp_host& host) + else { - core::mcp::tool w; - w.name = "job_wait"; - w.title = "Wait for a job"; - w.description = "Waits up to wait_s seconds for a job a tool started, and answers with its result once it " - "has finished, or with how far it has got."; - w.input_schema = - R"({"type":"object","properties":{"job":{"type":"string"},"wait_s":{"type":"number","minimum":0,"maximum":600}},"required":["job"],"additionalProperties":false})"; - w.annotations.read_only = true; - w.handler = [&host](const core::mcp::call_ptr& call) - { - const auto job = host.find_job(call->text("job")); - - if (!job) - { - call->finish(core::mcp::tool_result::error( - std::format("There is no job {}: status lists the session's jobs", call->text("job")))); - return; - } - - host.wait(call, job, mcp_host::wait_seconds(*call), true); - }; - host.add(std::move(w), tool_tier::read, false); - - core::mcp::tool c; - c.name = "job_cancel"; - c.title = "Cancel a job"; - c.description = "Stops a job a tool started. A render stops without leaving a movie behind."; - c.input_schema = - R"({"type":"object","properties":{"job":{"type":"string"}},"required":["job"],"additionalProperties":false})"; - c.handler = [&host](const core::mcp::call_ptr& call) - { - const auto job = host.find_job(call->text("job")); - - if (!job) - { - call->finish(core::mcp::tool_result::error(std::format("There is no job {}", call->text("job")))); - return; - } - - job->cancel(); - call->finish(core::mcp::tool_result::text(job->is_done() ? std::format("{} has stopped", job->id()) - : std::format("{} is stopping", job->id()))); - }; - host.add(std::move(c), tool_tier::read, false); + known = false; } - void add_window(mcp_host& host) + // The parts the keyboard steps through - the stars of a rating, a monitor's buttons - or none, for what is only + // pointed into. + if (const auto* const source = dynamic_cast(e.get())) { - core::mcp::tool t; - t.name = "window"; - t.title = "Make or size the window"; - t.description = "Makes the window, if no tool has yet, and sizes it: width and height are its client area " - "in pixels, the size screenshots and recordings are made at. Where it is - out of sight or " - "on the desktop - is the session's, set by -mcp-ui."; - t.input_schema = - R"({"type":"object","properties":{"width":{"type":"integer","minimum":320,"maximum":7680},"height":{"type":"integer","minimum":240,"maximum":4320},"maximized":{"type":"boolean"}},"additionalProperties":false})"; - t.handler = [&host](const core::mcp::call_ptr& call) - { - const auto& frame = host.app()._app_frame; - const auto maximize = call->has("maximized") && call->flag("maximized", false); - const auto width = call->number("width"); - const auto height = call->number("height"); - const auto resize = !maximize && (width || height || call->has("maximized")); - - if (maximize) frame->sys_command(platform::sys_command_type::MAXIMIZE); - else if (resize && frame->is_maximized()) frame->sys_command(platform::sys_command_type::RESTORE); - - // Once the window has had the command, which is posted to it: a restore it had yet to have would undo - // the size. - platform::run_ui([&host, call, resize, width, height] - { - const auto& frame = host.app()._app_frame; - - if (resize && (width || height)) - { - // The drawn caption makes the whole window client area, so the window's size is the client's. - auto bounds = frame->window_bounds(); - bounds.right = bounds.left + static_cast(width.value_or(bounds.width())); - bounds.bottom = bounds.top + static_cast(height.value_or(bounds.height())); - frame->window_bounds(bounds, true); - } - - const auto bounds = frame->window_bounds(); - const auto presence = presence_name(host.options().presence); - json_writer json; - json.object().text("presence", presence); - json.integer("width", bounds.width()).integer("height", bounds.height()); - json.boolean("maximized", frame->is_maximized()).end_object(); - call->finish( - structured_result(std::format("The window is {}x{}, {}", bounds.width(), bounds.height(), presence), - json.str())); - }); - }; - host.add(std::move(t), tool_tier::read, true); + description.parts = source->keyboard_parts(); + known = true; } + + return known; } -void add_session_tools(mcp_host& host) +ui::command_ptr diffractor_agent::agent_hover_command(const commands id) { - add_help(host); - add_status(host); - add_wait_until_idle(host); - add_diagnostics(host); - add_log_read(host); - add_jobs(host); - add_window(host); + return _app.find_command(id); } -/////////////////////////////////////////////////////////////////////////////////////////////////// -// -tool: -/////////////////////////////////////////////////////////////////////////////////////////////////// - -std::string tool_arguments_json(const std::string_view input_schema, const std::vector& pairs, - std::string& error) +std::vector diffractor_agent::agent_dialogs() { - rapidjson::Document schema; - schema.Parse(input_schema.data(), input_schema.size()); - const auto* const properties = schema.IsObject() && schema.HasMember("properties") ? &schema["properties"] - : nullptr; - - const auto type_of = [properties](const std::string& name) -> std::string - { - if (!properties || !properties->IsObject() || !properties->HasMember(name.c_str())) return {}; - const auto& p = (*properties)[name.c_str()]; - return p.IsObject() && p.HasMember("type") && p["type"].IsString() ? p["type"].GetString() : ""; - }; - - json_writer json; - json.object(); + std::vector result; - for (const auto& pair : pairs) + for (const auto& weak : open_dialogs()) { - const auto equals = pair.find('='); + const auto d = weak.lock(); + if (!d) continue; - if (equals == std::string::npos || equals == 0) - { - error = std::format("{} is not name=value", pair); - return {}; - } - - const auto name = pair.substr(0, equals); - const auto value = std::string_view(pair).substr(equals + 1); - const auto type = type_of(name); - json.key(name); - - if (type == "integer" || type == "number") - { - double number = 0; - const auto [end, ec] = std::from_chars(value.data(), value.data() + value.size(), number); - - if (ec != std::errc{} || end != value.data() + value.size()) - { - error = std::format("{} is a number, not {}", name, value); - return {}; - } - - if (type == "integer") json.integer(static_cast(number)); - else json.number(number); - } - else if (type == "boolean") - { - const auto yes = value == "true" || value == "1" || value == "yes"; - const auto no = value == "false" || value == "0" || value == "no"; - - if (!yes && !no) - { - error = std::format("{} is true or false, not {}", name, value); - return {}; - } - - json.boolean(yes); - } - else if (type == "array") - { - json.array(); - for (const auto part : core::split(value, false, [](const char c) { return c == ','; })) json.text(part); - json.end_array(); - } - else if (type == "object") - { - rapidjson::Document object; - - if (object.Parse(value.data(), value.size()).HasParseError() || !object.IsObject()) - { - error = std::format("{} is a JSON object, not {}", name, value); - return {}; - } - - json.raw(value); - } - else + ui::agent_dialog listed; + listed.frame = d->frame(); + listed.host = d; + listed.shows_work = d->_shows_work; + // A dialog that reports work under way stops the work as its Cancel button does. + listed.cancel = [weak] { - json.text(value); - } + const auto shown = weak.lock(); + if (!shown) return; + if (const auto stop = shown->_close_cb) stop(); + else shown->close(true); + }; + result.push_back(std::move(listed)); } - json.end_object(); - return json.str(); + return result; } -int run_tool_once(const std::shared_ptr& host, const std::string_view name, - const std::vector& pairs) +std::vector diffractor_agent::agent_image_types() { - // Through the C runtime's streams, which the console mode bound to whatever the caller redirected. - const auto print_error = [](const std::string_view text) - { - std::fprintf(stderr, "%.*s\n", static_cast(text.size()), text.data()); - std::fflush(stderr); - }; - - const auto print = [](const std::string_view text) - { - std::fprintf(stdout, "%.*s\n", static_cast(text.size()), text.data()); - std::fflush(stdout); - }; - - if (!host) - { - print_error("-tool: there is no tool host"); - return 2; - } - - const auto schema = host->input_schema(name); - - if (schema.empty()) - { - print_error(std::format("-tool: there is no tool {}; the tools are: {}", name, - join_text(host->server()->tool_names(), ", "))); - return 2; - } - - std::string error; - const auto arguments = tool_arguments_json(schema, pairs, error); - - if (!error.empty()) - { - print_error(std::format("-tool:{}: {}", name, error)); - return 2; - } - - std::string answer; - host->server()->connect([&answer](const std::string_view message) { answer = message; }, - [](std::function task) { task(); }); - host->server()->receive( - std::format(R"({{"jsonrpc":"2.0","id":1,"method":"tools/call","params":{{"name":{},"arguments":{}}}}})", - core::mcp::quote(name), arguments)); - - rapidjson::Document response; - response.Parse(answer.c_str()); - - if (!response.IsObject() || !response.HasMember("result")) - { - const auto message = response.IsObject() && response.HasMember("error") && - response["error"].HasMember("message") - ? std::string(response["error"]["message"].GetString()) - : answer; - print_error(std::format("-tool:{}: {}", name, message)); - return 2; - } + return {".jpg", ".jpeg", ".jpe", ".webp", ".jxl", ".avif"}; +} - const auto& result = response["result"]; - const auto is_error = result.HasMember("isError") && result["isError"].IsBool() && result["isError"].GetBool(); +std::vector diffractor_agent::agent_encode(const core::const_surface_ptr& image, + const std::string_view extension) +{ + files ff; + const auto encoded = ff.surface_to_image(image, libfiles::metadata_blocks{}, file_encode_params{}, + extension_to_format(extension)); + if (!encoded) return {}; + const auto& data = encoded->data(); + return {data.begin(), data.end()}; +} - if (result.HasMember("structuredContent")) - { - print(core::mcp::to_json(result["structuredContent"])); - } - else if (result.HasMember("content") && result["content"].IsArray()) - { - for (const auto& c : result["content"].GetArray()) - { - if (c.HasMember("text") && c["text"].IsString()) - { - // What went wrong is not a result: stdout is kept for those. - if (is_error) print_error(c["text"].GetString()); - else print(c["text"].GetString()); - } - } - } +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Diffractor's own tools +/////////////////////////////////////////////////////////////////////////////////////////////////// - return is_error ? 1 : 0; +void add_diffractor_tools(ui::agent_host& host, app_frame& app) +{ + add_engine_tools(host, app); + add_library_tools(host, app); + add_ui_tools(host, app); + add_face_tools(host, app); } diff --git a/src/app_mcp.h b/src/app_mcp.h index 5e05ce4d..a7949c44 100644 --- a/src/app_mcp.h +++ b/src/app_mcp.h @@ -5,264 +5,71 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The agent session (-mcp) and the single tool call (-tool:): the tools Diffractor offers an agent over MCP, -// what a session may do (-mcp-allow) and where its window is (-mcp-ui), the jobs long work runs as, and how a tool -// reaches the application - the window it makes when a tool first needs one, the UI thread, and copies of itself for -// work that must not share its process. The protocol is libdesktop's (core/mcp.h); each tool adapts a function the -// views or the command line already use. docs/agents.md owns the session. +// Purpose: Diffractor's agent session (-mcp) and single tool call (-tool:), served by libdesktop's agent host +// (libdesktop/ui/agent.h), which owns the session, its switches and tiers, its jobs and waits, and the tools any window +// answers. Here is what Diffractor tells the host of itself - its window, made when a tool first needs it, its +// commands and what each needs, what keeps it busy, what its window shows and offers, its dialogs and the picture +// types it saves - and its own tools: the library's, the Movie and developer's tools, the window's navigation, +// selection and task panels, its input acted out as a tutorial's steps, tutorials and recordings, and faces. +// docs/agents.md owns Diffractor's part of the session. #pragma once -#include "libdesktop/core/mcp.h" +#include "libdesktop/ui/agent.h" class app_frame; -// Where a session's window is: made when a tool first needs it and kept where nobody sees it, made at once where -// nobody sees it, or made at once on the desktop. -enum class agent_presence -{ - none, - offscreen, - visible, -}; - -// What a session may do beyond reading. Each is the user's to grant, in the client's configuration. -struct agent_allow -{ - // Change files: render, rename, edit metadata, and any input or command that can. - bool write = false; - // Return or save pictures: of the screen, and of the user's media. - bool capture = false; - // Reach the network on the session's behalf: update checks, crash reports, map tiles, dictionaries. - bool network = false; - // The developer's tools: the test suite, translations, documentation, the duplicate report. - bool dev = false; - // Open another program, a folder or a web page on the user's desktop: the help, a file's folder, a map, Open with. - bool launch = false; -}; - -struct agent_options -{ - agent_presence presence = agent_presence::none; - agent_allow allow; - // What -mcp-ui and -mcp-allow said that was not understood, which status reports. - std::vector problems; -}; - -agent_options parse_agent_options(std::string_view ui, std::string_view allow); - -enum class tool_tier -{ - read, - write, - capture, - dev, -}; - -// Long work - a render, a test run, a tutorial, a command that can open a dialog - runs as a job, which the call -// that started it waits for. Every member is safe from any thread. -class agent_job +// What the agent host asks of Diffractor. +class diffractor_agent final : public ui::agent_app { public: - agent_job(std::string id, std::string tool); - - const std::string& id() const { return _id; } - const std::string& tool() const { return _tool; } - - // How far it has got, from 0 to 1, or below 0 for work of unknown size; and what it is doing. - void progress(double fraction, std::string_view message); - // A line of what it reports, the latest of which a call still waiting is shown. - void output(std::string_view line); - // Its answer. Only the first counts. - void complete(core::mcp::tool_result result); - // How to stop it; it completes itself once stopped. Run on the UI thread. - void on_cancel(std::function cancel); - void cancel(); - - bool is_done() const; - core::mcp::tool_result result() const; - double fraction() const; - std::string message() const; - // The last lines it reported, joined. - std::string recent_output(size_t lines) const; - // The whole of what it reported, up to a bound. - std::string all_output() const; - double seconds() const; + explicit diffractor_agent(app_frame& app) : _app(app) {} + + core::mcp::server_info agent_info() override; + ui::frame_ptr agent_window() override; + ui::frame_host* agent_window_host() override; + bool make_agent_window(std::string& why) override; + std::vector> agent_help() override; + std::vector agent_commands() override; + void agent_run(const ui::agent_command& c) override; + void agent_open_menu(const ui::command_ptr& c) override; + std::vector agent_busy() override; + bool agent_caught_up() override; + void agent_update() override; + std::string agent_status(core::json::writer& json) override; + void agent_window_status(core::json::writer& json) override; + std::string agent_view(core::json::writer& json, size_t listed) override; + std::vector> agent_facts() override; + std::vector> agent_counters() override; + void agent_targets(ui::agent_walk& walk) override; + bool agent_describe(const ui::element_ptr& e, ui::agent_element& description) override; + ui::command_ptr agent_hover_command(commands id) override; + std::vector agent_dialogs() override; + std::vector agent_image_types() override; + std::vector agent_encode(const core::const_surface_ptr& image, std::string_view extension) override; private: - std::string _id; - std::string _tool; - double _started = 0.0; - mutable std::mutex _mutex; - std::function _cancel; - double _fraction = -1.0; - std::string _message; - std::deque _lines; - size_t _output_bytes = 0; - bool _done = false; - bool _cancelled = false; - core::mcp::tool_result _result; -}; - -using agent_job_ptr = std::shared_ptr; - -class mcp_host : public std::enable_shared_from_this -{ -public: - // How long a call waits for its job before answering with how far it has got, unless it asks for longer. - static constexpr double default_wait_seconds = 50.0; - static constexpr double longest_wait_seconds = 600.0; - - mcp_host(app_frame& app, agent_options options, bool console); - - const core::mcp::server_ptr& server() const { return _server; } - const agent_options& options() const { return _options; } - // A -tool: call, run once in the console, rather than an agent session. - bool is_console() const { return _console; } - app_frame& app() const { return _app; } - - // Offers the tool where the session's tiers allow it, and otherwise says what would; a tool that needs the - // window makes it first. - void add(core::mcp::tool tool, tool_tier tier, bool needs_window); - // The tools withheld, each with what would let it in. - const std::vector>& withheld() const { return _withheld; } - - // On the UI thread: the window and the index, made when a tool first needs them. False, with why, where they - // cannot be. - bool ensure_window(std::string& why); - // Whether a dialog or a menu holds the window, which is what input waits behind. - bool modal_ui_open() const; - // Whether a dialog shows or a menu is open: what a client can see and answer. Work that holds the window while it - // runs, with nothing showing or with a dialog that only shows it under way, is not one. - bool answerable_ui_open() const; - - agent_job_ptr start_job(std::string_view tool); - agent_job_ptr find_job(std::string_view id) const; - std::vector jobs() const; - // Answers the call with the job's result once it is done; sooner where the wait passes - with how far it has got, - // and the job to wait on - or, where interruptible, where a dialog shows or a menu opens. - void wait(const core::mcp::call_ptr& call, const agent_job_ptr& job, double wait_s, bool interruptible); - // The wait a call asked for, in seconds: wait_s, bounded, or the default. - static double wait_seconds(const core::mcp::call& call); - // Runs then on the UI thread once ready has held for quiet_seconds, with true, or once timeout_seconds pass, with - // false. - void when(std::function ready, double quiet_seconds, double timeout_seconds, - std::function then); - // Answers the call once settled has held for quiet_seconds, or once timeout_seconds pass, with what answer makes of - // whether it settled. - void wait_until(const core::mcp::call_ptr& call, std::string_view tool, std::function settled, - double quiet_seconds, double timeout_seconds, - std::function answer); - - // Runs a copy of this program with these arguments as the call's job, for work that must not share the session's - // process: what it writes to stderr is the job's output and progress, and once it exits, answer makes the result of - // its exit code and what it wrote to stdout. - void run_child( - const core::mcp::call_ptr& call, std::string_view tool, std::vector arguments, - std::function answer); - // A tool's input schema, as -tool: types its arguments by; empty for a tool the session withholds. - std::string input_schema(std::string_view tool) const; - - // Each frame tick, on the UI thread. - void tick(); - // Once init has run: the session is ready to answer. - void started(); - - // A mark in the log, and the lines written since one. - uint64_t log_mark() const; - std::vector log_since(uint64_t mark, size_t most) const; - -private: - struct waiter - { - core::mcp::call_ptr call; - agent_job_ptr job; - double deadline = 0.0; - bool interruptible = false; - std::string last_message; - double last_fraction = -2.0; - }; - - struct condition - { - std::function ready; - std::function then; - double quiet_seconds = 0.0; - double since = -1.0; - double deadline = 0.0; - }; - - void release(waiter& w, std::string_view why); - app_frame& _app; - agent_options _options; - bool _console = false; - core::mcp::server_ptr _server; - std::vector> _withheld; - std::map> _jobs; - std::vector _waiters; - std::vector _conditions; - std::map _schemas; - // Each copy of the program a job runs, kept until its job is done: its callbacks end with it. - std::vector>> _children; - uint64_t _next_job = 1; - mutable std::mutex _jobs_mutex; }; -// A result in words for the model, with the same as a JSON object for a client that reads it. -inline core::mcp::tool_result structured_result(std::string text, std::string json, const bool is_error = false) -{ - auto result = core::mcp::tool_result::text(std::move(text)); - result.structured = std::move(json); - result.is_error = is_error; - return result; -} - -// Whether the window has caught up and nothing is loading, scanning, searching, indexing, acting out steps or showing -// work under way; and if not, what is still busy. -bool agent_window_settled(const app_frame& app); +// Diffractor's own tools, offered beside the host's. Each area's. +void add_diffractor_tools(ui::agent_host& host, app_frame& app); +void add_engine_tools(ui::agent_host& host, app_frame& app); +void add_library_tools(ui::agent_host& host, app_frame& app); +void add_ui_tools(ui::agent_host& host, app_frame& app); +void add_face_tools(ui::agent_host& host, app_frame& app); + +// A command as a session runs it: its name, and what it needs beyond reading - write, network, launch, or refused - +// and why. +ui::agent_command agent_command_of(const app_frame& app, commands id); +// Whether the window has caught up with what was done: nothing waiting to be laid out or drawn, and no task's review +// still being worked out. +bool agent_window_caught_up(const app_frame& app); +// What keeps the window busy - loading, scanning, indexing, acting out steps, running a task - which the host waits +// out. std::vector agent_window_busy(const app_frame& app); std::string_view agent_view_name(view_type v); -// The modal dialogs showing, as a JSON array: each one's title, text, buttons, check boxes and fields; and as text. -std::string describe_dialogs_json(app_frame& app); -std::string describe_dialogs_text(app_frame& app); -// The open menu, as a JSON object - each level's rows: text, keys, and whether each is enabled, checked and opens a -// submenu - or null where none is; and as text, empty where none is. -std::string describe_menu_json(); -std::string describe_menu_text(); -// The view, the search and the items shown, naming the first `listed` of them and of the selection: as a JSON object, -// and as text. -std::string agent_view_json(const app_frame& app, size_t listed); +// The view, the search and the items shown, naming the first `listed` of them and of the selection: into an open +// object, and as text. +void write_agent_view(core::json::writer& json, const app_frame& app, size_t listed); std::string agent_view_text(const app_frame& app, size_t listed); -// What working a command needs of the session beyond reading - "write", "network", "launch" or "refused" - empty for -// reading; and why the session does not run it, empty where it does. -std::string_view agent_command_need(commands id); -std::string agent_command_refusal(const mcp_host& host, commands id); -// Opens a command's menu as a press on its button does, beside the button where a bar shows it and otherwise in the -// middle of the view; the menu's loop runs inside the call. False where the command has no menu to open. -bool open_command_menu(app_frame& app, const ui::command_ptr& command); -// From now on, refuses each command the session may not run however it is reached, saying why in the log, and counts -// each command run and menu opened, and each control used, for coverage: once the window has made the commands. -void track_command_use(app_frame& app); -// What each dialog showing work under way says - "Saving photo.avif..." - which is waited out, not answered. -std::vector dialogs_showing_work(); -// Whether a dialog showing waits on an answer: one showing work does not. -bool dialog_awaits_answer(); - -// Each area's tools. -void add_session_tools(mcp_host& host); -void add_engine_tools(mcp_host& host); -void add_library_tools(mcp_host& host); -void add_ui_tools(mcp_host& host); -void add_control_tools(mcp_host& host); -void add_face_tools(mcp_host& host); - -// -tool: name=value...: calls the tool once, without a session, and prints its result: its structured content -// as JSON on stdout where it has some, otherwise its text, and what it reports on the way on stderr. The process's -// exit code: 0 for a result, 1 for an error, 2 for a call that could not be made. -int run_tool_once(const std::shared_ptr& host, std::string_view name, const std::vector& pairs); - -// name=value pairs as a tool's JSON arguments, each value read as the input schema types it: a number, true or -// false, a list split at commas, or text. Why not, where a pair cannot be read. -std::string tool_arguments_json(std::string_view input_schema, const std::vector& pairs, - std::string& error); diff --git a/src/app_mcp_controls.cpp b/src/app_mcp_controls.cpp deleted file mode 100644 index 208898d8..00000000 --- a/src/app_mcp_controls.cpp +++ /dev/null @@ -1,1458 +0,0 @@ -// This file is part of the Diffractor photo and video organizer -// Copyright 2026 Zac Walker -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. - -// Purpose: The agent tools that work the window as a user does, from what it shows (app_mcp.h): ui_controls lists -// what can be pressed, typed into or pointed at now - the bars' buttons, boxes and slider, the view's links, parts and -// panel, the dialog in front and the open menu's rows - ui_act works one with input given to its window as the -// platform's own is, menu_respond chooses from the open menu, and coverage says which commands have run and which of -// the controls listed have been used, so a sweep can press every button and know what it has missed. - -#include "pch.h" - -#include "app_mcp.h" -#include "app_mcp_json.h" -#include "model_db.h" -#include "model_index.h" -#include "model.h" -#include "ui_view.h" -#include "ui_dialog.h" -#include "ui_controls.h" -#include "app.h" - -namespace -{ - constexpr std::string_view wait_property = - R"("wait_s":{"type":"number","minimum":0,"maximum":600,"description":"How long to wait for the answer before replying with a job to wait on; 50 by default."})"; - - // What the window reports once it has caught up with what was done. - constexpr double caught_up_quiet_s = 0.05; - constexpr double caught_up_timeout_s = 5.0; - - bool window_caught_up(const app_frame& app) - { - return app._invalids.load() == view_invalid::none && !(app._view && app._view->reviewing()); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Coverage - /////////////////////////////////////////////////////////////////////////////////////////////////// - - // What the session has exercised: how often each command has run and each menu opened, the controls listed, and - // how often each has been used - by ui_act or menu_respond, or by any input that reached it. On the UI thread. - struct usage_record - { - bool tracking = false; - std::map runs; - std::map menus; - // Each id listed, with its scope and kind. - std::map, std::less<>> listed; - std::map> used; - // The id the latest listing gave each control, and each button of a toolbar by its command. - std::map, std::string> ids; - // Controls used that no listing named, by what they are and say. - std::map> used_unlisted; - }; - - usage_record& usage() - { - static usage_record record; - return record; - } - - std::optional command_of(const ui::command_ptr& c) - { - if (!c) return {}; - if (const auto* const id = std::any_cast(&c->opaque)) return *id; - return {}; - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // What the window offers - /////////////////////////////////////////////////////////////////////////////////////////////////// - - // Something a user can work: a control, a toolbar's button, a link or another part of what the view draws, an area - // only pointed into - a picture, a chart, a map - the view itself, or a row of the open menu. Its id is where it is, - // what it is and what it says, numbered where several say the same: "status/button/Rotate clockwise". - struct agent_target - { - std::string id; - std::string scope; - std::string kind; - std::string label; - bool enabled = true; - std::optional checked; - std::optional value; - std::string why_disabled; - // The frame its input goes to, and where that frame draws it, in its client pixels. - ui::frame_ptr frame; - recti bounds; - // Where its frame shows what scrolls, and how to scroll it into view; empty and null where it is always shown. - recti visible; - std::function reveal; - ui::command_ptr command; - ui::control_ptr control; - view_element_ptr element; - // A part of the view's frame: its area and which of its element's parts it is. - std::optional area; - int part = 0; - // A menu row: whether it opens a submenu, and the rows it is in from the first level down, itself last. - bool submenu = false; - std::vector path; - }; - - // What text reads as in an id: its first line, without its mnemonic marker, its runs of space made one, and short. - // An icon font's glyphs - the private use area - and control characters read as nothing. - std::string short_label(const std::string_view text) - { - constexpr size_t longest = 60; - const auto parsed = ui::parse_mnemonic(text.substr(0, text.find_first_of("\r\n"))).text; - const std::string_view view(parsed); - std::string result; - auto space = false; - - for (auto i = view.begin(); i != view.end();) - { - const auto start = i; - const auto c = core::pop_utf8_char(i, view.end()); - if (i == start) break; - - if (c == ' ' || c == '\t') - { - space = !result.empty(); - continue; - } - - if (c < 0x20 || (c >= 0xE000 && c <= 0xF8FF)) continue; - if (space) result += ' '; - space = false; - result.append(start, i); - } - - if (result.size() > longest) - { - auto end = longest; - while (end > 0 && (static_cast(result[end]) & 0xC0) == 0x80) --end; - result.resize(end); - result += "..."; - } - - return result; - } - - // What an element is, by its type's name, for one that says nothing of itself: "photo_control". - std::string type_label(const view_element& e) - { - std::string name = typeid(e).name(); - - for (const auto prefix : {"class "sv, "struct "sv}) - { - if (name.starts_with(prefix)) name.erase(0, prefix.size()); - } - - if (const auto colons = name.rfind("::"); colons != std::string::npos) name.erase(0, colons + 2); - // A mangled name leads with its length. - while (!name.empty() && std::isdigit(static_cast(name.front()))) name.erase(0, 1); - return name; - } - - // The first thing a tooltip's elements say. - std::string first_text(const view_element_ptr& e) - { - if (!e) return {}; - if (const auto* const text = dynamic_cast(e.get()); text && !text->text().empty()) - return text->text(); - if (const auto* const title = dynamic_cast(e.get()); title && !title->text().empty()) - return title->text(); - if (const auto* const title2 = dynamic_cast(e.get()); - title2 && !title2->title().empty()) - return title2->title(); - - std::string found; - e->visit_children([&found](const view_element_ptr& child) - { - if (found.empty()) found = first_text(child); - }); - return found; - } - - // How a walk of a tree of elements finds its targets: the scope they are in, the frame drawing them, how that - // frame scrolls them, and the text read last, which names the field after it as dialog_respond names it. - struct agent_walk - { - app_frame* app = nullptr; - std::string scope; - ui::frame_ptr frame; - recti visible; - std::function reveal; - std::optional area; - std::string read_before; - std::vector* out = nullptr; - }; - - void add_target(agent_walk& w, agent_target t) - { - if (t.bounds.is_empty()) return; - t.scope = w.scope; - t.frame = w.frame; - t.visible = w.visible; - t.reveal = w.reveal; - if (t.element) t.area = w.area; - w.out->push_back(std::move(t)); - } - - // What a field is called: its own label, or else what is read just before it, where that is short enough to be one. - std::string field_name(const std::string& own, const std::string& before) - { - constexpr size_t longest_label = 80; - if (!own.empty()) return short_label(own); - - auto label = std::string(core::trim(before)); - if (const auto stop = label.find(". "); stop != std::string::npos) label.resize(stop); - while (!label.empty() && (label.back() == ':' || label.back() == ' ' || label.back() == '.')) label.pop_back(); - return label.size() <= longest_label ? short_label(label) : std::string{}; - } - - // What a part says: a command link its command's name, a link its text, and anything else what its tooltip says - // first there. - std::string part_label(const agent_walk& w, const view_element_ptr& e, const recti bounds, const pointi offset, - ui::command_ptr& command) - { - if (const auto link = std::dynamic_pointer_cast(e)) - { - command = link->command(); - return short_label(!command->toolbar_text.empty() ? command->toolbar_text : command->text); - } - - if (const auto* const text = dynamic_cast(e.get())) - { - if (auto label = short_label(text->text()); !label.empty()) return label; - } - - view_hover_element hover; - hover.clear(); - e->tooltip(hover, bounds.center(), offset); - - if (hover.id != commands::none && w.app) - { - if (auto c = w.app->find_command(hover.id)) - { - command = std::move(c); - return short_label(command->text); - } - } - - return short_label(first_text(hover.elements)); - } - - void add_control(agent_walk& w, const ui::control_ptr& c, const bool enabled, const std::string& label) - { - if (!c || !c->is_visible()) return; - - agent_target t; - t.control = c; - t.bounds = c->frame_bounds(); - t.enabled = enabled && c->enabled; - - if (const auto toolbar = std::dynamic_pointer_cast(c)) - { - for (const auto& b : toolbar->buttons()) - { - if (!b.visible || !b.command) continue; - - agent_target button = t; - button.kind = "button"; - button.label = short_label(b.text); - button.command = b.command; - button.bounds = b.bounds; - button.enabled = t.enabled && b.enabled; - if (b.checked || b.command->checkable) button.checked = b.checked; - if (!button.enabled) button.why_disabled = b.command->disabled_reason; - add_target(w, std::move(button)); - } - - return; - } - - if (const auto button = std::dynamic_pointer_cast(c)) - { - t.kind = c->traits.push_button ? "button" : c->traits.radio_group >= 0 ? "radio" : "check"; - t.label = short_label(button->window_text()); - if (!c->traits.push_button) - { - t.checked = button->is_checked(); - w.read_before = button->window_text(); - } - } - else if (const auto edit = std::dynamic_pointer_cast(c)) - { - t.kind = "edit"; - t.label = field_name(label, w.read_before); - t.value = edit->window_text(); - w.read_before.clear(); - } - else if (const auto date = std::dynamic_pointer_cast(c)) - { - t.kind = "date"; - t.label = field_name(label, w.read_before); - t.value = date->date().is_valid() ? date->date().to_xmp_date() : std::string{}; - w.read_before.clear(); - } - else if (const auto slider = std::dynamic_pointer_cast(c)) - { - t.kind = "slider"; - t.label = field_name(label, w.read_before); - t.value = std::to_string(slider->get_pos()); - w.read_before.clear(); - } - else - { - t.kind = "control"; - t.label = !label.empty() ? short_label(label) : type_label(*c); - } - - add_target(w, std::move(t)); - } - - // Each control and each part that acts, as Tab finds them, and what is only pointed into as one area: disabled ones - // too, said to be. - void walk_element(const view_element_ptr& e, const pointi offset, const bool enabled, const std::string& label, - agent_walk& w) - { - if (!e || !e->is_visible()) return; - - const auto here_enabled = enabled && e->is_enabled(); - auto here_label = label; - - if (const auto* const title = dynamic_cast(e.get())) - { - if (!title->text().empty()) w.read_before = title->text(); - } - else if (const auto* const title2 = dynamic_cast(e.get())) - { - if (!title2->title().empty()) w.read_before = title2->title(); - } - else if (const auto* const labelled = dynamic_cast(e.get())) - { - if (!labelled->label().empty()) here_label = labelled->label(); - } - else if (const auto* const row = dynamic_cast(e.get())) - { - if (!row->row_label().empty()) here_label = std::string(row->row_label()); - } - - if (e->kind == ui::element_kind::control) - { - add_control(w, std::static_pointer_cast(e), here_enabled, here_label); - return; - } - - if (e->kind != ui::element_kind::content) return; - - if (const auto* const source = dynamic_cast(e.get())) - { - const auto parts = source->keyboard_parts(); - - if (parts.empty()) - { - agent_target t; - t.kind = "area"; - t.label = type_label(*e); - t.enabled = here_enabled; - t.bounds = e->bounds.offset(offset); - t.element = e; - add_target(w, std::move(t)); - return; - } - - for (size_t i = 0; i < parts.size(); ++i) - { - agent_target t; - t.kind = "part"; - t.bounds = parts[i].offset(offset); - t.label = part_label(w, e, t.bounds, offset, t.command); - if (t.label.empty()) t.label = std::format("{} {}", type_label(*e), i + 1); - t.enabled = here_enabled; - t.element = e; - t.part = static_cast(i); - add_target(w, std::move(t)); - } - - return; - } - - auto holds = false; - const auto children_offset = offset + e->children_offset(); - - e->visit_children([&](const view_element_ptr& child) - { - holds = true; - walk_element(child, children_offset, here_enabled, here_label, w); - }); - - if (holds) return; - - const auto* const text = dynamic_cast(e.get()); - - if (e->can_invoke()) - { - agent_target t; - t.bounds = e->bounds.offset(offset); - t.label = part_label(w, e, t.bounds, offset, t.command); - t.kind = text || std::dynamic_pointer_cast(e) ? "link" : "part"; - if (t.label.empty()) t.label = type_label(*e); - t.enabled = here_enabled && (!t.command || t.command->enable); - if (t.command && !t.command->enable) t.why_disabled = t.command->disabled_reason; - t.element = e; - add_target(w, std::move(t)); - } - - if (text && !text->text().empty()) w.read_before = text->text(); - } - - std::shared_ptr front_dialog() - { - const auto& dialogs = open_dialogs(); - - for (auto i = dialogs.rbegin(); i != dialogs.rend(); ++i) - { - if (auto d = i->lock(); d && d->frame()->is_visible()) return d; - } - - return nullptr; - } - - std::string_view area_name(const keyboard_area area) - { - switch (area) - { - case keyboard_area::sidebar: return "sidebar"; - case keyboard_area::listing: return "listing"; - case keyboard_area::media: return "media"; - case keyboard_area::panel: return "panel"; - case keyboard_area::view: break; - } - - return "view"; - } - - // The open menu's rows: an item, or each button of a row of them, named by its path from the first level down. - void add_menu_targets(std::vector& out) - { - const auto* const session = ui::open_menu_session(); - if (!session || session->done()) return; - - const auto levels = session->levels(); - std::vector> prefixes(levels.size()); - - for (size_t l = 0; l < levels.size(); ++l) - { - const auto& level = levels[l]; - - if (l > 0 && level.opened_from >= 0 && static_cast(level.opened_from) < levels[l - 1].rows.size()) - { - prefixes[l] = prefixes[l - 1]; - prefixes[l].push_back(levels[l - 1].rows[level.opened_from].text); - } - - const auto add = [&](const ui::menu_row_state& row, const std::string_view kind) - { - agent_target t; - t.scope = "menu"; - t.kind = kind; - t.frame = level.popup; - t.bounds = row.bounds; - t.command = row.command; - t.enabled = row.enabled; - if (row.checked || (row.command && row.command->checkable)) t.checked = row.checked; - if (!row.enabled && row.command) t.why_disabled = row.command->disabled_reason; - t.submenu = row.submenu; - t.path = prefixes[l]; - t.path.push_back(row.text); - t.label = short_label(join_text(t.path, " > ")); - if (!t.bounds.is_empty()) out.push_back(std::move(t)); - }; - - for (const auto& row : level.rows) - { - if (row.type == ui::menu_row_state::kind::item) add(row, "item"); - else if (row.type == ui::menu_row_state::kind::buttons) - { - for (const auto& cell : row.cells) add(cell, "button"); - } - } - } - } - - // Everything the window offers now, in the order Tab visits it, with the dialog in front and the open menu last; and - // each one listed is remembered, for coverage. - std::vector window_targets(app_frame& app) - { - std::vector out; - if (!app._window_started) return out; - - const auto walk_bar = [&](const std::shared_ptr& bar, const std::string_view scope) - { - if (!bar || !app._show_bars) return; - - agent_walk w{.app = &app, .scope = std::string(scope), .frame = bar->frame(), .out = &out}; - - for (const auto& c : bar->_controls) - { - const auto* const name = c == app._search_edit ? "address" - : c == app._filter_edit ? "filter" - : c == app._item_size ? "item size" - : c == app._face_filter_edit ? "people filter" - : c == app._face_size ? "face size" - : ""; - add_control(w, c, true, name); - } - }; - - walk_bar(app._title_bar, "title"); - - // The logo beside the title, which opens the help. - if (app._show_bars && app._app_logo && !app._title_bounds.is_empty()) - { - agent_target logo; - logo.scope = "title"; - logo.kind = "link"; - logo.label = "logo"; - logo.frame = app._title_bar->frame(); - logo.bounds = app._title_bounds; - logo.command = app.find_command(commands::view_help); - out.push_back(std::move(logo)); - } - - if (const auto& view = app._view_frame) - { - for (auto& region : view->keyboard_regions()) - { - agent_walk w{.app = &app, - .scope = std::string(area_name(region.area)), - .frame = view->frame(), - .visible = region.clip, - .reveal = region.reveal, - .area = region.area, - .out = &out}; - - for (const auto& root : region.roots) walk_element(root, region.offset, true, {}, w); - } - - if (!view->_view_bounds.is_empty()) - { - agent_target content; - content.scope = "view"; - content.kind = "content"; - content.label = agent_view_name(app._state.view_mode()); - content.frame = view->frame(); - content.bounds = view->_view_bounds; - out.push_back(std::move(content)); - } - - if (view->_strip->is_visible() && app._selector_frame && !app._selector_frame->_view_bounds.is_empty()) - { - agent_target strip; - strip.scope = "strip"; - strip.kind = "content"; - strip.label = "strip"; - strip.frame = app._selector_frame->frame(); - strip.bounds = app._selector_frame->_view_bounds; - out.push_back(std::move(strip)); - } - } - - walk_bar(app._status_bar, "status"); - - if (const auto d = front_dialog()) - { - agent_walk w{.app = &app, .scope = "dialog", .frame = d->frame(), .out = &out}; - d->visit_elements([&w](const view_element_ptr& e, const pointi offset) - { walk_element(e, offset, true, {}, w); }); - } - - add_menu_targets(out); - - std::map> counts; - - for (auto& t : out) - { - auto base = std::format("{}/{}/{}", t.scope, t.kind, t.label.empty() ? "unlabelled"s : t.label); - const auto n = ++counts[base]; - t.id = n == 1 ? std::move(base) : std::format("{}#{}", base, n); - } - - auto& record = usage(); - record.ids.clear(); - - for (const auto& t : out) - { - record.listed[t.id] = {t.scope, t.kind}; - const auto* const toolbar_command = std::dynamic_pointer_cast(t.control) ? t.command.get() - : nullptr; - if (t.control) record.ids[{t.control.get(), toolbar_command}] = t.id; - } - - return out; - } - - const agent_target* find_target(const std::vector& targets, const std::string_view id) - { - const auto found = std::ranges::find_if(targets, [id](const agent_target& t) { return t.id == id; }); - return found == targets.end() ? nullptr : &*found; - } - - // The ids most like one not found, for the error that says so. - std::vector similar_ids(const std::vector& targets, const std::string_view id) - { - constexpr size_t most = 8; - const auto last = id.substr(id.rfind('/') == std::string_view::npos ? 0 : id.rfind('/') + 1); - std::vector result; - - for (const auto& t : targets) - { - if (result.size() >= most) break; - if (core::ifind(t.id, last) != std::string_view::npos) result.push_back(t.id); - } - - return result; - } - - void write_target(json_writer& json, const agent_target& t) - { - json.object().text("id", t.id).text("scope", t.scope).text("kind", t.kind).text("label", t.label); - json.boolean("enabled", t.enabled); - if (!t.why_disabled.empty()) json.text("why_disabled", t.why_disabled); - if (t.checked) json.boolean("checked", *t.checked); - if (t.value) json.text("value", *t.value); - if (const auto id = command_of(t.command)) - { - json.text("command", command_name(*id)); - if (const auto need = agent_command_need(*id); !need.empty()) json.text("needs", need); - } - if (t.submenu) json.boolean("submenu", true); - if (!t.path.empty()) - { - json.key("path").array(); - for (const auto& row : t.path) json.text(row); - json.end_array(); - } - if (!t.visible.is_empty() && !t.visible.contains(t.bounds.center())) json.boolean("scrolled_away", true); - json.key("bounds").array().integer(t.bounds.left).integer(t.bounds.top).integer(t.bounds.width()); - json.integer(t.bounds.height()).end_array(); - if (const auto used = usage().used.find(t.id); used != usage().used.end()) json.integer("used", used->second); - json.end_object(); - } - - std::string target_text(const agent_target& t) - { - auto text = t.id; - if (t.checked) text += *t.checked ? " [x]" : " [ ]"; - if (t.value) text += std::format(" = '{}'", short_label(*t.value)); - if (t.submenu) text += " >"; - if (const auto id = command_of(t.command); id && t.kind != "button" && t.kind != "item") - text += std::format(" ({})", command_name(*id)); - if (!t.enabled) - text += t.why_disabled.empty() ? " (disabled)"s : std::format(" (disabled: {})", t.why_disabled); - return text; - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Working them - /////////////////////////////////////////////////////////////////////////////////////////////////// - - // What is in front of the window: the dialog that waits on an answer, and the open menu with how deep it is open. - struct modal_state - { - const void* dialog = nullptr; - const void* menu = nullptr; - size_t levels = 0; - - bool operator==(const modal_state&) const = default; - }; - - modal_state modal_now() - { - modal_state s; - if (const auto d = front_dialog(); d && !d->_shows_work) s.dialog = d.get(); - - if (const auto* const m = ui::open_menu_session(); m && !m->done()) - { - s.menu = m; - s.levels = m->popups().size(); - } - - return s; - } - - // Whether a dialog or a menu - or a deeper level of one - has opened since. - bool opened_since(const modal_state& before) - { - const auto now = modal_now(); - return now != before && (now.dialog || now.menu); - } - - struct act_request - { - std::string tool; - std::string id; - std::string action = "press"; - std::string text; - char32_t key = 0; - platform::key_state keys; - pointi drag; - int notches = 0; - // menu_respond's: the rows to press, from the first level down, or none with cancel. - std::vector path; - bool cancel = false; - }; - - core::mcp::tool_result act_answer(app_frame& app, const act_request& r, const bool opened, - const std::string& failed) - { - const auto what = r.tool == "menu_respond" - ? (r.cancel ? "Cancelled the menu"s : std::format("Chose {}", join_text(r.path, " > "))) - : std::format("{} {}", r.action, r.id); - json_writer json; - json.object().text("tool", r.tool).text("id", r.id).text("action", r.cancel ? "cancel"sv : r.action); - json.boolean("opened", opened); - if (!failed.empty()) json.text("failed", failed); - json.key("window").raw(agent_view_json(app, 10)); - json.key("dialogs").raw(describe_dialogs_json(app)); - json.key("menu").raw(describe_menu_json()); - json.end_object(); - - auto text = !failed.empty() ? std::format("{}: {}. {}", what, failed, agent_view_text(app, 0)) - : opened ? std::format("{}: a dialog or menu opened, which waits on an answer.", what) - : std::format("{}. {}", what, agent_view_text(app, 0)); - text += describe_dialogs_text(app); - text += describe_menu_text(); - return structured_result(std::move(text), json.str(), !failed.empty()); - } - - bool send_click(const ui::frame_ptr& frame, const pointi at, const platform::pointer_button button, - const platform::key_state keys) - { - return ui::send_pointer(frame, ui::pointer_input::down, button, at, keys) && - ui::send_pointer(frame, ui::pointer_input::up, button, at, keys); - } - - // Presses the open menu's rows along a path: each submenu on the way opened as a press opens it, then the last row - // chosen. A row named alone is looked for in the deepest level open first. Why not, where it cannot be. - std::string press_menu_path(mcp_host& host, app_frame& app, const std::vector& path) - { - const auto left = platform::pointer_button::left; - - for (size_t i = 0; i < path.size(); ++i) - { - const auto targets = window_targets(app); - const agent_target* found = nullptr; - - for (auto t = targets.rbegin(); t != targets.rend() && !found; ++t) - { - if (t->scope != "menu" || t->path.empty() || core::icmp(t->path.back(), path[i]) != 0) continue; - - // A path from the first level is matched row by row; a row named alone, at any depth. - const auto matches = path.size() == 1 || - (t->path.size() == i + 1 && - std::ranges::equal(t->path, std::span(path).first(i + 1), - [](const std::string& a, const std::string& b) - { return core::icmp(a, b) == 0; })); - if (matches) found = &*t; - } - - if (!found) - return std::format("the menu shows no '{}'", - join_text(std::vector(path.begin(), path.begin() + static_cast(i) + 1), - " > ")); - if (!found->enabled) - return std::format("'{}' is disabled{}", found->label, - found->why_disabled.empty() ? "" : ": " + found->why_disabled); - - const auto last = i + 1 == path.size(); - - if (last) - { - if (found->submenu) return std::format("'{}' opens a submenu: name a row of it", found->label); - - // What is chosen runs as its command would from command_run, and needs what that needs; a row with no - // command of the window's own - one made for what the menu is on - can change anything. - const auto id = command_of(found->command); - const auto why = id ? agent_command_refusal(host, *id) - : host.options().allow.write - ? std::string{} - : std::format("'{}' acts on what the menu is on, which needs -mcp-allow:write", - found->label); - if (!why.empty()) return why; - usage().used[found->id]++; - } - else if (!found->submenu) - { - return std::format("'{}' opens no submenu", found->label); - } - - const auto at = found->bounds.center(); - ui::send_pointer(found->frame, ui::pointer_input::move, left, at); - if (!send_click(found->frame, at, left, {})) return "the menu took no input"; - } - - return {}; - } - - // Gives the target the input the action is, as the platform gives its window real input: the pointer moved to it - // first, as a hand moves it. Why not, where it took none. - std::string perform(mcp_host& host, app_frame& app, const act_request& r) - { - if (r.cancel) - { - if (auto* const session = ui::open_menu_session()) session->cancel(); - return {}; - } - - if (!r.path.empty()) return press_menu_path(host, app, r.path); - - auto targets = window_targets(app); - const auto* found = find_target(targets, r.id); - if (!found) return "it is no longer shown"; - - // One its frame has scrolled out of sight is scrolled into view first, as a user scrolls to it. The frame is laid - // out then, as it is before any input a user could give next, so the controls in it have moved with the scroll. - if (found->reveal && !found->visible.is_empty() && !found->visible.contains(found->bounds.center())) - { - found->reveal(found->bounds); - if (found->frame) found->frame->layout(); - targets = window_targets(app); - found = find_target(targets, r.id); - if (!found) return "it went once scrolled into view"; - } - - const auto target = *found; - const auto& frame = target.frame; - const auto at = target.bounds.center(); - const auto left = platform::pointer_button::left; - const auto keys = r.keys; - const auto move = [&](const pointi p) - { - return ui::send_pointer(frame, ui::pointer_input::move, left, p, keys); - }; - - if (!move(at)) return "its window takes no input now: a dialog holds it"; - usage().used[target.id]++; - - if (r.action == "hover") return {}; - - if (r.action == "press") - { - send_click(frame, at, left, keys); - } - else if (r.action == "double_click") - { - send_click(frame, at, left, keys); - ui::send_pointer(frame, ui::pointer_input::double_click, left, at, keys); - ui::send_pointer(frame, ui::pointer_input::up, left, at, keys); - } - else if (r.action == "right_click") - { - send_click(frame, at, platform::pointer_button::right, keys); - ui::send_context_menu(frame, at); - } - else if (r.action == "drag") - { - constexpr auto steps = 8; - ui::send_pointer(frame, ui::pointer_input::down, left, at, keys); - - for (auto i = 1; i <= steps; ++i) move({at.x + r.drag.x * i / steps, at.y + r.drag.y * i / steps}); - - ui::send_pointer(frame, ui::pointer_input::up, left, at + r.drag, keys); - } - else if (r.action == "wheel") - { - constexpr auto wheel_detent = 120; - ui::send_wheel(frame, at, r.notches * wheel_detent, keys); - } - else if (r.action == "type") - { - // As a user replaces what a box holds: a press into it, Ctrl+A, then the text, Enter starting each new line. - send_click(frame, at, left, {}); - platform::key_state control; - control.control = true; - ui::send_key(frame, U'A', control); - size_t start = 0; - - for (auto end = r.text.find('\n'); start <= r.text.size(); end = r.text.find('\n', start)) - { - const auto line = std::string_view(r.text).substr(start, end == std::string::npos ? end : end - start); - if (!line.empty()) ui::send_text(frame, line); - if (end == std::string::npos) break; - ui::send_key(frame, platform::keys::RETURN, {}); - start = end + 1; - } - } - else if (r.action == "key") - { - // The keyboard goes to it as Tab takes it there, then the key is pressed. - if (target.control) target.control->focus(); - else if (target.area && target.element && app._view_frame) - { - const keyboard_part part{target.element, target.part, target.bounds}; - app._view_frame->keyboard_to(*target.area, &part); - } - else if (target.kind == "content") - { - if (app._view_frame && frame == app._view_frame->frame()) app.focus_view(); - else if (frame) frame->focus(); - } - - ui::send_key(frame, r.key, r.keys); - } - - // What it did is looked at again where the pointer is now, as the platform's own pointer would be. - if (r.action != "key" && r.action != "right_click") move(r.action == "drag" ? at + r.drag : at); - return {}; - } - - // Gives the input as the call's job, in a task of its own, so a dialog or menu it opens runs its loop there. The - // call is answered as soon as one opens, or once the window has caught up with what the input did. - void act(mcp_host& host, const core::mcp::call_ptr& call, act_request request) - { - auto& app = host.app(); - const auto job = host.start_job(request.tool); - const auto before = modal_now(); - - host.when([job, before] { return job->is_done() || opened_since(before); }, 0.0, mcp_host::longest_wait_seconds, - [&app, job, request](const bool met) - { - if (met && !job->is_done()) job->complete(act_answer(app, request, true, {})); - }); - - platform::run_ui([&host, &app, job, request] - { - const auto failed = perform(host, app, request); - - if (!failed.empty()) - { - if (!job->is_done()) job->complete(act_answer(app, request, false, failed)); - return; - } - - host.when([&app] { return window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, - [&host, &app, job, request](bool) - { - // Work the input left a dialog showing - a file being saved - is part of it, done once that has gone. - host.when([] { return dialogs_showing_work().empty(); }, 0.0, mcp_host::longest_wait_seconds, - [&app, job, request](bool) - { - if (!job->is_done()) job->complete(act_answer(app, request, false, {})); - }); - }); - }); - - host.wait(call, job, mcp_host::wait_seconds(*call), false); - } - - // ctrl+, shift+ and alt+ before a key: a letter, a digit, or a key's name, as a script's key step takes it. - bool parse_key_chord(const std::string_view chord, char32_t& key, platform::key_state& keys) - { - return parse_tutorial_key(chord, key, keys); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // The tools - /////////////////////////////////////////////////////////////////////////////////////////////////// - - void add_ui_controls(mcp_host& host) - { - core::mcp::tool t; - t.name = "ui_controls"; - t.title = "List what can be worked"; - t.description = - "Everything in the window a user can work now, each with an id ui_act takes: the title and status bars' " - "buttons, boxes and slider; the view's links and parts - the sidebar's, the listing's and the media " - "pane's - its panel's controls, the view itself and the strip; the dialog in front; and the open menu's " - "rows. Each says its scope, its kind - button, check, radio, edit, slider, date, link, part, area (a " - "picture, chart or map, only pointed into), content or item (a menu's) - what it says, whether it can be " - "used now and why not, its value or whether it is checked, the command it runs and what that needs, " - "where its window draws it, and for a menu's row its path, which menu_respond takes. scope, kind and " - "contains narrow the list."; - t.input_schema = - R"({"type":"object","properties":{"scope":{"type":"string","description":"title, status, sidebar, listing, media, panel, view, strip, dialog or menu"},"kind":{"type":"string"},"contains":{"type":"string","description":"Only those whose id or command has these letters"},"enabled_only":{"type":"boolean"},"offset":{"type":"integer","minimum":0},"limit":{"type":"integer","minimum":0,"maximum":5000,"description":"How many to name; 500 by default"}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto scope = call->text("scope"); - const auto kind = call->text("kind"); - const auto contains = call->text("contains"); - const auto enabled_only = call->flag("enabled_only", false); - const auto offset = static_cast(call->number("offset").value_or(0)); - const auto limit = static_cast(call->number("limit").value_or(500)); - - app.update_button_state(false); - const auto targets = window_targets(app); - std::vector matching; - - for (const auto& target : targets) - { - if (!scope.empty() && core::icmp(target.scope, scope) != 0) continue; - if (!kind.empty() && core::icmp(target.kind, kind) != 0) continue; - if (enabled_only && !target.enabled) continue; - - if (!contains.empty()) - { - const auto id = command_of(target.command); - const auto in_command = id && core::ifind(command_name(*id), contains) != std::string_view::npos; - if (core::ifind(target.id, contains) == std::string_view::npos && !in_command) continue; - } - - matching.push_back(&target); - } - - const auto first = std::min(offset, matching.size()); - const auto last = std::min(matching.size(), first + limit); - json_writer json; - json.object().key("controls").array(); - std::string text; - - for (auto i = first; i < last; ++i) - { - write_target(json, *matching[i]); - text += "\n" + target_text(*matching[i]); - } - - json.end_array().integer("count", static_cast(matching.size())); - json.integer("offset", static_cast(first)).boolean("more", last < matching.size()); - json.boolean("menu_open", ui::open_menu_session() != nullptr); - json.boolean("dialog_open", dialog_awaits_answer()).end_object(); - - auto head = std::format("{} of {} shown{}", last - first, matching.size(), - last < matching.size() ? std::format("; offset {} reads on", last) : ""s); - call->finish(structured_result(head + text, json.str())); - }; - host.add(std::move(t), tool_tier::read, true); - } - - void add_ui_act(mcp_host& host) - { - core::mcp::tool t; - t.name = "ui_act"; - t.title = "Work a control"; - t.description = - "Works what ui_controls lists, by its id, with the input a user gives it - sent to its window as the " - "platform's own input is, so it takes the path a user's does, through whatever is in front: press (the " - "default), double_click, right_click (which opens its context menu), hover, drag by dx and dy pixels, " - "wheel by notches (positive away from the user, up), type text into a box - pressed into, its text " - "selected and replaced, Enter for each new line - or key, a key pressed with the keyboard taken there " - "first: ctrl+a, escape, f2. One scrolled out of sight is scrolled into view first. What it runs needs " - "what its command needs. Answers once the window has caught up, or as soon as a dialog or menu opens: " - "dialog_respond and menu_respond answer those, and ui_act works them too."; - t.input_schema = std::format( - R"({{"type":"object","properties":{{"id":{{"type":"string"}},"action":{{"type":"string","enum":["press","double_click","right_click","hover","drag","wheel","type","key"]}},"text":{{"type":"string"}},"key":{{"type":"string","description":"ctrl+, shift+ and alt+ before a letter, a digit, or enter, escape, space, tab, backspace, delete, insert, left, right, up, down, home, end, page-up, page-down, plus, minus, apps or f1 to f12"}},"dx":{{"type":"integer"}},"dy":{{"type":"integer"}},"notches":{{"type":"integer","minimum":-50,"maximum":50}},"ctrl":{{"type":"boolean"}},"shift":{{"type":"boolean"}},{}}},"required":["id"],"additionalProperties":false}})", - wait_property); - t.annotations.destructive = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto refuse = [&call](std::string why) - { - call->finish(core::mcp::tool_result::error(std::move(why))); - }; - - if (app._tutorial) return refuse("Steps are being acted out: wait for their job, or job_cancel it"); - - act_request request; - request.tool = "ui_act"; - request.id = call->text("id"); - request.action = call->text("action", "press"); - request.text = call->text("text"); - request.drag = {static_cast(call->number("dx").value_or(0)), - static_cast(call->number("dy").value_or(0))}; - request.notches = static_cast(call->number("notches").value_or(-1)); - request.keys.control = call->flag("ctrl", false); - request.keys.shift = call->flag("shift", false); - - if (request.action == "key" && !parse_key_chord(call->text("key"), request.key, request.keys)) - return refuse(std::format("'{}' is no key: ctrl+a, escape, f2 and the like", call->text("key"))); - if (request.action == "drag" && request.drag == pointi{}) - return refuse("Say how far to drag it: dx, dy or both, in pixels"); - - app.update_button_state(false); - const auto targets = window_targets(app); - const auto* const target = find_target(targets, request.id); - - if (!target) - { - const auto like = similar_ids(targets, request.id); - return refuse(std::format("Nothing shown now is {}{}", request.id, - like.empty() ? ": ui_controls lists what is"s - : std::format(". Perhaps: {}", join_text(like, ", ")))); - } - - const auto pointing = request.action == "hover" || request.action == "wheel"; - - if (!pointing && !target->enabled) - { - return refuse(std::format("{} is disabled{}", target->id, - target->why_disabled.empty() ? "" : ": " + target->why_disabled)); - } - - if (request.action == "type" && target->kind != "edit") - return refuse(std::format("{} is a {}, not a box to type into", target->id, target->kind)); - - // What a press runs needs what its command needs. - if (!pointing) - { - if (const auto id = command_of(target->command)) - { - if (auto why = agent_command_refusal(host, *id); !why.empty()) return refuse(std::move(why)); - } - } - - if (dialog_awaits_answer() && target->scope != "dialog" && target->scope != "menu") - return refuse("A dialog holds the window, and input waits behind it: work the dialog first"); - - act(host, call, std::move(request)); - }; - host.add(std::move(t), tool_tier::write, true); - } - - void add_menu_respond(mcp_host& host) - { - core::mcp::tool t; - t.name = "menu_respond"; - t.title = "Choose from a menu"; - t.description = - "Chooses from the menu open now, as ui_state shows it: a row by its text - Name - or by its path from the " - "first level down - Sort by > Name - each submenu on the way opened as a press opens it, the row pressed " - "where the menu shows it; or cancels the menu, as Escape does. A row named alone is looked for in the " - "deepest level open first. What is chosen needs what its command needs - a row made for what the menu is " - "on can change anything, so needs -mcp-allow:write - and cancelling needs nothing. command_run opens a " - "command's menu, and ui_act's right_click a context menu. Answers once the menu has closed, with what the " - "window shows then, or with the dialog or menu the choice opened."; - t.input_schema = std::format( - R"({{"type":"object","properties":{{"choose":{{"type":"string","description":"A row's text, or a path of them joined by >"}},"cancel":{{"type":"boolean"}},{}}},"additionalProperties":false}})", - wait_property); - t.handler = [&host](const core::mcp::call_ptr& call) - { - const auto refuse = [&call](std::string why) - { - call->finish(core::mcp::tool_result::error(std::move(why))); - }; - - const auto* const session = ui::open_menu_session(); - - if (!session || session->done()) - { - return refuse("No menu is open: command_run opens a command's menu - menu_main and the like - and " - "ui_act's right_click a context menu"); - } - - act_request request; - request.tool = "menu_respond"; - request.cancel = call->flag("cancel", false); - const auto choose = call->text("choose"); - - if (request.cancel == !choose.empty()) return refuse("Choose a row, or cancel: one of them"); - - for (auto rest = std::string_view(choose); !rest.empty();) - { - const auto split = rest.find('>'); - const auto row = core::trim(rest.substr(0, split)); - if (!row.empty()) request.path.emplace_back(row); - rest = split == std::string_view::npos ? std::string_view{} : rest.substr(split + 1); - } - - if (!request.cancel && request.path.empty()) return refuse("Name the row to choose"); - request.id = request.cancel ? "menu" : join_text(request.path, " > "); - act(host, call, std::move(request)); - }; - host.add(std::move(t), tool_tier::read, true); - } - - void add_coverage(mcp_host& host) - { - core::mcp::tool t; - t.name = "coverage"; - t.title = "What has been exercised"; - t.description = - "What the session has exercised: how often each command has run and each command's menu opened - from its " - "button, a menu, its keys, command_run or ui_act - and the commands that have not, each with whether it " - "can run now, why not, and what it needs; and of everything ui_controls has listed, what has been used - " - "by ui_act, menu_respond or any input that reached it - and what has not. reset starts counting again."; - t.input_schema = - R"({"type":"object","properties":{"reset":{"type":"boolean"},"list":{"type":"integer","minimum":0,"maximum":5000,"description":"How many of what has not been exercised to name; 200 by default"}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - auto& record = usage(); - const auto listed_most = static_cast(call->number("list").value_or(200)); - - if (call->flag("reset", false)) - { - record.runs.clear(); - record.menus.clear(); - record.listed.clear(); - record.used.clear(); - record.used_unlisted.clear(); - call->finish(structured_result("Coverage starts again from nothing.", R"({"reset":true})")); - return; - } - - app.update_button_state(false); - json_writer json; - json.object().key("commands").object(); - auto total = 0; - auto exercised = 0; - std::vector not_run_text; - json.key("run").array(); - - for (const auto id : all_commands()) - { - const auto command = app.find_command(id); - if (!command) continue; - ++total; - - const auto runs = record.runs.contains(id) ? record.runs.at(id) : 0; - const auto menus = record.menus.contains(id) ? record.menus.at(id) : 0; - if (runs == 0 && menus == 0) continue; - ++exercised; - json.object().text("name", command_name(id)).integer("runs", runs).integer("menus", menus).end_object(); - } - - json.end_array().key("not_run").array(); - - for (const auto id : all_commands()) - { - const auto command = app.find_command(id); - if (!command || record.runs.contains(id) || record.menus.contains(id)) continue; - - if (not_run_text.size() < listed_most) - { - const auto need = agent_command_need(id); - json.object().text("name", command_name(id)).boolean("enabled", command->enable); - if (!command->enable && !command->disabled_reason.empty()) - json.text("why_disabled", command->disabled_reason); - if (!need.empty()) json.text("needs", need); - json.end_object(); - not_run_text.push_back( - std::format("{}{}{}", command_name(id), need.empty() ? ""s : std::format(" [{}]", need), - command->enable - ? ""s - : std::format(" (disabled{})", command->disabled_reason.empty() - ? ""s - : ": " + command->disabled_reason))); - } - } - - json.end_array().integer("total", total).integer("exercised", exercised).end_object(); - - std::vector not_used; - json.key("controls").object().key("not_used").array(); - - for (const auto& [id, where] : record.listed) - { - if (record.used.contains(id)) continue; - if (not_used.size() < listed_most) - { - json.text(id); - not_used.push_back(id); - } - } - - const auto used = std::ranges::count_if(record.listed, [&](const auto& entry) - { return record.used.contains(entry.first); }); - json.end_array().integer("listed", static_cast(record.listed.size())); - json.integer("used", static_cast(used)).key("used_unlisted").array(); - for (const auto& [what, count] : record.used_unlisted) - json.object().text("what", what).integer("uses", count).end_object(); - json.end_array().end_object().end_object(); - - auto text = std::format("Commands: {} of {} exercised. Controls: {} of {} listed used.", exercised, total, - used, record.listed.size()); - if (!not_run_text.empty()) text += "\nNot run: " + join_text(not_run_text, ", "); - if (!not_used.empty()) text += "\nNot used: " + join_text(not_used, ", "); - call->finish(structured_result(std::move(text), json.str())); - }; - host.add(std::move(t), tool_tier::read, true); - } -} - -std::string describe_menu_json() -{ - const auto* const session = ui::open_menu_session(); - if (!session || session->done()) return "null"; - - json_writer json; - json.object().key("levels").array(); - - for (const auto& level : session->levels()) - { - json.object().integer("opened_from", level.opened_from).key("rows").array(); - - const auto write_row = [&json](const ui::menu_row_state& row) - { - json.object().text("text", row.text); - if (!row.keys.empty()) json.text("keys", row.keys); - json.boolean("enabled", row.enabled); - if (row.checked) json.boolean("checked", true); - if (row.submenu) json.boolean("submenu", true); - if (const auto id = command_of(row.command)) json.text("command", command_name(*id)); - json.end_object(); - }; - - for (const auto& row : level.rows) - { - switch (row.type) - { - case ui::menu_row_state::kind::item: write_row(row); break; - case ui::menu_row_state::kind::separator: json.object().boolean("separator", true).end_object(); break; - case ui::menu_row_state::kind::content: json.object().boolean("content", true).end_object(); break; - case ui::menu_row_state::kind::buttons: - json.object().key("buttons").array(); - for (const auto& cell : row.cells) write_row(cell); - json.end_array().end_object(); - break; - } - } - - json.end_array().end_object(); - } - - json.end_array().end_object(); - return json.str(); -} - -std::string describe_menu_text() -{ - const auto* const session = ui::open_menu_session(); - if (!session || session->done()) return {}; - - const auto levels = session->levels(); - std::string text = "\nMenu (menu_respond chooses from it):"; - - for (size_t l = 0; l < levels.size(); ++l) - { - const auto& level = levels[l]; - if (l > 0 && level.opened_from >= 0 && static_cast(level.opened_from) < levels[l - 1].rows.size()) - text += std::format("\n {} >", levels[l - 1].rows[level.opened_from].text); - - const auto indent = std::string(2 * (l + 1), ' '); - - for (const auto& row : level.rows) - { - const auto describe = [](const ui::menu_row_state& r) - { - return std::format("{}{}{}{}{}", r.checked ? "[x] " : "", r.text, - r.keys.empty() ? ""s : std::format(" ({})", r.keys), r.submenu ? " >" : "", - r.enabled ? "" : " (disabled)"); - }; - - switch (row.type) - { - case ui::menu_row_state::kind::item: text += "\n" + indent + describe(row); break; - case ui::menu_row_state::kind::separator: text += "\n" + indent + "---"; break; - case ui::menu_row_state::kind::content: break; - case ui::menu_row_state::kind::buttons: - { - std::vector cells; - for (const auto& cell : row.cells) cells.push_back("[" + describe(cell) + "]"); - text += "\n" + indent + join_text(cells, " "); - } - break; - } - } - } - - return text; -} - -bool open_command_menu(app_frame& app, const ui::command_ptr& command) -{ - if (!command || !command->menu) return false; - - // As a press on the command's button opens it, where a bar shows one. - for (const auto& target : window_targets(app)) - { - if (target.command != command || target.kind != "button" || !target.enabled) continue; - - const auto left = platform::pointer_button::left; - const auto at = target.bounds.center(); - ui::send_pointer(target.frame, ui::pointer_input::move, left, at); - if (send_click(target.frame, at, left, {})) return true; - } - - const auto& view = app._view_frame; - if (!view) return false; - const auto middle = view->frame()->client_to_screen(view->_view_bounds.center()); - app.track_menu(view->frame(), recti(middle, sizei{}), command->menu()); - return true; -} - -void track_command_use(app_frame& app) -{ - auto& record = usage(); - if (record.tracking || app._commands.empty()) return; - record.tracking = true; - - for (const auto& [id, command] : app._commands) - { - const auto counted = id; - - if (command->invoke) - { - // The session's tiers hold however a command is reached: a key, a toolbar's button, a menu row or a step. - // Exit stays the watching user's way to close the window - the agent's own tools refuse it before this. - command->invoke = [&app, counted, run = std::move(command->invoke)] - { - if (app._mcp && counted != commands::exit) - { - if (const auto why = agent_command_refusal(*app._mcp, counted); !why.empty()) - { - core::log("track_command_use", why); - return; - } - } - - ++usage().runs[counted]; - run(); - }; - } - - if (command->menu) - { - command->menu = [counted, open = std::move(command->menu)] - { - ++usage().menus[counted]; - return open(); - }; - } - } - - ui::on_control_used([](const ui::control& c, const ui::command_ptr& command) - { - auto& used = usage(); - const auto toolbar = dynamic_cast(&c) != nullptr; - - if (const auto found = used.ids.find({&c, toolbar ? command.get() : nullptr}); found != used.ids.end()) - { - ++used.used[found->second]; - } - else - { - const auto name = command ? short_label(command->text) : std::string{}; - ++used.used_unlisted[name.empty() ? type_label(c) : std::format("{} {}", type_label(c), name)]; - } - }); -} - -void add_control_tools(mcp_host& host) -{ - add_ui_controls(host); - add_ui_act(host); - add_menu_respond(host); - add_coverage(host); -} diff --git a/src/app_mcp_faces.cpp b/src/app_mcp_faces.cpp index f68b9f18..78cfa3b4 100644 --- a/src/app_mcp_faces.cpp +++ b/src/app_mcp_faces.cpp @@ -13,7 +13,6 @@ #include "pch.h" #include "app_mcp.h" -#include "app_mcp_json.h" #include "model_db.h" #include "model_faces_search.h" #include "model_index.h" @@ -31,15 +30,10 @@ namespace // Face search publishes what it read in batches, so it must stay settled a moment to have finished. constexpr double settle_quiet_s = 0.5; - bool window_caught_up(const app_frame& app) - { - return app._invalids.load() == view_invalid::none; - } - // Face search has settled, and the window - the Faces view where it shows - shows what it found. bool faces_caught_up(const app_frame& app) { - if (!window_caught_up(app) || !app._state.item_index.faces().is_settled()) return false; + if (!agent_window_caught_up(app) || !app._state.item_index.faces().is_settled()) return false; return app._state.view_mode() != view_type::faces || !app._view_faces || app._view_faces->is_current(); } @@ -55,7 +49,7 @@ namespace return fraction; } - void write_at(json_writer& json, const app_frame& app, const recti bounds) + void write_at(core::json::writer& json, const app_frame& app, const recti bounds) { json.key("at"); const auto at = bounds.is_empty() ? std::nullopt : window_fraction(app, bounds.center()); @@ -69,7 +63,7 @@ namespace } // Where a rect of the view frame is, as fractions of the window: its left, top, right and bottom. - void write_box(json_writer& json, const app_frame& app, const recti bounds) + void write_box(core::json::writer& json, const app_frame& app, const recti bounds) { json.key("box"); const auto top_left = bounds.is_empty() ? std::nullopt : window_fraction(app, pointi(bounds.left, bounds.top)); @@ -128,7 +122,7 @@ namespace // The faces on the picture the window shows, where it shows one whole, upright and flat: whom each is, and where, // as the pointer finds them to offer their buttons (docs/faces.md#93-faces-on-a-picture). A video's faces are each // on the frame they were found in, which says whether it is the frame shown, paused. - void write_picture(json_writer& json, std::string& text, const app_frame& app) + void write_picture(core::json::writer& json, std::string& text, const app_frame& app) { const auto& display = app._state._display; const auto video = display && display->is_one() && display->_item1 && display->_selected_texture1 && @@ -182,7 +176,7 @@ namespace { auto& faces = app._state.item_index.faces(); const auto mode = app._state.view_mode(); - json_writer json; + core::json::writer json; json.object().text("view", agent_view_name(mode)); const auto progress = faces.progress(); @@ -378,7 +372,7 @@ namespace } json.end_object(); - return structured_result(std::move(text), json.str()); + return core::mcp::structured_result(std::move(text), json.str()); } size_t size_of(const core::mcp::call& call, const std::string_view name, const size_t fallback) @@ -387,7 +381,7 @@ namespace return n && *n >= 0.0 ? static_cast(*n) : fallback; } - void add_faces_state(mcp_host& host) + void add_faces_state(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "faces_state"; @@ -402,9 +396,8 @@ namespace R"({"type":"object","properties":{"faces":{"type":"integer","minimum":0,"maximum":500,"description":"How many faces to list; 50 by default"},"offset":{"type":"integer","minimum":0,"description":"The first face to list"},"wait_s":{"type":"number","minimum":0,"maximum":600,"description":"How long to wait for face search to settle; 0, the default, answers at once"}},"additionalProperties":false})"; t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto listed = size_of(*call, "faces", 50); const auto offset = size_of(*call, "offset", 0); const auto wait_s = call->number("wait_s").value_or(0.0); @@ -415,13 +408,13 @@ namespace return; } - host.wait_until(call, "faces_state", [&app] { return faces_caught_up(app); }, settle_quiet_s, wait_s, - [&app, listed, offset](bool) { return faces_answer(app, listed, offset); }); + host.answer_when(call, "faces_state", [&app] { return faces_caught_up(app); }, settle_quiet_s, wait_s, + false, [&app, listed, offset](bool) { return faces_answer(app, listed, offset); }); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } - void add_faces_select(mcp_host& host) + void add_faces_select(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "faces_select"; @@ -431,9 +424,8 @@ namespace "cell index. What is selected is what the review commands act on. Answers with faces_state."; t.input_schema = R"({"type":"object","properties":{"rows":{"type":"array","items":{"type":"integer","minimum":0}},"people":{"type":"array","items":{"type":"string"},"description":"Keys or titles, as faces_state shows them"},"cells":{"type":"array","items":{"type":"integer","minimum":0}}},"additionalProperties":false})"; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto& view = app._view_faces; if (app._state.view_mode() != view_type::faces || !view) @@ -480,7 +472,7 @@ namespace { call->finish(core::mcp::tool_result::error( std::format("No visible People row is called {}: faces_state lists them", - join_text(missing, ", ")))); + core::combine(missing, ", ", false)))); return; } @@ -494,13 +486,13 @@ namespace view->select_cells(cells); } - host.wait_until(call, "faces_select", [&app] { return window_caught_up(app); }, caught_up_quiet_s, - caught_up_timeout_s, [&app](bool) { return faces_answer(app, 50, 0); }); + host.answer_when(call, "faces_select", [&app] { return agent_window_caught_up(app); }, caught_up_quiet_s, + caught_up_timeout_s, false, [&app](bool) { return faces_answer(app, 50, 0); }); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } - void add_faces_data(mcp_host& host) + void add_faces_data(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "faces_data"; @@ -512,7 +504,7 @@ namespace "data and Import face data do, without the file pickers a session cannot show. Paths are full paths."; t.input_schema = R"({"type":"object","properties":{"export":{"type":"string"},"import":{"type":"string"}},"additionalProperties":false})"; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { const auto is_export = call->has("export"); const auto text = call->text(is_export ? "export" : "import"); @@ -530,18 +522,18 @@ namespace job->complete(ok ? core::mcp::tool_result::text(message) : core::mcp::tool_result::error(message)); }; - auto& state = host.app()._state; + auto& state = app._state; if (is_export) export_face_book(state, core::file_path(text), std::move(done)); else import_face_book(state, core::file_path(text), std::move(done)); host.wait(call, job, 60.0, false); }; - host.add(std::move(t), tool_tier::write, true); + host.add(std::move(t), ui::agent_tier::write, true); } } -void add_face_tools(mcp_host& host) +void add_face_tools(ui::agent_host& host, app_frame& app) { - add_faces_state(host); - add_faces_select(host); - add_faces_data(host); + add_faces_state(host, app); + add_faces_select(host, app); + add_faces_data(host, app); } diff --git a/src/app_mcp_json.h b/src/app_mcp_json.h deleted file mode 100644 index 48c965dd..00000000 --- a/src/app_mcp_json.h +++ /dev/null @@ -1,130 +0,0 @@ -// This file is part of the Diffractor photo and video organizer -// Copyright 2026 Zac Walker -// -// This Source Code Form is subject to the terms of the Mozilla Public -// License, v. 2.0. If a copy of the MPL was not distributed with this -// file, You can obtain one at https://mozilla.org/MPL/2.0/. - -// Purpose: What the agent tools (app_mcp*.cpp) build their answers with: a JSON object written as it is built, for a -// tool's structured result, and the text helpers they share. - -#pragma once - -#include -#include - -#include -#include - -class json_writer -{ - rapidjson::StringBuffer _buffer; - rapidjson::Writer _writer{_buffer}; - - static rapidjson::SizeType size_of(const std::string_view text) - { - return static_cast(text.size()); - } - -public: - json_writer() = default; - json_writer(const json_writer&) = delete; - json_writer& operator=(const json_writer&) = delete; - - json_writer& object() - { - _writer.StartObject(); - return *this; - } - - json_writer& end_object() - { - _writer.EndObject(); - return *this; - } - - json_writer& array() - { - _writer.StartArray(); - return *this; - } - - json_writer& end_array() - { - _writer.EndArray(); - return *this; - } - - json_writer& key(const std::string_view k) - { - _writer.Key(k.data(), size_of(k)); - return *this; - } - - json_writer& text(const std::string_view v) - { - _writer.String(v.data(), size_of(v)); - return *this; - } - - // A number that is not finite has no JSON spelling, so it is written as null. - json_writer& number(const double v) - { - if (std::isfinite(v)) _writer.Double(v); - else _writer.Null(); - return *this; - } - - json_writer& integer(const int64_t v) - { - _writer.Int64(v); - return *this; - } - - json_writer& boolean(const bool v) - { - _writer.Bool(v); - return *this; - } - - json_writer& null() - { - _writer.Null(); - return *this; - } - - // A value that is JSON already. - json_writer& raw(const std::string_view json) - { - _writer.RawValue(json.data(), json.size(), rapidjson::kObjectType); - return *this; - } - - json_writer& text(const std::string_view k, const std::string_view v) { return key(k).text(v); } - json_writer& number(const std::string_view k, const double v) { return key(k).number(v); } - json_writer& integer(const std::string_view k, const int64_t v) { return key(k).integer(v); } - json_writer& boolean(const std::string_view k, const bool v) { return key(k).boolean(v); } - - std::string str() const { return {_buffer.GetString(), _buffer.GetSize()}; } -}; - -inline std::string join_text(const std::vector& parts, const std::string_view separator) -{ - std::string result; - - for (const auto& part : parts) - { - if (!result.empty()) result += separator; - result += part; - } - - return result; -} - -// The whole number text begins with, or zero. -inline int parse_int(const std::string_view text) -{ - auto value = 0; - std::from_chars(text.data(), text.data() + text.size(), value); - return value; -} diff --git a/src/app_mcp_tools.cpp b/src/app_mcp_tools.cpp index 8c002256..dcb6cc78 100644 --- a/src/app_mcp_tools.cpp +++ b/src/app_mcp_tools.cpp @@ -14,7 +14,6 @@ #include "pch.h" #include "app_mcp.h" -#include "app_mcp_json.h" #include "app_movie_batch.h" #include "app_dup_report.h" #include "model_db.h" @@ -44,7 +43,8 @@ namespace // In a session, work runs on the agent's thread as the call's job, which keeps what it prints; called once from // the command line, it runs here, printing to stderr. - void run_work(mcp_host& host, const core::mcp::call_ptr& call, const std::string_view tool, work_fn work) + void run_work(ui::agent_host& host, app_frame& app, const core::mcp::call_ptr& call, const std::string_view tool, + work_fn work) { if (host.is_console()) { @@ -57,7 +57,7 @@ namespace job->on_cancel([cancelled] { *cancelled = true; }); job->progress(-1.0, "waiting for the agent's thread"); - host.app().queue_async(async_queue::agent, [job, cancelled, work = std::move(work)] + app.queue_async(async_queue::agent, [job, cancelled, work = std::move(work)] { const print_fn print = [&job](const std::string_view line) { @@ -71,7 +71,7 @@ namespace job->complete(work(print, progress, core::cancel_token(*cancelled))); }); - host.wait(call, job, mcp_host::wait_seconds(*call), false); + host.wait(call, job, ui::agent_host::wait_seconds(*call), false); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -97,10 +97,10 @@ namespace report.projects.size() == 1 ? "" : "s", counts); } - void run_movie(mcp_host& host, const core::mcp::call_ptr& call, const std::string_view tool, + void run_movie(ui::agent_host& host, app_frame& app, const core::mcp::call_ptr& call, const std::string_view tool, movie_batch_options options) { - run_work(host, call, tool, + run_work(host, app, call, tool, [tool = std::string(tool), options = std::move(options)](const print_fn& print, const progress_fn& progress, const core::cancel_token& cancel) @@ -113,15 +113,15 @@ namespace printed += '\n'; }, cancel, progress); - return structured_result(std::format("{}\n\n{}", movie_summary(tool, report), printed), - format_movie_batch_report(report), !report.succeeded); + return core::mcp::structured_result(std::format("{}\n\n{}", movie_summary(tool, report), printed), + format_movie_batch_report(report), !report.succeeded); }); } constexpr std::string_view wait_property = R"("wait_s":{"type":"number","minimum":0,"maximum":600,"description":"How long to wait for the answer before replying with a job to wait on; 50 by default."})"; - void add_movie_check(mcp_host& host) + void add_movie_check(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "movie_check"; @@ -135,18 +135,18 @@ namespace wait_property); t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { movie_batch_options options; options.projects = call->text("projects"); options.skip_missing = call->flag("skip_missing", false); options.mode = movie_batch_mode::check; - run_movie(host, call, "movie_check", std::move(options)); + run_movie(host, app, call, "movie_check", std::move(options)); }; - host.add(std::move(t), tool_tier::read, false); + host.add(std::move(t), ui::agent_tier::read, false); } - void add_movie_render(mcp_host& host) + void add_movie_render(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "movie_render"; @@ -160,7 +160,7 @@ namespace R"({{"type":"object","properties":{{"projects":{{"type":"string","description":"The full path of a .dfv project, or of a folder of them"}},"output":{{"type":"string","description":"The full path of the folder the movies go to"}},"overwrite":{{"type":"boolean"}},"skip_missing":{{"type":"boolean","description":"Leave out clips whose source cannot be used, rather than refusing the project"}},{}}},"required":["projects"],"additionalProperties":false}})", wait_property); t.annotations.destructive = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { movie_batch_options options; options.projects = call->text("projects"); @@ -168,9 +168,9 @@ namespace options.overwrite = call->flag("overwrite", false); options.skip_missing = call->flag("skip_missing", false); options.mode = movie_batch_mode::render; - run_movie(host, call, "movie_render", std::move(options)); + run_movie(host, app, call, "movie_render", std::move(options)); }; - host.add(std::move(t), tool_tier::write, false); + host.add(std::move(t), ui::agent_tier::write, false); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -179,7 +179,7 @@ namespace // The test runner's report: a line a test, " PASS (ms)" or " FAIL (ms)" with why on the // lines indented beneath, then "Results:

passed, failed, total". - core::mcp::tool_result test_report(const int exit_code, const std::string& out, const agent_job& job) + core::mcp::tool_result test_report(const int exit_code, const std::string& out, const ui::agent_job& job) { struct failure { @@ -221,9 +221,9 @@ namespace const auto parts = core::split(text.substr(9), false, [](const char c) { return c == ','; }); if (parts.size() >= 3) { - passed = parse_int(core::trim(parts[0])); - failed = parse_int(core::trim(parts[1])); - total = parse_int(core::trim(parts[2])); + passed = core::to_int(core::trim(parts[0])); + failed = core::to_int(core::trim(parts[1])); + total = core::to_int(core::trim(parts[2])); } } } @@ -235,7 +235,7 @@ namespace job.recent_output(40) + out.substr(out.size() > 4000 ? out.size() - 4000 : 0))); } - json_writer json; + core::json::writer json; json.object().integer("passed", passed).integer("failed", failed).integer("total", total); json.integer("exit_code", exit_code).number("seconds", job.seconds()); json.key("failures").array(); @@ -244,10 +244,10 @@ namespace auto text = std::format("{} passed, {} failed, {} total, in {:.0f} s", passed, failed, total, job.seconds()); for (const auto& f : failures) text += std::format("\n\nFAIL {}\n{}", f.test, f.message); - return structured_result(std::move(text), json.str(), failed > 0 || exit_code != 0); + return core::mcp::structured_result(std::move(text), json.str(), failed > 0 || exit_code != 0); } - void add_run_tests(mcp_host& host) + void add_run_tests(ui::agent_host& host) { core::mcp::tool t; t.name = "run_tests"; @@ -262,12 +262,28 @@ namespace t.handler = [&host](const core::mcp::call_ptr& call) { const auto filter = call->text("filter", "*"); - host.run_child(call, "run_tests", {std::format("-test:{}", filter)}, test_report); + // How many tests the run says it runs, and how many it has reported. + const auto tests = std::make_shared>(0, 0); + + host.run_child(call, "run_tests", {std::format("-test:{}", filter)}, test_report, + [tests](const std::string_view line, ui::agent_job& job) + { + if (line.starts_with("Running ") && line.ends_with(" tests...")) + { + tests->first = core::to_int(line.substr(8)); + } + else if ((line.starts_with(" PASS") || line.starts_with(" FAIL")) && tests->first > 0) + { + ++tests->second; + job.progress(static_cast(tests->second) / tests->first, + std::format("{} of {} tests", tests->second, tests->first)); + } + }); }; - host.add(std::move(t), tool_tier::dev, false); + host.add(std::move(t), ui::agent_tier::dev, false); } - void add_validate_translations(mcp_host& host) + void add_validate_translations(ui::agent_host& host) { core::mcp::tool t; t.name = "validate_translations"; @@ -281,18 +297,18 @@ namespace t.handler = [&host](const core::mcp::call_ptr& call) { host.run_child(call, "validate_translations", {"-validate-po"}, - [](const int exit_code, const std::string& out, const agent_job&) + [](const int exit_code, const std::string& out, const ui::agent_job&) { - json_writer json; + core::json::writer json; json.object().boolean("ok", exit_code == 0).integer("exit_code", exit_code).end_object(); - return structured_result(out.empty() ? std::format("Ended with code {}", exit_code) : out, json.str(), - exit_code != 0); + return core::mcp::structured_result(out.empty() ? std::format("Ended with code {}", exit_code) : out, + json.str(), exit_code != 0); }); }; - host.add(std::move(t), tool_tier::dev, false); + host.add(std::move(t), ui::agent_tier::dev, false); } - void add_generate_docs(mcp_host& host) + void add_generate_docs(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "generate_docs"; @@ -302,9 +318,9 @@ namespace t.input_schema = std::format( R"({{"type":"object","properties":{{"folder":{{"type":"string","description":"The full path of the folder to write to"}},{}}},"additionalProperties":false}})", wait_property); - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - run_work(host, call, "generate_docs", + run_work(host, app, call, "generate_docs", [folder = call->text("folder")](const print_fn& print, const progress_fn&, const core::cancel_token&) { @@ -318,10 +334,10 @@ namespace return code == 0 ? core::mcp::tool_result::text(printed) : core::mcp::tool_result::error(printed); }); }; - host.add(std::move(t), tool_tier::dev, false); + host.add(std::move(t), ui::agent_tier::dev, false); } - void add_duplicate_report(mcp_host& host) + void add_duplicate_report(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "duplicate_report"; @@ -333,9 +349,9 @@ namespace R"({{"type":"object","properties":{{"folder":{{"type":"string","description":"The full path of the library folder"}},"output":{{"type":"string","description":"The full path of a file to write the report to"}},{}}},"required":["folder"],"additionalProperties":false}})", wait_property); t.annotations.read_only = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - run_work(host, call, "duplicate_report", + run_work(host, app, call, "duplicate_report", [folder = call->text("folder"), output = call->text("output")](const print_fn& print, const progress_fn&, const core::cancel_token&) @@ -350,7 +366,7 @@ namespace return code == 0 ? core::mcp::tool_result::text(printed) : core::mcp::tool_result::error(printed); }); }; - host.add(std::move(t), tool_tier::dev, false); + host.add(std::move(t), ui::agent_tier::dev, false); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -375,18 +391,18 @@ namespace return text; } - void write_date(json_writer& json, const std::string_view key, const core::date_t date) + void write_date(core::json::writer& json, const std::string_view key, const core::date_t date) { if (date.is_valid()) json.text(key, date.to_xmp_date()); } - void write_text(json_writer& json, const std::string_view key, const core::cached value) + void write_text(core::json::writer& json, const std::string_view key, const core::cached value) { if (!value.is_empty()) json.text(key, value.sv()); } // What the metadata says, leaving out what it does not. - void write_metadata(json_writer& json, const prop::item_metadata& md) + void write_metadata(core::json::writer& json, const prop::item_metadata& md) { json.key("metadata").object(); write_text(json, "title", md.title); @@ -467,7 +483,7 @@ namespace } // One file the index holds: its kind, size and dates, the copies of it, and its metadata where asked. - void write_file(json_writer& json, const core::file_path path, const df::index_file_item& file, + void write_file(core::json::writer& json, const core::file_path path, const df::index_file_item& file, const bool with_metadata) { json.text("path", path.str()).text("kind", "file"); @@ -550,7 +566,7 @@ namespace const auto first = std::min(offset, total); const auto last = std::min(total, first + limit); - json_writer json; + core::json::writer json; json.object().text("query", query).text("search", search.text()); json.integer("total", static_cast(total)).integer("offset", static_cast(first)); json.boolean("complete", complete).boolean("more", last < total).boolean("index_busy", index_busy); @@ -598,10 +614,10 @@ namespace json.end_array().end_object(); if (last < total) text += std::format("\n... {} more: offset {} reads on", total - last, last); - return structured_result(std::move(text), json.str()); + return core::mcp::structured_result(std::move(text), json.str()); } - void add_search(mcp_host& host) + void add_search(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "search"; @@ -618,9 +634,8 @@ namespace wait_property); t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto query = call->text("query"); const auto limit = static_cast(call->number("limit").value_or(100)); const auto offset = static_cast(call->number("offset").value_or(0)); @@ -629,7 +644,7 @@ namespace const auto order = sort == "created" ? result_order::created : sort == "duplicates" ? result_order::duplicates : result_order::path; - const auto wait_s = mcp_host::wait_seconds(*call); + const auto wait_s = ui::agent_host::wait_seconds(*call); const auto job = host.start_job("search"); const auto cancelled = std::make_shared(false); @@ -667,10 +682,10 @@ namespace host.wait(call, job, wait_s + 10.0, false); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } - void add_item_info(mcp_host& host) + void add_item_info(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "item_info"; @@ -683,9 +698,8 @@ namespace R"({"type":"object","properties":{"path":{"type":"string","description":"The file's full path"}},"required":["path"],"additionalProperties":false})"; t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto text = call->text("path"); if (!core::is_path(text)) @@ -701,14 +715,15 @@ namespace if (indexed.ft) { - json_writer json; + core::json::writer json; json.object().boolean("in_index", true); write_file(json, path, indexed, true); json.end_object(); const auto md = indexed.metadata.load(); - call->finish(structured_result(file_summary(path, indexed.ft, indexed.size.to_int64(), md.get()) + - "; in the index", - json.str())); + call->finish( + core::mcp::structured_result(file_summary(path, indexed.ft, indexed.size.to_int64(), md.get()) + + "; in the index", + json.str())); return; } @@ -727,7 +742,7 @@ namespace files reader; const auto scanned = reader.scan_file(path, false, ft); - json_writer json; + core::json::writer json; json.object().boolean("in_index", false).text("path", path.str()).text("kind", "file"); if (ft && ft->group) json.text("type", ft->group->name); json.integer("size", static_cast(info.size)); @@ -737,15 +752,15 @@ namespace if (md) write_metadata(json, *md); json.end_object(); - job->complete( - structured_result(file_summary(path, ft, info.size, md.get()) + - (md ? "; read from the file"s : "; Diffractor reads no metadata from it"s), - json.str())); + job->complete(core::mcp::structured_result(file_summary(path, ft, info.size, md.get()) + + (md ? "; read from the file"s + : "; Diffractor reads no metadata from it"s), + json.str())); }); - host.wait(call, job, mcp_host::wait_seconds(*call), false); + host.wait(call, job, ui::agent_host::wait_seconds(*call), false); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -840,7 +855,7 @@ namespace size_t suggested = 0; for (const auto& group : a.groups) suggested += group.items.size(); - json_writer json; + core::json::writer json; json.object().text("query", a.query).integer("max_gap_minutes", a.max_gap_minutes); json.integer("unplaced", static_cast(a.unplaced)) .integer("suggested", static_cast(suggested)); @@ -896,7 +911,8 @@ namespace const auto last_taken = minute_text(group.items.back().created); text += std::format("\n\nGroup {}: {} taken {}, within {} of {}, taken {} at {} {}{}. Search: {}", i + 1, counted(group.items.size(), "item", "items"), - first_taken == last_taken ? first_taken : first_taken + " to " + last_taken, + first_taken == last_taken ? first_taken + : std::format("{} to {}", first_taken, last_taken), gap_text(widest), located.path, minute_text(located.created), core::to_string(located.coordinate.latitude(), 5), core::to_string(located.coordinate.longitude(), 5), place.empty() ? "" : ", " + place, @@ -922,10 +938,10 @@ namespace "writes it."; } - return structured_result(std::move(text), json.str()); + return core::mcp::structured_result(std::move(text), json.str()); } - void add_location_suggest(mcp_host& host) + void add_location_suggest(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "location_suggest"; @@ -942,16 +958,15 @@ namespace wait_property); t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); location_suggest_answer answer; answer.query = call->text("query"); answer.max_gap_minutes = std::clamp(static_cast(call->number("max_gap_minutes").value_or(15)), int64_t{1}, int64_t{1440}); const auto limit = static_cast(call->number("limit").value_or(20)); const auto offset = static_cast(call->number("offset").value_or(0)); - const auto wait_s = mcp_host::wait_seconds(*call); + const auto wait_s = ui::agent_host::wait_seconds(*call); const auto job = host.start_job("location_suggest"); const auto cancelled = std::make_shared(false); @@ -1017,23 +1032,23 @@ namespace host.wait(call, job, wait_s + 10.0, false); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } } -void add_engine_tools(mcp_host& host) +void add_engine_tools(ui::agent_host& host, app_frame& app) { - add_movie_check(host); - add_movie_render(host); + add_movie_check(host, app); + add_movie_render(host, app); add_run_tests(host); add_validate_translations(host); - add_generate_docs(host); - add_duplicate_report(host); + add_generate_docs(host, app); + add_duplicate_report(host, app); } -void add_library_tools(mcp_host& host) +void add_library_tools(ui::agent_host& host, app_frame& app) { - add_search(host); - add_item_info(host); - add_location_suggest(host); + add_search(host, app); + add_item_info(host, app); + add_location_suggest(host, app); } diff --git a/src/app_mcp_ui.cpp b/src/app_mcp_ui.cpp index a0bc312c..00ac6380 100644 --- a/src/app_mcp_ui.cpp +++ b/src/app_mcp_ui.cpp @@ -5,15 +5,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The agent tools over the window (app_mcp.h): what it shows, its commands, where it is and what is selected, -// input acted out as a tutorial script's steps, the dialogs that open and their answers, screenshots and recordings, -// and tutorials played and filmed. Commands and input that can change files need -mcp-allow:write; pictures need -// capture. +// Purpose: Diffractor's own tools over the window (app_mcp.h): where it is and what is selected, input acted out as a +// tutorial script's steps, tutorials played and filmed, recordings, and the task views' panels and reviews. The host +// (libdesktop/ui/agent.h) answers what any window answers - what it shows, its controls, commands, dialogs, menus and +// screenshots. Input that can change files needs -mcp-allow:write; pictures need capture. #include "pch.h" #include "app_mcp.h" -#include "app_mcp_json.h" #include "files.h" #include "model_db.h" #include "model_faces_search.h" @@ -39,486 +38,6 @@ namespace constexpr double caught_up_quiet_s = 0.05; constexpr double caught_up_timeout_s = 5.0; - // Including a task's review, which a change to its panel or the selection sets working out again. - bool window_caught_up(const app_frame& app) - { - return app._invalids.load() == view_invalid::none && !(app._view && app._view->reviewing()); - } - - bool refused_while_modal(const mcp_host& host, const core::mcp::call_ptr& call) - { - if (!host.modal_ui_open()) return false; - - // Input waits behind work a dialog shows under way as it does behind a question, but there is nothing to answer. - const auto work = dialogs_showing_work(); - call->finish(core::mcp::tool_result::error( - !work.empty() && !host.answerable_ui_open() - ? std::format("Diffractor is busy - {} - and input waits behind it: wait_until_idle, then try again", - join_text(work, ", ")) - : "A dialog or menu is open, and input waits behind it: ui_state shows it, dialog_respond answers a " - "dialog and menu_respond a menu"s)); - return true; - } - - // Answers the call once ready has held for quiet_s, or once timeout_s pass, with what answer makes of it; and - // sooner, where interruptible, if a dialog or menu opens - the job then goes on, for job_wait. - void answer_when(mcp_host& host, const core::mcp::call_ptr& call, const std::string_view tool, - std::function ready, const double quiet_s, const double timeout_s, - const bool interruptible, std::function answer) - { - const auto job = host.start_job(tool); - host.when(std::move(ready), quiet_s, timeout_s, [job, answer = std::move(answer)](const bool met) - { - if (!job->is_done()) job->complete(answer(met)); - }); - host.wait(call, job, timeout_s + 1.0, interruptible); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Dialogs - /////////////////////////////////////////////////////////////////////////////////////////////////// - - // A control's text as it reads: its mnemonic marker taken out. - std::string plain_label(const std::string_view text) - { - std::string result; - - for (size_t i = 0; i < text.size(); ++i) - { - if (text[i] == '&') - { - if (i + 1 < text.size() && text[i + 1] == '&') - { - result += '&'; - ++i; - } - - continue; - } - - result += text[i]; - } - - return result; - } - - // What a dialog shows, and the controls an answer works. - struct dialog_parts - { - struct button_part - { - ui::button_ptr control; - std::string text; - bool is_default = false; - bool enabled = true; - }; - - struct check_part - { - ui::button_ptr control; - std::string text; - bool checked = false; - bool radio = false; - bool enabled = true; - }; - - // A field is typed into, or holds a date. - struct field_part - { - ui::edit_ptr edit; - ui::date_time_control_ptr date; - std::string label; - std::string text; - bool enabled = true; - }; - - std::shared_ptr

owner; - // A prompt the system put up in front, rather than one of Diffractor's dialogs: answered through the platform, - // by its buttons alone. - uintptr_t system_prompt = 0; - std::vector titles; - std::vector texts; - std::vector buttons; - std::vector checks; - std::vector fields; - // A list a search fills - Copy to folder's folders, the people naming a face offers - each row by its text. - struct row_part - { - std::shared_ptr list; - ui::auto_complete_match_ptr match; - std::string text; - bool selected = false; - }; - std::vector rows; - // What was read last on the way to the next field. - std::string read_before; - }; - - std::string date_text(const core::date_t date) - { - return date.is_valid() ? date.to_xmp_date() : std::string{}; - } - - std::optional parse_date(const std::string_view text) - { - core::date_t date; - if (date.parse(core::trim(text)) && date.is_valid()) return date; - return std::nullopt; - } - - // What a field is called: its own label, or else what is read just before it - the heading above it, or the check - // box it belongs to - where that is short enough to be one. A heading that goes on to explain is called by its - // first sentence. - std::string field_label(const std::string& own, const std::string& before) - { - constexpr size_t longest_label = 80; - if (!own.empty()) return own; - - auto label = std::string(core::trim(before)); - if (const auto stop = label.find(". "); stop != std::string::npos) label.resize(stop); - while (!label.empty() && (label.back() == ':' || label.back() == ' ' || label.back() == '.')) label.pop_back(); - return label.size() <= longest_label ? label : std::string{}; - } - - void collect(const view_element_ptr& e, const std::string& label, const bool enabled, dialog_parts& parts) - { - if (!e || !e->is_visible()) return; - - const auto here_enabled = enabled && e->is_enabled(); - auto here_label = label; - - if (const auto* const title = dynamic_cast(e.get())) - { - if (!title->text().empty()) - { - parts.titles.push_back(title->text()); - parts.read_before = title->text(); - } - } - else if (const auto* const title2 = dynamic_cast(e.get())) - { - if (!title2->title().empty()) - { - parts.titles.push_back(title2->title()); - parts.read_before = title2->title(); - } - - if (!title2->details().empty()) parts.texts.push_back(title2->details()); - } - else if (const auto* const busy = dynamic_cast(e.get())) - { - if (!busy->text().empty()) parts.texts.push_back(busy->text()); - } - else if (const auto* const paragraph = dynamic_cast(e.get())) - { - if (!paragraph->text().empty()) - { - parts.texts.push_back(paragraph->text()); - parts.read_before = paragraph->text(); - } - } - else if (const auto* const labelled = dynamic_cast(e.get())) - { - if (!labelled->label().empty()) here_label = plain_label(labelled->label()); - } - else if (const auto* const row = dynamic_cast(e.get())) - { - if (!row->row_label().empty()) here_label = plain_label(row->row_label()); - } - else if (const auto button = std::dynamic_pointer_cast(e)) - { - const auto usable = here_enabled && button->enabled; - auto text = plain_label(button->window_text()); - - if (button->traits.push_button) - { - parts.buttons.push_back({button, std::move(text), button->traits.default_button, usable}); - } - else - { - parts.read_before = text; - parts.checks.push_back( - {button, std::move(text), button->is_checked(), button->traits.radio_group >= 0, usable}); - } - } - else if (const auto edit = std::dynamic_pointer_cast(e)) - { - parts.fields.push_back({edit, nullptr, field_label(here_label, parts.read_before), edit->window_text(), - here_enabled && edit->enabled}); - parts.read_before.clear(); - } - else if (const auto date = std::dynamic_pointer_cast(e)) - { - parts.fields.push_back({nullptr, date, field_label(here_label, parts.read_before), date_text(date->date()), - here_enabled && date->enabled}); - parts.read_before.clear(); - } - else if (const auto list = std::dynamic_pointer_cast(e)) - { - for (const auto& r : list->_results) - { - if (!r) continue; - const auto selected = list->_completes && list->_completes->selected() == r; - parts.rows.push_back({list, r, r->edit_text(), selected}); - } - } - - e->visit_children([&](const view_element_ptr& child) { collect(child, here_label, here_enabled, parts); }); - } - - // Oldest first: the last is the one in front. - std::vector open_dialog_parts() - { - std::vector result; - - for (const auto& weak : open_dialogs()) - { - const auto d = weak.lock(); - if (!d || !d->frame()->is_visible()) continue; - - dialog_parts parts; - parts.owner = d; - for (const auto& c : d->_controls) collect(c, {}, true, parts); - result.push_back(std::move(parts)); - } - - return result; - } - - // Diffractor's dialogs, then what the system has put up in front of them all - a shell confirmation or error, a - // message box - read as a screen reader reads it, since nobody is there to answer it but the agent. - std::vector dialogs_and_prompts() - { - auto result = open_dialog_parts(); - - for (auto& prompt : platform::system_prompts()) - { - dialog_parts parts; - parts.system_prompt = prompt.id; - parts.titles.push_back(std::move(prompt.title)); - parts.texts = std::move(prompt.texts); - for (auto& b : prompt.buttons) parts.buttons.push_back({nullptr, std::move(b), false, true}); - result.push_back(std::move(parts)); - } - - return result; - } - - std::shared_ptr front_dialog() - { - const auto& dialogs = open_dialogs(); - - for (auto i = dialogs.rbegin(); i != dialogs.rend(); ++i) - { - if (auto d = i->lock(); d && d->frame()->is_visible()) return d; - } - - return nullptr; - } - - // The check boxes and fields of a dialog or a task's panel, into an open object. - void write_checks_and_fields(json_writer& json, const dialog_parts& parts) - { - json.key("checks").array(); - - for (const auto& c : parts.checks) - { - json.object().text("text", c.text).boolean("checked", c.checked).boolean("radio", c.radio); - json.boolean("enabled", c.enabled).end_object(); - } - - json.end_array(); - json.key("fields").array(); - - for (const auto& f : parts.fields) - { - json.object().text("label", f.label).text("text", f.text); - if (f.date) json.text("kind", "date"); - json.boolean("enabled", f.enabled).end_object(); - } - - json.end_array(); - } - - std::string checks_and_fields_text(const dialog_parts& parts) - { - std::string text; - - for (const auto& f : parts.fields) - { - text += std::format("\n {}field {}: '{}'{}", f.date ? "date "s : ""s, - f.label.empty() ? "(unlabelled)"s : f.label, f.text, f.enabled ? "" : " (disabled)"); - } - - for (const auto& c : parts.checks) - { - const auto* const mark = c.radio ? (c.checked ? "(o)" : "( )") : (c.checked ? "[x]" : "[ ]"); - text += std::format("\n {} {}{}", mark, c.text, c.enabled ? "" : " (disabled)"); - } - - return text; - } - - void write_dialog(json_writer& json, const dialog_parts& parts) - { - json.object(); - json.text("title", parts.titles.empty() ? std::string{} : parts.titles.front()); - if (parts.system_prompt != 0) json.boolean("system", true); - json.key("text").array(); - for (size_t i = 1; i < parts.titles.size(); ++i) json.text(parts.titles[i]); - for (const auto& t : parts.texts) json.text(t); - json.end_array(); - json.key("buttons").array(); - - for (const auto& b : parts.buttons) - { - json.object().text("text", b.text).boolean("default", b.is_default).boolean("enabled", b.enabled); - json.end_object(); - } - - json.end_array(); - write_checks_and_fields(json, parts); - if (!parts.rows.empty()) - { - json.key("rows").array(); - for (const auto& r : parts.rows) - json.object().text("text", r.text).boolean("selected", r.selected).end_object(); - json.end_array(); - } - json.end_object(); - } - - void write_dialogs(json_writer& json, const std::vector& dialogs) - { - json.key("dialogs").array(); - for (const auto& d : dialogs) write_dialog(json, d); - json.end_array(); - } - - std::string dialogs_text(const std::vector& dialogs) - { - std::string text; - - for (const auto& d : dialogs) - { - text += std::format("\n{}: {}", d.system_prompt != 0 ? "Windows' dialog"sv : "Dialog"sv, - d.titles.empty() ? "(untitled)"s : d.titles.front()); - for (size_t i = 1; i < d.titles.size(); ++i) text += "\n " + d.titles[i]; - for (const auto& t : d.texts) text += "\n " + t; - text += checks_and_fields_text(d); - - if (!d.rows.empty()) - { - text += "\n rows:"; - for (const auto& r : d.rows) text += std::format(" [{}]{}", r.text, r.selected ? " (chosen)" : ""); - } - - if (!d.buttons.empty()) - { - text += "\n buttons:"; - for (const auto& b : d.buttons) text += std::format(" [{}]{}", b.text, b.enabled ? "" : " (disabled)"); - } - } - - return text; - } - - // The fields and check boxes an answer names, found and checked before anything is touched. - struct form_answer - { - std::vector> fills; - std::vector> ticks; - }; - - // The object an argument holds, where it names anything. - const rapidjson::Value* named_values(const rapidjson::Value& arguments, const char* const name) - { - if (!arguments.HasMember(name)) return nullptr; - const auto& value = arguments[name]; - return value.IsObject() && value.MemberCount() > 0 ? &value : nullptr; - } - - // How ready a field an answer names must be: there and taking input, as one about to be typed into; there, enabled - // or not, where a check box set by the same answer can still enable it; or not there yet, where such a check box - // can still show it. - enum class field_need - { - enabled, - present, - may_appear, - }; - - void find_fields(const dialog_parts& parts, const rapidjson::Value& fields, const field_need need, - form_answer& answer, std::vector& problems) - { - for (const auto& m : fields.GetObject()) - { - const std::string_view label(m.name.GetString(), m.name.GetStringLength()); - std::string value(m.value.GetString(), m.value.GetStringLength()); - const auto found = std::ranges::find_if(parts.fields, - [label](const auto& f) { return core::icmp(f.label, label) == 0; }); - - if (found == parts.fields.end()) - { - if (need != field_need::may_appear) problems.push_back(std::format("there is no field '{}'", label)); - } - else if (need == field_need::enabled && !found->enabled) - problems.push_back(std::format("the field '{}' is disabled", label)); - else if (found->date && !parse_date(value)) - { - problems.push_back( - std::format("'{}' holds a date, given as yyyy-mm-dd or yyyy-mm-dd hh:mm:ss, not '{}'", label, - value)); - } - else answer.fills.emplace_back(&*found, std::move(value)); - } - } - - void find_checks(const dialog_parts& parts, const rapidjson::Value& checks, form_answer& answer, - std::vector& problems) - { - for (const auto& m : checks.GetObject()) - { - const std::string_view text(m.name.GetString(), m.name.GetStringLength()); - const auto found = std::ranges::find_if(parts.checks, - [text](const auto& c) { return core::icmp(c.text, text) == 0; }); - - if (found == parts.checks.end()) problems.push_back(std::format("there is no check box '{}'", text)); - else if (!found->enabled) problems.push_back(std::format("'{}' is disabled", text)); - else if (found->radio && !m.value.GetBool()) - { - problems.push_back(std::format("'{}' is a radio button: choose another to turn it off", text)); - } - else answer.ticks.emplace_back(&*found, m.value.GetBool()); - } - } - - void tick_checks(const form_answer& answer) - { - for (const auto& [check, value] : answer.ticks) - { - if (check->checked != value) check->control->click(); - } - } - - // As typing does, or choosing a date: the field's owner hears of each change. - void fill_fields(const form_answer& answer) - { - for (const auto& [field, value] : answer.fills) - { - if (field->date) - { - field->date->date(*parse_date(value)); - continue; - } - - field->edit->focus(); - field->edit->select_all(); - field->edit->on_key(platform::keys::DEL, {}); - field->edit->on_text(value); - } - } - /////////////////////////////////////////////////////////////////////////////////////////////////// // What the window shows /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -559,7 +78,7 @@ namespace // The view, the search and the items shown, naming the first `listed` of them and of the selection, into an open // object. - void write_view(json_writer& json, const app_frame& app, const size_t listed) + void write_view(core::json::writer& json, const app_frame& app, const size_t listed) { const auto& state = app._state; json.text("view", agent_view_name(state.view_mode())).boolean("full_screen", state.is_full_screen); @@ -608,358 +127,11 @@ namespace return text; } - void add_ui_state(mcp_host& host) - { - core::mcp::tool t; - t.name = "ui_state"; - t.title = "What the window shows"; - t.description = "What the window shows now: the view, the folder or search, how many items it finds and " - "shows, the first of them and of the selection, the media shown - where it is, whether it " - "plays, and the parts of a video where faces the search found it by are seen - whether it is " - "busy, and any dialog in front - its text, buttons, check boxes and fields, for dialog_respond " - "- menu open - its rows, for menu_respond - recording or steps being acted out."; - t.input_schema = std::format(R"({{"type":"object","properties":{{{}}},"additionalProperties":false}})", - list_property); - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto listed = static_cast(call->number("list").value_or(20)); - const auto dialogs = dialogs_and_prompts(); - const auto busy = agent_window_busy(app); - const auto bounds = app._app_frame->window_bounds(); - - json_writer json; - json.object(); - write_view(json, app, listed); - json.key("window").object().integer("width", bounds.width()).integer("height", bounds.height()); - json.boolean("maximized", app._app_frame->is_maximized()).end_object(); - json.key("busy").array(); - for (const auto& b : busy) json.text(b); - json.end_array(); - json.boolean("menu_open", ui::menu_active > 0); - json.key("menu").raw(describe_menu_json()); - write_dialogs(json, dialogs); - json.boolean("acting", app._tutorial != nullptr); - if (app._recording) - json.key("recording").object().number("seconds", app._recording->elapsed()).end_object(); - json.end_object(); - - auto text = view_text(app, listed); - if (!busy.empty()) text += "\nBusy: " + join_text(busy, ", "); - if (ui::menu_active > 0) - { - const auto menu = describe_menu_text(); - text += menu.empty() ? "\nA menu is open."s : menu; - } - text += dialogs_text(dialogs); - call->finish(structured_result(std::move(text), json.str())); - }; - host.add(std::move(t), tool_tier::read, true); - } - - /////////////////////////////////////////////////////////////////////////////////////////////////// - // Commands - /////////////////////////////////////////////////////////////////////////////////////////////////// - - enum class command_need - { - read, - write, - network, - launch, - refused, - }; - - struct command_rule - { - command_need need = command_need::read; - std::string_view why; - }; - - // What a command needs of the session beyond reading: one that changes files, the clipboard or the system needs - // write; one that opens another program, a folder or a web page on the user's desktop needs launch; one that ends - // the session is not run. One that opens a menu needs nothing: what is chosen from it needs what its own command - // needs. - command_rule rule_of(const commands id) - { - constexpr std::string_view changes = "changes files, the clipboard or the system"; - constexpr std::string_view opens = "opens another program, a folder or a web page on the user's desktop"; - - switch (id) - { - case commands::exit: return {command_need::refused, "ends the session: close the session's input instead"}; - case commands::tool_scan: return {command_need::refused, "works a scanner through the system's own windows"}; -#ifndef WINSTORE - case commands::info_new_version: return {command_need::refused, "installs another version of Diffractor"}; - case commands::info_check_for_updates: - return {command_need::network, "asks diffractor.com for a newer version"}; -#endif - - case commands::browse_open_containingfolder: - case commands::browse_open_googlemap: - case commands::browse_open_in_file_browser: - case commands::options_help: - case commands::tool_open_with: - case commands::view_help: return {command_need::launch, opens}; - - case commands::edit_copy: - case commands::edit_copy_item_path: - case commands::edit_cut: - case commands::edit_item_save: - case commands::edit_item_save_and_next: - case commands::edit_item_save_and_prev: - case commands::edit_item_save_as: - case commands::edit_paste: - case commands::import_run: - case commands::label_approved: - case commands::label_none: - case commands::label_review: - case commands::label_second: - case commands::label_select: - case commands::label_to_do: - case commands::locate_run: - case commands::print: - case commands::rate_1: - case commands::rate_2: - case commands::rate_3: - case commands::rate_4: - case commands::rate_5: - case commands::rate_none: - case commands::rate_rejected: - case commands::sync_run: - case commands::tags_run: - case commands::tool_burn: - case commands::tool_copy_to_folder: - case commands::tool_delete: - case commands::tool_desktop_background: - case commands::tool_edit_description: - case commands::tool_eject: - case commands::tool_file_properties: - case commands::tool_move_to_folder: - case commands::tool_movie_render: - case commands::tool_movie_save: - case commands::tool_new_folder: - case commands::tool_rotate_anticlockwise: - case commands::tool_rotate_clockwise: - case commands::tool_rotate_reset: - case commands::tool_run: - case commands::tool_save_current_video_frame: - case commands::tool_share: return {command_need::write, changes}; - - // docs/faces.md#6-the-face-book: what the user tells Diffractor about faces is theirs, as their files are. - case commands::face_confirm: - case commands::face_hide: - case commands::face_import: - case commands::face_name: - case commands::face_name_picture: - case commands::face_reject: - case commands::face_rename_person: - case commands::face_undo_placement: - case commands::face_show_again: return {command_need::write, "changes the user's face book"}; - case commands::face_export: - case commands::face_save_names: return {command_need::write, changes}; - - default: return {}; - } - } - - std::string_view need_name(const command_need need) - { - switch (need) - { - case command_need::write: return "write"; - case command_need::network: return "network"; - case command_need::launch: return "launch"; - case command_need::refused: return "refused"; - case command_need::read: break; - } - - return {}; - } - - // Why the session does not run the command; empty where it does. - std::string command_refusal(const mcp_host& host, const commands id) - { - const auto rule = rule_of(id); - const auto& allow = host.options().allow; - const auto name = command_name(id); - - if (rule.need == command_need::refused) return std::format("{} is not run: it {}", name, rule.why); - if (rule.need == command_need::write && !allow.write) - { - return std::format("{} {}, which needs -mcp-allow:write", name, rule.why); - } - if (rule.need == command_need::network && !allow.network) - { - return std::format("{} {}, which needs -mcp-allow:network", name, rule.why); - } - if (rule.need == command_need::launch && !allow.launch) - { - return std::format("{} {}, which needs -mcp-allow:launch", name, rule.why); - } - - return {}; - } - - void add_command_list(mcp_host& host) - { - core::mcp::tool t; - t.name = "command_list"; - t.title = "List the commands"; - t.description = "Every command the window offers - what its menus, toolbars and keys run - by the name " - "command_run and ui_input's command step take: what each is called, whether it can run now and " - "if not why, whether it is checked, its keys, and what it needs of the session beyond reading. " - "contains narrows the list to names or text with those letters."; - t.input_schema = - R"({"type":"object","properties":{"contains":{"type":"string"},"enabled_only":{"type":"boolean"}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto contains = call->text("contains"); - const auto enabled_only = call->flag("enabled_only", false); - app.update_button_state(false); - - json_writer json; - json.object().key("commands").array(); - std::string text; - auto count = 0; - - for (const auto id : all_commands()) - { - const auto command = app.find_command(id); - if (!command) continue; - - const auto name = command_name(id); - const auto label = plain_label(command->text); - - if (!contains.empty() && core::ifind(name, contains) == std::string_view::npos && - core::ifind(label, contains) == std::string_view::npos) - { - continue; - } - - if (enabled_only && !command->enable) continue; - - const auto rule = rule_of(id); - json.object().text("name", name).text("text", label); - if (!command->tooltip_text.empty()) json.text("tooltip", command->tooltip_text); - json.boolean("enabled", command->enable); - if (!command->enable && !command->disabled_reason.empty()) - { - json.text("why_disabled", command->disabled_reason); - } - if (command->checkable || command->checked) json.boolean("checked", command->checked); - if (!command->keyboard_accelerator_text.empty()) json.text("keys", command->keyboard_accelerator_text); - if (rule.need != command_need::read) json.text("needs", need_name(rule.need)); - json.end_object(); - - text += std::format("\n{} - {}{}{}", name, label, command->enable ? "" : " (disabled)", - rule.need == command_need::read ? ""s : std::format(" [{}]", need_name(rule.need))); - ++count; - } - - json.end_array().integer("count", count).end_object(); - call->finish(structured_result(std::format("{} commands:{}", count, text), json.str())); - }; - host.add(std::move(t), tool_tier::read, true); - } - - void add_command_run(mcp_host& host) - { - core::mcp::tool t; - t.name = "command_run"; - t.title = "Run a command"; - t.description = "Runs a command as its menu item, button or key would, by the name command_list gives - " - "view_fullscreen, select_all, tool_rename. One that cannot run now says why. Commands that " - "change files, the clipboard or the system need -mcp-allow:write. One that opens a menu - " - "menu_main and the like - opens it as a press on its button does, and answers with the menu, " - "which menu_respond chooses from; one that opens a dialog answers with the dialog, which " - "dialog_respond answers."; - t.input_schema = std::format( - R"({{"type":"object","properties":{{"command":{{"type":"string"}},{}}},"required":["command"],"additionalProperties":false}})", - wait_property); - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto name = call->text("command"); - const auto id = command_from_name(name); - - if (!id) - { - call->finish(core::mcp::tool_result::error( - std::format("There is no command {}: command_list names them", name))); - return; - } - - if (const auto why = command_refusal(host, *id); !why.empty()) - { - call->finish(core::mcp::tool_result::error(why)); - return; - } - - if (refused_while_modal(host, call)) return; - - app.update_button_state(false); - const auto command = app.find_command(*id); - - if (!command || !command->enable) - { - const auto why = command && !command->disabled_reason.empty() ? command->disabled_reason - : "it is not offered here"s; - auto message = std::format("{} cannot run now: {}", name, why); - - // A task's command waits on the index the window loads; refused meanwhile, its reason can mislead. - if (const auto busy = agent_window_busy(app); !busy.empty()) - { - message += std::format(". Diffractor is still busy - {} - which may be why: wait_until_idle, then " - "try again", - join_text(busy, ", ")); - } - - call->finish(core::mcp::tool_result::error(std::move(message))); - return; - } - - const auto job = host.start_job("command_run"); - - // A task of its own: a command that opens a dialog or a menu runs its loop in it, and this call is answered - // with the dialog or menu meanwhile. What the command did is read once the window has caught up with it. - platform::run_ui([&host, &app, job, id = *id, name, command] - { - if (!command->invoke && command->menu) open_command_menu(app, command); - else app.invoke(id); - host.when([&app] { return window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, - [&host, &app, job, name](bool) - { - // Work the command left a dialog showing - an edit being saved - is part of it, done once that has - // gone. - host.when([] { return dialogs_showing_work().empty(); }, 0.0, mcp_host::longest_wait_seconds, - [&app, job, name](bool) - { - json_writer json; - json.object().text("command", name); - write_view(json, app, 10); - json.end_object(); - job->complete( - structured_result(std::format("Ran {}. {}", name, view_text(app, 0)), json.str())); - }); - }); - }); - - host.wait(call, job, mcp_host::wait_seconds(*call), true); - }; - host.add(std::move(t), tool_tier::read, true); - } - /////////////////////////////////////////////////////////////////////////////////////////////////// // Where the window is, and what is selected /////////////////////////////////////////////////////////////////////////////////////////////////// - void add_navigate(mcp_host& host) + void add_navigate(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "navigate"; @@ -970,9 +142,8 @@ namespace t.input_schema = std::format( R"({{"type":"object","properties":{{"to":{{"type":"string","description":"A folder's full path, or a search"}},{},{}}},"required":["to"],"additionalProperties":false}})", list_property, wait_property); - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto to = call->text("to"); const auto listed = static_cast(call->number("list").value_or(20)); @@ -982,25 +153,25 @@ namespace return; } - if (refused_while_modal(host, call)) return; + if (host.refused_while_modal(call)) return; app._state.open(app._view_frame, std::string_view(to)); - answer_when(host, call, "navigate", - [&app] { return !app._state.is_opening() && app._item_index.searching == 0; }, 0.3, - mcp_host::wait_seconds(*call), true, [&app, listed](const bool settled) + host.answer_when(call, "navigate", + [&app] { return !app._state.is_opening() && app._item_index.searching == 0; }, 0.3, + ui::agent_host::wait_seconds(*call), true, [&app, listed](const bool settled) { - json_writer json; + core::json::writer json; json.object(); write_view(json, app, listed); json.boolean("settled", settled).end_object(); - return structured_result(view_text(app, listed), json.str()); + return core::mcp::structured_result(view_text(app, listed), json.str()); }); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } - void add_select(mcp_host& host) + void add_select(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "select"; @@ -1009,14 +180,13 @@ namespace "added to it - or all of them, none, or the inverse. What is selected is what commands act on."; t.input_schema = R"({"type":"object","properties":{"names":{"type":"array","items":{"type":"string"},"description":"File names, as the window shows them, or full paths, which tell apart files of one name in different folders"},"add":{"type":"boolean","description":"Add to the selection rather than replace it"},"all":{"type":"boolean"},"none":{"type":"boolean"},"invert":{"type":"boolean"}},"additionalProperties":false})"; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); auto& state = app._state; const auto& view = app._view_frame; std::vector missing; - if (refused_while_modal(host, call)) return; + if (host.refused_while_modal(call)) return; if (call->flag("all", false)) { @@ -1067,11 +237,11 @@ namespace } } - answer_when(host, call, "select", [&app] { return window_caught_up(app); }, caught_up_quiet_s, - caught_up_timeout_s, false, [&app, missing](bool) + host.answer_when(call, "select", [&app] { return agent_window_caught_up(app); }, caught_up_quiet_s, + caught_up_timeout_s, false, [&app, missing](bool) { const auto& state = app._state; - json_writer json; + core::json::writer json; json.object(); write_view(json, app, 50); json.key("not_shown").array(); @@ -1079,20 +249,23 @@ namespace json.end_array().end_object(); auto text = std::format("{} selected", state.selected_count()); - if (!missing.empty()) text += std::format("; not shown in the window: {}", join_text(missing, ", ")); - return structured_result(std::move(text), json.str(), state.selected_count() == 0 && !missing.empty()); + if (!missing.empty()) + text += std::format("; not shown in the window: {}", core::combine(missing, ", ", false)); + return core::mcp::structured_result(std::move(text), json.str(), + state.selected_count() == 0 && !missing.empty()); }); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// - // Input, tutorials and dialogs + // Input and tutorials /////////////////////////////////////////////////////////////////////////////////////////////////// - core::mcp::tool_result player_answer(const app_frame& app, const tutorial_outcome& outcome, const agent_job& job) + core::mcp::tool_result player_answer(const app_frame& app, const tutorial_outcome& outcome, + const ui::agent_job& job) { - json_writer json; + core::json::writer json; json.object().boolean("ok", outcome.ok).text("summary", outcome.summary).integer("missed", outcome.missed); if (!outcome.movie.is_empty()) json.text("movie", outcome.movie.str()); if (!outcome.markers.is_empty()) json.text("markers", outcome.markers.str()); @@ -1105,21 +278,22 @@ namespace auto text = std::format("{}\n{}", outcome.summary, view_text(app, 0)); if (const auto said = job.all_output(); !said.empty()) text += "\n\n" + said; - return structured_result(std::move(text), json.str(), !outcome.ok); + return core::mcp::structured_result(std::move(text), json.str(), !outcome.ok); } // Acts the steps out as the call's job, a step at a time from the frame tick. Steps alone cannot see past a dialog, // so a call acting them out is answered once one shows; a tutorial's player waits for a dialog to close itself, // and says so. - void play(mcp_host& host, const core::mcp::call_ptr& call, const std::string_view tool, tutorial_options options) + void play(ui::agent_host& host, app_frame& app, const core::mcp::call_ptr& call, const std::string_view tool, + tutorial_options options) { - auto& app = host.app(); + const auto job = host.start_job(tool); const auto interruptible = options.steps_only; // A step reaches the commands command_run does, and is held to the same tiers. - options.refusal = [&host](const commands id) + options.refusal = [&host, &app](const commands id) { - return agent_command_refusal(host, id); + return host.command_refusal(agent_command_of(app, id)); }; options.said = [job](const std::string_view line) { @@ -1136,7 +310,7 @@ namespace { if (app._tutorial) app._tutorial->cancel(); }); - host.wait(call, job, mcp_host::wait_seconds(*call), interruptible); + host.wait(call, job, ui::agent_host::wait_seconds(*call), interruptible); } bool refused_while_acting(const app_frame& app, const core::mcp::call_ptr& call) @@ -1147,7 +321,7 @@ namespace return true; } - void add_ui_input(mcp_host& host) + void add_ui_input(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "ui_input"; @@ -1166,19 +340,19 @@ namespace R"({{"type":"object","properties":{{"steps":{{"type":"string","description":"One step a line"}},{}}},"required":["steps"],"additionalProperties":false}})", wait_property); t.annotations.destructive = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - if (refused_while_modal(host, call) || refused_while_acting(host.app(), call)) return; + if (host.refused_while_modal(call) || refused_while_acting(app, call)) return; tutorial_options options; options.text = call->text("steps"); options.steps_only = true; - play(host, call, "ui_input", std::move(options)); + play(host, app, call, "ui_input", std::move(options)); }; - host.add(std::move(t), tool_tier::write, true); + host.add(std::move(t), ui::agent_tier::write, true); } - void add_tutorial_run(mcp_host& host) + void add_tutorial_run(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "tutorial_run"; @@ -1193,9 +367,8 @@ namespace R"({{"type":"object","properties":{{"script":{{"type":"string","description":"The .dft script's full path"}},"text":{{"type":"string","description":"The script itself, in place of a file"}},"record":{{"type":"string","description":"The full path of the MP4 to film it to"}},{}}},"additionalProperties":false}})", wait_property); t.annotations.destructive = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto script = call->text("script"); const auto text = call->text("text"); const auto record = call->text("record"); @@ -1220,7 +393,7 @@ namespace { if (!core::is_path(record)) return refuse(std::format("Give the movie's full path, not {}", record)); - if (host.options().presence != agent_presence::visible) + if (host.options().presence != ui::agent_presence::visible) { return refuse("A recording films the window as the screen shows it, so the window must be on the " "desktop: start the session with -mcp-ui:visible, or leave out record to rehearse"); @@ -1228,215 +401,15 @@ namespace } if (app._recording) return refuse("The window is being recorded already: record_stop ends that first"); - if (refused_while_modal(host, call) || refused_while_acting(app, call)) return; + if (host.refused_while_modal(call) || refused_while_acting(app, call)) return; tutorial_options options; if (!script.empty()) options.script = core::file_path(script); options.text = text; if (!record.empty()) options.record = core::file_path(record); - play(host, call, "tutorial_run", std::move(options)); - }; - host.add(std::move(t), tool_tier::capture, true); - } - - void add_dialog_respond(mcp_host& host) - { - core::mcp::tool t; - t.name = "dialog_respond"; - t.title = "Answer a dialog"; - t.description = - "Answers the dialog in front, as ui_state shows it: fills fields by their label - a date as " - "yyyy-mm-dd hh:mm:ss - and sets check boxes and radio buttons by their text, then presses a " - "button by its text - or cancels the dialog, as Escape does. choose picks a row of the list a " - "search fills - Copy to folder's folders, the people naming a face offers - by its text, as a " - "click picks it, and then presses the button named, or else the default one. One Windows puts up " - "itself, marked system, is answered by its buttons or cancelled. A session that may not write can " - "only cancel: the rest can change files. Answers once the dialog has closed or another has " - "opened, with what is in front then."; - t.input_schema = std::format( - R"({{"type":"object","properties":{{"button":{{"type":"string","description":"The text of the button to press"}},"choose":{{"type":"string","description":"The text of a row of the dialog's list"}},"cancel":{{"type":"boolean"}},"checks":{{"type":"object","additionalProperties":{{"type":"boolean"}},"description":"Check boxes and radio buttons, by their text"}},"fields":{{"type":"object","additionalProperties":{{"type":"string"}},"description":"Fields, by their label"}},{}}},"additionalProperties":false}})", - wait_property); - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - auto dialogs = dialogs_and_prompts(); - const auto refuse = [&call](std::string why) - { - call->finish(core::mcp::tool_result::error(std::move(why))); - }; - - if (dialogs.empty()) - { - return refuse(ui::menu_active > 0 ? "A menu is open, not a dialog: menu_respond chooses from it" - : "No dialog is open"); - } - - auto& target = dialogs.back(); - const auto cancel = call->flag("cancel", false); - const auto button = call->text("button"); - const auto choose = call->text("choose"); - const auto* const checks = named_values(call->arguments(), "checks"); - const auto* const fields = named_values(call->arguments(), "fields"); - - if (cancel && (!button.empty() || !choose.empty())) - return refuse("Press a button or choose a row, or cancel: not both"); - if (!cancel && button.empty() && choose.empty() && !checks && !fields) - { - return refuse("Say what to do: fields or checks to set, a row to choose, a button to press, or cancel"); - } - - if ((!button.empty() || !choose.empty() || checks || fields) && !host.options().allow.write) - { - return refuse("This session can only cancel a dialog: pressing a button, choosing a row, setting a " - "check box or filling a field can change files, which needs -mcp-allow:write"); - } - - // Windows' own: pressed by its button's text, or cancelled, through the platform; it has nothing else this - // session can set. The answer waits for it to go, or for what it asks to have been answered. - if (const auto prompt = target.system_prompt; prompt != 0) - { - if (checks || fields || !choose.empty()) - { - return refuse("Nothing was changed: a dialog Windows shows is answered by its buttons alone." + - dialogs_text({target})); - } - - if (!button.empty() && std::ranges::none_of(target.buttons, [&button](const auto& b) - { return core::icmp(b.text, button) == 0; })) - { - return refuse( - std::format("Nothing was changed: there is no button '{}'.{}", button, dialogs_text({target}))); - } - - platform::run_ui([prompt, button] { platform::answer_system_prompt(prompt, button); }); - answer_when(host, call, "dialog_respond", [prompt] { return !platform::system_prompt_shown(prompt); }, - 0.2, mcp_host::wait_seconds(*call), false, [&app](const bool settled) - { - const auto now = dialogs_and_prompts(); - json_writer json; - json.object().boolean("closed", settled); - write_dialogs(json, now); - write_view(json, app, 0); - json.end_object(); - - auto text = now.empty() ? "The dialog has closed. " + view_text(app, 0) - : "In front now:" + dialogs_text(now); - if (!settled) text = "The dialog is still open. " + text; - return structured_result(std::move(text), json.str()); - }); - return; - } - - // Everything is found before anything is touched, so a wrong name changes nothing. - std::vector problems; - form_answer answer; - const dialog_parts::button_part* press = nullptr; - - if (fields) find_fields(target, *fields, field_need::enabled, answer, problems); - if (checks) find_checks(target, *checks, answer, problems); - - if (!button.empty()) - { - const auto found = std::ranges::find_if(target.buttons, [&button](const auto& b) - { return core::icmp(b.text, button) == 0; }); - - if (found == target.buttons.end()) problems.push_back(std::format("there is no button '{}'", button)); - else if (!found->enabled) problems.push_back(std::format("'{}' is disabled", button)); - else press = &*found; - } - - // A row is chosen as a click chooses it; the dialog is then answered by its default button, where no other - // is named. - const dialog_parts::row_part* chosen = nullptr; - if (!choose.empty()) - { - const auto found = std::ranges::find_if(target.rows, [&choose](const auto& r) - { return core::icmp(r.text, choose) == 0; }); - - if (found == target.rows.end()) problems.push_back(std::format("there is no row '{}'", choose)); - else chosen = &*found; - - if (chosen && button.empty()) - { - const auto answer_button = std::ranges::find_if(target.buttons, [](const auto& b) - { return b.is_default && b.enabled; }); - if (answer_button != target.buttons.end()) press = &*answer_button; - } - } - - if (!problems.empty()) - { - return refuse( - std::format("Nothing was changed: {}.{}", join_text(problems, "; "), dialogs_text({target}))); - } - - fill_fields(answer); - tick_checks(answer); - - if (!press && !cancel && !chosen) - { - const auto now = dialogs_and_prompts(); - json_writer json; - json.object(); - write_dialogs(json, now); - json.end_object(); - call->finish(structured_result("Set." + dialogs_text(now), json.str())); - return; - } - - const std::weak_ptr answered = target.owner; - - // A task of its own: what a button does may open another dialog, whose loop runs there. - if (chosen) - { - platform::run_ui( - [list = chosen->list, match = chosen->match, answered, control = press ? press->control : nullptr] - { - list->selected(match, ui::complete_strategy_t::select_type::click); - // A click on a row can answer the dialog itself, as Open with's does. - if (const auto d = answered.lock(); control && d && front_dialog() == d) control->click(); - }); - } - else if (press) - { - platform::run_ui([control = press->control] { control->click(); }); - } - else - { - platform::run_ui([answered] - { - const auto d = answered.lock(); - if (!d) return; - - // A dialog that reports work under way stops the work as its Cancel button does. - if (const auto stop = d->_close_cb) stop(); - else d->close(true); - }); - } - - // Answered once the dialog has gone, or another is in front of it - Windows' own among them, as a delete's - // confirmation can be. - answer_when(host, call, "dialog_respond", - [answered] - { - const auto d = answered.lock(); - return !d || front_dialog() != d || platform::system_prompt_shown(); - }, 0.2, mcp_host::wait_seconds(*call), false, [&app](const bool settled) - { - const auto now = dialogs_and_prompts(); - json_writer json; - json.object().boolean("closed", settled); - write_dialogs(json, now); - write_view(json, app, 0); - json.end_object(); - - auto text = now.empty() ? "The dialog has closed. " + view_text(app, 0) - : "In front now:" + dialogs_text(now); - if (!settled) text = "The dialog is still open. " + text; - return structured_result(std::move(text), json.str()); - }); + play(host, app, call, "tutorial_run", std::move(options)); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::capture, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1450,16 +423,11 @@ namespace constexpr std::string_view rows_properties = R"("contains":{"type":"string","description":"Only the review's rows with a cell holding this"},"column":{"type":"string","description":"The column contains looks in, by its heading; every column by default"},"offset":{"type":"integer","minimum":0,"description":"How many rows to pass over first, to read on"},"limit":{"type":"integer","minimum":0,"maximum":1000,"description":"How many rows to name; 20 by default"})"; - dialog_parts panel_parts(const app_frame& app) + // The task's panel, read as a dialog is read. + ui::agent_form panel_form(const ui::agent_host& host, const app_frame& app) { - dialog_parts parts; - - if (const auto panel = app._view_frame ? app._view_frame->_panel : nullptr) - { - for (const auto& c : panel->_controls) collect(c, {}, true, parts); - } - - return parts; + const auto panel = app._view_frame ? app._view_frame->_panel : nullptr; + return panel ? host.read_form(panel->_controls) : ui::agent_form{}; } // Which of a review's rows to name: those with a cell holding `contains` - in `column` where it names one - a page @@ -1493,7 +461,7 @@ namespace // The review of a task that is reviewed before it runs - or, after a run, what it did to each row - into an open // object, and as text. - void write_review(json_writer& json, std::string& text, review_list& list, const rows_wanted& wanted) + void write_review(core::json::writer& json, std::string& text, review_list& list, const rows_wanted& wanted) { const auto titles = list.column_titles(); std::vector columns; @@ -1505,6 +473,7 @@ namespace } std::vector headings; + headings.reserve(columns.size()); for (const auto c : columns) headings.push_back(titles[c].sv()); // The columns contains looks in: the one named, or all of them. @@ -1570,6 +539,7 @@ namespace for (auto i = first; i < last; ++i) { std::vector cells; + cells.reserve(columns.size()); for (const auto c : columns) cells.emplace_back(matching[i]->_text[c]); text += "\n " + join_cells(cells); } @@ -1582,20 +552,20 @@ namespace // The task view the window shows: its commands, status and progress, its panel's text, check boxes and fields, // and its review where it has one. - core::mcp::tool_result task_answer(app_frame& app, const rows_wanted& wanted) + core::mcp::tool_result task_answer(const ui::agent_host& host, app_frame& app, const rows_wanted& wanted) { const auto mode = app._state.view_mode(); const auto view = app._view; - json_writer json; + core::json::writer json; json.object().text("view", agent_view_name(mode)); if (!is_task_view(mode) || !view) { json.boolean("task", false).end_object(); - return structured_result(std::format("The window shows the {} view, which is no task: command_run opens " - "one with {}.", - agent_view_name(mode), task_commands), - json.str()); + return core::mcp::structured_result( + std::format("The window shows the {} view, which is no task: command_run opens one with {}.", + agent_view_name(mode), task_commands), + json.str()); } const auto progress = view->progress(); @@ -1630,21 +600,19 @@ namespace const auto command = id ? app.find_command(*id) : nullptr; if (!command || !command->visible) continue; - const auto name = command_name(*id); - const auto rule = rule_of(*id); - json.object().text("name", name).text("text", plain_label(command->text)); + const auto agent_command = agent_command_of(app, *id); + const auto need = ui::agent_tier_name(agent_command.need); + json.object().text("name", agent_command.name).text("text", ui::parse_mnemonic(command->text).text); json.boolean("enabled", command->enable); if (!command->enable && !command->disabled_reason.empty()) { json.text("why_disabled", command->disabled_reason); } - if (rule.need != command_need::read) json.text("needs", need_name(rule.need)); + if (!need.empty()) json.text("needs", need); json.end_object(); - command_text += std::format(" {}{}{}", name, - rule.need == command_need::read - ? ""s - : std::format(" [{}]", need_name(rule.need)), + command_text += std::format(" {}{}{}", agent_command.name, + need.empty() ? ""s : std::format(" [{}]", need), command->enable ? "" : " (disabled)"); } } @@ -1652,26 +620,26 @@ namespace json.end_array(); if (!command_text.empty()) text += "\nCommands:" + command_text; - const auto parts = panel_parts(app); + const auto form = panel_form(host, app); json.key("panel").object().key("text").array(); - for (const auto& t : parts.titles) json.text(t); - for (const auto& t : parts.texts) json.text(t); + for (const auto& t : form.titles) json.text(t); + for (const auto& t : form.texts) json.text(t); json.end_array(); - write_checks_and_fields(json, parts); + form.write_checks_and_fields(json); json.end_object(); text += "\nPanel:"; - for (const auto& t : parts.titles) text += "\n " + t; - for (const auto& t : parts.texts) text += "\n " + t; - text += checks_and_fields_text(parts); + for (const auto& t : form.titles) text += "\n " + t; + for (const auto& t : form.texts) text += "\n " + t; + text += form.checks_and_fields_text(); if (const auto list = std::dynamic_pointer_cast(view)) write_review(json, text, *list, wanted); json.end_object(); - return structured_result(std::move(text), json.str()); + return core::mcp::structured_result(std::move(text), json.str()); } - void add_task_state(mcp_host& host) + void add_task_state(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "task_state"; @@ -1687,49 +655,50 @@ namespace rows_properties); t.annotations.read_only = true; t.annotations.idempotent = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - call->finish(task_answer(host.app(), rows_wanted_of(*call))); + call->finish(task_answer(host, app, rows_wanted_of(*call))); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } // Answers task_set's job with the task as it stands once the window has caught up with what was set. The keyboard // goes back to the view first, which closes any suggestions a field offered as it was typed into. - void answer_task_set(mcp_host& host, app_frame& app, const agent_job_ptr& job) + void answer_task_set(ui::agent_host& host, app_frame& app, const ui::agent_job_ptr& job) { if (app._view_frame) app._view_frame->keyboard_to(keyboard_area::view, nullptr); - host.when([&app] { return window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, [&app, job](bool) + host.when([&app] { return agent_window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, + [&host, &app, job](bool) { - if (!job->is_done()) job->complete(task_answer(app, {.limit = 10})); + if (!job->is_done()) job->complete(task_answer(host, app, {.limit = 10})); }); } // Fills the fields task_set names as the panel shows them now - when every check box that could show or enable one // has been set - then answers. - void fill_task_fields(mcp_host& host, app_frame& app, const rapidjson::Value& fields, const bool ticked, - const agent_job_ptr& job) + void fill_task_fields(ui::agent_host& host, app_frame& app, const core::mcp::value& fields, const bool ticked, + const ui::agent_job_ptr& job) { - const auto now = panel_parts(app); + const auto now = panel_form(host, app); std::vector problems; - form_answer filled; - find_fields(now, fields, field_need::enabled, filled, problems); + ui::agent_form_answer filled; + filled.find_fields(now, fields, ui::agent_form_answer::field_need::enabled, problems); if (!problems.empty()) { job->complete(core::mcp::tool_result::error( std::format("{}: {}.\nThe panel:{}", ticked ? "The check boxes were set, but no field was filled" : "Nothing was changed", - join_text(problems, "; "), checks_and_fields_text(now)))); + core::combine(problems, "; ", false), now.checks_and_fields_text()))); return; } - fill_fields(filled); + filled.fill(); answer_task_set(host, app, job); } - void add_task_set(mcp_host& host) + void add_task_set(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "task_set"; @@ -1741,9 +710,8 @@ namespace "analyzing needs nothing more, running needs -mcp-allow:write. Answers with the task as it then stands."; t.input_schema = R"({"type":"object","properties":{"checks":{"type":"object","additionalProperties":{"type":"boolean"},"description":"Check boxes and radio buttons, by their text"},"fields":{"type":"object","additionalProperties":{"type":"string"},"description":"Fields, by their label"}},"additionalProperties":false})"; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&host, &app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto refuse = [&call](std::string why) { call->finish(core::mcp::tool_result::error(std::move(why))); @@ -1756,7 +724,7 @@ namespace agent_view_name(app._state.view_mode()), task_commands)); } - if (refused_while_modal(host, call)) return; + if (host.refused_while_modal(call)) return; if (app._view && app._view->progress().active) { @@ -1764,32 +732,33 @@ namespace "for it"); } - const auto* const checks = named_values(call->arguments(), "checks"); - const auto* const fields = named_values(call->arguments(), "fields"); + const auto* const checks = ui::agent_named_values(call->arguments(), "checks"); + const auto* const fields = ui::agent_named_values(call->arguments(), "fields"); if (!checks && !fields) return refuse("Say what to set: check boxes, fields or both"); - const auto parts = panel_parts(app); + const auto form = panel_form(host, app); std::vector problems; - form_answer answer; - if (checks) find_checks(parts, *checks, answer, problems); + ui::agent_form_answer answer; + if (checks) answer.find_checks(form, *checks, problems); // A check box this call changes can show or enable the fields under it, so until it is set a field need // only be there - and where one changes, not even that. - const auto changes_checks = std::ranges::any_of(answer.ticks, [](const auto& tick) - { return tick.first->checked != tick.second; }); + const auto changes_checks = answer.changes_checks(); if (fields) { - find_fields(parts, *fields, changes_checks ? field_need::may_appear : field_need::present, answer, - problems); + answer.find_fields(form, *fields, + changes_checks ? ui::agent_form_answer::field_need::may_appear + : ui::agent_form_answer::field_need::present, + problems); } if (!problems.empty()) { - return refuse(std::format("Nothing was changed: {}.\nThe panel:{}", join_text(problems, "; "), - checks_and_fields_text(parts))); + return refuse(std::format("Nothing was changed: {}.\nThe panel:{}", + core::combine(problems, "; ", false), form.checks_and_fields_text())); } - tick_checks(answer); + answer.tick(); const auto job = host.start_job("task_set"); if (!fields) @@ -1806,7 +775,7 @@ namespace // has found its controls where they now are. The fields are filled after that, as a user types into a // field once it can be seen. The call is held for the arguments fields points into. app.invalidate_view(view_invalid::view_layout); - host.when([&app] { return window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, + host.when([&app] { return agent_window_caught_up(app); }, caught_up_quiet_s, caught_up_timeout_s, [&host, &app, call, fields, job](bool) { if (job->is_done()) return; @@ -1826,7 +795,7 @@ namespace // Long enough for the window to catch up with the check boxes, then with the fields. host.wait(call, job, 2.0 * caught_up_timeout_s + 1.0, false); }; - host.add(std::move(t), tool_tier::read, true); + host.add(std::move(t), ui::agent_tier::read, true); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -1834,7 +803,7 @@ namespace /////////////////////////////////////////////////////////////////////////////////////////////////// // Capture makes new files; one saved over a file already there changes the user's files, which needs write. - std::string replace_refusal(const mcp_host& host, const std::initializer_list paths) + std::string replace_refusal(const ui::agent_host& host, const std::initializer_list paths) { if (host.options().allow.write) return {}; @@ -1847,126 +816,13 @@ namespace return {}; } - core::mcp::tool_result take_screenshot(app_frame& app, const std::string& target, const std::string& path, - const bool include_image, const int max_size, const bool settled) - { - auto frame = app._app_frame; - - if (target == "dialog") - { - const auto d = front_dialog(); - if (!d) return core::mcp::tool_result::error("No dialog is open"); - frame = d->frame(); - } - - const auto captured = platform::capture_window_surface(frame->handle()); - if (!captured) return core::mcp::tool_result::error("The window could not be captured: log_read says why"); - - files ff; - const auto surface = max_size > 0 ? ff.fit_within(captured, {max_size, max_size}) : captured; - const auto dimensions = surface->dimensions(); - - core::mcp::tool_result result; - std::string text; - - if (!path.empty()) - { - const auto file_path = core::file_path(path); - const auto image = ff.surface_to_image(surface, libfiles::metadata_blocks{}, file_encode_params{}, - extension_to_format(file_path.extension())); - const auto file = image ? platform::open_file(file_path, platform::file_open_mode::create) - : platform::file_ptr{}; - const auto saved = file && file->write(image->data().data(), image->data().size()) == image->data().size(); - if (!saved) return core::mcp::tool_result::error(std::format("The picture could not be saved to {}", path)); - text = std::format("Saved {}, {}x{}", path, dimensions.cx, dimensions.cy); - } - - if (include_image) - { - const auto png = ff.surface_to_image(surface, libfiles::metadata_blocks{}, file_encode_params{}, - core::image_format::PNG); - if (!png) return core::mcp::tool_result::error("The picture could not be encoded"); - - core::mcp::content image; - image.kind = core::mcp::content::kind_t::image; - image.data.assign(reinterpret_cast(png->data().data()), png->data().size()); - image.mime_type = "image/png"; - result.content.push_back(std::move(image)); - if (text.empty()) text = std::format("{}x{}", dimensions.cx, dimensions.cy); - } - - if (!settled) text += std::format("; taken while still busy: {}", join_text(agent_window_busy(app), ", ")); - result.content.insert(result.content.begin(), core::mcp::content{.text = std::move(text)}); - - json_writer json; - json.object().integer("width", dimensions.cx).integer("height", dimensions.cy).boolean("settled", settled); - if (!path.empty()) json.text("path", path); - json.end_object(); - result.structured = json.str(); - return result; - } - - void add_screenshot(mcp_host& host) - { - core::mcp::tool t; - t.name = "screenshot"; - t.title = "Take a screenshot"; - t.description = - "A picture of the window - or of the dialog in front - as it is drawn, on the desktop or out " - "of sight. Waits up to settle_s seconds for the window to settle first. Saved to path where " - "one is given, as PNG, JPEG, WebP, JPEG XL or AVIF by its extension, and returned as a PNG unless " - "it was saved and image is false. max_size bounds its longer side in pixels: 1600 for a picture " - "returned, none for one only saved."; - t.input_schema = - R"({"type":"object","properties":{"target":{"type":"string","enum":["window","dialog"]},"path":{"type":"string","description":"The full path to save it to"},"image":{"type":"boolean"},"max_size":{"type":"integer","minimum":64,"maximum":16384},"settle_s":{"type":"number","minimum":0,"maximum":120,"description":"How long to wait for the window to settle; 10 by default"}},"additionalProperties":false})"; - t.annotations.read_only = true; - t.handler = [&host](const core::mcp::call_ptr& call) - { - auto& app = host.app(); - const auto target = call->text("target", "window"); - const auto path = call->text("path"); - - if (!path.empty()) - { - if (!core::is_path(path)) - { - call->finish( - core::mcp::tool_result::error(std::format("Give the full path to save to, not {}", path))); - return; - } - - if (!files::can_save(core::file_path(path))) - { - call->finish(core::mcp::tool_result::error("Save as .png, .jpg, .webp, .jxl or .avif")); - return; - } - - if (const auto why = replace_refusal(host, {core::file_path(path)}); !why.empty()) - { - call->finish(core::mcp::tool_result::error(why)); - return; - } - } - - const auto include_image = call->flag("image", path.empty()); - const auto max_size = static_cast(call->number("max_size").value_or(include_image ? 1600 : 0)); - const auto settle_s = call->number("settle_s").value_or(10.0); - - answer_when(host, call, "screenshot", [&app, settle_s] - { return settle_s <= 0.0 || agent_window_settled(app); }, settle_s > 0.0 ? 0.3 : 0.0, settle_s, false, - [&app, target, path, include_image, max_size](const bool settled) - { return take_screenshot(app, target, path, include_image, max_size, settled); }); - }; - host.add(std::move(t), tool_tier::capture, true); - } - // What a recording that ended by itself wrote, for record_stop to say. struct recording_notes { std::string ended; }; - void add_recording(mcp_host& host) + void add_recording(ui::agent_host& host, app_frame& app) { const auto notes = std::make_shared(); @@ -1976,19 +832,19 @@ namespace start.description = "Films the window to an MP4 at 30 frames a second, as the screen shows it - menus, bubbles " "and the pointer with it - until record_stop, or for seconds. record_mark names moments " "in it. Needs the window on the desktop: -mcp-ui:visible. While it records, the window is " - "held above others unless present is false."; + "held above others unless present is false. On Linux it films the window's own pixels, so " + "a menu or bubble is not in it and the window is not held."; start.input_schema = R"({"type":"object","properties":{"path":{"type":"string","description":"The full path of the MP4"},"seconds":{"type":"number","minimum":0},"pointer":{"type":"boolean","description":"Draw the system pointer; true by default"},"present":{"type":"boolean"}},"required":["path"],"additionalProperties":false})"; - start.handler = [&host, notes](const core::mcp::call_ptr& call) + start.handler = [&host, &app, notes](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto path = call->text("path"); const auto refuse = [&call](std::string why) { call->finish(core::mcp::tool_result::error(std::move(why))); }; - if (host.options().presence != agent_presence::visible) + if (host.options().presence != ui::agent_presence::visible) { return refuse("A recording films the window as the screen shows it, so the window must be on the " "desktop: start the session with -mcp-ui:visible"); @@ -2019,7 +875,7 @@ namespace call->finish(core::mcp::tool_result::text( std::format("Recording {}: record_mark names a moment in it, record_stop ends it", path))); }; - host.add(std::move(start), tool_tier::capture, true); + host.add(std::move(start), ui::agent_tier::capture, true); core::mcp::tool mark; mark.name = "record_mark"; @@ -2028,10 +884,8 @@ namespace "\"\" a line, in .markers.txt, once it is finished."; mark.input_schema = R"({"type":"object","properties":{"name":{"type":"string","minLength":1}},"required":["name"],"additionalProperties":false})"; - mark.handler = [&host](const core::mcp::call_ptr& call) + mark.handler = [&app](const core::mcp::call_ptr& call) { - auto& app = host.app(); - if (!app._recording) { call->finish(core::mcp::tool_result::error("Nothing is being recorded")); @@ -2042,16 +896,15 @@ namespace app._recording->mark(name); call->finish(core::mcp::tool_result::text(std::format("{} at {:.2f} s", name, app._recording->elapsed()))); }; - host.add(std::move(mark), tool_tier::capture, true); + host.add(std::move(mark), ui::agent_tier::capture, true); core::mcp::tool stop; stop.name = "record_stop"; stop.title = "Stop recording"; stop.description = "Ends the recording and finishes its file: says what was written - its length and size - " "or why nothing was."; - stop.handler = [&host, notes](const core::mcp::call_ptr& call) + stop.handler = [&app, notes](const core::mcp::call_ptr& call) { - auto& app = host.app(); std::string summary; if (app._recording) summary = app.finish_recording(); @@ -2066,11 +919,11 @@ namespace notes->ended.clear(); call->finish(core::mcp::tool_result::text(summary)); }; - host.add(std::move(stop), tool_tier::capture, true); + host.add(std::move(stop), ui::agent_tier::capture, true); } #ifdef _DEBUG - void add_debug_action(mcp_host& host) + void add_debug_action(ui::agent_host& host, app_frame& app) { core::mcp::tool t; t.name = "debug_action"; @@ -2081,49 +934,20 @@ namespace t.input_schema = R"({"type":"object","properties":{"action":{"type":"string","enum":["reset-graphics","new-version","send-crash-report","crash"]}},"required":["action"],"additionalProperties":false})"; t.annotations.destructive = true; - t.handler = [&host](const core::mcp::call_ptr& call) + t.handler = [&app](const core::mcp::call_ptr& call) { - auto& app = host.app(); const auto action = call->text("action"); platform::run_ui([&app, action] { app.run_test_action(action); }); call->finish(core::mcp::tool_result::text(std::format("{} is under way", action))); }; - host.add(std::move(t), tool_tier::dev, true); + host.add(std::move(t), ui::agent_tier::dev, true); } #endif } -std::string describe_dialogs_json(app_frame& /*app*/) -{ - json_writer json; - json.array(); - for (const auto& parts : dialogs_and_prompts()) write_dialog(json, parts); - json.end_array(); - return json.str(); -} - -std::string describe_dialogs_text(app_frame& /*app*/) -{ - return dialogs_text(dialogs_and_prompts()); -} - -std::string_view agent_command_need(const commands id) -{ - return need_name(rule_of(id).need); -} - -std::string agent_command_refusal(const mcp_host& host, const commands id) -{ - return command_refusal(host, id); -} - -std::string agent_view_json(const app_frame& app, const size_t listed) +void write_agent_view(core::json::writer& json, const app_frame& app, const size_t listed) { - json_writer json; - json.object(); write_view(json, app, listed); - json.end_object(); - return json.str(); } std::string agent_view_text(const app_frame& app, const size_t listed) @@ -2131,44 +955,16 @@ std::string agent_view_text(const app_frame& app, const size_t listed) return view_text(app, listed); } -std::vector dialogs_showing_work() -{ - std::vector result; - - for (const auto& parts : open_dialog_parts()) - { - if (parts.owner->_shows_work) result.push_back(parts.texts.empty() ? "working"s : join_text(parts.texts, " ")); - } - - return result; -} - -bool dialog_awaits_answer() -{ - return platform::system_prompt_shown() || std::ranges::any_of(open_dialogs(), [](const std::weak_ptr& weak) - { - const auto d = weak.lock(); - return d && d->frame()->is_visible() && !d->_shows_work; - }); -} - -void add_ui_tools(mcp_host& host) +void add_ui_tools(ui::agent_host& host, app_frame& app) { - add_ui_state(host); - add_command_list(host); - add_command_run(host); - add_navigate(host); - add_select(host); - add_dialog_respond(host); - add_task_state(host); - add_task_set(host); - add_ui_input(host); - add_tutorial_run(host); - add_screenshot(host); - add_recording(host); + add_navigate(host, app); + add_select(host, app); + add_task_state(host, app); + add_task_set(host, app); + add_ui_input(host, app); + add_tutorial_run(host, app); + add_recording(host, app); #ifdef _DEBUG - add_debug_action(host); + add_debug_action(host, app); #endif - add_control_tools(host); - add_face_tools(host); } diff --git a/src/app_movie_batch.cpp b/src/app_movie_batch.cpp index 9076105a..683f2240 100644 --- a/src/app_movie_batch.cpp +++ b/src/app_movie_batch.cpp @@ -14,17 +14,16 @@ #include "pch.h" #include "app_movie_batch.h" #include "app_text.h" +#include "av_movie_writer.h" #include "files.h" #include "model_movie.h" +#include "libdesktop/core/json_writer.h" #include "libdesktop/platform.h" #include "view_movie.h" #include #include -#include -#include - namespace { // A project file is a document, not a stream. Mirrors the limit the view's Open applies. @@ -598,98 +597,54 @@ namespace return project_outcome::rendered; } - void write_paths(rapidjson::Writer& w, const char* name, - const std::vector& paths) + void write_paths(core::json::writer& json, const std::string_view name, const std::vector& paths) { - w.Key(name); - w.StartArray(); - - for (const auto& path : paths) - { - const auto text = path.str(); - w.String(text.c_str(), static_cast(text.size())); - } - - w.EndArray(); + json.key(name).array(); + for (const auto& path : paths) json.text(path.str()); + json.end_array(); } - void write_text(rapidjson::Writer& w, const char* name, const std::string_view text) + void write_texts(core::json::writer& json, const std::string_view name, const std::vector& texts) { - w.Key(name); - w.String(text.data(), static_cast(text.size())); + json.key(name).array(); + for (const auto& text : texts) json.text(text); + json.end_array(); } } std::string format_movie_batch_report(const movie_batch_report& report) { - rapidjson::StringBuffer buffer; - rapidjson::Writer w(buffer); - w.StartObject(); - w.Key("succeeded"); - w.Bool(report.succeeded); - if (!report.failure.empty()) write_text(w, "failure", report.failure); - w.Key("projects"); - w.StartArray(); + core::json::writer json; + json.object().boolean("succeeded", report.succeeded); + if (!report.failure.empty()) json.text("failure", report.failure); + json.key("projects").array(); for (const auto& p : report.projects) { - w.StartObject(); - write_text(w, "project", p.project.str()); - write_text(w, "outcome", p.outcome); - w.Key("reasons"); - w.StartArray(); - for (const auto& r : p.reasons) w.String(r.c_str(), static_cast(r.size())); - w.EndArray(); - w.Key("unreadable_lines"); - w.StartArray(); - + json.object().text("project", p.project.str()).text("outcome", p.outcome); + write_texts(json, "reasons", p.reasons); + json.key("unreadable_lines").array(); for (const auto& l : p.unreadable_lines) - { - w.StartObject(); - w.Key("line"); - w.Int(l.line); - write_text(w, "reason", l.reason); - w.EndObject(); - } - - w.EndArray(); - w.Key("videos"); - w.Uint64(p.videos); - w.Key("photos"); - w.Uint64(p.photos); - w.Key("audio"); - w.Uint64(p.audio); - w.Key("text_screens"); - w.Uint64(p.text_screens); - w.Key("captions"); - w.Uint64(p.captions); - w.Key("stabilize"); - w.Uint64(p.stabilize); - w.Key("youtube_short"); - w.Bool(p.youtube_short); - w.Key("seconds"); - w.Double(p.seconds); - w.Key("width"); - w.Int(p.size.cx); - w.Key("height"); - w.Int(p.size.cy); - w.Key("frame_rate"); - w.Int(p.frame_rate); - write_paths(w, "missing", p.missing); - write_paths(w, "unreadable", p.unreadable); - write_paths(w, "sounds_missing", p.sounds_missing); - write_paths(w, "sounds_unreadable", p.sounds_unreadable); - w.Key("warnings"); - w.StartArray(); - for (const auto& r : p.warnings) w.String(r.c_str(), static_cast(r.size())); - w.EndArray(); - if (!p.movie.is_empty()) write_text(w, "movie", p.movie.str()); - w.EndObject(); + json.object().integer("line", l.line).text("reason", l.reason).end_object(); + json.end_array(); + json.integer("videos", static_cast(p.videos)).integer("photos", static_cast(p.photos)); + json.integer("audio", static_cast(p.audio)); + json.integer("text_screens", static_cast(p.text_screens)); + json.integer("captions", static_cast(p.captions)); + json.integer("stabilize", static_cast(p.stabilize)); + json.boolean("youtube_short", p.youtube_short).number("seconds", p.seconds); + json.integer("width", p.size.cx).integer("height", p.size.cy).integer("frame_rate", p.frame_rate); + write_paths(json, "missing", p.missing); + write_paths(json, "unreadable", p.unreadable); + write_paths(json, "sounds_missing", p.sounds_missing); + write_paths(json, "sounds_unreadable", p.sounds_unreadable); + write_texts(json, "warnings", p.warnings); + if (!p.movie.is_empty()) json.text("movie", p.movie.str()); + json.end_object(); } - w.EndArray(); - w.EndObject(); - return {buffer.GetString(), buffer.GetSize()}; + json.end_array().end_object(); + return json.str(); } bool movie_batch_test_seams::project_is_skipped(const core::file_path project, const movie_batch_options& options) @@ -790,7 +745,7 @@ movie_batch_report run_movie_batch(const movie_batch_options& options, } // Absent rather than failing per project: no project could render, so none is attempted. - if (mode == movie_batch_mode::render && !platform::can_write_movies()) + if (mode == movie_batch_mode::render && !df::can_write_movies()) { return refuse("this system has no movie encoder, so nothing can be rendered"); } diff --git a/src/app_perf.cpp b/src/app_perf.cpp index c1c1d6b9..ded6daea 100644 --- a/src/app_perf.cpp +++ b/src/app_perf.cpp @@ -5,7 +5,8 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The session's performance counters and the summary of them written to the log at exit. +// Purpose: The session's performance counters and the summary of them written to the log at exit, with libdesktop's +// rows of what rendering cost among them. #include "pch.h" @@ -61,12 +62,6 @@ namespace return v.load(std::memory_order_relaxed); } - std::string format_latency(const core::latency_counters& counters) - { - return std::format(">16.7ms={}; >50ms={}; >100ms={}", format_perf_count(load(counters.over_16ms)), - format_perf_count(load(counters.over_50ms)), format_perf_count(load(counters.over_100ms))); - } - void append_perf_row(std::string& report, const std::string_view area, const std::string_view operation, const std::string_view runs, const std::string_view total, const std::string_view average, const std::string_view maximum, const std::string_view detail = "-"sv) @@ -74,6 +69,17 @@ namespace report += std::format("| {} | {} | {} | {} | {} | {} | {} |\n", area, operation, runs, total, average, maximum, detail); } + + // libdesktop's account of what rendering cost, in this table's columns. + void append_render_row(std::string& report, const render::counter_row& row) + { + const auto runs = row.runs ? format_perf_count(*row.runs) : "-"s; + const auto total = row.total_us ? format_us(*row.total_us) : "-"s; + const auto average = row.total_us && row.runs ? format_average(*row.total_us, *row.runs) : "-"s; + const auto maximum = row.max_us ? format_us(*row.max_us) : "-"s; + append_perf_row(report, row.area, row.operation, runs, total, average, maximum, + row.detail.empty() ? "-"sv : std::string_view(row.detail)); + } } df::queue_counters* df::register_queue(const std::string_view name) @@ -103,22 +109,24 @@ df::queue_counters* df::register_queue(const std::string_view name) void df::log_perf_summary() { + // This report carries what rendering cost, so libdesktop's own lines at the end would say it again. + render::report_counters_at_exit(false); + const auto& t = thumbnail_perf; - const auto& u = render::ui_perf; - const auto& g = render::gpu_perf; const auto& d = db_perf; const auto& q = query_perf; const auto& f = file_perf; const auto& x = index_perf; const auto& h = platform::file_hash_perf; + const auto render_rows = render::counter_rows(); const auto queue_count = std::min(perf_queue_count.load(std::memory_order_acquire), max_perf_queues); auto has_queue_work = false; for (size_t i = 0; i < queue_count; ++i) has_queue_work |= load(perf_queues[i].tasks) != 0; - if (load(u.idle_drains) == 0 && load(u.paints) == 0 && load(g.frames) == 0 && load(f.scans) == 0 && - load(f.loads) == 0 && load(f.decodes) == 0 && load(d.read_batches) == 0 && load(d.write_batches) == 0 && - load(q.queries) == 0 && load(q.counts) == 0 && load(h.computed) == 0 && load(x.phash_computed) == 0 && - load(t.stage_requests) == 0 && load(t.plan_requests) == 0 && !has_queue_work) + if (render_rows.empty() && load(f.scans) == 0 && load(f.loads) == 0 && load(f.decodes) == 0 && + load(d.read_batches) == 0 && load(d.write_batches) == 0 && load(q.queries) == 0 && load(q.counts) == 0 && + load(h.computed) == 0 && load(x.phash_computed) == 0 && load(t.stage_requests) == 0 && + load(t.plan_requests) == 0 && !has_queue_work) { return; } @@ -141,75 +149,7 @@ void df::log_perf_summary() platform::format_size(file_size(memory.commit)))); } - append_perf_row(report, "UI", "Idle drain", format_perf_count(load(u.idle_drains)), format_us(load(u.idle_us)), - format_average(load(u.idle_us), load(u.idle_drains)), format_us(load(u.idle_max_us)), - std::format("tasks={}; peak-batch={}", format_perf_count(load(u.idle_tasks)), - load(u.idle_batch_peak))); - append_perf_row(report, "UI queue", "Ready-to-start wait", format_perf_count(load(u.idle_tasks)), - format_us(load(u.idle_wait_us)), format_average(load(u.idle_wait_us), load(u.idle_tasks)), - format_us(load(u.idle_wait_max_us))); - - if (load(u.paints) != 0) - { - const auto paints = load(u.paints); - append_perf_row(report, "Rendering", "Paint", format_perf_count(paints), format_us(load(u.paint_us)), - format_average(load(u.paint_us), paints), format_us(load(u.paint_max_us)), - format_latency(u.paint_latency)); - append_perf_row(report, "Rendering", "Scene build", format_perf_count(paints), - format_us(load(u.scene_build_us)), format_average(load(u.scene_build_us), paints), - format_us(load(u.scene_build_max_us)), - std::format("{}; {}% of paint", format_latency(u.scene_build_latency), - load(u.paint_us) ? load(u.scene_build_us) * 100 / load(u.paint_us) : 0)); - append_perf_row(report, "Rendering", "Backend render", format_perf_count(paints), - format_us(load(u.backend_render_us)), format_average(load(u.backend_render_us), paints), - format_us(load(u.backend_render_max_us)), format_latency(u.backend_render_latency)); - } - - append_perf_row( - report, "UI", "Frame requests", format_perf_count(load(u.frame_prepares)), "-", "-", "-", - std::format("invalidates={}; redraws={}; hidden-skips={}; paints/prepare={:.1f}; texture-uploads={}", - format_perf_count(load(u.invalidates)), format_perf_count(load(u.redraws)), - format_perf_count(load(u.hidden_skips)), - load(u.frame_prepares) == 0 ? 0.0 : static_cast(load(u.paints)) / load(u.frame_prepares), - format_perf_count(load(u.texture_uploads)))); - append_perf_row(report, "UI", "Animation prepares", format_perf_count(load(u.prepares_registered_anim)), "-", "-", - "-", - std::format("display={}; display-invalid={}; live peak={}", - format_perf_count(load(u.prepares_display_anim)), - format_perf_count(load(u.prepares_display_invalid)), load(u.animations_peak))); - - if (load(g.frames) != 0) - { - const auto frames = load(g.frames); - - append_perf_row(report, "GPU", "Submit", format_perf_count(frames), format_us(load(g.submit_us)), - format_average(load(g.submit_us), frames), format_us(load(g.submit_max_us)), - format_latency(g.submit_latency)); - append_perf_row(report, "GPU", "Present", format_perf_count(frames), format_us(load(g.present_us)), - format_average(load(g.present_us), frames), format_us(load(g.present_max_us)), - format_latency(g.present_latency)); - - // Per frame rather than per session: the absolute totals scale with how long the app was - // left open, but the per-frame figures are what a change to the batching has to move. - append_perf_row(report, "GPU", "Draw batching", format_perf_count(frames), format_perf_count(load(g.draws)), - std::format("{:.1f}/frame", static_cast(load(g.draws)) / frames), - format_perf_count(load(g.draws_peak)), - std::format("merged={}; geometry={} ({} /frame)", format_perf_count(load(g.merged)), - format_perf_count(load(g.geometry_bytes)), - format_perf_count(load(g.geometry_bytes) / frames))); - append_perf_row(report, "GPU", "State changes", format_perf_count(frames), "-", "-", "-", - std::format("shader={}; view={}; sampler={}; cbuffer={}", - format_perf_count(load(g.shader_binds)), format_perf_count(load(g.view_binds)), - format_perf_count(load(g.sampler_binds)), - format_perf_count(load(g.cbuffer_uploads)))); - append_perf_row(report, "GPU", "Resources created", "-", "-", "-", "-", - std::format("views={}; targets={}; textures={}; reused={}; buffers={}; vram={}MB; peak={}MB", - format_perf_count(load(g.views_created)), - format_perf_count(load(g.targets_created)), - format_perf_count(load(g.textures_created)), - format_perf_count(load(g.textures_reused)), - format_perf_count(load(g.buffers_created)), load(g.vram_mb), load(g.vram_peak_mb))); - } + for (const auto& row : render_rows) append_render_row(report, row); for (size_t i = 0; i < queue_count; ++i) { diff --git a/src/app_perf.h b/src/app_perf.h index 9c2437e7..d893f8ee 100644 --- a/src/app_perf.h +++ b/src/app_perf.h @@ -6,8 +6,8 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // Purpose: Session-aggregate performance diagnostics: what thumbnails, the database, queries, files, the -// index and the worker queues cost this session, summarised once at exit with what painting and -// Direct3D cost, which the render layer counts (libdesktop/render.h). +// index and the worker queues cost this session, summarised once at exit with the rows libdesktop's render +// layer gives of what painting, Direct3D and the software renderer cost (render::counter_rows). #pragma once diff --git a/src/app_record.cpp b/src/app_record.cpp new file mode 100644 index 00000000..99e5296e --- /dev/null +++ b/src/app_record.cpp @@ -0,0 +1,573 @@ +// This file is part of the Diffractor photo and video organizer +// Copyright 2026 Zac Walker +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Purpose: What every screen recorder shares. The pointer a script shows, gliding and clicking, and the ring a click +// spreads, drawn into a frame; the moments a script names and the markers file they are written to; and the recorder +// of a platform that can only read a window's own pixels, which asks the UI thread for each frame at a steady rate +// and encodes on a worker of its own, writing every frame the wall clock has reached so a script's timings stay true +// in the movie. + +#include "pch.h" +#include "app_record.h" +#include "av_movie_writer.h" + +#include +#include +#include +#include +#include +#include +#include + +pointi scripted_pointer::at(const double t) const +{ + if (move_seconds <= 0.0 || t >= move_start + move_seconds) return to; + if (t <= move_start) return from; + + // Eased in and out, as a hand moves a mouse. + const auto u = (t - move_start) / move_seconds; + const auto eased = u * u * (3.0 - 2.0 * u); + return {from.x + static_cast(std::lround((to.x - from.x) * eased)), + from.y + static_cast(std::lround((to.y - from.y) * eased))}; +} + +recti click_ring::bounds() const +{ + const auto reach = static_cast(std::ceil(radius + thickness)) + 1; + return {center.x - reach, center.y - reach, center.x + reach + 1, center.y + reach + 1}; +} + +void recording_script::pointer(const std::optional screen, const double glide_seconds, const double now) +{ + const std::lock_guard lock(_mutex); + + if (!screen) + { + _pointer.shown = false; + return; + } + + _pointer.from = _pointer.shown ? _pointer.at(now) : *screen; + _pointer.to = *screen; + _pointer.move_start = now; + _pointer.move_seconds = _pointer.shown ? std::max(0.0, glide_seconds) : 0.0; + _pointer.shown = true; +} + +void recording_script::click(const double now) +{ + const std::lock_guard lock(_mutex); + _pointer.click_at = now; + _click_point = _pointer.at(now); +} + +void recording_script::mark(const std::string_view name, const double now) +{ + const std::lock_guard lock(_mutex); + _markers.emplace_back(now, std::string(name)); +} + +recording_script::view recording_script::current() const +{ + const std::lock_guard lock(_mutex); + return {_pointer, _click_point}; +} + +// The ring grows from the pointer's tip, eased out, and fades as it does. +std::optional recording_script::view::ring(const double t, const int cell) const +{ + const auto age = t - pointer.click_at; + if (!pointer.shown || pointer.click_at < 0.0 || age < 0.0 || age >= click_ring_seconds) return {}; + + const auto progress = age / click_ring_seconds; + const auto spread = 1.0 - (1.0 - progress) * (1.0 - progress); + + click_ring result; + result.center = click_point; + result.radius = cell * (0.12 + 0.5 * spread); + result.thickness = std::max(2.0, cell * 0.07); + result.opacity = 0.9 * (1.0 - progress); + return result; +} + +bool recording_script::write_markers(const core::file_path movie, const double length) const +{ + std::string text; + + { + const std::lock_guard lock(_mutex); + for (const auto& [seconds, name] : _markers) text += std::format("{:.3f}\t{}\n", seconds, name); + } + + text += std::format("{:.3f}\tend\n", length); + + const auto path = screen_recording_markers_path(movie); + + if (!platform::blob_save_to_file({std::bit_cast(text.data()), text.size()}, path)) + { + core::log(__FUNCTION__, std::format("Recording's markers could not be written to {}", path)); + return false; + } + + return true; +} + +namespace +{ + // Diffractor's accent, in the order a surface stores it. + constexpr uint8_t ring_blue = 0xff; + constexpr uint8_t ring_green = 0x9e; + constexpr uint8_t ring_red = 0x4a; + + // The arrow's outline on a 12 x 19 grid, as the system's own arrow is drawn: tip first, down the left edge to the + // notch, round the tail and back to the right wing. + constexpr std::array, 7> arrow_outline = { + {{0.0, 0.0}, {0.0, 16.0}, {4.0, 12.0}, {7.0, 19.0}, {9.0, 18.0}, {6.0, 11.0}, {11.0, 11.0}}}; + constexpr double arrow_grid_height = 19.0; + + // How far a point is from a segment. + double distance_to_segment(const double px, const double py, const std::pair a, + const std::pair b) + { + const auto dx = b.first - a.first; + const auto dy = b.second - a.second; + const auto length_squared = dx * dx + dy * dy; + const auto along = length_squared > 0.0 + ? std::clamp(((px - a.first) * dx + (py - a.second) * dy) / length_squared, 0.0, 1.0) + : 0.0; + return std::hypot(px - (a.first + along * dx), py - (a.second + along * dy)); + } + + using seconds_t = std::chrono::duration; + using clock = std::chrono::steady_clock; + + // What only the UI thread can read for one frame: the window's pixels, where its client area is on the screen, and + // where the system's pointer is in it. + struct window_frame + { + core::surface_ptr pixels; + pointi origin; + std::optional pointer; + }; + + // A request for a frame, made to the UI thread, which the recorder waits on and gives up on once it is stopped or + // the thread has not answered for too long: a UI thread that has gone is not one to wait for. + class frame_request + { + public: + void complete(window_frame frame) + { + const std::lock_guard lock(_mutex); + _frame = std::move(frame); + _done = true; + _signal.notify_all(); + } + + bool wait(const std::atomic_bool& stopping, const double timeout_seconds, window_frame& frame) + { + const auto give_up = clock::now() + std::chrono::duration_cast(seconds_t(timeout_seconds)); + std::unique_lock lock(_mutex); + + while (!_done) + { + if (stopping.load() || clock::now() >= give_up) return false; + _signal.wait_for(lock, std::chrono::milliseconds(10)); + } + + frame = std::move(_frame); + return true; + } + + private: + std::mutex _mutex; + std::condition_variable _signal; + window_frame _frame; + bool _done = false; + }; + + class window_recording final : public screen_recording + { + public: + window_recording(screen_recording_request request, std::function capture) : + _request(std::move(request)), _capture(std::move(capture)), _alive(std::make_shared(true)) + { + _worker = platform::create_serial_executor("recording"); + + if (!_worker || !_worker->post([this] { run(); })) + { + finish("Recording failed: no thread to record on"); + } + } + + ~window_recording() override { stop(); } + + window_recording(const window_recording&) = delete; + window_recording& operator=(const window_recording&) = delete; + + bool is_finished() const override { return _finished.load(); } + + void stop() override + { + _stopping.store(true); + if (_worker) _worker->stop(); + // A frame still asked of the UI thread is answered with nothing, so the window is not read after this. + _alive->store(false); + } + + std::string summary() const override + { + const std::lock_guard lock(_summary_mutex); + return _summary; + } + + double elapsed() const override + { + const auto started = _started.load(); + if (started == not_started) return -1.0; + return seconds_t(clock::now().time_since_epoch() - clock::duration(started)).count(); + } + + void pointer(const std::optional screen, const double glide_seconds) override + { + _script.pointer(screen, glide_seconds, std::max(0.0, elapsed())); + } + + void click() override { _script.click(std::max(0.0, elapsed())); } + + void mark(const std::string_view name) override { _script.mark(name, std::max(0.0, elapsed())); } + + private: + static constexpr clock::rep not_started = std::numeric_limits::min(); + + // Longer than this, the UI thread has not answered and the frame is taken for lost. + static constexpr double frame_timeout_seconds = 3.0; + // A window nothing can be read from for this long is gone, and the movie ends where it did. + static constexpr double give_up_seconds = 2.0; + + void run() { finish(record()); } + + void finish(std::string summary) + { + core::log(__FUNCTION__, summary); + + { + const std::lock_guard lock(_summary_mutex); + _summary = std::move(summary); + } + + _finished.store(true); + } + + // One frame, from the UI thread. + window_frame capture_frame() + { + const auto request = std::make_shared(); + + platform::run_ui([request, alive = _alive, capture = _capture, origin = _request.client_origin, + pointer = _request.window_pointer] + { + window_frame frame; + + if (alive->load()) + { + frame.pixels = capture(); + if (origin) frame.origin = origin(); + if (pointer) frame.pointer = pointer(); + } + + request->complete(std::move(frame)); + }); + + window_frame frame; + request->wait(_stopping, frame_timeout_seconds, frame); + return frame; + } + + // Waits until `at`, in short steps so that a stop is not waited out. + void pause_until(const clock::time_point at) const + { + using namespace std::chrono_literals; + + while (!_stopping.load()) + { + const auto now = clock::now(); + if (now >= at) return; + std::this_thread::sleep_for(std::min(at - now, 10ms)); + } + } + + // The window as the movie shows it: its pixels at the movie's size, from its top left and black where it has + // none, with the pointers over them where each was when the frame was captured, `t` seconds in. + void compose(const window_frame& frame, const sizei extent, const double t, core::surface& picture) const + { + picture.alloc(extent, core::texture_format::RGB); + picture.make_blank(); + + const auto size = frame.pixels->dimensions(); + const auto rows = std::min(size.cy, extent.cy); + const auto row_bytes = static_cast(std::min(size.cx, extent.cx)) * 4; + + for (auto y = 0; y < rows; ++y) memcpy(picture.pixels_line(y), frame.pixels->pixels_line(y), row_bytes); + + // A pointer's image is 32 pixels at 96 DPI, which a window of 1080 rows is taken to be at. A script's is + // half as large again, as a viewer watches it on a smaller screen than it was made on. + const auto cell = std::max(24, static_cast(std::lround(48.0 * extent.cy / 1080.0))); + const auto in_picture = [extent](const pointi p) + { + return p.x >= 0 && p.y >= 0 && p.x < extent.cx && p.y < extent.cy; + }; + + if (_request.draw_pointer && frame.pointer && in_picture(*frame.pointer)) + { + draw_pointer_arrow(picture, *frame.pointer, cell * 2 / 3); + } + + const auto script = _script.current(); + const auto to_picture = [&frame](const pointi screen) + { + return pointi{screen.x - frame.origin.x, screen.y - frame.origin.y}; + }; + + if (auto ring = script.ring(t, cell)) + { + ring->center = to_picture(ring->center); + draw_click_ring(picture, *ring); + } + + if (script.pointer.shown) draw_pointer_arrow(picture, to_picture(script.pointer.at(t)), cell); + } + + std::string record() + { + const auto fps = std::max(1, _request.frame_rate); + _started.store(clock::now().time_since_epoch().count()); + + // The first frame gives the movie its size, which a window resized meanwhile does not change: it is + // recorded at the size it started at, from its top left. Not every window has been drawn yet. + window_frame current; + + for (auto tries = 0; tries < 10 && !current.pixels && !_stopping.load(); ++tries) + { + current = capture_frame(); + if (!current.pixels) pause_until(clock::now() + std::chrono::milliseconds(100)); + } + + if (!current.pixels) + { + return _stopping.load() ? "Recording failed: it was stopped before the window gave a frame" + : "Recording failed: there is no window to record"; + } + + const auto size = current.pixels->dimensions(); + // Even, as every encoder here wants. + const sizei extent{size.cx & ~1, size.cy & ~1}; + if (extent.cx < 16 || extent.cy < 16) return "Recording failed: the window has no client area to record"; + + platform::movie_writer_request request; + request.path = _request.path; + request.extent = extent; + request.frame_rate = fps; + request.video_bitrate = screen_recording_bitrate(extent, fps); + const auto writer = df::create_movie_writer(request); + if (!writer) return std::format("Recording failed: no movie can be written to {}", _request.path); + + const auto picture = std::make_shared(); + + const auto max_frames = _request.seconds > 0 ? std::max(1, std::llround(_request.seconds * fps)) + : std::numeric_limits::max(); + int64_t written = 0; + int64_t captures = 0; + int64_t late = 0; + int64_t lost = 0; + auto capture_seconds = 0.0; + std::string failure; + + while (!_stopping.load() && written < max_frames) + { + const auto capture_started = elapsed(); + + if (captures > 0) + { + auto next = capture_frame(); + + if (next.pixels) + { + current = std::move(next); + lost = 0; + } + else if (++lost > give_up_seconds * fps) + { + break; + } + } + + capture_seconds += elapsed() - capture_started; + ++captures; + compose(current, extent, capture_started, *picture); + + // Every frame up to now is written, so the movie keeps the wall clock's time: a frame the loop was late + // for repeats the picture rather than shortening the movie, and a script's timings stay true in it. + const auto due = std::min(max_frames - 1, static_cast(elapsed() * fps)); + late += std::max(0, due - written); + + for (; written <= due; ++written) + { + if (!writer->write_frame(picture, static_cast(written) / fps)) + { + failure = writer->last_error(); + break; + } + } + + if (!failure.empty()) break; + + pause_until(clock::time_point(clock::duration(_started.load())) + + std::chrono::duration_cast(seconds_t(static_cast(written) / fps))); + } + + if (!failure.empty()) + { + writer->abandon(); + return std::format("Recording failed: {}", failure); + } + + if (written == 0) + { + writer->abandon(); + return "Recording failed: no frame was written"; + } + + if (!writer->close()) + return std::format("Recording failed to finish {}: {}", _request.path, writer->last_error()); + + const auto length = static_cast(written) / fps; + _script.write_markers(_request.path, length); + + return std::format("Recorded {}: {}x{} at {} fps, {:.2f} s in {} frames ({} late) from the window's own " + "pixels, {:.1f} ms a capture", + _request.path, extent.cx, extent.cy, fps, length, written, late, + captures > 0 ? capture_seconds * 1000.0 / static_cast(captures) : 0.0); + } + + screen_recording_request _request; + std::function _capture; + std::shared_ptr _alive; + std::atomic_bool _stopping = false; + std::atomic_bool _finished = false; + std::atomic _started = not_started; + mutable std::mutex _summary_mutex; + std::string _summary; + recording_script _script; + // Last, so everything the worker reads exists before it starts. + platform::serial_executor_ptr _worker; + }; +} + +void draw_click_ring(core::surface& frame, const click_ring& ring) +{ + const auto size = frame.dimensions(); + const auto bounds = ring.bounds(); + const auto blend = [](const uint8_t under, const uint8_t over, const double amount) + { + return static_cast(std::lround(under + (over - under) * amount)); + }; + + for (auto y = std::max(0, bounds.top); y < std::min(size.cy, bounds.bottom); ++y) + { + auto* const line = frame.pixels_line(y); + + for (auto x = std::max(0, bounds.left); x < std::min(size.cx, bounds.right); ++x) + { + const auto distance = std::hypot(x - ring.center.x, y - ring.center.y); + const auto coverage = std::clamp(ring.thickness / 2.0 + 0.5 - std::abs(distance - ring.radius), 0.0, 1.0) * + ring.opacity; + if (coverage <= 0.0) continue; + + auto* const pixel = line + static_cast(x) * 4; + pixel[0] = blend(pixel[0], ring_blue, coverage); + pixel[1] = blend(pixel[1], ring_green, coverage); + pixel[2] = blend(pixel[2], ring_red, coverage); + } + } +} + +void draw_pointer_arrow(core::surface& frame, const pointi tip, const int cell) +{ + const auto size = frame.dimensions(); + const auto scale = 0.6 * cell / arrow_grid_height; + // The dark edge lies outside the white, as the system's arrow has it. + const auto edge = std::max(1.25, scale * 1.1); + + std::array, arrow_outline.size()> points{}; + auto left = std::numeric_limits::max(); + auto top = left; + auto right = std::numeric_limits::lowest(); + auto bottom = right; + + for (size_t i = 0; i < points.size(); ++i) + { + points[i] = {tip.x + arrow_outline[i].first * scale, tip.y + arrow_outline[i].second * scale}; + left = std::min(left, points[i].first); + right = std::max(right, points[i].first); + top = std::min(top, points[i].second); + bottom = std::max(bottom, points[i].second); + } + + const auto reach = edge + 1.0; + const auto blend = [](const uint8_t under, const uint8_t over, const double amount) + { + return static_cast(std::lround(under + (over - under) * amount)); + }; + + for (auto y = std::max(0, static_cast(std::floor(top - reach))); + y < std::min(size.cy, static_cast(std::ceil(bottom + reach))); ++y) + { + auto* const line = frame.pixels_line(y); + + for (auto x = std::max(0, static_cast(std::floor(left - reach))); + x < std::min(size.cx, static_cast(std::ceil(right + reach))); ++x) + { + // The pixel's centre, and how far it is from the arrow: negative inside it. + const auto px = x + 0.5; + const auto py = y + 0.5; + auto nearest = std::numeric_limits::max(); + auto inside = false; + + for (size_t i = 0; i < points.size(); ++i) + { + const auto a = points[i]; + const auto b = points[(i + 1) % points.size()]; + nearest = std::min(nearest, distance_to_segment(px, py, a, b)); + + if ((a.second > py) != (b.second > py) && + px < (b.first - a.first) * (py - a.second) / (b.second - a.second) + a.first) + { + inside = !inside; + } + } + + const auto distance = inside ? -nearest : nearest; + const auto dark = std::clamp(edge + 0.5 - distance, 0.0, 1.0); + const auto light = std::clamp(0.5 - distance, 0.0, 1.0); + if (dark <= 0.0) continue; + + auto* const pixel = line + static_cast(x) * 4; + + for (auto c = 0; c < 3; ++c) + { + pixel[c] = blend(pixel[c], 0x18, dark); + pixel[c] = blend(pixel[c], 0xff, light); + } + } + } +} + +std::unique_ptr start_window_recording(const screen_recording_request& request, + std::function capture) +{ + return std::make_unique(request, std::move(capture)); +} diff --git a/src/app_record.h b/src/app_record.h index 9621598c..110bf77d 100644 --- a/src/app_record.h +++ b/src/app_record.h @@ -5,11 +5,14 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The screen recorder, for tutorial videos made from the running application: its -// window's client area as the screen shows it - menus, bubbles and the pointer included - written to an MP4 -// at a steady rate until it is stopped, with the pointer and clicks a script shows drawn in, and the moments -// it names written beside the movie. What the application asks of it; the capture is the platform's -// (platform_win_record.cpp) and the encoder is libdesktop's movie writer. Linux records nothing. +// Purpose: The screen recorder, for tutorial videos made from the running application: its window's client area - +// menus, bubbles and the pointer included where the platform can ask the desktop for them, as Windows can +// (platform_win_record.cpp), and as the window itself draws it where it cannot, as on Linux +// (platform_linux_app.cpp) - written to an MP4 at a steady rate until it is stopped, with the pointer and clicks a +// script shows drawn in, and the moments it names written beside the movie. What the application asks of it; the +// capture is the platform's and the encoder the movie writer's (av_movie_writer.h). What both platforms share is +// app_record.cpp's: the script's pointer, the ring a click spreads, the markers file, and the recorder that polls a +// window's own pixels. #pragma once @@ -28,8 +31,15 @@ struct screen_recording_request // Draws the system pointer into the frames, where it is over the window. bool draw_pointer = true; // Holds the window still for an audience while it records: above every other window, so nothing that pops up - // covers it, and with square corners and no border, so its edges are its own. + // covers it, and with square corners and no border, so its edges are its own. Where a platform cannot hold a + // window so, it records the window as it is. bool present_window = false; + // What a platform that records the window's own pixels cannot ask the desktop, asked on the UI thread: where + // the window's client area starts on the screen, which a script's screen points are measured from, and where + // the system's pointer is, in the window's client pixels. A platform that records the desktop does not ask + // them, and a request without them has the client area at the screen's origin and no pointer to draw. + std::function client_origin; + std::function()> window_pointer; }; class screen_recording @@ -65,3 +75,89 @@ inline core::file_path screen_recording_markers_path(const core::file_path movie { return movie.folder().combine_file(std::format("{}.markers.txt", movie.file_name_without_extension())); } + +// The bitrate a recording is written at. A recording is a first generation that Movie mixer encodes again at 0.10 +// bits a pixel a frame, so it is kept well above that - 0.25 - since interface text and thumbnail edges are what a +// second generation softens first. +inline int screen_recording_bitrate(const sizei extent, const int frame_rate) +{ + constexpr auto bits_per_pixel = 0.25; + constexpr auto most = 60000000.0; + return static_cast(std::min(most, static_cast(extent.cx) * extent.cy * frame_rate * bits_per_pixel)); +} + +// The pointer a script shows: where it glides from and to, and when, and when it last clicked - all in seconds +// into the movie, so each frame draws it where it was when the frame was captured. +struct scripted_pointer +{ + bool shown = false; + pointi from; + pointi to; + double move_start = 0.0; + double move_seconds = 0.0; + double click_at = -1.0; + + pointi at(double t) const; +}; + +// The ring a click spreads from its pointer: Diffractor's accent, smoothed at its edges, `opacity` of it over what +// is under. It takes this long to spread and fade. +inline constexpr double click_ring_seconds = 0.45; + +struct click_ring +{ + pointi center; + double radius = 0.0; + double thickness = 0.0; + double opacity = 0.0; + + recti bounds() const; +}; + +// What a script shows - the pointer, and the ring a click spreads from it - and the moments it names, the same on +// every platform. Its times are seconds into the movie, given by the recorder that holds it, and its points are +// those the script gave: on the screen. +class recording_script +{ +public: + void pointer(std::optional screen, double glide_seconds, double now); + void click(double now); + void mark(std::string_view name, double now); + + // The script as it stood, so one frame is drawn from one moment of it: the pointer, and where it clicked last. + struct view + { + scripted_pointer pointer; + pointi click_point; + + // The ring that click has spread to `t` seconds in, if it is spreading. `cell` is the size of the pointer's + // image, which the ring grows from. + std::optional ring(double t, int cell) const; + }; + + view current() const; + + // Writes the moments named, and the movie's end at `length`, beside the movie. False where the file could not be + // written, which is logged. + bool write_markers(core::file_path movie, double length) const; + +private: + mutable std::mutex _mutex; + scripted_pointer _pointer; + pointi _click_point; + std::vector> _markers; +}; + +// Draws the ring into the frame, over what is under it. +void draw_click_ring(core::surface& frame, const click_ring& ring); + +// An arrow pointer with its tip at `tip`, drawn into the frame: white with a dark edge, smoothed. `cell` is the +// size of the square a pointer's image is made in - 32 pixels at 96 DPI - which the arrow fills three fifths of. +// For a platform that has no pointer image of the system's to draw. +void draw_pointer_arrow(core::surface& frame, pointi tip, int cell); + +// Records a window by polling its pixels: `capture` gives the window as it draws itself now, as a surface, and is +// called on the UI thread, once for each frame it is asked for. A platform that cannot record the desktop's pixels +// records the window's own so. Frames are encoded on a worker of the recorder's own, through the movie writer. +std::unique_ptr start_window_recording(const screen_recording_request& request, + std::function capture); diff --git a/src/app_resources.h b/src/app_resources.h index d67db6a0..bde2cc8c 100644 --- a/src/app_resources.h +++ b/src/app_resources.h @@ -18,10 +18,5 @@ enum class app_resource core::blob load_app_resource(app_resource r); -namespace ui -{ - class surface; -} - // Draws the application's mark centred on a surface, transparent around it. void fill_app_logo(core::surface& surface); diff --git a/src/app_search.cpp b/src/app_search.cpp index 583f5b00..bfdb57fa 100644 --- a/src/app_search.cpp +++ b/src/app_search.cpp @@ -783,7 +783,7 @@ void app_frame::set_search_edit_text(const std::string_view text) void app_frame::preview_search_prediction(const std::string& text) { - _search_session.preview(text); + _search_session.preview(); set_search_edit_text(text); } diff --git a/src/app_search.h b/src/app_search.h index b6e4a60c..8b71b83c 100644 --- a/src/app_search.h +++ b/src/app_search.h @@ -5,13 +5,15 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: The address box editing session. Holds the committed address, the typed draft and -// whether a completion is being previewed, and answers what each key should do with them. Kept -// apart from app_frame so the behavior design.md specifies can be reasoned about, and tested, -// without a window. +// Purpose: The address bar's completion strategy, built through a factory so its ranking and content +// rules can be driven from a test without a window. The address box's editing session - the committed +// address, the typed draft and whether a completion is being previewed - is libdesktop's +// ui::completion_session. #pragma once +#include "libdesktop/ui/completion_box.h" + namespace ui { class complete_strategy_t; @@ -19,122 +21,7 @@ namespace ui class view_state; -// The address bar's completion strategy. Built through a factory so the ranking and content rules -// it implements can be driven from a test without a window; the concrete type stays in app_search.cpp. +// The address bar's completion strategy. The concrete type stays in app_search.cpp. std::shared_ptr make_search_auto_complete(view_state& state, std::function set_text, std::function repaint = {}); - -class search_edit_session -{ - // The address as it stood when editing began. Escape returns here. - std::string _original; - - // The latest text the user actually typed, which a completion preview must not overwrite. - std::string _typed; - - bool _previewing = false; - -public: - // What the caller should do with the address box and the completion popup. - struct outcome - { - std::string edit_text; - bool set_edit_text = false; - bool select_first_completion = false; - bool refresh_completions = false; - bool close_popup = false; - bool focus_view = false; - bool handled = false; - }; - - // Focusing the address box begins a session and snapshots the committed address. - void begin(const std::string_view committed) - { - _original = committed; - _typed = committed; - _previewing = false; - } - - // Focus leaving the address box ends the session. A preview is a suggestion the user was - // looking at, not one they chose, so the draft they typed comes back with them - otherwise the - // highlighted completion is left sitting in the box and becomes the address as far as the next - // Enter, and anything else reading the box, can tell. - outcome end() - { - outcome result; - - if (_previewing) - { - result.edit_text = _typed; - result.set_edit_text = true; - } - - _previewing = false; - return result; - } - - // Typing maintains a draft separate from the committed address. - void typed(const std::string_view text) - { - _previewing = false; - _typed = text; - } - - // Up and Down preview a completion in the address box without changing the draft. - void preview(const std::string_view text) - { - _previewing = true; - (void)text; - } - - // Escape is two-stage: back to the draft first, then back to where editing began. - outcome escape() - { - outcome result; - result.handled = true; - - if (_previewing) - { - _previewing = false; - result.edit_text = _typed; - result.set_edit_text = true; - result.select_first_completion = true; - return result; - } - - result.edit_text = _original; - result.set_edit_text = true; - result.close_popup = true; - result.focus_view = true; - return result; - } - - // Tab accepts the highlighted completion into the draft without running it. - outcome accept(const bool has_selection, const std::string_view selected_text) - { - outcome result; - - if (!has_selection) return result; - - _previewing = false; - _typed = selected_text; - - result.handled = true; - result.edit_text = _typed; - result.set_edit_text = true; - result.refresh_completions = true; - return result; - } - - // Enter commits the highlighted completion when there is one, otherwise the visible address. - std::string commit(const bool has_selection, const std::string_view selected_text, - const std::string_view visible_text) const - { - return std::string(has_selection ? selected_text : visible_text); - } - - bool is_previewing() const { return _previewing; } - const std::string& typed_text() const { return _typed; } - const std::string& original_text() const { return _original; } -}; diff --git a/src/app_settings.cpp b/src/app_settings.cpp index a02a1be7..c01b6ede 100644 --- a/src/app_settings.cpp +++ b/src/app_settings.cpp @@ -393,8 +393,10 @@ settings_t::settings_t() show_rotated = true; show_results = true; create_originals = true; -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES check_for_updates = true; +#endif +#ifndef WINSTORE send_crash_dumps = true; #endif show_hidden = false; @@ -1041,8 +1043,10 @@ void settings_t::read() store.read({}, s_create_originals, create_originals); store.read({}, s_media_index_first, media_index_first); store.read({}, s_media_repair, media_repair); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES store.read({}, s_check_for_updates, check_for_updates); +#endif +#ifndef WINSTORE store.read({}, s_send_crash_dumps, send_crash_dumps); #endif @@ -1266,8 +1270,10 @@ void settings_t::write() const store.write({}, s_create_originals, create_originals); store.write({}, s_media_index_first, media_index_first); store.write({}, s_media_repair, media_repair); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES store.write({}, s_check_for_updates, check_for_updates); +#endif +#ifndef WINSTORE store.write({}, s_send_crash_dumps, send_crash_dumps); #endif store.write({}, s_last_run, core::utc_now().to_days()); diff --git a/src/app_settings.h b/src/app_settings.h index 0771f58d..ff4348e2 100644 --- a/src/app_settings.h +++ b/src/app_settings.h @@ -321,8 +321,10 @@ class settings_t // far as it can be read, rather than not at all. bool media_index_first = false; bool media_repair = false; -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES bool check_for_updates = false; +#endif +#ifndef WINSTORE bool send_crash_dumps = false; #endif repeat_mode repeat = repeat_mode::repeat_none; diff --git a/src/app_text.cpp b/src/app_text.cpp index f014ae48..da5bb555 100644 --- a/src/app_text.cpp +++ b/src/app_text.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -267,6 +267,34 @@ std::string_view tt_prep(std::string_view result) return result; } +bool wastebasket_is_trash(const platform::os_family family) +{ + return family == platform::os_family::linux_; +} + +namespace +{ + // The system does not change while the application runs, and Windows answers environment() with several + // system calls. + bool this_platform_has_trash() + { + static const auto trash = wastebasket_is_trash(platform::environment().family); + return trash; + } +} + +const text_t& wastebasket_text(const text_t& recycle_bin, const text_t& trash) +{ + // NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter): callers pass tt's texts, which outlive the result + return this_platform_has_trash() ? trash : recycle_bin; +} + +const plural_text& wastebasket_text(const plural_text& recycle_bin, const plural_text& trash) +{ + // NOLINTNEXTLINE(bugprone-return-const-ref-from-parameter): callers pass tt's texts, which outlive the result + return this_platform_has_trash() ? trash : recycle_bin; +} + static std::optional parse_msgstr_plural_index(const std::string& line, std::vector& errors, const size_t line_number) { @@ -1132,6 +1160,7 @@ void app_text_t::calc_text_mapping() delete_error, delete_fmt, delete_no_recycle_warning, + delete_no_trash_warning, desktop_background_info, destination_folder, disk_capacity, @@ -1476,9 +1505,11 @@ void app_text_t::calc_text_mapping() import_reading_device_fmt, import_copying_device_fmt, import_device_empty_fmt, + import_device_unavailable_fmt, import_device_no_space_fmt, import_device_copies, import_replace_warning, + import_replace_warning_trash, import_dest_folder_structure, import_set_created_date, index_maintenance_help, @@ -1595,6 +1626,11 @@ void app_text_t::calc_text_mapping() platform_text.menu_paste, platform_text.menu_select_all, platform_text.menu_undo, + platform_text.message_box_cancel, + platform_text.message_box_no, + platform_text.message_box_ok, + platform_text.message_box_retry, + platform_text.message_box_yes, metadata, midtones, words.month_april, @@ -1656,6 +1692,7 @@ void app_text_t::calc_text_mapping() options_backup_copy, options_check_for_update, options_confirm_del, + options_confirm_del_trash, options_confirm_rotate, options_jpeg_quality, options_webp_quality, @@ -1713,6 +1750,40 @@ void app_text_t::calc_text_mapping() pasted_file_name, photo, photos, + platform_text.picker_all_files, + platform_text.picker_button_cancel, + platform_text.picker_button_open, + platform_text.picker_button_replace, + platform_text.picker_button_save, + platform_text.picker_button_select, + platform_text.picker_button_up, + platform_text.picker_cannot_read_fmt, + platform_text.picker_choose_file, + platform_text.picker_column_modified, + platform_text.picker_column_name, + platform_text.picker_column_size, + platform_text.picker_count_fmt, + platform_text.picker_empty, + platform_text.picker_filter_cue, + platform_text.picker_invalid_name, + platform_text.picker_loading, + platform_text.picker_name_label, + platform_text.picker_no_folders, + platform_text.picker_no_match, + platform_text.picker_not_found_fmt, + platform_text.picker_open_file, + platform_text.picker_open_files, + platform_text.picker_place_desktop, + platform_text.picker_place_documents, + platform_text.picker_place_downloads, + platform_text.picker_place_home, + platform_text.picker_place_music, + platform_text.picker_place_pictures, + platform_text.picker_place_videos, + platform_text.picker_replace_fmt, + platform_text.picker_replace_title, + platform_text.picker_save_file, + platform_text.picker_type_name, pixels_icon, pixels_identical_files_not_identical, resolution_none, @@ -1958,6 +2029,7 @@ void app_text_t::calc_text_mapping() sync_delete_local_action, sync_delete_remote_action, sync_delete_warning, + sync_delete_warning_trash, sync_delete_local, sync_delete_remote, sync_info_1, @@ -2128,6 +2200,7 @@ void app_text_t::calc_text_mapping() ignored_previous_fmt, import_date_unset_fmt, delete_info_fmt, + delete_info_trash_fmt, delete_info_permanent_fmt, delete_many_warning_fmt, copy_fmt, diff --git a/src/app_text.h b/src/app_text.h index f922b7fd..37c16826 100644 --- a/src/app_text.h +++ b/src/app_text.h @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -96,6 +96,13 @@ std::string format_plural_text(const plural_text& fmt, const std::vector tbButtonsNav1 = { find_command(commands::view_show_sidebar), -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES find_command(commands::info_new_version), #endif find_command(commands::browse_back), find_command(commands::browse_forward), @@ -267,109 +267,6 @@ std::vector app_frame::measure_bar(render::measure_context& mc, const return result; } -bar_arrangement arrange_bar(const recti bounds, const std::vector& slots, const int gap, - const bar_alignment alignment) -{ - // A leading bar is a trailing one seen in a mirror: its slots in reverse, arranged from the right - // and reflected back, so both ends give way by the same rules. - if (alignment == bar_alignment::leading) - { - const std::vector reversed(slots.rbegin(), slots.rend()); - const auto mirrored = arrange_bar(bounds, reversed, gap, bar_alignment::trailing); - const auto reflect = [&bounds](const recti r) - { - return recti(bounds.left + bounds.right - r.right, r.top, bounds.left + bounds.right - r.left, r.bottom); - }; - - bar_arrangement result; - result.slots.resize(slots.size()); - - for (auto i = 0u; i < slots.size(); ++i) - { - const auto placed = mirrored.slots[slots.size() - 1 - i]; - if (!placed.is_empty()) result.slots[i] = reflect(placed); - } - - result.remainder = reflect(mirrored.remainder); - return result; - } - - const auto count = slots.size(); - std::vector widths(count); - std::vector shown(count, true); - - for (auto i = 0u; i < count; ++i) - { - widths[i] = std::max(0, slots[i].extent.cx); - shown[i] = widths[i] > 0; - } - - const auto total = [&] - { - auto sum = 0; - auto visible = 0; - - for (auto i = 0u; i < count; ++i) - { - if (!shown[i]) continue; - sum += widths[i]; - ++visible; - } - - return sum + std::max(0, visible - 1) * gap; - }; - - const auto available = std::max(0, bounds.width()); - - for (auto i = 0u; i < count && total() > available; ++i) - { - if (slots[i].optional) shown[i] = false; - } - - for (auto i = 0u; i < count && total() > available; ++i) - { - if (!shown[i] || slots[i].min_width <= 0 || slots[i].min_width >= widths[i]) continue; - widths[i] -= std::min(total() - available, widths[i] - slots[i].min_width); - } - - // Cut from the leading end. A part past its minimum is no use at any width, so parts go whole, - // and only the last one standing is clipped to the bar. - for (auto i = 0u; i < count && total() > available; ++i) - { - if (!shown[i]) continue; - - if (std::count(shown.begin() + i + 1, shown.end(), true) > 0) - { - shown[i] = false; - } - else - { - widths[i] = std::max(0, widths[i] - (total() - available)); - } - } - - bar_arrangement result; - result.slots.resize(count); - - auto x = bounds.right; - auto leading = bounds.right; - - for (auto i = count; i-- > 0;) - { - if (!shown[i]) continue; - - const auto height = std::min(slots[i].extent.cy, bounds.height()); - const auto top = bounds.top + (bounds.height() - height) / 2; - result.slots[i] = recti(x - widths[i], top, x, top + height); - leading = x - widths[i]; - x = leading - gap; - } - - const auto remainder_right = leading == bounds.right ? bounds.right : leading - gap; - result.remainder = recti(bounds.left, bounds.top, std::max(bounds.left, remainder_right), bounds.bottom); - return result; -} - bool app_frame::filter_key_down(const char32_t key, const platform::key_state keys) { if (key == platform::keys::ESCAPE) @@ -678,12 +575,12 @@ void app_frame::update_button_state(const bool resize) const auto can_process_local_items = is_media_or_items_view && local_items_result.success(); const auto can_save_metadata = is_media_or_items_view && save_metadata_result.success(); const auto can_save_pixels = is_media_or_items_view && save_pixels_result.success(); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES // Not cached: the update snooze is measured in days, so a session left open overnight has to // see the new day arrive. const auto now_days = core::utc_now().to_days(); const auto new_version_avail = is_media_or_items_view && - core::version(s_app_version) < core::version(setting.available_version) && + df::app_version(s_app_version) < df::app_version(setting.available_version) && static_cast(now_days) >= setting.min_show_update_day; const auto show_new_version = is_media_or_items_view && (setting.force_available_version || new_version_avail); #endif @@ -692,7 +589,7 @@ void app_frame::update_button_state(const bool resize) const auto search_has_selector = _state.search().has_selector(); // This line remains unchanged const auto has_save_folder = _state.search().is_showing_folder(); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES _commands[commands::info_new_version]->visible = !is_edit_view && show_new_version; // The whole point of this button is to be noticed, so it carries the accent fill. _commands[commands::info_new_version]->highlight = true; @@ -840,7 +737,7 @@ void app_frame::update_button_state(const bool resize) _view_import->can_analyze(); _commands[commands::import_run]->enable = view_mode == view_type::import && !view_processing && _view_import && _view_import->can_run(); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES // Must match the visibility test above: a button that appears only to sit dimmed reads as broken. _commands[commands::info_new_version]->enable = is_media_or_items_view; _commands[commands::info_check_for_updates]->enable = true; @@ -921,7 +818,9 @@ void app_frame::update_button_state(const bool resize) _commands[commands::playback_volume25]->enable = is_media_or_items_view; _commands[commands::playback_volume50]->enable = is_media_or_items_view; _commands[commands::playback_volume75]->enable = is_media_or_items_view; - _commands[commands::print]->enable = can_process_local_files; + // A command whose platform service is a stand-in is absent rather than dim, as Burn and Eject are. + _commands[commands::print]->visible = platform::can_print(); + _commands[commands::print]->enable = can_process_local_files && platform::can_print(); _commands[commands::rate_1]->enable = can_save_metadata; _commands[commands::rate_2]->enable = can_save_metadata; _commands[commands::rate_3]->enable = can_save_metadata; @@ -975,14 +874,23 @@ void app_frame::update_button_state(const bool resize) _commands[commands::tool_convert]->enable = is_media_or_items_view && photos_only_result.success(); _commands[commands::tool_copy_to_folder]->enable = can_process_local_items; _commands[commands::tool_delete]->enable = can_process_local_items; - _commands[commands::tool_desktop_background]->enable = is_media_or_items_view && selection_status.showing_image; + _commands[commands::tool_desktop_background]->visible = platform::can_set_desktop_wallpaper(); + _commands[commands::tool_desktop_background]->enable = is_media_or_items_view && selection_status.showing_image && + platform::can_set_desktop_wallpaper(); _commands[commands::tool_edit]->enable = is_media_or_items_view && _state.can_edit_media(); _commands[commands::tool_edit_description]->enable = can_save_metadata; _commands[commands::tool_edit_metadata]->enable = can_save_metadata; - _commands[commands::tool_share]->enable = can_process_local_files; - // Ejecting a drive does not depend on what is being browsed, so it answers from every view. - _commands[commands::tool_eject]->enable = true; - _commands[commands::tool_file_properties]->enable = has_selection; + // Share ends in the share sheet, or an email draft where there is none; with neither it can do nothing. + const auto can_share = platform::can_share_files() || platform::can_send_mail(); + _commands[commands::tool_share]->visible = can_share; + _commands[commands::tool_share]->enable = can_process_local_files && can_share; + // Ejecting a drive does not depend on what is being browsed, so it answers from every view. A platform that cannot + // eject has no such command, as one with no burner has no Burn: dimming would say "not now" for good. + const auto can_eject = platform::can_eject(); + _commands[commands::tool_eject]->visible = can_eject; + _commands[commands::tool_eject]->enable = can_eject; + _commands[commands::tool_file_properties]->visible = platform::can_show_file_properties(); + _commands[commands::tool_file_properties]->enable = has_selection && platform::can_show_file_properties(); _commands[commands::tool_import]->enable = is_media_or_items_view; _commands[commands::tool_locate]->enable = can_save_metadata; _commands[commands::tool_move_to_folder]->enable = can_process_local_items; @@ -1021,7 +929,8 @@ void app_frame::update_button_state(const bool resize) _commands[commands::tool_rotate_clockwise]->enable = can_save_pixels; _commands[commands::tool_rotate_reset]->enable = is_edit_view; _commands[commands::tool_save_current_video_frame]->enable = is_single_media_selection; - _commands[commands::tool_scan]->enable = is_media_or_items_view; + _commands[commands::tool_scan]->visible = platform::can_scan(); + _commands[commands::tool_scan]->enable = is_media_or_items_view && platform::can_scan(); _commands[commands::tool_sync]->enable = is_media_or_items_view; _commands[commands::tool_tag]->enable = can_save_metadata; _commands[commands::verbose_metadata]->enable = is_media_or_items_view; @@ -1452,7 +1361,7 @@ void app_frame::update_command_text() def_command(commands::menu_navigate, command_group::none, icon_index::none, tt.command_navigate); def_command(commands::tool_new_folder, command_group::file_management, icon_index::new_folder, tt.command_new_folder); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES def_command(commands::info_new_version, command_group::none, icon_index::lightbulb, tt.command_new_version); def_command(commands::info_check_for_updates, command_group::help, icon_index::lightbulb, tt.command_check_for_updates); @@ -1920,13 +1829,13 @@ void app_frame::tooltip(view_hover_element& hover, const commands id) const hover.elements->add(std::make_shared(selected.summary(), flex_item::line_break)); } } -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES else if (id == commands::info_new_version) { hover.elements->add(std::make_shared(tt.update_available, render::font_face::dialog, render::text_style::multiline, flex_item::line_break)); - hover.elements->add( - std::make_shared(str_format(tt.update_avail_version_fmt.sv(), setting.available_version))); + hover.elements->add(std::make_shared( + str_format(tt.update_avail_version_fmt.sv(), df::app_version(setting.available_version).to_string()))); hover.elements->add( std::make_shared(str_format(tt.update_current_version_fmt.sv(), s_app_version))); } diff --git a/src/app_tutorial.cpp b/src/app_tutorial.cpp index dc30c482..a02e4cda 100644 --- a/src/app_tutorial.cpp +++ b/src/app_tutorial.cpp @@ -11,6 +11,7 @@ #include "pch.h" +#include "libdesktop/ui/agent.h" #include "model_index.h" #include "model.h" #include "ui_dialog.h" @@ -141,12 +142,6 @@ namespace return value; } - size_t count_characters(const std::string_view text) - { - return static_cast( - std::ranges::count_if(text, [](const char c) { return (static_cast(c) & 0xC0) != 0x80; })); - } - struct cue_span { size_t begin = 0; @@ -260,62 +255,6 @@ namespace {"options", commands::options}, }; - std::optional key_code(const std::string_view name) - { - if (name.size() == 1) - { - const auto c = name[0]; - if (c >= 'a' && c <= 'z') return static_cast(c - 'a' + 'A'); - if ((c >= 'A' && c <= 'Z') || (c >= '0' && c <= '9')) return static_cast(c); - return {}; - } - - // The platform's codes are its own, so they are looked up as the script is read rather than tabled. - const std::pair named[] = { - {"enter", &platform::keys::RETURN}, {"escape", &platform::keys::ESCAPE}, - {"space", &platform::keys::SPACE}, {"tab", &platform::keys::TAB}, - {"backspace", &platform::keys::BACK}, {"delete", &platform::keys::DEL}, - {"left", &platform::keys::LEFT}, {"right", &platform::keys::RIGHT}, - {"up", &platform::keys::UP}, {"down", &platform::keys::DOWN}, - {"home", &platform::keys::HOME}, {"end", &platform::keys::END}, - {"page-up", &platform::keys::PRIOR}, {"page-down", &platform::keys::NEXT}, - {"insert", &platform::keys::INSERT}, {"apps", &platform::keys::APPS}, - {"plus", &platform::keys::OEM_PLUS}, {"minus", &platform::keys::OEM_MINUS}, - {"f1", &platform::keys::F1}, {"f2", &platform::keys::F2}, - {"f3", &platform::keys::F3}, {"f4", &platform::keys::F4}, - {"f5", &platform::keys::F5}, {"f6", &platform::keys::F6}, - {"f7", &platform::keys::F7}, {"f8", &platform::keys::F8}, - {"f9", &platform::keys::F9}, {"f10", &platform::keys::F10}, - {"f11", &platform::keys::F11}, {"f12", &platform::keys::F12}, - }; - - for (const auto& [key_name, code] : named) - { - if (core::icmp(key_name, name) == 0) return *code; - } - - return {}; - } - - // ctrl+, shift+ and alt+, in any order, then the key. - bool parse_key(std::string_view chord, char32_t& key, platform::key_state& keys) - { - for (auto plus = chord.find('+'); plus != std::string_view::npos && plus + 1 < chord.size(); - plus = chord.find('+')) - { - const auto modifier = chord.substr(0, plus); - if (core::icmp(modifier, "ctrl") == 0) keys.control = true; - else if (core::icmp(modifier, "shift") == 0) keys.shift = true; - else if (core::icmp(modifier, "alt") == 0) keys.alt = true; - else return false; - chord.remove_prefix(plus + 1); - } - - const auto code = key_code(chord); - if (code) key = *code; - return code.has_value(); - } - std::string read_text(const core::file_path path) { const auto file = platform::open_file(path, platform::file_open_mode::read); @@ -359,11 +298,6 @@ std::optional tutorial_command(const std::string_view name) return command_from_name(name); } -bool parse_tutorial_key(const std::string_view chord, char32_t& key, platform::key_state& keys) -{ - return parse_key(chord, key, keys); -} - std::optional tutorial_narration::cue(const std::string_view name) const { for (const auto& [cue_name, cue_seconds] : cues) @@ -406,13 +340,14 @@ std::string tutorial_spoken_text(const std::string_view narration) tutorial_narration estimate_tutorial_narration(const std::string_view narration) { tutorial_narration result; - const auto spoken = static_cast(count_characters(tutorial_spoken_text(narration))); + const auto spoken = static_cast(core::utf8_codepoint_count(tutorial_spoken_text(narration))); const auto speaking = spoken / guessed_characters_per_second; result.seconds = speaking + guessed_breath_seconds; for (const auto& cue : find_cues(narration)) { - const auto before = static_cast(count_characters(tutorial_spoken_text(narration.substr(0, cue.begin)))); + const auto before = static_cast( + core::utf8_codepoint_count(tutorial_spoken_text(narration.substr(0, cue.begin)))); result.cues.emplace_back(cue.name, spoken > 0.0 ? speaking * before / spoken : 0.0); } @@ -737,7 +672,7 @@ tutorial_script parse_tutorial_script(const std::string_view text) { step.kind = tutorial_step_kind::key; - if (!word(1) || !parse_key(*word(1), step.key, step.keys)) + if (!word(1) || !ui::parse_key_chord(*word(1), step.key, step.keys)) { problem(std::format("key {} is no key", word(1).value_or(""))); return; @@ -1218,7 +1153,7 @@ void tutorial_player::begin_step(const tutorial_step& step) const auto glide = step.seconds > 0.0 ? step.seconds : glide_seconds; _step_seconds = _pointer_shown ? glide : 0.0; _pointed = step.anchor; - move_pointer(*at, glide); + move_pointer(at, glide); } else { @@ -1262,7 +1197,7 @@ void tutorial_player::begin_step(const tutorial_step& step) _dragged_to = _pointer_to; _step_seconds = glide; _pointed = step.anchor; - move_pointer(*to, glide); + move_pointer(to, glide); } else { @@ -1282,7 +1217,8 @@ void tutorial_player::begin_step(const tutorial_step& step) break; case tutorial_step_kind::text: - _step_seconds = static_cast(count_characters(step.text)) / typing_characters_per_second + typed_seconds; + _step_seconds = static_cast(core::utf8_codepoint_count(step.text)) / typing_characters_per_second + + typed_seconds; if (!ui::send_text(app._app_frame, step.text)) { ++_outcome.missed; @@ -1295,7 +1231,8 @@ void tutorial_player::begin_step(const tutorial_step& step) app._search_edit->window_text({}); app.search_text_changed({}); _typed = 0; - _step_seconds = static_cast(count_characters(step.text)) / typing_characters_per_second + typed_seconds; + _step_seconds = static_cast(core::utf8_codepoint_count(step.text)) / typing_characters_per_second + + typed_seconds; break; case tutorial_step_kind::key: diff --git a/src/app_tutorial.h b/src/app_tutorial.h index b2508fe7..f3c7319d 100644 --- a/src/app_tutorial.h +++ b/src/app_tutorial.h @@ -151,9 +151,6 @@ tutorial_script parse_tutorial_script(std::string_view text); // The commands a script names, and the name each has. std::optional tutorial_command(std::string_view name); -// A key as a script's key step names it - ctrl+, shift+ and alt+ before a letter, a digit or a key's name - and its -// modifiers, added to keys. False for one that is no key. -bool parse_tutorial_key(std::string_view chord, char32_t& key, platform::key_state& keys); // How long a beat's voice lasts, and when it reaches each of its cues, in seconds from its start. struct tutorial_narration diff --git a/src/app_util.cpp b/src/app_util.cpp index 7dcc415e..dfda571a 100644 --- a/src/app_util.cpp +++ b/src/app_util.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -31,7 +31,7 @@ std::function(core::file_path destinatio crash_files_db& crash_files() { static crash_files_db instance(platform::probe_data_file("diffractor-files-that-crash.txt"), - crash_files_db::release_tag(s_app_version)); + crash_files_db::release_tag(s_app_version), true); return instance; } @@ -1316,8 +1316,7 @@ std::vector calc_import_sources(std::optional sele for (const auto& d : import_source_drives(drives, drive_max)) { - const auto text = std::format("{} {} {}", d.name, d.vol_name, d.used); - result.emplace_back(text, core::folder_path(d.name)); + result.emplace_back(describe_import_drive(d), core::folder_path(d.name)); } for (auto& device : platform::portable_devices()) @@ -1502,6 +1501,15 @@ platform::drives import_source_drives(const platform::drives& drives, const size return result; } +std::string describe_import_drive(const platform::drive_t& d) +{ + // The label stays beside a name that is a drive letter. A medium the desktop mounts is a folder named for its label, + // which its name already ends with. + const auto named_for_label = !d.vol_name.empty() && + core::icmp(core::folder_path(d.name).name().sv(), d.vol_name) == 0; + return named_for_label ? std::format("{} {}", d.name, d.used) : std::format("{} {} {}", d.name, d.vol_name, d.used); +} + std::string relative_combine(const std::string& relative, const core::cached name) { auto result = relative; diff --git a/src/app_util.h b/src/app_util.h index 7ece6d3e..83375328 100644 --- a/src/app_util.h +++ b/src/app_util.h @@ -293,6 +293,10 @@ void clear_abandoned_device_staging(core::folder_path root); // limit applies after the filter, so fixed drives and empty card-reader slots cannot use it up. platform::drives import_source_drives(const platform::drives& drives, size_t max); +// A removable drive as Import lists it: its name, its label, and how much it holds - the label left out where the name +// already ends with it, as a Linux medium's folder name does. +std::string describe_import_drive(const platform::drive_t& d); + size_t count_imports(const std::vector& items); size_t count_imports(const import_analysis_result& items); diff --git a/src/app_version.h b/src/app_version.h index b452472a..cbb39aaa 100644 --- a/src/app_version.h +++ b/src/app_version.h @@ -6,6 +6,10 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // Purpose: The application's version and build, which app.cpp defines, and how they read. +// +// A version is major.minor.patch, as releases, tags and the Store name it: 1.27.4. Builds up to 1.27.4.1316 named +// themselves in two parts, the major folded into the minor - 127.4 - and they still report and expect that form, so +// diffractor.com's update check answers in it. app_version reads either, so both compare as the same version. #pragma once @@ -14,5 +18,22 @@ extern const std::string_view g_app_build; namespace df { + struct app_version + { + int major = 0; + int minor = 0; + int patch = 0; + + // "1.27.4", or the two-part "127.4" older builds and the update check use. A trailing build number - the 1316 + // of 1.27.4.1316 or 127.4.1316 - is not part of the version. + explicit app_version(std::string_view text); + + // The release line a version belongs to - 127 for 1.27.4 - as the crash skip list has always tagged it. + int line() const { return major * 100 + minor; } + std::string to_string() const; + + friend auto operator<=>(const app_version&, const app_version&) = default; + }; + std::string format_version(bool short_text); } diff --git a/src/av_c64.cpp b/src/av_c64.cpp index 551aee81..810a8355 100644 --- a/src/av_c64.cpp +++ b/src/av_c64.cpp @@ -12,15 +12,14 @@ #include "pch.h" #include "av_c64.h" -#include "disk.h" -#include "machine.h" +#include "lib64/machine.h" namespace { // The largest file the machine is given: a 1 MB EasyFlash cartridge with its headers, with room to spare. constexpr size_t max_c64_file_bytes = 4 * 1024 * 1024; // A PAL frame: 19656 cycles at 985248 Hz. - constexpr double frame_seconds = pal_cycles_per_frame / static_cast(sid_clock_pal); + constexpr double frame_seconds = lib64::pal_cycles_per_frame / static_cast(lib64::pal_clock_hz); // The sound device's ring: long enough to ride out a slow frame, short enough that a key is heard promptly. constexpr double audio_ring_seconds = 0.08; // Sound queued before the device starts, so it does not run dry on its first period. @@ -28,18 +27,13 @@ namespace // While the KERNAL boots and the program loads, frames run as fast as they go and only some are shown. constexpr int warp_frames_per_picture = 8; - bool has_prefix(const core::blob& b, const std::string_view prefix) - { - return b.size() >= prefix.size() && std::memcmp(b.data(), prefix.data(), prefix.size()) == 0; - } - // The sound device in its own format: each frame's mono samples converted and spread over the front left // and right speakers, at the device's rate or a whole fraction of it. Writing waits for room, which is // what paces the machine to the device's clock. class c64_audio { public: - bool open(const std::string& device, machine& m) + bool open(const std::string& device, lib64::machine& m) { _out = platform::create_audio_output(device, audio_ring_seconds); if (!_out) return false; @@ -203,42 +197,29 @@ void c64_session::volume(const double v) _volume = std::clamp(core::round(v * 1000.0), 0, 1000); } -bool c64_session::boot(machine& m) const +bool c64_session::boot(lib64::machine& m) const { const auto bytes = platform::blob_head_from_file(_path, max_c64_file_bytes); if (bytes.empty() || bytes.size() >= max_c64_file_bytes) return false; - const auto* data = bytes.data(); - const auto size = bytes.size(); - - // Told apart in the order libfiles lists them (list_c64_media), so a file runs as what its listing shows. - // autostart_prg takes a .p00's program as it takes a .prg. - if (has_prefix(bytes, "C64File")) return m.autostart_prg(data, size); - - // A T64's 32-byte description is not fixed text, but every writer's says "tape". - if (has_prefix(bytes, "C64") && size > 32 && - std::string_view(reinterpret_cast(data), 32).find("tape") != std::string_view::npos) - { - std::vector program; - return read_tape_file_entry(data, size, _entry.data(), _entry.size(), program) && - m.autostart_prg(program.data(), program.size()); - } - - if (has_prefix(bytes, "C64 CARTRIDGE ")) return m.load_crt(data, size); - - if (disk_directory dir; read_disk_directory(data, size, dir)) - return m.autostart_disk(data, size, _entry.data(), _entry.size()); - - return m.autostart_prg(data, size); + // lib64 tells the file apart as it lists it, so a file runs as what its listing shows: a disk's or a tape's + // entry by the name it is stored under, a program file or a cartridge. + const auto started = m.autostart({bytes.data(), bytes.size()}, _entry); + if (!started) core::log(__FUNCTION__, lib64::describe(started.error())); + return started.has_value(); } -void c64_session::apply_input(machine& m) +void c64_session::apply_input(lib64::machine& m) { + // The joystick's bits are lib64's lines. + static_assert(joy_up == lib64::joystick_up && joy_down == lib64::joystick_down && + joy_left == lib64::joystick_left && joy_right == lib64::joystick_right && + joy_fire == lib64::joystick_fire); + const auto bits = static_cast(_joystick.load() | _joystick_taps.exchange(0)); const auto port = _port.load(); - m.set_joystick(port, (bits & joy_up) != 0, (bits & joy_down) != 0, (bits & joy_left) != 0, (bits & joy_right) != 0, - (bits & joy_fire) != 0); - m.set_joystick(port == 1 ? 2 : 1, false, false, false, false, false); + m.set_joystick(port, bits); + m.set_joystick(port == 1 ? 2 : 1, 0); std::vector keys; { @@ -250,9 +231,9 @@ void c64_session::apply_input(machine& m) if (_restore.exchange(false)) m.press_restore(); } -void c64_session::publish(const machine& m) +void c64_session::publish(const lib64::machine& m) { - static_assert(picture_width == machine::framebuffer_width() && picture_height == machine::framebuffer_height()); + static_assert(picture_width == lib64::frame_width && picture_height == lib64::frame_height); constexpr int w = picture_width; constexpr int h = picture_height; @@ -267,7 +248,7 @@ void c64_session::publish(const machine& m) } // The frame buffer is 0x00RRGGBB, which in memory is the blue, green, red order an RGB surface holds. - const auto* source = m.framebuffer(); + const auto* source = m.framebuffer().data(); for (int y = 0; y < h; ++y) { std::memcpy(slot->pixels_line(y), source + static_cast(y) * w, static_cast(w) * 4); @@ -282,11 +263,11 @@ void c64_session::publish(const machine& m) _next_surface ^= 1; } -int c64_session::frame(machine& m, int16_t* out, const bool publish_picture) +int c64_session::frame(lib64::machine& m, int16_t* out, const bool publish_picture) { apply_input(m); - m.exec(pal_cycles_per_frame); - const auto samples = std::max(0, m.generate_audio(out, max_frame_samples)); + m.exec(lib64::pal_cycles_per_frame); + const auto samples = static_cast(m.generate_audio({out, max_frame_samples})); if (publish_picture) publish(m); return samples; } @@ -307,7 +288,7 @@ void c64_session::run(const std::string& audio_device) void c64_session::run_machine(const std::string& audio_device) { - auto m = std::make_unique(); + auto m = std::make_unique(); if (_stop.load() || !boot(*m)) { @@ -374,67 +355,51 @@ void c64_session::run_machine(const std::string& audio_device) _status = status::stopped; } -int c64_matrix_keys(const char32_t key, uint8_t rows[2], uint8_t cols[2]) +std::optional c64_key(const char32_t key) { - const auto one = [&](const int row, const int col) - { - rows[0] = static_cast(row); - cols[0] = static_cast(col); - return 1; - }; - // Typed on the C64 with its left shift held. - const auto shifted = [&](const int row, const int col) - { - rows[0] = 1; - cols[0] = 7; - rows[1] = static_cast(row); - cols[1] = static_cast(col); - return 2; - }; + // Only letters and digits are characters: other key codes share values with lower-case ASCII. + if ((key >= U'A' && key <= U'Z') || (key >= U'0' && key <= U'9')) return lib64::key_for_character(key); - // Letters and digits sit where they do on the C64's keyboard, as VICE places them. - static constexpr std::array, 26> letters = {{ - {1, 2}, {3, 4}, {2, 4}, {2, 2}, {1, 6}, {2, 5}, {3, 2}, {3, 5}, {4, 1}, {4, 2}, {4, 5}, {5, 2}, {4, 4}, - {4, 7}, {4, 6}, {5, 1}, {7, 6}, {2, 1}, {1, 5}, {2, 6}, {3, 6}, {3, 7}, {1, 1}, {2, 7}, {3, 1}, {1, 4}, - }}; - static constexpr std::array, 10> digits = { - {{4, 3}, {7, 0}, {7, 3}, {1, 0}, {1, 3}, {2, 0}, {2, 3}, {3, 0}, {3, 3}, {4, 0}}}; - - if (key >= U'A' && key <= U'Z') return one(letters[key - U'A'][0], letters[key - U'A'][1]); - if (key >= U'0' && key <= U'9') return one(digits[key - U'0'][0], digits[key - U'0'][1]); - - if (key == platform::keys::OEM_COMMA) return one(5, 7); - if (key == platform::keys::OEM_PERIOD) return one(5, 4); - if (key == platform::keys::OEM_2) return one(6, 7); - if (key == platform::keys::OEM_1) return one(6, 2); - if (key == platform::keys::OEM_MINUS) return one(5, 3); - if (key == platform::keys::OEM_PLUS) return one(5, 0); - if (key == platform::keys::OEM_3) return one(7, 1); - if (key == platform::keys::OEM_7) return one(5, 5); - if (key == platform::keys::OEM_4) return one(5, 6); - if (key == platform::keys::OEM_6) return one(6, 1); - if (key == platform::keys::OEM_5 || key == platform::keys::OEM_102) return one(6, 6); - if (key == platform::keys::NEXT) return one(6, 5); - if (key == platform::keys::END) return one(6, 0); - if (key == platform::keys::RETURN) return one(0, 1); - if (key == platform::keys::SPACE) return one(7, 4); - if (key == platform::keys::BACK || key == platform::keys::DEL) return one(0, 0); - if (key == platform::keys::INSERT) return shifted(0, 0); - if (key == platform::keys::SHIFT) return one(1, 7); - if (key == platform::keys::CONTROL) return one(7, 2); - if (key == platform::keys::TAB) return one(7, 5); - if (key == platform::keys::HOME) return one(6, 3); + using enum lib64::key; + + switch (key) + { + case platform::keys::OEM_COMMA: return comma; + case platform::keys::OEM_PERIOD: return period; + case platform::keys::OEM_2: return slash; + case platform::keys::OEM_1: return semicolon; + case platform::keys::OEM_MINUS: return minus; + case platform::keys::OEM_PLUS: return plus; + case platform::keys::OEM_3: return left_arrow; + case platform::keys::OEM_7: return colon; + case platform::keys::OEM_4: return at; + case platform::keys::OEM_6: return asterisk; + case platform::keys::OEM_5: + case platform::keys::OEM_102: return up_arrow; + case platform::keys::NEXT: return equals; + case platform::keys::END: return pound; + case platform::keys::RETURN: return return_; + case platform::keys::SPACE: return space; + case platform::keys::BACK: + case platform::keys::DEL: return inst_del; + case platform::keys::INSERT: return insert; + case platform::keys::SHIFT: return left_shift; + case platform::keys::CONTROL: return ctrl; + case platform::keys::TAB: return commodore; + case platform::keys::HOME: return clr_home; // Escape leaves the machine, so RUN/STOP is on Pause and F9. - if (key == platform::keys::PAUSE || key == platform::keys::F9) return one(7, 7); - if (key == platform::keys::F1) return one(0, 4); - if (key == platform::keys::F3) return one(0, 5); - if (key == platform::keys::F5) return one(0, 6); - if (key == platform::keys::F7) return one(0, 3); - if (key == platform::keys::F2) return shifted(0, 4); - if (key == platform::keys::F4) return shifted(0, 5); - if (key == platform::keys::F6) return shifted(0, 6); - if (key == platform::keys::F8) return shifted(0, 3); - return 0; + case platform::keys::PAUSE: + case platform::keys::F9: return run_stop; + case platform::keys::F1: return f1; + case platform::keys::F2: return f2; + case platform::keys::F3: return f3; + case platform::keys::F4: return f4; + case platform::keys::F5: return f5; + case platform::keys::F6: return f6; + case platform::keys::F7: return f7; + case platform::keys::F8: return f8; + default: return std::nullopt; + } } namespace @@ -448,6 +413,12 @@ namespace if (key == platform::keys::SPACE) return c64_session::joy_fire; return 0; } + + void hold_c64_key(c64_session& session, const std::optional key, const bool pressed) + { + if (!key) return; + for (const auto [row, col] : lib64::key_positions(*key)) session.key(row, col, pressed); + } } bool c64_keyboard::press(c64_session& session, const char32_t key, const bool repeat) @@ -463,9 +434,9 @@ bool c64_keyboard::press(c64_session& session, const char32_t key, const bool re // Space is the joystick's fire and the C64's space bar both, as in lib64's own host, so a title screen // that waits for SPACE starts as one that waits for fire does. - held_key held{key, joystick_bit(key), 0, {}, {}}; - if (!held.joystick || key == platform::keys::SPACE) held.count = c64_matrix_keys(key, held.rows, held.cols); - if (!held.joystick && held.count == 0) return false; + held_key held{key, joystick_bit(key), std::nullopt}; + if (!held.joystick || key == platform::keys::SPACE) held.c64 = c64_key(key); + if (!held.joystick && !held.c64) return false; if (held.joystick) { @@ -473,7 +444,7 @@ bool c64_keyboard::press(c64_session& session, const char32_t key, const bool re session.joystick(_joystick); } - for (auto i = 0; i < held.count; ++i) session.key(held.rows[i], held.cols[i], true); + hold_c64_key(session, held.c64, true); _held.push_back(held); return true; } @@ -487,7 +458,7 @@ void c64_keyboard::sync(c64_session& session) if (platform::is_key_down_async(held.key)) return false; joystick &= static_cast(~held.joystick); - for (auto i = 0; i < held.count; ++i) session.key(held.rows[i], held.cols[i], false); + hold_c64_key(session, held.c64, false); return true; }); @@ -500,10 +471,7 @@ void c64_keyboard::sync(c64_session& session) void c64_keyboard::release_all(c64_session& session) { - for (const auto& held : _held) - { - for (auto i = 0; i < held.count; ++i) session.key(held.rows[i], held.cols[i], false); - } + for (const auto& held : _held) hold_c64_key(session, held.c64, false); _held.clear(); _joystick = 0; diff --git a/src/av_c64.h b/src/av_c64.h index 1195f53a..18a01551 100644 --- a/src/av_c64.h +++ b/src/av_c64.h @@ -13,7 +13,12 @@ #include "util_interfaces.h" -class machine; +#include "lib64/keyboard.h" + +namespace lib64 +{ + class machine; +} // The live machine. Shared by the emulator queue's worker, which alone touches the emulator, and the UI // thread, which reads the published picture and status and hands over keys; see implementation.md's @@ -62,8 +67,8 @@ class c64_session final : public std::enable_shared_from_this // The worker's own steps, public for the tests: reading and starting the file, and one frame - emulated, // with its picture published. A frame's samples are written to out, which must hold // max_frame_samples. Returns the number of samples. - bool boot(machine& m) const; - int frame(machine& m, int16_t* out, bool publish); + bool boot(lib64::machine& m) const; + int frame(lib64::machine& m, int16_t* out, bool publish); static constexpr int max_frame_samples = 4096; // The picture's size: the VIC-II's visible area, its border included. @@ -82,8 +87,8 @@ class c64_session final : public std::enable_shared_from_this private: void run(const std::string& audio_device); void run_machine(const std::string& audio_device); - void apply_input(machine& m); - void publish(const machine& m); + void apply_input(lib64::machine& m); + void publish(const lib64::machine& m); const core::file_path _path; const std::vector _entry; @@ -136,22 +141,13 @@ class c64_keyboard { char32_t key; uint8_t joystick; - int count; - uint8_t rows[2]; - uint8_t cols[2]; + std::optional c64; }; std::vector _held; uint8_t _joystick = 0; }; -// The C64 keyboard matrix positions a host key stands for, as row and column: one, or two for a key the C64 -// types with its shift held. Returns how many; 0 for a key it does not have. -int c64_matrix_keys(char32_t key, uint8_t rows[2], uint8_t cols[2]); - -// Whether a listing row, by its type byte, names something the machine can start: a program on a disk, the -// cartridge, or any file on a tape. -constexpr bool c64_row_runs(const uint8_t file_type, const bool tape) -{ - return tape || file_type == 0x99 || (file_type & 0x07) == 2; -} +// The C64 key a host key stands for, held down where lib64::key_positions has it - with the C64's shift for a key +// it types shifted. None for a key it does not have. +std::optional c64_key(char32_t key); diff --git a/src/av_format.cpp b/src/av_format.cpp index ec1f9a94..d7f6f03b 100644 --- a/src/av_format.cpp +++ b/src/av_format.cpp @@ -22,6 +22,7 @@ #include "av_tracker.h" #include "metadata.h" #include "files.h" +#include "libfiles/hdr.h" #include "libfiles/media.h" // Both of these are MSVC dialect repairs. excpt.h has no equivalent elsewhere, and __restrict__ is @@ -4561,50 +4562,6 @@ static std::array tone_map_key(const AVFrame& frame) return key; } -// SMPTE ST 2084: PQ signal, 0 to 1, against absolute light in nits. -namespace pq -{ - constexpr double m1 = 2610.0 / 16384.0; - constexpr double m2 = 2523.0 / 4096.0 * 128.0; - constexpr double c1 = 3424.0 / 4096.0; - constexpr double c2 = 2413.0 / 4096.0 * 32.0; - constexpr double c3 = 2392.0 / 4096.0 * 32.0; - - static double to_nits(const double signal) - { - const auto p = std::pow(std::clamp(signal, 0.0, 1.0), 1.0 / m2); - return 10000.0 * std::pow(std::max(p - c1, 0.0) / (c2 - c3 * p), 1.0 / m1); - } - - static double from_nits(const double nits) - { - const auto y = std::pow(std::clamp(nits / 10000.0, 0.0, 1.0), m1); - return std::pow((c1 + c2 * y) / (1.0 + c3 * y), m2); - } -} - -// The BT.2390 EETF, between PQ signals: light from a source whose peak is source_peak, onto a display -// whose peak is target_peak. Below the knee the signal passes untouched, so midtones and reference -// white keep their brightness; above it a Hermite spline rolls the highlights into the target's peak -// rather than clipping them. -static double bt2390_eetf(const double signal, const double source_peak, const double target_peak) -{ - if (source_peak <= target_peak) return std::min(signal, target_peak); - - const auto max_lum = target_peak / source_peak; - const auto knee = 1.5 * max_lum - 0.5; - const auto e = std::clamp(signal / source_peak, 0.0, 1.0); - if (e < knee) return e * source_peak; - - const auto t = (e - knee) / (1.0 - knee); - const auto t2 = t * t; - const auto t3 = t2 * t; - const auto rolled = (2.0 * t3 - 3.0 * t2 + 1.0) * knee + (t3 - 2.0 * t2 + t) * (1.0 - knee) + - (-2.0 * t3 + 3.0 * t2) * max_lum; - - return rolled * source_peak; -} - static core::tone_map_lut_ptr make_tone_map_lut(const AVFrame& frame) { // 33 samples an axis is the size colour grading uses: fine enough that trilinear blending between @@ -4698,8 +4655,8 @@ static core::tone_map_lut_ptr make_tone_map_lut(const AVFrame& frame) return {}; } - const auto source_peak = hlg ? 0.0 : pq::from_nits(pq_source_peak_nits(frame)); - const auto target_peak = pq::from_nits(sdr_white_nits); + const auto source_peak = hlg ? 0.0 : libfiles::pq_from_nits(pq_source_peak_nits(frame)); + const auto target_peak = libfiles::pq_from_nits(sdr_white_nits); auto lut = std::make_shared(); lut->size = n; @@ -4713,16 +4670,17 @@ static core::tone_map_lut_ptr make_tone_map_lut(const AVFrame& frame) for (auto i = 0; i < n * n; ++i) { const auto* const px = row + i * 3; - const std::array light = {pq::to_nits(px[0] / 65535.0), pq::to_nits(px[1] / 65535.0), - pq::to_nits(px[2] / 65535.0)}; + const std::array light = {libfiles::pq_to_nits(px[0] / 65535.0), libfiles::pq_to_nits(px[1] / 65535.0), + libfiles::pq_to_nits(px[2] / 65535.0)}; - // PQ is rolled off on luminance, with every channel scaled alike so a highlight keeps its hue - // as it compresses. Luminance is a smooth function of the signal, so the cube's blending - // between samples follows it; the brightest channel bends along the grey axis, and blended - // there it would darken every neutral tone. HLG already peaks at white. + // PQ is rolled off on luminance, by BT.2390's EETF, with every channel scaled alike so a + // highlight keeps its hue as it compresses. Luminance is a smooth function of the signal, so the + // cube's blending between samples follows it; the brightest channel bends along the grey axis, + // and blended there it would darken every neutral tone. HLG already peaks at white. const auto luminance = 0.2126 * light[0] + 0.7152 * light[1] + 0.0722 * light[2]; const auto mapped = hlg ? luminance - : pq::to_nits(bt2390_eetf(pq::from_nits(luminance), source_peak, target_peak)); + : libfiles::pq_to_nits(libfiles::bt2390_eetf(libfiles::pq_from_nits(luminance), + source_peak, target_peak)); const auto gain = luminance > 0.0 ? mapped / luminance : 1.0; const auto white = std::min(mapped / sdr_white_nits, 1.0); diff --git a/src/av_movie_writer.cpp b/src/av_movie_writer.cpp new file mode 100644 index 00000000..77b94b6f --- /dev/null +++ b/src/av_movie_writer.cpp @@ -0,0 +1,899 @@ +// This file is part of the Diffractor photo and video organizer +// Copyright 2026 Zac Walker +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Purpose: FFmpeg's movie writer, libdesktop's movie_writer contract kept where the system has no encoder to ask. +// Frames are converted to 4:2:0 BT.709 limited range on the caller's thread and encoded as AV1 by libaom's real-time +// encoder, itself threaded, on a worker of the writer's own, so the next frame is composed while the last is encoded; +// sound is converted to the planar floats FFmpeg's AAC encoder takes and cut into its frames. Both go into an MP4 +// with its index in front, written under the path the request names and left there only once close has finished it. +// The times a caller gives are kept: a hole in them is filled with what came before it, as the sink Media Foundation +// writes through shows the last picture until the next. + +#include "pch.h" +#include "av_movie_writer.h" + +#include +#include +#include +#include + +// An MSVC dialect repair: __restrict__ is a real keyword on GCC and Clang, which FFmpeg's headers rely on. +#ifdef _MSC_VER +#include +// NOLINTNEXTLINE(bugprone-reserved-identifier): the GCC spelling FFmpeg's headers use +#define __restrict__ +#endif + +// FFmpeg's C clipping helpers in libavutil/common.h narrow an int implicitly, which MSVC's /W4 reports. +#ifdef _MSC_VER +#pragma warning(push) +#pragma warning(disable : 4244) +#endif +extern "C" +{ +#include "libavcodec/avcodec.h" +#include "libavformat/avformat.h" +#include "libavutil/audio_fifo.h" +#include "libavutil/channel_layout.h" +#include "libavutil/cpu.h" +#include "libavutil/dict.h" +#include "libavutil/frame.h" +#include "libswresample/swresample.h" +#include "libswscale/swscale.h" +} +#ifdef _MSC_VER +#pragma warning(pop) +#endif + +namespace +{ + // The encoders' own names, which are not the names configure takes for them: libaom_av1 there. + constexpr auto video_encoder_name = "libaom-av1"; + constexpr auto audio_encoder_name = "aac"; + constexpr auto container_name = "mp4"; + + // What Movie mixer derives its bitrate from (model_movie.h): 0.10 bits a pixel a frame, between 1 and 60 + // Mbit/s, which is 6.2 Mbit/s at 1080p30. A request that gives none is written at the same. + constexpr double default_bits_per_pixel = 0.10; + constexpr double min_bitrate = 1000000.0; + constexpr double max_bitrate = 60000000.0; + + // A key frame at least this often, which is what a player seeks to. + constexpr double key_frame_seconds = 2.0; + + // The most threads libaom is given. Its row-based threading uses no more than a frame's rows of + // superblocks keep busy, so more only idle - and take cores from what is composing the next frame. + constexpr int most_encoder_threads = 16; + + // The pictures a frame is converted into and then encoded from: the one the caller last made, which a hole in the + // times repeats, the one being made, and two the encoder is on or has waiting. The caller is held there when the + // encoder is the slower, so a render's memory is the same whichever of composing and encoding is. + constexpr size_t pictures_in_flight = 4; + + // The longest hole in the times a caller gives that is filled rather than refused: a time that far ahead is a + // mistake, not a pause. + constexpr double longest_gap_seconds = 60.0; + + // libaom's real-time speeds run from 5, the best, to 12, the fastest, and FFmpeg's own option stops at 8. The + // faster the load - pixels a second - the faster the speed: 7 to 9 is where a desktop's cores keep 1080p at 30 + // frames a second in step with the picture being made. + int encoder_speed(const sizei extent, const int frame_rate) + { + const auto pixels_a_second = static_cast(extent.cx) * extent.cy * frame_rate; + if (pixels_a_second <= 30e6) return 7; + if (pixels_a_second <= 70e6) return 8; + if (pixels_a_second <= 200e6) return 9; + return 10; + } + + // As many tile columns as the threads can use, none narrower than 256 pixels, and no more than 4 - or 8 from + // 2560 wide - which is as many as libaom's row threading leaves worth having; as a power of two, as libaom takes it. + int tile_columns_log2(const int width, const int threads) + { + const auto most = width >= 2560 ? 3 : 2; + auto log2 = 0; + while (log2 < most && (2 << log2) <= threads && (width >> (log2 + 1)) >= 256) ++log2; + return log2; + } + + std::string ffmpeg_error(const int code) + { + char text[AV_ERROR_MAX_STRING_SIZE] = {}; + av_strerror(code, text, sizeof(text)); + return text; + } + + struct frame_deleter + { + void operator()(AVFrame* frame) const { av_frame_free(&frame); } + }; + + struct packet_deleter + { + void operator()(AVPacket* packet) const { av_packet_free(&packet); } + }; + + struct codec_deleter + { + void operator()(AVCodecContext* codec) const { avcodec_free_context(&codec); } + }; + + struct scaler_deleter + { + void operator()(SwsContext* scaler) const { sws_free_context(&scaler); } + }; + + struct resampler_deleter + { + void operator()(SwrContext* resampler) const { swr_free(&resampler); } + }; + + struct fifo_deleter + { + void operator()(AVAudioFifo* fifo) const { av_audio_fifo_free(fifo); } + }; + + // A muxer's file is closed first, as FFmpeg asks of a context whose I/O it opened. + struct format_deleter + { + void operator()(AVFormatContext* format) const + { + if (format->pb) avio_closep(&format->pb); + avformat_free_context(format); + } + }; + + // The pictures not in use. One is handed out as a shared pointer that puts it back when the last reference goes - + // the caller's, which keeps the picture a hole repeats, and each job the encoder is yet to run. + struct picture_pool + { + std::mutex lock; + std::condition_variable returned; + std::vector> idle; + }; + + void give_back(const std::shared_ptr& pool, AVFrame* const picture) + { + { + std::lock_guard guard(pool->lock); + pool->idle.emplace_back(picture); + } + + pool->returned.notify_one(); + } + + class ffmpeg_movie_writer final : public platform::movie_writer + { + public: + explicit ffmpeg_movie_writer(const platform::movie_writer_request& request) : _request(request) {} + + ~ffmpeg_movie_writer() override { abandon(); } + + ffmpeg_movie_writer(const ffmpeg_movie_writer&) = delete; + ffmpeg_movie_writer& operator=(const ffmpeg_movie_writer&) = delete; + + bool open() + { + const auto& extent = _request.extent; + + if (extent.cx <= 0 || extent.cy <= 0 || _request.frame_rate <= 0) + { + return fail("invalid movie geometry"); + } + + const auto* const video = avcodec_find_encoder_by_name(video_encoder_name); + if (!video) return fail("this FFmpeg has no AV1 encoder"); + + const AVCodec* audio = nullptr; + + if (_request.with_audio) + { + audio = avcodec_find_encoder_by_name(audio_encoder_name); + if (!audio) return fail("this FFmpeg has no AAC encoder"); + } + + const auto url = _request.path.str(); + AVFormatContext* format = nullptr; + + if (const auto made = avformat_alloc_output_context2(&format, nullptr, container_name, url.c_str()); + made < 0 || !format) + { + return fail("cannot make an MP4 writer", made); + } + + _format.reset(format); + _video_packet.reset(av_packet_alloc()); + _audio_packet.reset(av_packet_alloc()); + if (!_video_packet || !_audio_packet) return fail("out of memory"); + + if (!open_video(*video) || (audio && !open_audio(*audio))) return false; + + if (const auto created = avio_open2(&_format->pb, url.c_str(), AVIO_FLAG_WRITE, nullptr, nullptr); + created < 0) + { + return fail("cannot create the file", created); + } + + _created_file = true; + + // The index in front, so the movie plays while it is still being copied or uploaded. The muxer makes it at the + // end, by moving what it wrote, and so wants the file it is writing to be one it can read again. + AVDictionary* options = nullptr; + av_dict_set(&options, "movflags", "+faststart", 0); + const auto started = avformat_write_header(_format.get(), &options); + av_dict_free(&options); + if (started < 0) return fail("cannot write the MP4's header", started); + + _worker = platform::create_serial_executor("movie encoder"); + if (!_worker) return fail("cannot start the worker that encodes the pictures"); + + _writing = true; + return true; + } + + bool write_frame(const core::const_surface_ptr& surface, const double time) override + { + if (!_writing || _failed || !surface || surface->empty()) return false; + + const auto extent = surface->dimensions(); + + if (extent.cx != _request.extent.cx || extent.cy != _request.extent.cy) + { + return refuse("frame does not match the movie geometry"); + } + + if (!is_packed(surface->format())) return refuse("frame is not packed 32-bit pixels"); + + if (!std::isfinite(time) || time < 0.0) return refuse("a frame's time is not a time in the movie"); + + const auto slot = static_cast(std::llround(time * _request.frame_rate)); + + if (_next_slot < 0) + { + _next_slot = slot; + } + else if (slot < _next_slot) + { + return refuse("a frame is not after the one before it"); + } + else if (slot - _next_slot > static_cast(longest_gap_seconds * _request.frame_rate)) + { + return refuse("a frame is too far after the one before it"); + } + + // What came before shows until this frame does. + while (_next_slot < slot) + { + if (!post_picture(_last, _next_slot++)) return false; + } + + const auto waited = std::chrono::steady_clock::now(); + const auto picture = take_picture(); + if (!picture) return false; + + const auto converting = std::chrono::steady_clock::now(); + _wait_seconds += std::chrono::duration(converting - waited).count(); + + if (const auto writable = av_frame_make_writable(picture.get()); writable < 0) + { + return fail("cannot make a picture to convert into", writable); + } + + // The fourth byte of a pixel is padding, not alpha: the picture is opaque. + const uint8_t* const source[4] = {surface->pixels(), nullptr, nullptr, nullptr}; + const int stride[4] = {static_cast(surface->stride()), 0, 0, 0}; + + if (sws_scale(_scaler.get(), source, stride, 0, extent.cy, picture->data, picture->linesize) != extent.cy) + { + return fail("cannot convert a frame to YUV"); + } + + _convert_seconds += std::chrono::duration(std::chrono::steady_clock::now() - converting).count(); + _last = picture; + ++_frames; + return post_picture(picture, _next_slot++); + } + + bool write_audio(const int16_t* samples, const size_t sample_count, const double time) override + { + if (!_writing || _failed || !_audio || !samples || sample_count == 0) return false; + + const auto channels = _audio->ch_layout.nb_channels; + auto frames = static_cast(sample_count / static_cast(channels)); + if (frames == 0) return true; + + if (!std::isfinite(time) || time < 0.0) return refuse("a sound's time is not a time in the movie"); + + const auto rate = static_cast(_audio->sample_rate); + const auto start = static_cast(std::llround(time * rate)); + + if (_audio_next < 0) + { + _audio_next = _audio_pts = start; + } + else if (start > _audio_next) + { + const auto gap = start - _audio_next; + if (gap > static_cast(longest_gap_seconds * rate)) + return refuse("a sound is too far after the one before it"); + if (!append_silence(gap)) return false; + } + else if (start < _audio_next) + { + // The part already written is not written again. + const auto overlap = std::min(frames, _audio_next - start); + samples += overlap * channels; + frames -= overlap; + if (frames == 0) return true; + } + + if (!append_samples(samples, static_cast(frames))) return false; + return encode_audio(false); + } + + bool close() override + { + if (!_format || !_writing) return false; + + _writing = false; + + // The pictures already handed over are encoded and in the file before the end of it is written. + stop_worker(); + + auto ok = !_failed && send_and_drain(_video.get(), nullptr, _video_stream, _video_packet.get()); + + if (ok && _audio) + { + ok = encode_audio(true) && send_and_drain(_audio.get(), nullptr, _audio_stream, _audio_packet.get()); + } + + if (ok) + { + if (const auto trailer = av_write_trailer(_format.get()); trailer < 0) + { + ok = fail("cannot finish the MP4", trailer); + } + } + + // The file's last bytes, and its index moved to the front, are on disk once this has returned. + if (const auto closed = avio_closep(&_format->pb); ok && closed < 0) + ok = fail("cannot close the file", closed); + + if (ok) + { + const auto per_frame = [this](const double seconds) + { + return _frames > 0 ? seconds * 1000.0 / static_cast(_frames) : 0.0; + }; + + core::log(__FUNCTION__, + std::format("Wrote {}: {}x{} at {} fps, {} frames, {} kbit/s, speed {}; a frame took " + "{:.1f} ms to convert and {:.1f} ms in the encoder, and waited {:.1f} ms " + "for it", + _request.path.name().sv(), _request.extent.cx, _request.extent.cy, + _request.frame_rate, _frames, _video->bit_rate / 1000, + encoder_speed(_request.extent, _request.frame_rate), per_frame(_convert_seconds), + per_frame(_encode_seconds), per_frame(_wait_seconds))); + _created_file = false; // The file is the caller's now. + } + + release(); + return ok; + } + + void abandon() override + { + _writing = false; + _quitting = true; + stop_worker(); + release(); + + if (_created_file) + { + _created_file = false; + platform::delete_file(_request.path); + } + } + + std::string last_error() const override + { + std::lock_guard guard(_error_lock); + return _error; + } + + private: + bool open_video(const AVCodec& codec) + { + _video.reset(avcodec_alloc_context3(&codec)); + if (!_video) return fail("out of memory"); + + auto* const encoder = _video.get(); + const auto& extent = _request.extent; + const auto fps = _request.frame_rate; + const auto threads = std::clamp(av_cpu_count(), 1, most_encoder_threads); + const auto speed = encoder_speed(extent, fps); + + encoder->width = extent.cx; + encoder->height = extent.cy; + encoder->pix_fmt = AV_PIX_FMT_YUV420P; + encoder->time_base = {1, fps}; + encoder->framerate = {fps, 1}; + encoder->sample_aspect_ratio = {1, 1}; + encoder->gop_size = std::max(1, static_cast(std::lround(key_frame_seconds * fps))); + encoder->max_b_frames = 0; + encoder->thread_count = threads; + encoder->bit_rate = _request.video_bitrate > 0 ? _request.video_bitrate + : av_default_movie_bitrate(extent, fps); + + // What the converted pictures are in, said once to every player. + encoder->color_primaries = AVCOL_PRI_BT709; + encoder->color_trc = AVCOL_TRC_BT709; + encoder->colorspace = AVCOL_SPC_BT709; + encoder->color_range = AVCOL_RANGE_MPEG; + encoder->chroma_sample_location = AVCHROMA_LOC_LEFT; + + // An MP4 holds the sequence header apart from the pictures, which libaom's wrapper makes only when asked. + if (_format->oformat->flags & AVFMT_GLOBALHEADER) encoder->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + // Real-time usage never looks ahead, so a frame comes out as it goes in, and the bitrate is held as it + // is asked: a render's size is what its panel said it would be. + AVDictionary* options = nullptr; + av_dict_set(&options, "usage", "realtime", 0); + av_dict_set_int(&options, "cpu-used", std::min(speed, 8), 0); + av_dict_set_int(&options, "row-mt", 1, 0); + av_dict_set_int(&options, "tile-columns", tile_columns_log2(extent.cx, threads), 0); + av_dict_set_int(&options, "lag-in-frames", 0, 0); + // The speeds above FFmpeg's own range are libaom's, reached through its options. + if (speed > 8) av_dict_set(&options, "aom-params", std::format("cpu-used={}", speed).c_str(), 0); + + const auto opened = avcodec_open2(encoder, &codec, &options); + + if (opened >= 0 && av_dict_count(options) > 0) + { + core::log(__FUNCTION__, std::format("the AV1 encoder ignored {} option(s)", av_dict_count(options))); + } + + av_dict_free(&options); + if (opened < 0) return fail("the AV1 encoder would not open", opened); + + _video_stream = avformat_new_stream(_format.get(), nullptr); + if (!_video_stream) return fail("out of memory"); + + if (const auto described = avcodec_parameters_from_context(_video_stream->codecpar, encoder); described < 0) + { + return fail("cannot describe the video", described); + } + + _video_stream->time_base = encoder->time_base; + _video_stream->avg_frame_rate = encoder->framerate; + _video_stream->sample_aspect_ratio = encoder->sample_aspect_ratio; + + _pool = std::make_shared(); + + for (size_t i = 0; i < pictures_in_flight; ++i) + { + std::unique_ptr picture(av_frame_alloc()); + if (!picture) return fail("out of memory"); + + picture->format = encoder->pix_fmt; + picture->width = extent.cx; + picture->height = extent.cy; + picture->color_primaries = encoder->color_primaries; + picture->color_trc = encoder->color_trc; + picture->colorspace = encoder->colorspace; + picture->color_range = encoder->color_range; + picture->chroma_location = encoder->chroma_sample_location; + picture->duration = 1; + + if (const auto buffered = av_frame_get_buffer(picture.get(), 0); buffered < 0) + { + return fail("cannot make a picture to convert into", buffered); + } + + _pool->idle.push_back(std::move(picture)); + } + + return open_scaler(); + } + + // From the packed pixels a surface holds to the 4:2:0 the encoder takes, the matrix set where swscale would + // otherwise take BT.601's for any YUV: the picture is full range RGB, and leaves as BT.709's limited range. + bool open_scaler() + { + const auto& extent = _request.extent; + _scaler.reset(sws_alloc_context()); + if (!_scaler) return fail("out of memory"); + + _scaler->src_w = _scaler->dst_w = extent.cx; + _scaler->src_h = _scaler->dst_h = extent.cy; + _scaler->src_format = AV_PIX_FMT_BGR0; + _scaler->dst_format = AV_PIX_FMT_YUV420P; + _scaler->flags = SWS_BICUBIC | SWS_ACCURATE_RND; + + if (const auto initialised = sws_init_context(_scaler.get(), nullptr, nullptr); initialised < 0) + { + return fail("cannot convert pixels to YUV", initialised); + } + + const auto* const bt709 = sws_getCoefficients(SWS_CS_ITU709); + + if (sws_setColorspaceDetails(_scaler.get(), bt709, 1, bt709, 0, 0, 1 << 16, 1 << 16) < 0) + { + return fail("cannot set the colour matrix of the conversion"); + } + + return true; + } + + bool open_audio(const AVCodec& codec) + { + _audio.reset(avcodec_alloc_context3(&codec)); + if (!_audio) return fail("out of memory"); + + auto* const encoder = _audio.get(); + const auto channels = std::max(1, _request.channels); + const auto rate = std::max(8000, _request.sample_rate); + + encoder->sample_fmt = AV_SAMPLE_FMT_FLTP; + encoder->sample_rate = rate; + encoder->time_base = {1, rate}; + encoder->bit_rate = std::max(1, _request.audio_bitrate); + av_channel_layout_default(&encoder->ch_layout, channels); + if (_format->oformat->flags & AVFMT_GLOBALHEADER) encoder->flags |= AV_CODEC_FLAG_GLOBAL_HEADER; + + if (const auto opened = avcodec_open2(encoder, &codec, nullptr); opened < 0) + { + return fail("the AAC encoder would not open", opened); + } + + _audio_stream = avformat_new_stream(_format.get(), nullptr); + if (!_audio_stream) return fail("out of memory"); + + if (const auto described = avcodec_parameters_from_context(_audio_stream->codecpar, encoder); described < 0) + { + return fail("cannot describe the sound", described); + } + + _audio_stream->time_base = encoder->time_base; + + // The caller's samples are 16-bit and interleaved; the encoder's are planar floats. + SwrContext* resampler = nullptr; + + if (const auto made = swr_alloc_set_opts2(&resampler, &encoder->ch_layout, AV_SAMPLE_FMT_FLTP, rate, + &encoder->ch_layout, AV_SAMPLE_FMT_S16, rate, 0, nullptr); + made < 0) + { + return fail("cannot convert sound for the encoder", made); + } + + _resampler.reset(resampler); + if (const auto ready = swr_init(resampler); ready < 0) + return fail("cannot convert sound for the encoder", ready); + + // The encoder takes frames of one length - 1024 samples - and a caller's chunks are any. + const auto frame_size = std::max(1, encoder->frame_size); + _fifo.reset(av_audio_fifo_alloc(AV_SAMPLE_FMT_FLTP, channels, frame_size * 4)); + if (!_fifo) return fail("out of memory"); + + _audio_frame.reset(av_frame_alloc()); + if (!_audio_frame) return fail("out of memory"); + + _audio_frame->format = encoder->sample_fmt; + _audio_frame->sample_rate = rate; + _audio_frame->nb_samples = frame_size; + if (const auto copied = av_channel_layout_copy(&_audio_frame->ch_layout, &encoder->ch_layout); copied < 0) + { + return fail("out of memory", copied); + } + + if (const auto buffered = av_frame_get_buffer(_audio_frame.get(), 0); buffered < 0) + { + return fail("cannot make a frame of sound", buffered); + } + + _planes.assign(static_cast(channels), {}); + return true; + } + + // The next picture to convert into, once the encoder has finished with one. Empty once the writer has failed, + // which is also what lets go a caller waiting here. + std::shared_ptr take_picture() + { + std::unique_lock lock(_pool->lock); + _pool->returned.wait(lock, [this] { return !_pool->idle.empty() || _failed; }); + if (_failed) return {}; + + AVFrame* const picture = _pool->idle.back().release(); + _pool->idle.pop_back(); + lock.unlock(); + + return {picture, [pool = _pool](AVFrame* done) { give_back(pool, done); }}; + } + + // Hands a converted picture to the worker, to be encoded as the frame of this slot. A hole in the times is a + // picture handed over again, so one picture may be in several jobs, which the worker runs one after another. + bool post_picture(const std::shared_ptr& picture, const int64_t slot) + { + if (!picture) return fail("there is no picture to repeat"); + + if (!_worker->post([this, picture, slot] { encode_picture(*picture, slot); })) + { + return fail("the worker that encodes the pictures has stopped"); + } + + return true; + } + + // On the worker. Frames arrive in the order they were written, so the encoder and the file see them so; after + // a failure, or an abandon, the jobs left only let go of their pictures. + void encode_picture(AVFrame& picture, const int64_t slot) + { + if (_failed || _quitting) return; + + const auto began = std::chrono::steady_clock::now(); + picture.pts = slot; + send_and_drain(_video.get(), &picture, _video_stream, _video_packet.get()); + _encode_seconds += std::chrono::duration(std::chrono::steady_clock::now() - began).count(); + } + + // Ends the worker once it has run what it was handed: for a writer that has failed or been abandoned, no more + // than letting go of the pictures. + void stop_worker() + { + if (!_worker) return; + + _worker->stop(); + _worker.reset(); + } + + // Sound the encoder has enough of is cut into its frames and encoded; at the end, what is left is a short + // frame of its own. + bool encode_audio(const bool flush) + { + const auto frame_size = std::max(1, _audio->frame_size); + + while (av_audio_fifo_size(_fifo.get()) >= frame_size || (flush && av_audio_fifo_size(_fifo.get()) > 0)) + { + const auto count = std::min(av_audio_fifo_size(_fifo.get()), frame_size); + + if (const auto writable = av_frame_make_writable(_audio_frame.get()); writable < 0) + { + return fail("cannot make a frame of sound", writable); + } + + _audio_frame->nb_samples = count; + + if (av_audio_fifo_read(_fifo.get(), std::bit_cast(_audio_frame->extended_data), count) != + count) + { + return fail("cannot read the sound waiting to be encoded"); + } + + _audio_frame->pts = _audio_pts; + _audio_pts += count; + if (!send_and_drain(_audio.get(), _audio_frame.get(), _audio_stream, _audio_packet.get())) return false; + } + + return true; + } + + bool append_samples(const int16_t* samples, const int frames) + { + std::vector planes; + + for (auto& plane : _planes) + { + plane.resize(static_cast(frames)); + planes.push_back(std::bit_cast(plane.data())); + } + + const auto* const input = std::bit_cast(samples); + const auto converted = swr_convert(_resampler.get(), planes.data(), frames, &input, frames); + if (converted < 0) return fail("cannot convert sound for the encoder", converted); + + if (av_audio_fifo_write(_fifo.get(), std::bit_cast(planes.data()), converted) != converted) + { + return fail("cannot queue sound for the encoder"); + } + + _audio_next += converted; + return true; + } + + // Silence of this many sample frames, which is what a hole in a sound's times plays. + bool append_silence(const int64_t frames) + { + const auto channels = static_cast(_audio->ch_layout.nb_channels); + constexpr int64_t most = 8192; + const std::vector quiet(static_cast(std::min(frames, most)) * channels, 0); + + for (auto left = frames; left > 0; left -= most) + { + if (!append_samples(quiet.data(), static_cast(std::min(left, most)))) return false; + } + + return true; + } + + // Hands a frame - or the end, given none - to an encoder and writes every packet it has ready. The picture's + // encoder is the worker's and the sound's the caller's, each with a packet of its own; the file is the one thing + // they share. + bool send_and_drain(AVCodecContext* const encoder, const AVFrame* const frame, AVStream* const stream, + AVPacket* const packet) + { + if (const auto sent = avcodec_send_frame(encoder, frame); sent < 0 && sent != AVERROR_EOF) + { + return fail("an encoder refused a frame", sent); + } + + for (;;) + { + const auto received = avcodec_receive_packet(encoder, packet); + if (received == AVERROR(EAGAIN) || received == AVERROR_EOF) return true; + if (received < 0) return fail("an encoder failed", received); + + av_packet_rescale_ts(packet, encoder->time_base, stream->time_base); + packet->stream_index = stream->index; + + // Takes the packet whatever the answer, so there is nothing to free. + std::lock_guard guard(_file_lock); + + if (const auto written = av_interleaved_write_frame(_format.get(), packet); written < 0) + { + return fail("cannot write to the file", written); + } + } + } + + // A request the writer will not take, as a frame that is out of order: the reason is kept for last_error, and the + // movie goes on as it was. + bool refuse(const std::string_view what) + { + core::log(__FUNCTION__, what); + + std::lock_guard guard(_error_lock); + if (!_failed) _error = std::string(what); + return false; + } + + // One place records a failure of the writer's own, so a render that stops has a reason to report rather than + // just an absent file. The first is the cause of the rest, and every call after it answers false. + bool fail(const std::string_view what, const int code = 0) + { + auto text = code < 0 ? std::format("{}: {}", what, ffmpeg_error(code)) : std::string(what); + core::log(__FUNCTION__, text); + + { + std::lock_guard guard(_error_lock); + + if (!_failed) + { + _error = std::move(text); + _failed = true; + } + } + + // A caller held for a picture is let go to find it has none. + if (_pool) + { + { + std::lock_guard guard(_pool->lock); + } + + _pool->returned.notify_all(); + } + + return false; + } + + // Everything FFmpeg holds, the file closed first when the muxer's header was written and its trailer was not. The + // worker is gone by now, so nothing is using any of it. + void release() + { + _last.reset(); + _pool.reset(); + _fifo.reset(); + _audio_frame.reset(); + _resampler.reset(); + _scaler.reset(); + _video_packet.reset(); + _audio_packet.reset(); + _video.reset(); + _audio.reset(); + _video_stream = nullptr; + _audio_stream = nullptr; + _format.reset(); + } + + platform::movie_writer_request _request; + std::unique_ptr _format; + std::unique_ptr _video; + std::unique_ptr _audio; + std::unique_ptr _audio_frame; + std::unique_ptr _video_packet; + std::unique_ptr _audio_packet; + std::unique_ptr _scaler; + std::unique_ptr _resampler; + std::unique_ptr _fifo; + // Owned by the format context, which is why they are never freed here. + AVStream* _video_stream = nullptr; + AVStream* _audio_stream = nullptr; + // Planar floats a chunk of sound is converted into before the queue takes it. + std::vector> _planes; + // The pictures to convert into, and the last of them made, which a hole in the times shows again. + std::shared_ptr _pool; + std::shared_ptr _last; + // What a failure or a refusal said last; the lock is because the worker is where a failure may be found. + mutable std::mutex _error_lock; + std::string _error; + // Taken to write to the file, which the worker's pictures and the caller's sound are both written into. + std::mutex _file_lock; + std::atomic_bool _failed = false; + std::atomic_bool _quitting = false; + // The slot the next frame is due at, and so what a hole is filled up to; unset until the first frame. + int64_t _next_slot = -1; + int64_t _frames = 0; + // What a frame costs: converting it, waiting for the encoder to take it, and encoding it - the last on the + // worker - which is where a render's time goes. + double _convert_seconds = 0.0; + double _wait_seconds = 0.0; + double _encode_seconds = 0.0; + // The sample the next sound is due at, and the first sample of the next frame of sound the encoder is given. + int64_t _audio_next = -1; + int64_t _audio_pts = 0; + bool _created_file = false; + bool _writing = false; + // Last, so it is stopped before anything it uses is let go. + platform::serial_executor_ptr _worker; + }; +} + +int av_default_movie_bitrate(const sizei extent, const int frame_rate) +{ + const auto bits = static_cast(extent.cx) * extent.cy * std::max(1, frame_rate) * default_bits_per_pixel; + return static_cast(std::clamp(bits, min_bitrate, max_bitrate)); +} + +bool av_can_write_movies() +{ + // Asked of the encoders FFmpeg was configured with, not assumed: a build without libaom has no AV1 encoder, and + // the answer belongs to the build, not the platform. + static const auto answer = [function = __FUNCTION__] + { + const auto has_video = avcodec_find_encoder_by_name(video_encoder_name) != nullptr; + const auto has_audio = avcodec_find_encoder_by_name(audio_encoder_name) != nullptr; + + AVFormatContext* format = nullptr; + const auto has_container = avformat_alloc_output_context2(&format, nullptr, container_name, nullptr) >= 0 && + format != nullptr; + if (format) avformat_free_context(format); + + if (!has_video || !has_audio || !has_container) + { + core::log(function, std::format("required movie encoders unavailable (AV1: {}, AAC: {}, MP4: {})", + has_video, has_audio, has_container)); + } + + return has_video && has_audio && has_container; + }(); + + return answer; +} + +platform::movie_writer_ptr av_create_movie_writer(const platform::movie_writer_request& request) +{ + auto writer = std::make_shared(request); + + if (!writer->open()) + { + core::log(__FUNCTION__, std::format("cannot write {}: {}", request.path.name().sv(), writer->last_error())); + writer->abandon(); + return {}; + } + + return writer; +} diff --git a/src/av_movie_writer.h b/src/av_movie_writer.h new file mode 100644 index 00000000..ff3acba6 --- /dev/null +++ b/src/av_movie_writer.h @@ -0,0 +1,32 @@ +// This file is part of the Diffractor photo and video organizer +// Copyright 2026 Zac Walker +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Purpose: How Diffractor writes a movie. df::create_movie_writer is the seam every caller uses: on Windows it is +// the system's, Media Foundation's H.264 and AAC through libdesktop, and on Linux, where the system has no encoder to +// ask, it is FFmpeg's own writer - AV1 by libaom and AAC by FFmpeg's encoder, in an MP4 - which av_movie_writer.cpp +// implements for libdesktop's movie_writer contract. docs/movie.md owns what a render and a recording write. + +#pragma once + +namespace df +{ + // Whether this system can write a movie. Asked of the running system rather than fixed at build time, and the + // answer cached, as libdesktop's is: the first call belongs on a worker. + bool can_write_movies(); + + // A writer for the movie the request describes, or null where none can be made; why is in the log. + platform::movie_writer_ptr create_movie_writer(const platform::movie_writer_request& request); +} + +// FFmpeg's writer, whose encoders are those of the FFmpeg the build configured: the Linux configuration has +// libaom's AV1 and AAC, and the Windows one none, so there it is never offered. +bool av_can_write_movies(); +platform::movie_writer_ptr av_create_movie_writer(const platform::movie_writer_request& request); + +// The video bitrate a request that gives none is written at: the bits a pixel a frame Movie mixer derives its own +// from, so a file is about the size the Windows writer makes of the same movie. +int av_default_movie_bitrate(sizei extent, int frame_rate); diff --git a/src/av_sid.cpp b/src/av_sid.cpp index fd8e3dd6..121e8b1e 100644 --- a/src/av_sid.cpp +++ b/src/av_sid.cpp @@ -18,7 +18,7 @@ #include -#include "machine.h" +#include "lib64/machine.h" namespace { @@ -95,7 +95,7 @@ namespace gate = gated; } - cycles += pal_cycles_per_frame; + cycles += lib64::pal_cycles_per_frame; for (;;) { @@ -166,18 +166,19 @@ namespace sid_tune_length scan_sid_tune_length(const core::cspan file, const int song, const double max_seconds, const std::function& abandoned) { - sid_tune_info info; - if (!machine::parse_sid(file.data, file.size, info)) return {}; + const std::span tune(file.data, file.size); + const auto info = lib64::read_sid_tune(tune); + if (!info) return {}; - auto m = std::make_unique(); - if (!m->load_sid(file.data, file.size, song)) return {}; + auto m = std::make_unique(); + if (!m->load_sid(tune, song)) return {}; // Without its sound the chip only takes the registers the play routine writes, which is all the scan reads, // and the machine runs many times faster. m->set_audio_enabled(false); - const auto clock_hz = info.ntsc ? sid_clock_ntsc : sid_clock_pal; - const auto frame_seconds = static_cast(pal_cycles_per_frame) / clock_hz; + const auto clock_hz = info->ntsc ? lib64::ntsc_clock_hz : lib64::pal_clock_hz; + const auto frame_seconds = static_cast(lib64::pal_cycles_per_frame) / clock_hz; const auto max_frames = static_cast(std::max(0.0, max_seconds) / frame_seconds); // Each frame's voices, and whether anything could be heard. @@ -253,13 +254,12 @@ sid_tune_length scan_sid_tune_length(const core::cspan file, const int song, con }; std::array envelopes; - sid_snapshot before; - m->capture_sid(before); + auto before = m->capture_sid(); // lib64 runs at least the cycles asked for from wherever its last run stopped, so frames asked for one at a // time drift against the raster that calls the play routine, and the frame a play lands in slips once every // minute or two, differently on each pass. Each frame runs to its own boundary instead. - auto boundary = m->_state->clock_ticks; + auto boundary = m->cycles(); auto last_sound = -1; // The last frame anything a voice plays changed, or samples were played through the volume register, which // leaves the voices as they were. @@ -269,10 +269,9 @@ sid_tune_length scan_sid_tune_length(const core::cspan file, const int song, con { if (abandoned && (n & 255) == 0 && abandoned()) return {}; - boundary += pal_cycles_per_frame; - m->exec(static_cast(boundary - m->_state->clock_ticks)); - sid_snapshot s; - m->capture_sid(s); + boundary += lib64::pal_cycles_per_frame; + m->exec(static_cast(boundary - m->cycles())); + const auto s = m->capture_sid(); // Sound is a voice whose envelope has not died away, with a waveform and the volume up, or samples played // through the volume register, which a tune that plays them writes many times a frame. @@ -497,11 +496,12 @@ bool sid_tune_render::load() const auto bytes = platform::blob_head_from_file(_path, max_sid_file_bytes); if (bytes.empty() || bytes.size() >= max_sid_file_bytes) return false; - sid_tune_info info; - if (!machine::parse_sid(bytes.data(), bytes.size(), info)) return false; + const std::span tune(bytes.data(), bytes.size()); + const auto info = lib64::read_sid_tune(tune); + if (!info) return false; - auto m = std::make_unique(); - if (!m->load_sid(bytes.data(), bytes.size(), _requested_song)) return false; + auto m = std::make_unique(); + if (!m->load_sid(tune, _requested_song)) return false; const auto texts = read_sid_header_texts(bytes); @@ -509,11 +509,11 @@ bool sid_tune_render::load() details.title = texts.title; details.author = texts.author; details.released = texts.released; - details.songs = info.songs; + details.songs = info->songs; details.song = m->sid_song(); - details.chip_8580 = info.chip_8580; - details.ntsc = info.ntsc; - details.clock_hz = info.ntsc ? sid_clock_ntsc : sid_clock_pal; + details.chip_8580 = info->chip_8580; + details.ntsc = info->ntsc; + details.clock_hz = info->ntsc ? lib64::ntsc_clock_hz : lib64::pal_clock_hz; auto description = std::make_shared(files::scan_sid(bytes).to_info()); @@ -531,8 +531,7 @@ bool sid_tune_render::load() _frame_starts.reserve(frames); } - sid_snapshot initial; - m->capture_sid(initial); + const auto initial = m->capture_sid(); std::copy_n(std::begin(initial.writes), sid_register_count, _last_writes.begin()); _machine = std::move(m); @@ -551,13 +550,12 @@ void sid_tune_render::render_frame() const auto silent = _silent_mask.load(); for (int v = 0; v < 3; ++v) _machine->set_sid_voice_muted(v, (silent & (1 << v)) != 0); - _machine->exec(pal_cycles_per_frame); + _machine->exec(lib64::pal_cycles_per_frame); int16_t samples[max_frame_samples]; - const auto n = std::max(0, _machine->generate_audio(samples, max_frame_samples)); + const auto n = _machine->generate_audio(samples); - sid_snapshot snap; - _machine->capture_sid(snap); + const auto snap = _machine->capture_sid(); sid_frame_state frame; for (int r = 0; r < sid_register_count; ++r) diff --git a/src/av_sid.h b/src/av_sid.h index 149642e2..bad32436 100644 --- a/src/av_sid.h +++ b/src/av_sid.h @@ -17,6 +17,11 @@ class av_media_info; +namespace lib64 +{ + class machine; +} + // Seconds of a tune the player presents until the scan below says how long it lasts, and of one the scan // cannot tell: the file does not say, and a tune can play for ever. A tune that repeats ends in a fade. constexpr double sid_tune_seconds = 180.0; @@ -170,7 +175,7 @@ class sid_tune_render final : public pcm_audio_render // The emulator and what only the rendering thread touches. Held for the whole of a read. mutable core::mutex _render_mutex; - _Guarded_by_(_render_mutex) std::unique_ptr _machine; + _Guarded_by_(_render_mutex) std::unique_ptr _machine; _Guarded_by_(_render_mutex) std::array _last_writes = {}; _Guarded_by_(_render_mutex) bool _loaded = false; _Guarded_by_(_render_mutex) bool _load_ok = false; diff --git a/src/av_sound.h b/src/av_sound.h index 6eaada7d..992420a8 100644 --- a/src/av_sound.h +++ b/src/av_sound.h @@ -47,8 +47,8 @@ class audio_buffer final : core::no_copy uint32_t end_pos = 0; double time = 0.0; - const uint32_t data_alignment = 16u; - const uint32_t data_padding = 64u; + static constexpr uint32_t data_alignment = 16u; + static constexpr uint32_t data_padding = 64u; audio_info_t format; diff --git a/src/crypto_md5.cpp b/src/crypto_md5.cpp index fd068df2..784ada0a 100644 --- a/src/crypto_md5.cpp +++ b/src/crypto_md5.cpp @@ -211,7 +211,7 @@ static void II(uint32_t& a, const uint32_t b, const uint32_t c, const uint32_t d void md5::Transform(const uint8_t* block) { uint32_t a = state[0], b = state[1], c = state[2], d = state[3], x[16]; - Decode(x, {block, 64}); + Decode(x, block, 64); core::assert_true(!_finalized); // not just a user error, since the method is private /* Round 1 */ @@ -312,13 +312,13 @@ void md5::Encode(uint8_t* output, const uint32_t* input, const size_t len) // Decodes input (uint8_t) into output (uint32_t). Assumes len is // a multiple of 4. -void md5::Decode(uint32_t* output, const core::cspan input) +void md5::Decode(uint32_t* output, const uint8_t* input, const size_t len) { uint32_t i, j; - for (i = 0, j = 0; j < input.size; i++, j += 4) + for (i = 0, j = 0; j < len; i++, j += 4) { - output[i] = static_cast(input.data[j]) | static_cast(input.data[j + 1]) << 8 | - static_cast(input.data[j + 2]) << 16 | static_cast(input.data[j + 3]) << 24; + output[i] = static_cast(input[j]) | static_cast(input[j + 1]) << 8 | + static_cast(input[j + 2]) << 16 | static_cast(input[j + 3]) << 24; } } diff --git a/src/crypto_md5.h b/src/crypto_md5.h index 0f858f31..89230558 100644 --- a/src/crypto_md5.h +++ b/src/crypto_md5.h @@ -41,5 +41,5 @@ class md5 final : core::no_copy // that length is implied to be 64. static void Encode(uint8_t* dest, const uint32_t* src, size_t length); - static void Decode(uint32_t* dest, core::cspan src); + static void Decode(uint32_t* dest, const uint8_t* src, size_t length); }; diff --git a/src/files.cpp b/src/files.cpp index f29c995e..5f067e3d 100644 --- a/src/files.cpp +++ b/src/files.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -30,7 +30,8 @@ #include "libfiles/scan.h" #include "libfiles/write.h" -#include "machine.h" +#include "lib64/listing.h" +#include "lib64/sid.h" #define LIBARCHIVE_STATIC #include @@ -330,18 +331,18 @@ static void build_file_types() {file_group::video, "isma", {}, {}}, {file_group::video, "ismv", {}, {}}, {file_group::audio, "it", {}, {}}, - {file_group::video, "ivf", "Indeo Video Technology", {}}, + {file_group::video, "ivf", "On2 IVF video", {}}, {file_group::video, "ivr", {}, {}}, {file_group::audio, "j2b", {}, {}}, {file_group::photo, "j2c", {}, {}}, {file_group::photo, "j2k", {}, {}}, {file_group::photo, "jif", {}, {}}, {file_group::video, "jls", {}, {}}, - {file_group::photo, "jp2", "JPEG2000", {}}, + {file_group::photo, "jp2", "JPEG 2000", {}}, still_file_type(libfiles::image_format::jpeg), // Its metadata goes to a sidecar: nothing Diffractor uses writes a JPEG 2000 packet, and its own // scan would not read one back. - {file_group::photo, "jpx", "Jpeg 2000", file_traits::edit}, + {file_group::photo, "jpx", "JPEG 2000", file_traits::edit}, still_file_type(libfiles::image_format::jxl), {file_group::video, "jss", {}, {}}, {file_group::photo, "koa", {}, {}}, @@ -368,7 +369,7 @@ static void build_file_types() {file_group::video, "mjpeg", {}, {}}, {file_group::video, "mjpg", {}, {}}, {file_group::video, "mk3d", {}, {}}, - {file_group::audio, "mka", {}, {}}, + {file_group::audio, "mka", "Matroska audio", {}}, {file_group::video, "mks", {}, {}}, {file_group::video, "mkv", "Matroska video", {}}, {file_group::video, "mlp", {}, {}}, @@ -381,7 +382,8 @@ static void build_file_types() {file_group::photo, "mos", "Leaf raw", file_traits::raw | file_traits::edit}, {file_group::audio, "mp3", "MPEG Layer 3", file_traits::embedded_xmp | file_traits::edit | file_traits::thumbnail | file_traits::in_place_metadata}, - {file_group::video, "mov", {}, file_traits::embedded_xmp | file_traits::edit | file_traits::in_place_metadata}, + {file_group::video, "mov", "QuickTime movie", + file_traits::embedded_xmp | file_traits::edit | file_traits::in_place_metadata}, {file_group::video, "mp4,mp4a,mp4v,m4v,m4b,f4v,3g2,3gp2,3gp,3gpp,crm", "MPEG-4", file_traits::embedded_xmp | file_traits::edit | file_traits::in_place_metadata}, {file_group::video, "crm", "Canon Cinema RAW Light", @@ -415,9 +417,9 @@ static void build_file_types() {file_group::video, "nut", {}, {}}, {file_group::video, "obu", "AV1 video stream", {}}, {file_group::audio, "oga", "Ogg audio", {}}, - {file_group::audio, "ogg", "container, multimedia", {}}, + {file_group::audio, "ogg", "Ogg audio", {}}, {file_group::video, "ogm", {}, {}}, - {file_group::video, "ogv", {}, {}}, + {file_group::video, "ogv", "Ogg video", {}}, {file_group::video, "ogx", {}, {}}, {file_group::audio, "okt", {}, {}}, {file_group::video, "oma", {}, {}}, @@ -445,7 +447,7 @@ static void build_file_types() {file_group::photo, "ppm", "Portable Pixmap", {}}, still_file_type(libfiles::image_format::psd), {file_group::audio, "psm", {}, {}}, - {file_group::video, "psp", "Paint Shop Pro image", {}}, + {file_group::video, "psp", "Sony PSP video", {}}, {file_group::audio, "pt36", {}, {}}, {file_group::audio, "ptm", {}, {}}, {file_group::video, "pvf", {}, {}}, @@ -459,7 +461,7 @@ static void build_file_types() {file_group::video, "rcv", {}, {}}, {file_group::video, "rmd,r3d", "RED", {}}, {file_group::video, "rgb", "Silicon Graphics Image", {}}, - {file_group::video, "rm", "RealAudio (RA, RM)", {}}, + {file_group::video, "rm", "RealMedia", {}}, {file_group::video, "roq", "Quake 3 video", {}}, {file_group::video, "rsd", {}, {}}, {file_group::video, "rso", {}, {}}, @@ -552,29 +554,29 @@ static void build_file_types() {file_group::video, "yuv", "Raw YUV video format", {}}, {file_group::video, "yuv10", {}, {}}, - {file_group::archive, "zip", {}, {file_traits::archive}}, - {file_group::archive, "rar", {}, {file_traits::archive}}, - {file_group::archive, "7z", {}, {file_traits::archive}}, - {file_group::archive, "gz", {}, {file_traits::archive}}, - {file_group::archive, "tgz", {}, {file_traits::archive}}, - {file_group::archive, "cpio", {}, {file_traits::archive}}, - {file_group::archive, "iso", {}, {file_traits::archive}}, - {file_group::archive, "cab", {}, {file_traits::archive}}, - {file_group::archive, "pax", {}, {file_traits::archive}}, - {file_group::archive, "lzip", {}, {file_traits::archive}}, + {file_group::archive, "zip", "ZIP archive", {file_traits::archive}}, + {file_group::archive, "rar", "RAR archive", {file_traits::archive}}, + {file_group::archive, "7z", "7-Zip archive", {file_traits::archive}}, + {file_group::archive, "gz", "gzip-compressed tar archive", {file_traits::archive}}, + {file_group::archive, "tgz", "gzip-compressed tar archive", {file_traits::archive}}, + {file_group::archive, "cpio", "cpio archive", {file_traits::archive}}, + {file_group::archive, "iso", "ISO 9660 disc image", {file_traits::archive}}, + {file_group::archive, "cab", "Microsoft Cabinet", {file_traits::archive}}, + {file_group::archive, "pax", "POSIX pax archive", {file_traits::archive}}, + {file_group::archive, "lzip", "lzip-compressed tar archive", {file_traits::archive}}, {file_group::archive, "lza", {}, {file_traits::archive}}, - {file_group::archive, "bzip2,bz2", {}, {file_traits::archive}}, - {file_group::archive, "tar", {}, {file_traits::archive}}, - {file_group::archive, "lha", {}, {file_traits::archive}}, - {file_group::archive, "a,ar", {}, {file_traits::archive}}, - - {file_group::commodore, "d64", {}, {file_traits::disk_image | file_traits::commodore}}, - {file_group::commodore, "d71", {}, {file_traits::disk_image | file_traits::commodore}}, - {file_group::commodore, "d81", {}, {file_traits::disk_image | file_traits::commodore}}, - {file_group::commodore, "t64", {}, {file_traits::commodore}}, - {file_group::commodore, "crt", {}, {file_traits::commodore}}, - {file_group::commodore, "prg", {}, {file_traits::commodore}}, - {file_group::commodore, "p00", {}, {file_traits::commodore}}, + {file_group::archive, "bzip2,bz2", "bzip2-compressed tar archive", {file_traits::archive}}, + {file_group::archive, "tar", "Tape archive (tar)", {file_traits::archive}}, + {file_group::archive, "lha", "LHA archive", {file_traits::archive}}, + {file_group::archive, "a,ar", "Unix ar archive", {file_traits::archive}}, + + {file_group::commodore, "d64", "Commodore 1541 disk", {file_traits::disk_image | file_traits::commodore}}, + {file_group::commodore, "d71", "Commodore 1571 disk", {file_traits::disk_image | file_traits::commodore}}, + {file_group::commodore, "d81", "Commodore 1581 disk", {file_traits::disk_image | file_traits::commodore}}, + {file_group::commodore, "t64", "Commodore 64 tape archive", {file_traits::commodore}}, + {file_group::commodore, "crt", "Commodore 64 cartridge", {file_traits::commodore}}, + {file_group::commodore, "prg", "Commodore 64 program", {file_traits::commodore}}, + {file_group::commodore, "p00", "Commodore 64 program saved by PC64", {file_traits::commodore}}, }; int next_id = 0; @@ -1061,9 +1063,10 @@ namespace throw std::invalid_argument("Invalid clipboard image"); } - auto encoded = libfiles::encode_png(*view, 1, {}); - for (const auto& note : encoded.notes) core::log_once("libpng", note); - return std::move(encoded.data); + auto encoded = libfiles::encode_png(*view, {}); + if (!encoded) throw std::runtime_error(std::string(encoded.message())); + for (const auto& note : encoded->notes) core::log_once("libpng", note); + return std::move(encoded->data); } }; } @@ -2458,6 +2461,7 @@ file_scan_result files::scan_file(const platform::file_ptr& f, const core::file_ // A still's bytes went to scan_still_bytes, which checksums them; a small file of any other kind // is checksummed here. + // NOLINTNEXTLINE(bugprone-use-after-move): data is moved only for a still, which this skips if (!is_bitmap && !data.empty()) { result.crc32c = crc32c(data.data(), data.size()); @@ -2913,8 +2917,14 @@ static core::blob repack_as_jxl(const core::cspan jpeg, const core::file_path pa metadata_xmp::update(path_stage, path_src, edits, src_xmp_name, path_stage.extension(".xmp"), in_sidecar, path_dst); const auto staged = platform::blob_from_file(path_stage); auto repacked = libfiles::transcode_jpeg_to_jxl({staged.data(), staged.size()}); - for (const auto& note : repacked.notes) core::log(__FUNCTION__, note); - return core::blob(std::move(repacked.data)); + if (!repacked) + { + core::log(__FUNCTION__, repacked.message()); + return {}; + } + + for (const auto& note : repacked->notes) core::log(__FUNCTION__, note); + return core::blob(std::move(repacked->data)); } // A HEIF's gain map restated as its photo stands. libheif turns each item by its own rotation and mirror, and Apple's @@ -2977,13 +2987,11 @@ static std::optional gain_map_for(const core::const_surface_pt return {}; } - const libfiles::image_view signal_view{signal->pixels(), signal->stride(), signal->width(), signal->height(), - core::has_alpha(signal->format()) ? libfiles::pixel_format::rgba16 - : libfiles::pixel_format::rgbx16}; - const libfiles::image_view base_view{rendition->pixels(), rendition->stride(), rendition->width(), - rendition->height(), - core::has_alpha(rendition->format()) ? libfiles::pixel_format::bgra8 - : libfiles::pixel_format::bgrx8}; + const auto signal_view = libfiles_view(*signal, core::has_alpha(signal->format()) ? libfiles::pixel_format::rgba16 + : libfiles::pixel_format::rgbx16); + const auto base_view = libfiles_view(*rendition, core::has_alpha(rendition->format()) + ? libfiles::pixel_format::bgra8 + : libfiles::pixel_format::bgrx8); const auto made = libfiles::make_gain_map(signal_view, hdr, base_view, 2); if (made.pixels.empty()) return {}; @@ -4689,6 +4697,7 @@ namespace { .format = libfiles::image_format::webp, .extensions = "webp", + .description = "WebP image", .traits = xmp_edit, .encoded = core::image_format::WEBP, .scan = scan_photo_libfiles, @@ -5835,10 +5844,10 @@ namespace for (const auto& note : encoder.notes()) core::log("jpeg_encoder", note); } - [[noreturn]] void fail(const std::string_view where, const libfiles::encode_error& e) + [[noreturn]] void fail(const std::string_view where, const std::string_view why) { - core::log(where, e.what()); - throw app_exception(e.what()); + core::log(where, why); + throw app_exception(std::string(why)); } } @@ -5848,28 +5857,26 @@ core::blob turn_jpeg_losslessly(const libfiles::jpeg_transformer& transformer, l { if (over_budget) *over_budget = false; - try - { - // simple_transform counts from none at 0, where the EXIF orientation libfiles takes counts from 1. - const auto orientation = static_cast(static_cast(transform) + 1); - const auto budget = static_cast(std::max(render::max_decode_bytes, 0)); - auto turned = transformer.turn(src, encoder, orientation, budget); + // simple_transform counts from none at 0, where the EXIF orientation libfiles takes counts from 1. + const auto orientation = static_cast(static_cast(transform) + 1); + const auto budget = static_cast(std::max(render::max_decode_bytes, 0)); + auto turned = transformer.turn(src, encoder, orientation, budget); - if (turned.over_budget) - { - core::log(__FUNCTION__, - std::format("rotate of {} x {} needs {}, over the {} budget", turned.width, turned.height, - platform::format_size(core::file_size(turned.workspace_bytes)), - platform::format_size(core::file_size(render::max_decode_bytes)))); - if (over_budget) *over_budget = true; - } + // libjpeg failed part way through a stream it could read, which is an error; a stream cut short is a turn + // that cannot be lossless, and leaves the caller to encode it again. + if (turned.resource_limit) throw std::bad_alloc(); + if (turned.invalid && !turned.truncated) fail(__FUNCTION__, turned.error); - return core::blob(std::move(turned.data)); - } - catch (const libfiles::encode_error& e) + if (turned.over_budget) { - fail(__FUNCTION__, e); + core::log(__FUNCTION__, + std::format("rotate of {} x {} needs {}, over the {} budget", turned.width, turned.height, + platform::format_size(core::file_size(turned.workspace_bytes)), + platform::format_size(core::file_size(render::max_decode_bytes)))); + if (over_budget) *over_budget = true; } + + return core::blob(std::move(turned.data)); } // The edits that move a photo's pixels, at its gain map's scale. @@ -5932,12 +5939,11 @@ std::vector files::encode_gain_map(const core::const_surface_ptr& map, libfiles::jpeg_options options; options.quality = 95; - options.grayscale = grey; options.source = tables; + // Its four bytes a pixel, blue, green and red; or, grey, its green alone, which the encoder writes as one channel. + auto view = libfiles_view(*edited, libfiles::pixel_format::bgrx8); std::vector grey_rows; - const auto* pixels = edited->pixels(); - auto stride = edited->stride(); if (grey) { @@ -5949,13 +5955,15 @@ std::vector files::encode_gain_map(const core::const_surface_ptr& map, for (size_t x = 0; x < width; ++x) grey_rows[y * width + x] = line[x * 4 + 1]; } - pixels = grey_rows.data(); - stride = width; + view.pixels = grey_rows.data(); + view.stride = static_cast(width); + view.format = libfiles::pixel_format::gray8; } - auto encoded = _jpeg_encoder.encode(extent.cx, extent.cy, pixels, stride, 1, {}, options); + auto encoded = _jpeg_encoder.encode(view, {}, options); + if (!encoded) throw std::runtime_error(std::string(encoded.message())); log_notes(_jpeg_encoder); - return encoded; + return std::move(encoded->data); } std::vector files::edit_gain_map(const std::span gain_map, const image_edits& edits, @@ -6049,8 +6057,7 @@ core::surface_ptr sdr_rendition(const core::const_surface_ptr& signal, const lib auto out = std::make_shared(); if (!out->alloc(signal->dimensions(), format, signal->orientation())) return {}; - const libfiles::image_view view{signal->pixels(), signal->stride(), signal->width(), signal->height(), - alpha ? libfiles::pixel_format::rgba16 : libfiles::pixel_format::rgbx16}; + const auto view = libfiles_view(*signal, alpha ? libfiles::pixel_format::rgba16 : libfiles::pixel_format::rgbx16); const auto to = wide ? (alpha ? libfiles::pixel_format::rgba16 : libfiles::pixel_format::rgbx16) : (alpha ? libfiles::pixel_format::bgra8 : libfiles::pixel_format::bgrx8); if (!libfiles::map_hdr_to_sdr(view, hdr, to, {out->pixels(), out->stride()})) return {}; @@ -6070,7 +6077,13 @@ std::optional libfiles_view(const core::surface& s) default: return {}; } - return libfiles::image_view{s.pixels(), s.stride(), s.width(), s.height(), format}; + return libfiles_view(s, format); +} + +libfiles::image_view libfiles_view(const core::surface& s, const libfiles::pixel_format format) +{ + const auto v = s.view(); + return {v.pixels, v.stride, v.width, v.height, format}; } core::const_surface_ptr profile_rendition(const core::const_surface_ptr& pixels, const std::span profile, @@ -6148,7 +6161,6 @@ core::image_ptr save_jpeg(const core::const_surface_ptr& surface, const libfiles const auto surface_in = narrowed(surface); if (!is_valid(surface_in)) return {}; - const auto dimensions_in = surface_in->dimensions(); const auto orientation_in = surface_in->orientation(); libfiles::jpeg_options options; @@ -6158,21 +6170,16 @@ core::image_ptr save_jpeg(const core::const_surface_ptr& surface, const libfiles std::optional own; auto& e = encoder ? *encoder : own.emplace(); - try - { - auto data = e.encode(dimensions_in.cx, dimensions_in.cy, surface_in->pixels(), surface_in->stride(), - static_cast(orientation_in), metadata, options); - log_notes(e); + // Four bytes a pixel, the fourth not written, as JPEG has no alpha. + auto view = libfiles_view(*surface_in, libfiles::pixel_format::bgrx8); + view.orientation = static_cast(orientation_in); + auto encoded = e.encode(view, metadata, options); + log_notes(e); + if (!encoded) fail(__FUNCTION__, encoded.message()); - return std::make_shared(core::blob(std::move(data)), - sizei{static_cast(e.width()), static_cast(e.height())}, - core::image_format::JPEG, orientation_in); - } - catch (const libfiles::encode_error& ex) - { - log_notes(e); - fail(__FUNCTION__, ex); - } + return std::make_shared(core::blob(std::move(encoded->data)), + sizei{static_cast(e.width()), static_cast(e.height())}, + core::image_format::JPEG, orientation_in); } /////////////////////////////////////////////////////////////////////////////////////////////////// @@ -6185,38 +6192,35 @@ core::image_ptr save_png(const core::const_surface_ptr& surface_in, const libfil const auto dims = surface_in->dimensions(); - libfiles::image_view view; - view.pixels = surface_in->pixels(); - view.stride = surface_in->stride(); - view.width = static_cast(dims.cx); - view.height = static_cast(dims.cy); // Sixteen bits a channel stay sixteen. Anything but RGB is written with its fourth channel as alpha. + auto format = libfiles::pixel_format::bgra8; switch (surface_in->format()) { - case core::texture_format::RGB: view.format = libfiles::pixel_format::bgrx8; break; - case core::texture_format::RGBX16: view.format = libfiles::pixel_format::rgbx16; break; - case core::texture_format::RGBA16: view.format = libfiles::pixel_format::rgba16; break; - default: view.format = libfiles::pixel_format::bgra8; break; + case core::texture_format::RGB: format = libfiles::pixel_format::bgrx8; break; + case core::texture_format::RGBX16: format = libfiles::pixel_format::rgbx16; break; + case core::texture_format::RGBA16: format = libfiles::pixel_format::rgba16; break; + default: break; } + auto view = libfiles_view(*surface_in, format); + view.orientation = static_cast(surface_in->orientation()); + libfiles::embedded_metadata embedded(metadata); embedded.hdr = hdr; - try - { - auto encoded = libfiles::encode_png(view, static_cast(surface_in->orientation()), embedded); - - // libpng's warnings go to the quiet debug log rather than the console and the test output. - for (const auto& note : encoded.notes) core::log_once("libpng", note); + auto encoded = libfiles::encode_png(view, embedded); - return std::make_shared(core::blob(std::move(encoded.data)), dims, core::image_format::PNG, - surface_in->orientation()); - } - catch (const libfiles::encode_error& e) + if (!encoded) { - core::log_once(__FUNCTION__, e.what()); - throw app_exception(e.what()); + core::log_once(__FUNCTION__, encoded.message()); + throw app_exception(std::string(encoded.message())); } + + // libpng's warnings go to the quiet debug log rather than the console and the test output. + for (const auto& note : encoded->notes) core::log_once("libpng", note); + + return std::make_shared(core::blob(std::move(encoded->data)), dims, core::image_format::PNG, + surface_in->orientation()); } namespace @@ -6394,18 +6398,16 @@ core::image_ptr save_webp(const core::const_surface_ptr& surface, const libfiles const auto dimensions = surface_in->dimensions(); const auto cs = surface_in->color_space(); - libfiles::image_view view; - view.pixels = surface_in->pixels(); - view.stride = surface_in->stride(); - view.width = static_cast(dimensions.cx); - view.height = static_cast(dimensions.cy); + auto view = libfiles_view(*surface_in, libfiles::pixel_format::bgrx8); + view.orientation = static_cast(surface_in->orientation()); switch (surface_in->format()) { - case core::texture_format::RGB: view.format = libfiles::pixel_format::bgrx8; break; + case core::texture_format::RGB: break; case core::texture_format::ARGB: view.format = libfiles::pixel_format::bgra8; break; case core::texture_format::NV12: - // Only the matrix VP8 assumes: a rec709 or rec2020 frame would be encoded as if it were 601. + // Only the matrix VP8 assumes: a rec709 or rec2020 frame would be encoded as if it were 601. Its chroma + // follows its luma, at the luma's stride. if (cs != core::color_space::rec601_full && cs != core::color_space::rec601_limited) return {}; view.format = libfiles::pixel_format::nv12; view.limited_range = cs == core::color_space::rec601_limited; @@ -6419,11 +6421,16 @@ core::image_ptr save_webp(const core::const_surface_ptr& surface, const libfiles options.lossy_alpha = params.webp_lossy_alpha; options.fast = params.webp_fast; - auto encoded = libfiles::encode_webp(view, static_cast(surface_in->orientation()), metadata, options); - for (const auto& note : encoded.notes) core::log(__FUNCTION__, note); - if (encoded.data.empty()) return {}; + auto encoded = libfiles::encode_webp(view, metadata, options); + + if (!encoded) + { + core::log(__FUNCTION__, encoded.message()); + return {}; + } - return std::make_shared(core::blob(std::move(encoded.data)), dimensions, core::image_format::WEBP, + for (const auto& note : encoded->notes) core::log(__FUNCTION__, note); + return std::make_shared(core::blob(std::move(encoded->data)), dimensions, core::image_format::WEBP, surface_in->orientation()); } @@ -6477,8 +6484,8 @@ core::surface_ptr load_psd(read_stream& s, load_diagnostic* const diagnostic, co } /////////////////////////////////////////////////////////////////////////////////////////////////// -// Commodore 64 disk, tape, cartridge and program images: the listing libfiles makes of one, drawn by -// libfiles into a surface for the disk control's texture. And SID tunes, whose header lib64 reads. +// Commodore 64 disk, tape, cartridge and program images: the listing lib64 makes of one, drawn by lib64 +// into a surface for the disk control's texture. And SID tunes, whose header lib64 reads. namespace { @@ -6508,7 +6515,7 @@ namespace } } -core::const_surface_ptr files::c64_listing_surface(const libfiles::c64_listing& listing, const uint32_t fg, +core::const_surface_ptr files::c64_listing_surface(const lib64::media_listing& listing, const uint32_t fg, const uint32_t bg) { if (listing.rows.empty() || listing.columns == 0) return {}; @@ -6518,10 +6525,12 @@ core::const_surface_ptr files::c64_listing_surface(const libfiles::c64_listing& core::texture_format::RGB); if (!pixels) return {}; - // RGB textures upload as B8G8R8X8, the order libfiles draws in, given its colours as 0xRRGGBB. A - // listing is a whole number of eight-pixel cells wide, so its rows fill their stride, and no padding - // goes to the GPU unwritten. - libfiles::draw_c64_listing(listing, {pixels, surface->stride()}, core::bgr(fg), core::bgr(bg)); + // RGB textures upload as B8G8R8X8, which is how lib64's 0x00RRGGBB pixels lie in memory. A listing is a + // whole number of eight-pixel cells wide, so its rows fill their stride, and no padding goes to the GPU + // unwritten. + const auto stride = surface->stride() / sizeof(uint32_t); + const std::span rows(reinterpret_cast(pixels), stride * listing.height()); + if (!lib64::draw_listing(listing, rows, stride, core::bgr(fg), core::bgr(bg))) return {}; return surface; } @@ -6530,7 +6539,7 @@ file_scan_result files::scan_c64_media(const core::cspan data) file_scan_result result; if (data.empty()) return result; - const auto listing = libfiles::list_c64_media({data.data, data.size}); + const auto listing = lib64::list_media({data.data, data.size}).value(); if (listing.rows.empty() && listing.title.empty()) return result; // Each file by its name as the listing prints it, between its quotes. A cartridge, or a program file holding the @@ -6564,8 +6573,9 @@ file_scan_result files::scan_c64_media(const core::cspan data) file_scan_result files::scan_sid(const core::cspan data) { file_scan_result result; - sid_tune_info info; - if (data.empty() || !machine::parse_sid(data.data, data.size, info)) return result; + const auto tune = lib64::read_sid_tune({data.data, data.size}); + if (!tune) return result; + const auto& info = *tune; const auto texts = read_sid_header_texts(data); const auto& title = texts.title; diff --git a/src/files.h b/src/files.h index 92f737d9..ed6378a0 100644 --- a/src/files.h +++ b/src/files.h @@ -14,7 +14,7 @@ #include "model_location.h" #include "model_property.h" -#include "libfiles/commodore.h" +#include "lib64/listing.h" #include "libfiles/decode.h" #include "libfiles/encode.h" #include "libfiles/exif.h" @@ -769,6 +769,8 @@ core::const_surface_ptr profile_rendition(const core::const_surface_ptr& pixels, // A packed surface as libfiles reads one - RGB as bgrx8, ARGB as bgra8, RGBX16 and RGBA16 as themselves - and nothing // for a planar one. std::optional libfiles_view(const core::surface& s); +// A surface's pixels as libfiles reads them, as the format given, upright. +libfiles::image_view libfiles_view(const core::surface& s, libfiles::pixel_format format); // The gain map a JPEG holds after its primary, decoded, with how it applies; nothing when it holds none, or says // nothing a gain map applies by. Apple's is said in ISO 21496-1's terms, its headroom from the primary's maker note. std::optional load_jpeg_gain_map(std::span jpeg); @@ -1651,10 +1653,10 @@ class files final : core::no_copy static std::vector list_archive(core::file_path zip_file_path); - // A Commodore 64 image's listing, as libfiles lists it, drawn by libfiles into an RGB surface eight - // pixels a character, the glyphs in fg on bg; null when there is nothing to draw. The caller scales - // the texture to fit the space it has. - static core::const_surface_ptr c64_listing_surface(const libfiles::c64_listing& listing, uint32_t fg, uint32_t bg); + // A Commodore 64 image's listing, as lib64 lists it, drawn by lib64 into an RGB surface eight pixels a + // character, the glyphs in fg on bg; null when there is nothing to draw. The caller scales the texture to + // fit the space it has. + static core::const_surface_ptr c64_listing_surface(const lib64::media_listing& listing, uint32_t fg, uint32_t bg); // A Commodore 64 image's listing as its properties: the name it gives itself as its title, and the names of // the files it holds as its contents, so a search finds a game by a file on its disk. static file_scan_result scan_c64_media(core::cspan data); diff --git a/src/files_heif.cpp b/src/files_heif.cpp index b570255e..b638b4b2 100644 --- a/src/files_heif.cpp +++ b/src/files_heif.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -276,20 +276,9 @@ core::image_ptr save_avif(const core::const_surface_ptr& surface_in, const libfi const auto dimensions = surface_in->dimensions(); const auto turn = orientation.value_or(surface_in->orientation()); - libfiles::image_view view; - view.pixels = surface_in->pixels(); - view.stride = surface_in->stride(); - view.width = static_cast(dimensions.cx); - view.height = static_cast(dimensions.cy); - - switch (surface_in->format()) - { - case core::texture_format::RGB: view.format = libfiles::pixel_format::bgrx8; break; - case core::texture_format::ARGB: view.format = libfiles::pixel_format::bgra8; break; - case core::texture_format::RGBX16: view.format = libfiles::pixel_format::rgbx16; break; - case core::texture_format::RGBA16: view.format = libfiles::pixel_format::rgba16; break; - default: return {}; - } + auto view = libfiles_view(*surface_in); + if (!view) return {}; + view->orientation = static_cast(turn); libfiles::avif_options options; options.lossless = params.avif_lossless; @@ -298,19 +287,23 @@ core::image_ptr save_avif(const core::const_surface_ptr& surface_in, const libfi if (params.gain_map && is_valid(params.gain_map->pixels) && core::is_packed(params.gain_map->pixels->format())) { - const auto& map = *params.gain_map->pixels; - options.gain_map = libfiles::gain_map_image{{map.pixels(), map.stride(), map.width(), map.height(), - libfiles::pixel_format::bgrx8}, + options.gain_map = libfiles::gain_map_image{libfiles_view(*params.gain_map->pixels, + libfiles::pixel_format::bgrx8), params.gain_map->metadata}; } libfiles::embedded_metadata embedded(metadata); embedded.hdr = params.hdr; - auto encoded = libfiles::encode_avif(view, static_cast(turn), embedded, options); - for (const auto& note : encoded.notes) core::log(__FUNCTION__, note); - if (encoded.data.empty()) return {}; + auto encoded = libfiles::encode_avif(*view, embedded, options); + + if (!encoded) + { + core::log(__FUNCTION__, encoded.message()); + return {}; + } - return std::make_shared(core::blob(std::move(encoded.data)), dimensions, core::image_format::AVIF, + for (const auto& note : encoded->notes) core::log(__FUNCTION__, note); + return std::make_shared(core::blob(std::move(encoded->data)), dimensions, core::image_format::AVIF, turn); } diff --git a/src/files_jxl.cpp b/src/files_jxl.cpp index 3d77faff..ef8bbcbc 100644 --- a/src/files_jxl.cpp +++ b/src/files_jxl.cpp @@ -123,20 +123,9 @@ core::image_ptr save_jxl(const core::const_surface_ptr& surface_in, const libfil const auto dimensions = surface_in->dimensions(); const auto turn = orientation.value_or(surface_in->orientation()); - libfiles::image_view view; - view.pixels = surface_in->pixels(); - view.stride = surface_in->stride(); - view.width = static_cast(dimensions.cx); - view.height = static_cast(dimensions.cy); - - switch (surface_in->format()) - { - case core::texture_format::RGB: view.format = libfiles::pixel_format::bgrx8; break; - case core::texture_format::ARGB: view.format = libfiles::pixel_format::bgra8; break; - case core::texture_format::RGBX16: view.format = libfiles::pixel_format::rgbx16; break; - case core::texture_format::RGBA16: view.format = libfiles::pixel_format::rgba16; break; - default: return {}; - } + auto view = libfiles_view(*surface_in); + if (!view) return {}; + view->orientation = static_cast(turn); libfiles::jxl_options options; options.lossless = params.jxl_lossless; @@ -145,10 +134,15 @@ core::image_ptr save_jxl(const core::const_surface_ptr& surface_in, const libfil libfiles::embedded_metadata embedded(metadata); embedded.hdr = params.hdr; - auto encoded = libfiles::encode_jxl(view, static_cast(turn), embedded, options); - for (const auto& note : encoded.notes) core::log(__FUNCTION__, note); - if (encoded.data.empty()) return {}; + auto encoded = libfiles::encode_jxl(*view, embedded, options); + + if (!encoded) + { + core::log(__FUNCTION__, encoded.message()); + return {}; + } - return std::make_shared(core::blob(std::move(encoded.data)), dimensions, core::image_format::JXL, + for (const auto& note : encoded->notes) core::log(__FUNCTION__, note); + return std::make_shared(core::blob(std::move(encoded->data)), dimensions, core::image_format::JXL, turn); } diff --git a/src/media_edit.cpp b/src/media_edit.cpp index 15d3026a..4e483b8f 100644 --- a/src/media_edit.cpp +++ b/src/media_edit.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -330,9 +330,8 @@ core::const_surface_ptr apply_image_edits(const core::const_surface_ptr& source, const auto view = [](const core::surface& s) { - return libfiles::image_view{s.pixels(), s.stride(), s.width(), s.height(), - core::has_alpha(s.format()) ? libfiles::pixel_format::rgba16 - : libfiles::pixel_format::rgbx16}; + return libfiles_view(s, core::has_alpha(s.format()) ? libfiles::pixel_format::rgba16 + : libfiles::pixel_format::rgbx16); }; if (!libfiles::carry_sdr_edit(view(*surface_result), *hdr, view(*before), view(*after), diff --git a/src/metadata.cpp b/src/metadata.cpp index d9a8c08e..2e1e7c1b 100644 --- a/src/metadata.cpp +++ b/src/metadata.cpp @@ -456,6 +456,49 @@ static void record_xmp_error(const std::string_view context, const std::string_v core::log_once(context, message); } +namespace +{ + // A packet libfiles refuses where the XMP Toolkit throws - one it rejected whole as it parsed it, a path that + // names nothing it could hold, an edit it could not make - thrown, so that each read or write below stops there + // and reports it in libfiles' words, and nothing is written. libfiles keeps the first such failure in the + // packet's status. + class xmp_refused : public std::runtime_error + { + public: + using std::runtime_error::runtime_error; + }; + + // A write libfiles reports failed - the file changed after the update was planned, or a stream refused a read + // or a write - thrown, so that each caller reports it with the file it was writing. + class write_failure : public std::runtime_error + { + public: + using std::runtime_error::runtime_error; + }; + + void parse_packet(libfiles::xmp::meta& xmp, const std::string_view text) + { + if (!xmp.parse(text)) throw xmp_refused(std::string(xmp.status().message())); + } + + void require_whole(const libfiles::xmp::meta& xmp) + { + if (const auto status = xmp.status(); !status) throw xmp_refused(std::string(status.message())); + } + + std::string serialized(const libfiles::xmp::meta& xmp, const libfiles::xmp::serialize_options& options = {}) + { + auto text = xmp.serialize(options); + if (!text) throw xmp_refused(std::string(text.message())); + return std::move(*text); + } + + void require_written(const libfiles::result& written) + { + if (!written) throw write_failure(std::string(written.message())); + } +} + // ---- Face regions: docs/faces.md#10-saving-names-to-files -------------------------------------------------------------- namespace face_xmp @@ -586,7 +629,7 @@ static void apply_face_names(libfiles::xmp::meta& meta, const face_name_edits& e r.face = type && core::icmp(core::trim(*type), "Face") == 0; r.name = held(meta, regions, item + "Name"); - const auto at = item + "Area/" + st; + const auto at = std::format("{}Area/{}", item, st); const auto x = real_at(meta, regions, at + "x"); const auto y = real_at(meta, regions, at + "y"); const auto w = real_at(meta, regions, at + "w"); @@ -615,6 +658,9 @@ static void apply_face_names(libfiles::xmp::meta& meta, const face_name_edits& e list_items.push_back(std::move(r)); } + // A region the packet holds in a form its paths cannot name stops the edit, before anything is decided by it. + require_whole(meta); + const auto space = faces::space_of_regions(applied_to, edits.stored, edits.orientation); const auto has_areas = std::ranges::any_of(list_items, [](const region& r) { return r.area || r.foreign_unit; }); // Only an edit that places a face reads the areas: a rename, or a name taken out of the whole file, does not. @@ -891,12 +937,13 @@ static void apply_face_names(libfiles::xmp::meta& meta, const face_name_edits& e for (const auto& r : added) { const auto item = std::format("{}[{}]", list, meta.count_array_items(regions, list) + 1); + const auto fields = std::format("{}/{}", item, rs); meta.set_composite(regions, item, lx::value_is_struct); - meta.set_property(regions, item + "/" + rs + "Type", "Face"); - if (r.name) meta.set_property(regions, item + "/" + rs + "Name", *r.name); + meta.set_property(regions, fields + "Type", "Face"); + if (r.name) meta.set_property(regions, fields + "Name", *r.name); if (r.area) { - meta.set_composite(regions, item + "/" + rs + "Area", lx::value_is_struct); + meta.set_composite(regions, fields + "Area", lx::value_is_struct); write_area(meta, rs, st, item, *r.area); } } @@ -1242,7 +1289,7 @@ prop::panorama_geometry metadata_xmp::panorama(const core::file_path path) libfiles::xmp::meta xmp; if (const auto packet = read_file_packet(path)) { - if (!packet->packet.empty()) xmp.parse(packet->packet); + if (!packet->packet.empty()) parse_packet(xmp, packet->packet); } else { @@ -1251,7 +1298,7 @@ prop::panorama_geometry metadata_xmp::panorama(const core::file_path path) files ff; const auto scanned = ff.scan_file(path, false, ft); if (!scanned.success) record_xmp_error(__FUNCTION__, "the panorama metadata could not be read"); - if (!scanned.metadata.xmp.empty()) xmp.parse(packet_text(scanned.metadata.xmp)); + if (!scanned.metadata.xmp.empty()) parse_packet(xmp, packet_text(scanned.metadata.xmp)); } read_panorama_geometry(xmp, result); if (result.is_valid()) return result; @@ -1267,7 +1314,7 @@ prop::panorama_geometry metadata_xmp::panorama(const core::file_path path) if (!sidecar.empty()) { libfiles::xmp::meta xmp; - xmp.parse(std::string_view(std::bit_cast(sidecar.data()), sidecar.size())); + parse_packet(xmp, std::string_view(std::bit_cast(sidecar.data()), sidecar.size())); read_panorama_geometry(xmp, result); } } @@ -1451,6 +1498,9 @@ static libfiles::metadata_update update_of(const libfiles::xmp::meta& xmp, const // file beside it in one pass and swaps it in, so the file is never left half rewritten. static void write_with_libfiles(const core::file_path path, const libfiles::metadata_update& update) { + // The fields written outside the packet were read from it. + if (update.xmp) require_whole(*update.xmp); + auto f = platform::open_file(path, platform::file_open_mode::read); if (!f) throw app_exception("the file could not be opened for reading"); @@ -1470,7 +1520,7 @@ static void write_with_libfiles(const core::file_path path, const libfiles::meta if (!rw) throw app_exception("the file could not be opened for writing"); platform_file_stream file(rw); - libfiles::write_in_place(file, plan); + require_written(libfiles::write_in_place(file, plan)); return; } @@ -1486,7 +1536,7 @@ static void write_with_libfiles(const core::file_path path, const libfiles::meta if (!out) throw app_exception("the updated file could not be created"); platform_file_stream destination(out); - libfiles::write_updated(r, plan, destination); + require_written(libfiles::write_updated(r, plan, destination)); } source.reset(); @@ -1521,13 +1571,13 @@ static void read_embedded_source(const core::file_path src_path, const file_type if (const auto packet = read_file_packet(src_path)) { if (!packet->readable) throw app_exception("the existing metadata could not be read"); - if (!packet->packet.empty()) xmp.parse(packet->packet); + if (!packet->packet.empty()) parse_packet(xmp, packet->packet); } else { const auto& source = scan(); if (!source.success) throw app_exception("the existing metadata could not be read"); - if (!source.metadata.xmp.empty()) xmp.parse(packet_text(source.metadata.xmp)); + if (!source.metadata.xmp.empty()) parse_packet(xmp, packet_text(source.metadata.xmp)); } // A converted file keeps what its source shows. The new format may have no place for the source's @@ -1601,15 +1651,15 @@ static void read_edit_source(const core::file_path src_path, const file_type_ref if (!f.empty()) { - xmp.parse(std::string_view(std::bit_cast(f.data()), f.size())); + parse_packet(xmp, std::string_view(std::bit_cast(f.data()), f.size())); } } else if (src_ft->has_trait(file_traits::raw)) { if (s_test_raw_source_xmp_path == src_path && !s_test_raw_source_xmp.empty()) { - xmp.parse(std::string_view(std::bit_cast(s_test_raw_source_xmp.data()), - s_test_raw_source_xmp.size())); + parse_packet(xmp, std::string_view(std::bit_cast(s_test_raw_source_xmp.data()), + s_test_raw_source_xmp.size())); } else { @@ -1621,14 +1671,15 @@ static void read_edit_source(const core::file_path src_path, const file_type_ref } if (!scanned.metadata.xmp.empty()) { - xmp.parse(std::string_view(std::bit_cast(scanned.metadata.xmp.data()), - scanned.metadata.xmp.size())); + parse_packet(xmp, std::string_view(std::bit_cast(scanned.metadata.xmp.data()), + scanned.metadata.xmp.size())); } } } } edits.apply(xmp); + require_whole(xmp); } // A read or write failure, with what the system says about the file it happened to. @@ -1680,7 +1731,7 @@ xmp_update_result metadata_xmp::update(const core::file_path update_path, const { failing_path = dst_xmp_path; - const auto buffer = xmp.serialize({.omit_packet_wrapper = true}); + const auto buffer = serialized(xmp, {.omit_packet_wrapper = true}); const auto path_xmp = dst_xmp_path; const auto f = platform::open_file(path_xmp, platform::file_open_mode::create); @@ -1707,7 +1758,7 @@ xmp_update_result metadata_xmp::update(const core::file_path update_path, const } } } - catch (const libfiles::xmp::error& e) + catch (const xmp_refused& e) { // The packet itself refused the edit, such as a value for what the file holds as an array. core::log(__FUNCTION__, e.what()); @@ -1718,7 +1769,7 @@ xmp_update_result metadata_xmp::update(const core::file_path update_path, const core::log(__FUNCTION__, e.what()); throw file_failure(e, failing_path); } - catch (const libfiles::write_error& e) + catch (const write_failure& e) { core::log(__FUNCTION__, e.what()); throw file_failure(e, failing_path); @@ -1745,11 +1796,11 @@ core::blob metadata_xmp::encoded_packet(const core::file_path src_path, const co sidecar_holds_metadata(src_path, src_xmp_name), xmp); if (xmp.empty()) return {}; - const auto packet = xmp.serialize(); + const auto packet = serialized(xmp); const auto* const bytes = std::bit_cast(packet.data()); return core::blob(bytes, bytes + packet.size()); } - catch (const libfiles::xmp::error& e) + catch (const xmp_refused& e) { core::log(__FUNCTION__, e.what()); throw app_exception(e.what()); @@ -1789,6 +1840,7 @@ std::optional metadata_xmp::stage_update(const core::file_pat read_edit_source(src_path, src_ft, false, edits, src_xmp_name, false, xmp); const auto update = update_of(xmp, edits); + require_whole(xmp); const auto plan = libfiles::plan_update(r, update); if (!plan.ok()) throw app_exception(plan.error); @@ -1813,12 +1865,12 @@ std::optional metadata_xmp::stage_update(const core::file_pat if (!out) throw app_exception("the updated file could not be created"); platform_file_stream destination(out); - libfiles::write_updated(r, plan, destination); + require_written(libfiles::write_updated(r, plan, destination)); } result.success = true; } - catch (const libfiles::xmp::error& e) + catch (const xmp_refused& e) { // The packet itself refused the edit, such as a value for what the file holds as an array. core::log(__FUNCTION__, e.what()); @@ -1829,7 +1881,7 @@ std::optional metadata_xmp::stage_update(const core::file_pat core::log(__FUNCTION__, e.what()); throw file_failure(e, failing_path); } - catch (const libfiles::write_error& e) + catch (const write_failure& e) { core::log(__FUNCTION__, e.what()); throw file_failure(e, failing_path); @@ -1853,6 +1905,7 @@ bool metadata_xmp::patch(const core::file_path path, const metadata_edits& edits read_edit_source(path, files::file_type_from_name(path), false, edits, src_xmp_name, false, xmp); const auto update = update_of(xmp, edits); + require_whole(xmp); // One handle no one else may open meanwhile, for the plan and the patch: the bytes planned from // are the bytes patched. @@ -1866,10 +1919,10 @@ bool metadata_xmp::patch(const core::file_path path, const metadata_edits& edits if (!plan.ok()) throw app_exception(plan.error); if (!plan.patchable()) return false; - libfiles::write_in_place(file, plan); + require_written(libfiles::write_in_place(file, plan)); return true; } - catch (const libfiles::xmp::error& e) + catch (const xmp_refused& e) { // The packet itself refused the edit, such as a value for what the file holds as an array. core::log(__FUNCTION__, e.what()); @@ -1880,7 +1933,7 @@ bool metadata_xmp::patch(const core::file_path path, const metadata_edits& edits core::log(__FUNCTION__, e.what()); throw file_failure(e, path); } - catch (const libfiles::write_error& e) + catch (const write_failure& e) { core::log(__FUNCTION__, e.what()); throw file_failure(e, path); @@ -1892,11 +1945,11 @@ void metadata_xmp::update(std::string& buffer, const metadata_edits& edits) try { libfiles::xmp::meta meta; - meta.parse(buffer); + parse_packet(meta, buffer); edits.apply(meta); - buffer = core::utf8_cast(meta.serialize()); + buffer = core::utf8_cast(serialized(meta)); } - catch (const libfiles::xmp::error& e) + catch (const xmp_refused& e) { core::log(__FUNCTION__, e.what()); throw app_exception(e.what()); @@ -1983,7 +2036,7 @@ metadata_kv_list metadata_xmp::to_info(const std::span xmp, bool& const auto is_complete_packet = text.find("") != std::string_view::npos; libfiles::xmp::meta meta; - meta.parse(text); + parse_packet(meta, text); std::string current_schema; diff --git a/src/model.cpp b/src/model.cpp index a58fa432..4222bfea 100644 --- a/src/model.cpp +++ b/src/model.cpp @@ -1120,11 +1120,11 @@ void view_state::start_c64(const size_t row) const // The row is one of the listing the panel draws, made from the same bytes. const auto& data = d->_selected_item_data; - const auto listing = libfiles::list_c64_media({data.data(), data.size()}); + const auto listing = lib64::list_media({data.data(), data.size()}).value(); if (row >= listing.rows.size()) return; const auto& entry = listing.rows[row]; - if (!c64_row_runs(entry.file_type, file_type->extension == "t64")) return; + if (!entry.runs) return; d->_c64_keyboard = {}; d->_c64_texture.reset(); @@ -4640,6 +4640,7 @@ void view_state::load_display_state() { if (display_file_type->group == file_group::archive) { + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): a shared_ptr owns it; MSVC count opaque _async.queue_async(async_queue::load, [new_display = ui_owned(_async, new_display), display_path, loading = df::hold_loading_media()] { diff --git a/src/model_db.cpp b/src/model_db.cpp index 34707ed8..5bc581fb 100644 --- a/src/model_db.cpp +++ b/src/model_db.cpp @@ -520,6 +520,7 @@ bool database::request_rescan_since(const int stored_version) const std::vector database_test_seams::metadata_change_versions() { std::vector result; + result.reserve(metadata_changes.size()); for (const auto& change : metadata_changes) result.push_back(change.version); return result; } diff --git a/src/model_faces.cpp b/src/model_faces.cpp index 9712b39d..b49acb28 100644 --- a/src/model_faces.cpp +++ b/src/model_faces.cpp @@ -295,11 +295,6 @@ namespace faces return value >= 1 && value <= 8 ? static_cast(value) : libmug::orientation::top_left; } - bool is_limited(const core::color_space cs) - { - return cs == core::color_space::rec601_limited || cs == core::color_space::rec709_limited || - cs == core::color_space::rec2020_limited; - } // A decode as libmug reads it, without a copy: packed 32-bit as its blue, green and red, NV12 as its two // planes, each with the orientation it is shown in. None for any other format. @@ -307,27 +302,23 @@ namespace faces { if (!core::is_valid(surface)) return {}; - const auto extent = surface->dimensions(); - libmug::image_view view; - view.width = extent.cx; - view.height = extent.cy; - view.pixels = surface->pixels(); - view.stride = static_cast(surface->stride()); - view.orientation = to_libmug(surface->orientation()); + const auto v = surface->view(); + libmug::image_view view{v.pixels, v.stride, v.width, v.height}; + view.orientation = to_libmug(v.orientation); - if (core::is_packed(surface->format())) + if (core::is_packed(v.format)) { view.format = libmug::pixel_format::bgrx8; return view; } - // The chroma plane follows the luma plane, at its stride: NV12 surfaces are even in both dimensions. - if (surface->format() == core::texture_format::NV12 && extent.cx % 2 == 0 && extent.cy % 2 == 0) + // libmug reads NV12 at an even size alone, as NV12 surfaces are. + if (v.format == core::texture_format::NV12 && v.width % 2 == 0 && v.height % 2 == 0) { view.format = libmug::pixel_format::nv12; - view.chroma = surface->pixels() + surface->stride() * extent.cy; - view.chroma_stride = view.stride; - view.limited_range = is_limited(surface->color_space()); + view.limited_range = v.limited_range; + view.chroma = v.chroma; + view.chroma_stride = v.chroma_stride; return view; } @@ -366,7 +357,8 @@ namespace faces { const auto view = view_of(surface); if (!view) return {}; - return faces_of(detector.detect(*view, detect_options_of(t))); + // None where libmug cannot read the view, or its network: a failed detection's value is no faces. + return faces_of(*detector.detect(*view, detect_options_of(t))); } bool embed_face(libmug::face_embedder& embedder, const core::const_surface_ptr& decoded, const landmarks& marks, @@ -381,7 +373,10 @@ namespace faces libmug::landmarks points{}; for (auto i = 0; i < landmark_count; ++i) points[i] = {marks[i].X, marks[i].Y}; - return embedder.embed(*view, points, t.max_outside, result); + const auto embedded = embedder.embed(*view, points, t.max_outside); + if (!embedded) return false; + result = *embedded; + return true; } uint32_t model_id() @@ -961,7 +956,7 @@ namespace faces constexpr std::array reflected{top_right, top_left, bottom_left, bottom_right, right_top, left_top, left_bottom, right_bottom}; picture.orientation = reflected[static_cast(picture.orientation) - 1]; - auto found = detector.detect(picture, options); + auto found = *detector.detect(picture, options); for (auto& f : found.faces) { f.bounds.x = found.shown.width - (f.bounds.x + f.bounds.width); @@ -994,7 +989,7 @@ namespace faces // Weak small candidates can justify a closer look, but cannot themselves become reported faces. probe.confidence = std::min(options.confidence, 55); probe.min_face_edge = std::min(options.min_face_edge, 0.02); - auto found = faces_of(detector.detect(*picture, probe)); + auto found = faces_of(*detector.detect(*picture, probe)); record.extent = found.extent; const auto short_edge = std::min(found.extent.cx, found.extent.cy); const auto small = short_edge * 0.08; @@ -1049,8 +1044,8 @@ namespace faces // libmug reads the part where it lies, turned as the whole picture is. auto within = faces_of( - detector.detect(picture->part(stored_px.left, stored_px.top, stored_px.width(), stored_px.height()), - detect_options_of(t))); + *detector.detect(picture->part(stored_px.left, stored_px.top, stored_px.width(), stored_px.height()), + detect_options_of(t))); if (within.faces.empty()) continue; // The most confident face of the part that is not one already found - a neighbour the enlarged area reaches diff --git a/src/model_faces_search.cpp b/src/model_faces_search.cpp index 7a462125..cd097fd8 100644 --- a/src/model_faces_search.cpp +++ b/src/model_faces_search.cpp @@ -922,7 +922,9 @@ namespace faces scan_pass(session); } - if (_scan_wanted.load() && !platform::is_closing) start_scan(); + // A pass for a session that has ended read nothing, and the request it cleared as it began may have been the + // next session's: made while this pass waited to run, it found the pass running and left it to ask again. + if ((_scan_wanted.load() || !is_current(session)) && !platform::is_closing) start_scan(); } void face_search::scan_pass(const uint64_t session) @@ -1657,6 +1659,7 @@ namespace faces const auto& run = store->run(*r); if (run.model != model_id() || !run.is_current()) continue; std::vector boxes; + boxes.reserve(run.count); for (uint32_t i = 0; i < run.count; ++i) boxes.push_back(store->entry(run.first + i).bounds()); const auto matched = match_marks(marks, boxes); for (size_t m = 0; m < matched.size(); ++m) diff --git a/src/model_index.cpp b/src/model_index.cpp index b611b959..3af25a5c 100644 --- a/src/model_index.cpp +++ b/src/model_index.cpp @@ -4968,7 +4968,7 @@ void index_state::pump_visible_thumbnails() } } -void index_state::scan_visible_thumbnail(item_scan_request request) +void index_state::scan_visible_thumbnail(const item_scan_request& request) { core::scope_locked_inc scanning(scanning_items); const auto node = validate_folder(request.folder, false, core::utc_now()); @@ -5555,7 +5555,7 @@ void index_state::queue_update_summary() }); } -void index_state::queue_validate_changed_folders(core::unique_folders paths) +void index_state::queue_validate_changed_folders(const core::unique_folders& paths) { // Each folder's node as the change is reported. The scan of an item a listing shows validates its folder too, and // can publish the change before this pass does, which then finds nothing left to change - and that scan asks for diff --git a/src/model_index.h b/src/model_index.h index 30b4359e..9ec96dd7 100644 --- a/src/model_index.h +++ b/src/model_index.h @@ -1359,7 +1359,7 @@ class index_state final : public core::no_copy // Folder-watch response. Compares the watched folders against the index and only asks the view to // refresh when the comparison found something, so a write we made ourselves - whose new modified // time is already published - costs one enumeration and nothing more. - void queue_validate_changed_folders(core::unique_folders paths); + void queue_validate_changed_folders(const core::unique_folders& paths); // Whether a listing or a validation has given the folder a node. bool knows_folder(const core::folder_path folder) const { return _items.find(folder) != nullptr; } void queue_scan_listed_items(const df::item_set& listed_items); @@ -1629,7 +1629,7 @@ class index_state final : public core::no_copy void replan_visible_thumbnails(); std::deque release_visible_plan(); void pump_visible_thumbnails(); - void scan_visible_thumbnail(item_scan_request request); + void scan_visible_thumbnail(const item_scan_request& request); void decode_visible_thumbnail(const item_scan_request& request, const df::index_folder_item_ptr& folder, core::blob source, core::date_t read_at, core::date_t thumbnail_version, bool metadata_scan_wanted, core::date_t scanned_before); diff --git a/src/model_index_summary.cpp b/src/model_index_summary.cpp index 6994c1cd..bb69e476 100644 --- a/src/model_index_summary.cpp +++ b/src/model_index_summary.cpp @@ -285,7 +285,7 @@ std::vector suggest_locations(std::vector it item.gap_s = gap / per_second; if (result.empty() || !(result.back().located.path == nearest->path)) result.push_back({*nearest, {}}); - result.back().items.push_back(std::move(item)); + result.back().items.push_back(item); } return result; diff --git a/src/model_items.cpp b/src/model_items.cpp index ad238f2d..59c62239 100644 --- a/src/model_items.cpp +++ b/src/model_items.cpp @@ -1901,7 +1901,6 @@ sizei df::item_group::measure(render::measure_context& mc, const int width_limit // the top and bottom of its subject. const auto shrink = (avail_cx - gaps_cx) / total_width; for (int nn = 0; nn < col_count; nn++) dst_widths[nn] *= shrink; - total_width = avail_cx - gaps_cx; } else if (!is_end_break && col_count > 1) { @@ -2971,7 +2970,6 @@ void df::item_element::render(render::draw_context& dc, const item_group& group, const auto text = platform::format_date_time(info.modified); widths.modified.draw(dc, text, core::color{}, bb, text_font, text_style_far, text_color); } - text_x += widths.modified.width + text_padding; } if (show_folder) @@ -3295,8 +3293,6 @@ void df::item_element::render(render::draw_context& dc, const item_group& group, dc.draw_text(tt.command_rate_rejected, label_bounds, text_font, render::text_style::single_line_center, core::color(color_rate_rejected, text_alpha), {}); } - - y += stars_line_height; } // Badges are anchored to the tile rather than the text block. Hover/focus expands the @@ -3363,7 +3359,6 @@ void df::item_element::render(render::draw_context& dc, const item_group& group, { const recti bb(x_flag, y_flag, x_flag + cxy_flag, y_flag + cxy_flag); xdraw_icon(dc, icon_index::cloud, bb, text_color, bg_disk); - x_flag += bb.width(); } } } diff --git a/src/model_locations.cpp b/src/model_locations.cpp index c0db959e..4477f6b5 100644 --- a/src/model_locations.cpp +++ b/src/model_locations.cpp @@ -804,6 +804,7 @@ void location_cache::load_countries() for (auto i = 3 + localized_count; i < entry_count; i++) { + // NOLINTNEXTLINE(clang-analyzer-security.ArrayBound): scan_entries stops at max_location_cols auto&& csv_entry = entries[i]; if (!csv_entry.is_empty()) diff --git a/src/model_search.cpp b/src/model_search.cpp index cf57ab1a..b831e568 100644 --- a/src/model_search.cpp +++ b/src/model_search.cpp @@ -2820,21 +2820,27 @@ static bool matches_qualified_name(const std::string_view query, const core::cac } } -bool df::match_volume_label(const std::string_view folder_name, const hash_map& drive_labels, - const search_term& term) +df::drive_labels_t df::labelled_drives(const platform::drives& drives) { - if (folder_name.size() >= 2 && folder_name[1] == ':') - { - const auto drive_letter = static_cast(core::to_upper(static_cast(folder_name[0]))); - const auto found = drive_labels.find(drive_letter); + drive_labels_t result; - if (found != drive_labels.end()) - { - return same_term(found->second.sv(), term); - } + for (const auto& d : drives) + { + if (!d.name.empty() && !core::is_empty(d.vol_name)) result.emplace_back(d.name, core::cache(d.vol_name)); } - return false; + std::ranges::stable_sort(result, [](const auto& left, const auto& right) + { return left.first.size() > right.first.size(); }); + return result; +} + +bool df::match_volume_label(const std::string_view folder_name, const drive_labels_t& drive_labels, + const search_term& term) +{ + const auto drive = std::ranges::find_if(drive_labels, [folder_name](const auto& labelled) + { return core::folder_contains(labelled.first, folder_name); }); + + return drive != drive_labels.end() && same_term(drive->second.sv(), term); } df::search_result df::search_matcher::match_term(const core::cached folder_name, const index_file_item& file, diff --git a/src/model_search.h b/src/model_search.h index 3f3d389a..c4da633d 100644 --- a/src/model_search.h +++ b/src/model_search.h @@ -753,11 +753,16 @@ namespace df // address box and by folder completion, which would otherwise disagree about the same path. std::string quote_path_term(std::string_view path); - // Returns true when folder_name is on a drive whose volume label matches the - // term text (case-insensitive, wildcards supported). drive_labels maps an - // upper-case drive letter to its current volume label. - bool match_volume_label(std::string_view folder_name, const core::hash_map& drive_labels, - const search_term& term); + // The volume label of each drive that has one, with the drive's path - C:\ on Windows, a mount point such as + // /media/zac/Backup on Linux - which is how a folder finds the drive it is on. The innermost drive comes first, so + // a mount inside another decides for the folders in it. + using drive_labels_t = std::vector>; + drive_labels_t labelled_drives(const platform::drives& drives); + + // Returns true when folder_name is on a drive whose volume label matches the term text (case-insensitive, + // wildcards supported). The drive a folder is on is the one whose path holds it, with a path's case read as the + // platform reads it. + bool match_volume_label(std::string_view folder_name, const drive_labels_t& drive_labels, const search_term& term); // docs/locations.md#location-search: merges the tokens that follow a location scope into its term when they // are recognisably part of the place - a country code, a distance, or comma-bound text. @@ -1609,7 +1614,7 @@ namespace df const search_presence_mask _required_presence; const uint32_t _now_days = 0; const location_cache* _locations = nullptr; - core::hash_map _drive_labels; + drive_labels_t _drive_labels; struct resolved_place { @@ -1654,16 +1659,9 @@ namespace df { if (s.has_volume_term()) { - // Resolve current drive letters to volume labels once so a volume: - // term can match items by the label of the drive they live on. - for (const auto& d : platform::scan_drives()) - { - if (!d.name.empty() && !core::is_empty(d.vol_name)) - { - _drive_labels[static_cast(core::to_upper(static_cast(d.name[0])))] = - core::cache(d.vol_name); - } - } + // Resolve the current drives to volume labels once so a volume: term can match items by the + // label of the drive they live on. + _drive_labels = labelled_drives(platform::scan_drives()); } if (locations && s.has_named_location()) diff --git a/src/platform_linux_app.cpp b/src/platform_linux_app.cpp index 1bb41713..0408303f 100644 --- a/src/platform_linux_app.cpp +++ b/src/platform_linux_app.cpp @@ -6,16 +6,16 @@ // file, You can obtain one at https://mozilla.org/MPL/2.0/. // Purpose: The application's Linux glue: no hardware video decode for FFmpeg to use - the counterpart -// of platform_win_av.cpp - no screen recorder, which platform_win_record.cpp is on Windows, because Linux has -// no movie writer to record with, and no platform tests to register, since the Windows-only subject file is -// not built here. The entry point and generated icon-font registration are shared in app.cpp, which calls -// libdesktop's UI runner on both platforms. +// of platform_win_av.cpp - the movie writer, which is FFmpeg's own here, libaom's AV1 and FFmpeg's AAC in an MP4 +// (av_movie_writer.cpp), since the system has no encoder to ask, the screen recorder - the counterpart of +// platform_win_record.cpp - which films the window's own pixels, and the registration of the Linux platform tests, +// test_platform_linux.cpp, in place of the Windows-only subject file. The entry point and generated icon-font +// registration are shared in app.cpp, which calls libdesktop's UI runner on both platforms. #include "pch.h" #include "app_record.h" #include "av_format.h" -#include "av_sound.h" -#include "files.h" +#include "av_movie_writer.h" #include "model.h" #include "test_runner.h" @@ -54,18 +54,42 @@ void av_platform_decode_lock(const AVHWFramesContext*, render::video_picture&) } /////////////////////////////////////////////////////////////////////////////////////////////////// -// Recording. Linux has no movie writer, so there is nothing to record with. +// Movies. FFmpeg's own writer: the system offers no encoder to write one with. /////////////////////////////////////////////////////////////////////////////////////////////////// -std::unique_ptr start_screen_recording(const screen_recording_request&) +bool df::can_write_movies() { - return nullptr; + return av_can_write_movies(); +} + +platform::movie_writer_ptr df::create_movie_writer(const platform::movie_writer_request& request) +{ + return av_create_movie_writer(request); +} + +/////////////////////////////////////////////////////////////////////////////////////////////////// +// Recording. There is no desktop to ask for what the window shows with whatever is over it, so the window is +// recorded as it draws itself: its own pixels, read on the UI thread as the software renderer left them. +/////////////////////////////////////////////////////////////////////////////////////////////////// + +std::unique_ptr start_screen_recording(const screen_recording_request& request) +{ + if (!df::can_write_movies()) return nullptr; + + if (request.present_window) + { + core::log(__FUNCTION__, "a window is not held above others here: it is recorded as it is"); + } + + return start_window_recording(request, + [window = request.window] { return platform::capture_window_surface(window); }); } /////////////////////////////////////////////////////////////////////////////////////////////////// -// Tests. The Windows-only subject file is not built here, so the registration is empty. +// Tests. The Windows-only subject file is not built here; its counterpart is test_platform_linux.cpp. /////////////////////////////////////////////////////////////////////////////////////////////////// -void register_platform_tests(view_state&, test_registry&) +void register_platform_tests(view_state& state, test_registry& tests) { + register_platform_linux_tests(state, tests); } diff --git a/src/platform_win.manifest b/src/platform_win.manifest index 9aec9d39..d155ed17 100644 --- a/src/platform_win.manifest +++ b/src/platform_win.manifest @@ -3,7 +3,7 @@ diff --git a/src/platform_win_av.cpp b/src/platform_win_av.cpp index 82de36b1..ede976af 100644 --- a/src/platform_win_av.cpp +++ b/src/platform_win_av.cpp @@ -5,10 +5,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: FFmpeg's D3D11VA hardware decoding on Windows, the application's side of it: the one decoder +// Purpose: The application's Windows side of media: FFmpeg's D3D11VA hardware decoding, the one decoder // whose pictures the renderer can present, whether the driver decodes a stream, and the decode device - // the render device itself where it carries the video interfaces, else one made on the GPU the renderer -// draws with. +// draws with - and the movie writer, which is the system's here: Media Foundation's, through libdesktop. #include "pch.h" @@ -19,6 +19,7 @@ #include #include "av_format.h" +#include "av_movie_writer.h" extern "C" { @@ -217,3 +218,15 @@ void av_platform_decode_lock(const AVHWFramesContext* frames, render::video_pict picture.unlock = hwctx->unlock; picture.lock_context = hwctx->lock_ctx; } + +// Movies are written by the system here: Media Foundation's H.264 and AAC encoders, through libdesktop. The +// FFmpeg the Windows build links has no encoder to write one with. +bool df::can_write_movies() +{ + return platform::can_write_movies(); +} + +platform::movie_writer_ptr df::create_movie_writer(const platform::movie_writer_request& request) +{ + return platform::create_movie_writer(request); +} diff --git a/src/platform_win_record.cpp b/src/platform_win_record.cpp index 7b6cf161..ed1b3b60 100644 --- a/src/platform_win_record.cpp +++ b/src/platform_win_record.cpp @@ -7,8 +7,9 @@ // Purpose: The screen recorder on Windows. A thread of its own copies the window's client area as // the desktop shows it - menus, bubbles and the pointer included - by DXGI desktop duplication, or by GDI where -// the system offers no duplication, at a steady rate, and writes it through libdesktop's movie writer. A script's -// pointer, gliding and clicking, is drawn into the frames, and the moments it names are written beside the movie. +// the system offers no duplication, at a steady rate, and writes it through Diffractor's movie writer, Media +// Foundation's here. A script's pointer, gliding and clicking, is drawn into the frames, as the system's arrow +// is, and the moments it names are written beside the movie, both as app_record.cpp keeps them for every platform. #include "pch.h" @@ -18,17 +19,12 @@ #include #include #include -#include #include "app_record.h" +#include "av_movie_writer.h" namespace { - // Bits per pixel per frame. A recording is a first generation that Movie mixer encodes again at 0.10, so it - // is kept well above that: interface text and thumbnail edges are what a second generation softens first. - constexpr double recording_bits_per_pixel = 0.25; - constexpr double recording_max_bitrate = 60000000.0; - // Duplication lost this many times in a row - a remote session, a desktop mode it does not take - gives way // to GDI, which is an order slower but always there. constexpr int duplication_attempts = 30; @@ -104,34 +100,6 @@ namespace return rc; } - // Whether the user's own desktop is what the screen shows: not while the session is locked, when the lock screen - // covers it, nor while a secure prompt has the screen. (Windows 7 reports the lock the other way round; this is - // a Windows 10 and later tool.) - bool user_desktop_is_shown() - { - LPWSTR buffer = nullptr; - DWORD bytes = 0; - - if (WTSQuerySessionInformationW(WTS_CURRENT_SERVER_HANDLE, WTS_CURRENT_SESSION, WTSSessionInfoEx, &buffer, - &bytes) && - buffer) - { - const auto* const info = reinterpret_cast(buffer); - const auto locked = info->Level == 1 && info->Data.WTSInfoExLevel1.SessionFlags == WTS_SESSIONSTATE_LOCK; - WTSFreeMemory(buffer); - if (locked) return false; - } - - const auto desktop = OpenInputDesktop(0, FALSE, DESKTOP_READOBJECTS); - if (!desktop) return false; - - wchar_t name[32]{}; - DWORD needed = 0; - const auto named = GetUserObjectInformationW(desktop, UOI_NAME, name, sizeof(name), &needed) != FALSE; - CloseDesktop(desktop); - return named && _wcsicmp(name, L"Default") == 0; - } - void fill_black(core::surface& frame) { const auto size = frame.dimensions(); @@ -538,73 +506,6 @@ namespace } } - // The ring a click spreads: Diffractor's accent, smoothed at its edges, `opacity` of it over what is under. - constexpr uint8_t ring_blue = 0xff; - constexpr uint8_t ring_green = 0x9e; - constexpr uint8_t ring_red = 0x4a; - - recti ring_bounds(const pointi center, const double radius, const double thickness) - { - const auto reach = static_cast(std::ceil(radius + thickness)) + 1; - return {center.x - reach, center.y - reach, center.x + reach + 1, center.y + reach + 1}; - } - - void draw_ring(core::surface& frame, const pointi center, const double radius, const double thickness, - const double opacity) - { - const auto size = frame.dimensions(); - const auto bounds = ring_bounds(center, radius, thickness); - const auto blend = [](const uint8_t under, const uint8_t over, const double amount) - { - return static_cast(std::lround(under + (over - under) * amount)); - }; - - for (auto y = std::max(0, bounds.top); y < std::min(size.cy, bounds.bottom); ++y) - { - auto* const line = frame.pixels_line(y); - - for (auto x = std::max(0, bounds.left); x < std::min(size.cx, bounds.right); ++x) - { - const auto distance = std::hypot(x - center.x, y - center.y); - const auto coverage = std::clamp(thickness / 2.0 + 0.5 - std::abs(distance - radius), 0.0, 1.0) * - opacity; - if (coverage <= 0.0) continue; - - auto* const pixel = line + static_cast(x) * 4; - pixel[0] = blend(pixel[0], ring_blue, coverage); - pixel[1] = blend(pixel[1], ring_green, coverage); - pixel[2] = blend(pixel[2], ring_red, coverage); - } - } - } - - // How long a click's ring takes to spread and fade. - constexpr double click_seconds = 0.45; - - // The pointer a script shows: where it glides from and to, and when, and when it last clicked - all in seconds - // into the movie, so each frame draws it where it was when the frame was captured. - struct scripted_pointer - { - bool shown = false; - pointi from; - pointi to; - double move_start = 0.0; - double move_seconds = 0.0; - double click_at = -1.0; - - pointi at(const double t) const - { - if (move_seconds <= 0.0 || t >= move_start + move_seconds) return to; - if (t <= move_start) return from; - - // Eased in and out, as a hand moves a mouse. - const auto u = (t - move_start) / move_seconds; - const auto eased = u * u * (3.0 - 2.0 * u); - return {from.x + static_cast(std::lround((to.x - from.x) * eased)), - from.y + static_cast(std::lround((to.y - from.y) * eased))}; - } - }; - // Waits out the rest of a frame. High resolution where the system has it (Windows 10 1803 on), so a 33 ms // frame is not rounded to the scheduler's 15.6 ms tick. class frame_timer @@ -777,36 +678,12 @@ namespace void pointer(const std::optional screen, const double glide_seconds) override { - const auto now = std::max(0.0, elapsed()); - const std::lock_guard lock(_pointer_mutex); - - if (!screen) - { - _pointer.shown = false; - return; - } - - _pointer.from = _pointer.shown ? _pointer.at(now) : *screen; - _pointer.to = *screen; - _pointer.move_start = now; - _pointer.move_seconds = _pointer.shown ? std::max(0.0, glide_seconds) : 0.0; - _pointer.shown = true; + _script.pointer(screen, glide_seconds, std::max(0.0, elapsed())); } - void click() override - { - const auto now = std::max(0.0, elapsed()); - const std::lock_guard lock(_pointer_mutex); - _pointer.click_at = now; - _click_point = _pointer.at(now); - } + void click() override { _script.click(std::max(0.0, elapsed())); } - void mark(const std::string_view name) override - { - const auto now = std::max(0.0, elapsed()); - const std::lock_guard lock(_markers_mutex); - _markers.emplace_back(now, std::string(name)); - } + void mark(const std::string_view name) override { _script.mark(name, std::max(0.0, elapsed())); } private: using clock = std::chrono::steady_clock; @@ -832,14 +709,7 @@ namespace void draw_pointers(const RECT& area, const double t, const std::optional& arrow, gdi_bitmap& bitmap, frame_overlay& overlay, core::surface& frame) { - scripted_pointer scripted; - pointi click_point; - - { - const std::lock_guard lock(_pointer_mutex); - scripted = _pointer; - click_point = _click_point; - } + const auto script = _script.current(); const auto to_frame = [&area](const pointi screen) { @@ -851,22 +721,14 @@ namespace std::optional drawn; - if (scripted.shown && arrow) + if (script.pointer.shown && arrow) { drawn = arrow; - drawn->at = to_frame(scripted.at(t)); + drawn->at = to_frame(script.pointer.at(t)); } - // The ring grows from the pointer's tip, eased out, and fades as it does. - const auto click_age = t - scripted.click_at; - const auto clicking = scripted.shown && scripted.click_at >= 0.0 && click_age >= 0.0 && - click_age < click_seconds; - const auto ring_scale = arrow ? arrow->extent.cx : 48; - const auto progress = clicking ? click_age / click_seconds : 1.0; - const auto spread = 1.0 - (1.0 - progress) * (1.0 - progress); - const auto radius = ring_scale * (0.12 + 0.5 * spread); - const auto thickness = std::max(2.0, ring_scale * 0.07); - const auto ring_center = to_frame(click_point); + auto ring = script.ring(t, arrow ? arrow->extent.cx : 48); + if (ring) ring->center = to_frame(ring->center); recti covered; const auto cover = [&covered](const recti r) @@ -875,33 +737,15 @@ namespace }; if (system) cover(system->bounds()); if (drawn) cover(drawn->bounds()); - if (clicking) cover(ring_bounds(ring_center, radius, thickness)); + if (ring) cover(ring->bounds()); if (covered.is_empty()) return; overlay.keep(frame, covered); if (system) draw_cursor(bitmap, *system, frame); - if (clicking) draw_ring(frame, ring_center, radius, thickness, 0.9 * (1.0 - progress)); + if (ring) draw_click_ring(frame, *ring); if (drawn) draw_cursor(bitmap, *drawn, frame); } - void write_markers(const double length) const - { - std::string text; - - { - const std::lock_guard lock(_markers_mutex); - for (const auto& [seconds, name] : _markers) text += std::format("{:.3f}\t{}\n", seconds, name); - } - - text += std::format("{:.3f}\tend\n", length); - - const auto path = screen_recording_markers_path(_request.path); - if (!platform::blob_save_to_file({std::bit_cast(text.data()), text.size()}, path)) - { - core::log(__FUNCTION__, std::format("Recording's markers could not be written to {}", path)); - } - } - std::string record() { if (!_window || !IsWindow(_window)) return "Recording failed: there is no window to record"; @@ -917,10 +761,8 @@ namespace request.path = _request.path; request.extent = extent; request.frame_rate = fps; - request.video_bitrate = static_cast( - std::min(recording_max_bitrate, - static_cast(extent.cx) * extent.cy * fps * recording_bits_per_pixel)); - const auto writer = platform::create_movie_writer(request); + request.video_bitrate = screen_recording_bitrate(extent, fps); + const auto writer = df::create_movie_writer(request); if (!writer) return std::format("Recording failed: no movie can be written to {}", _request.path); const auto frame = std::make_shared(); @@ -959,8 +801,9 @@ namespace const RECT area{origin.left, origin.top, origin.left + extent.cx, origin.top + extent.cy}; const auto capture_started = elapsed(); - // Twice a second is often enough to say how much of a movie is black. - if (captures % (fps / 2 + 1) == 0) desktop_shown = user_desktop_is_shown(); + // Twice a second is often enough to say how much of a movie is black: the user's own desktop is not + // what the screen shows while the session is locked, nor while a secure prompt has the screen. + if (captures % (fps / 2 + 1) == 0) desktop_shown = !platform::is_screen_locked(); if (!use_gdi) { @@ -1037,7 +880,7 @@ namespace return std::format("Recording failed to finish {}: {}", _request.path, writer->last_error()); const auto length = static_cast(written) / fps; - write_markers(length); + _script.write_markers(_request.path, length); const auto hidden_note = hidden > 0 ? std::format("; {:.1f} s of it while the screen was locked or held by a secure " @@ -1060,11 +903,7 @@ namespace std::atomic _started = not_started; mutable std::mutex _summary_mutex; std::string _summary; - mutable std::mutex _pointer_mutex; - scripted_pointer _pointer; - pointi _click_point; - mutable std::mutex _markers_mutex; - std::vector> _markers; + recording_script _script; // Last, so everything the thread reads exists before it starts. std::thread _thread; }; diff --git a/src/platform_win_res.rc b/src/platform_win_res.rc index d1a76562..115d886b 100644 --- a/src/platform_win_res.rc +++ b/src/platform_win_res.rc @@ -94,8 +94,8 @@ IDR_MANIFEST RT_MANIFEST "platform_win.manifest" // VS_VERSION_INFO VERSIONINFO - FILEVERSION 1, 27, 4, 1316 - PRODUCTVERSION 1, 27, 4, 1316 + FILEVERSION 1, 27, 5, 1317 + PRODUCTVERSION 1, 27, 5, 1317 FILEFLAGSMASK 0x3fL #ifdef _DEBUG FILEFLAGS 0x1L @@ -112,12 +112,12 @@ BEGIN BEGIN VALUE "CompanyName", "Diffractor" VALUE "FileDescription", "Diffractor" - VALUE "FileVersion", "1.27.4.1316" + VALUE "FileVersion", "1.27.5.1317" VALUE "InternalName", "Diffractor.exe" VALUE "LegalCopyright", "Copyright (C) 2026 Diffractor - Zac Walker" VALUE "OriginalFilename", "Diffractor.exe" VALUE "ProductName", "Diffractor" - VALUE "ProductVersion", "1.27.4.1316" + VALUE "ProductVersion", "1.27.5.1317" END END BLOCK "VarFileInfo" diff --git a/src/render_globe.cpp b/src/render_globe.cpp index d08985e4..ebf0be32 100644 --- a/src/render_globe.cpp +++ b/src/render_globe.cpp @@ -13,10 +13,6 @@ #include "pch.h" #include "ui_globe.h" -#ifdef _MSC_VER -#include -#endif - // Pixels between exact evaluations of the sphere inverse. Everything between is interpolated in // source texel space, which is what keeps a drag affordable: the transcendentals cost a sixteenth // of what a per-pixel inverse would. @@ -497,15 +493,8 @@ bool globe_renderer::render(core::surface& destination, const globe_projection& } }; - // Side by side where the standard library does it on the system's own threads, as MSVC's does on the thread pool. - // libstdc++ hands parallel algorithms to TBB where its headers are installed, which would then have to be linked, - // so elsewhere the bands are drawn in turn. -#ifdef _MSC_VER - if (bands.size() > 1) std::for_each(std::execution::par, bands.begin(), bands.end(), draw_band); - else std::ranges::for_each(bands, draw_band); -#else - std::ranges::for_each(bands, draw_band); -#endif + // The bands are drawn side by side on the pool's threads, this one taking its share. + platform::parallel_for(bands.size(), [&bands, &draw_band](const size_t i) { draw_band(bands[i]); }); // The source hears what was wanted on this thread, in the order the rows were drawn. if (draws_tiles) diff --git a/src/test.h b/src/test.h index 724f55f3..11c0bf29 100644 --- a/src/test.h +++ b/src/test.h @@ -125,7 +125,16 @@ inline void assert_equal(const bool expected, const bool actual, const std::stri const std::string_view message = {}, const std::source_location& loc = std::source_location::current()) { - assert_equal(core::to_string(expected), core::to_string(actual), name, message, loc); + ++test_assert_count; + + // Compared as bools rather than as the words for them, so the static analyzer sees, as a reader does, that + // nothing after a failed assert_equal(true, p != nullptr) runs. + if (expected != actual) + { + throw test_assert_exception(std::format("{} - {}: expected '{}', got '{}' at {}", message, name, + core::to_string(expected), core::to_string(actual), + test_assert_where(loc))); + } } // Note: assert_true/assert_false are reserved: util.h already defines assert_true as a runtime diff --git a/src/test_app.cpp b/src/test_app.cpp index f366859b..9957b523 100644 --- a/src/test_app.cpp +++ b/src/test_app.cpp @@ -21,9 +21,11 @@ #include "util_crash_files_db.h" #include "util_zip.h" #include "app_command_line.h" +#include "app_crash_report.h" #include "app_dup_report.h" #include "app_mcp.h" #include "app_movie_batch.h" +#include "app_record.h" #include "app_util.h" #include "app_settings.h" #include "app_text.h" @@ -216,90 +218,6 @@ static void should_drop_damaged_recent_entries() assert_equal(true, recents.items() == reread.items(), "the cleaned list round-trips"); } -#ifndef _WIN32 -static void should_commit_linux_ini_file_settings_after_durable_save() -{ - const auto settings_folder = test_temps.folder().combine("linux-ini-settings"); - platform::create_folder(settings_folder); - const auto settings_path = settings_folder.combine_file("diffractor.ini"); - - auto settings = platform::create_ini_file_settings(settings_folder); - assert_equal(true, settings->write("test_section", "string_value", "original"), "initial write"); - - for (const auto failure : - {platform::linux_settings_test_failure::after_open, platform::linux_settings_test_failure::after_write, - platform::linux_settings_test_failure::before_replace}) - { - platform::test_linux_settings_failure(failure); - assert_equal(false, settings->write("test_section", "string_value", "updated"), "failed write reports false"); - platform::test_linux_settings_failure(platform::linux_settings_test_failure::none); - - std::string same_instance; - assert_equal(true, settings->read("test_section", "string_value", same_instance), - "same instance still has committed value"); - assert_equal("original", same_instance, "failed write does not publish uncommitted value"); - assert_equal(false, platform::exists(settings_folder.combine_file(".diffractor.ini.tmp")), - "failed write removes stage"); - - const auto reopened = platform::create_ini_file_settings(settings_folder); - std::string reopened_value; - assert_equal(true, reopened->read("test_section", "string_value", reopened_value), - "reopened settings read committed value"); - assert_equal("original", reopened_value, "failed write preserves on-disk value"); - assert_equal(true, platform::exists(settings_path), "settings file remains present"); - } - - assert_equal(true, settings->write("test_section", "string_value", "updated"), "write succeeds after failures"); - const auto reopened = platform::create_ini_file_settings(settings_folder); - std::string reopened_value; - assert_equal(true, reopened->read("test_section", "string_value", reopened_value), "reopened updated value"); - assert_equal("updated", reopened_value, "successful write reaches disk"); -} - -static void should_skip_unchanged_linux_ini_file_settings() -{ - const auto settings_folder = test_temps.folder().combine("linux-ini-unchanged"); - platform::create_folder(settings_folder); - auto settings = platform::create_ini_file_settings(settings_folder); - - platform::test_linux_reset_settings_save_count(); - assert_equal(true, settings->write("test_section", "string_value", "same"), "initial write"); - const auto saves_after_first = platform::test_linux_settings_save_count(); - assert_equal(true, saves_after_first > 0, "initial write saves"); - - assert_equal(true, settings->write("test_section", "string_value", "same"), "unchanged write succeeds"); - assert_equal(saves_after_first, platform::test_linux_settings_save_count(), "unchanged write does not save"); -} - -static void should_commit_linux_ini_file_settings_from_owned_stage() -{ - const auto settings_folder = test_temps.folder().combine("linux-ini-owned-stage"); - platform::create_folder(settings_folder); - auto first = platform::create_ini_file_settings(settings_folder); - auto second = platform::create_ini_file_settings(settings_folder); - - assert_equal(true, first->write("test_section", "string_value", "original"), "initial write"); - - bool nested = false; - platform::test_linux_before_settings_replace = [&] - { - if (nested) return; - nested = true; - platform::test_linux_before_settings_replace = {}; - assert_equal(true, second->write("test_section", "string_value", "second"), "nested write"); - }; - - const auto first_write = first->write("test_section", "string_value", "first"); - platform::test_linux_before_settings_replace = {}; - - assert_equal(true, first_write, "outer write succeeds with its own stage"); - const auto reopened = platform::create_ini_file_settings(settings_folder); - std::string value; - assert_equal(true, reopened->read("test_section", "string_value", value), "reopened setting"); - assert_equal("first", value, "outer complete write wins with complete bytes"); -} -#endif - static void should_rename_with_substitutions() { null_async_strategy as; @@ -825,18 +743,6 @@ static void should_adjust_item_dates_from_snapshot() "so does a file carrying no date at all"); } -#ifdef _WIN32 -// The numbers are MAPI's own result codes, so there is nothing to classify where MAPI is absent. -static void should_classify_mapi_results() -{ - assert_equal(true, platform::classify_mapi_send_result(0) == platform::mapi_send_result::sent, "MAPI success"); - assert_equal(true, platform::classify_mapi_send_result(1) == platform::mapi_send_result::canceled, - "MAPI user abort"); - assert_equal(true, platform::classify_mapi_send_result(3) == platform::mapi_send_result::failed, - "MAPI login failure"); -} -#endif - // Records what a run reported for each row so revalidation decisions can be asserted. struct recording_status final : df::status_i { @@ -3640,6 +3546,10 @@ static void should_record_crashes() "the tag carries no build number"); assert_equal(crash_files_db::release_tag("127.1") != crash_files_db::release_tag("128.0"), true, "the next release line retries"); + assert_equal(crash_files_db::release_tag("1.27.4"), crash_files_db::release_tag("127.1"), + "a list written by a two-part build keeps skipping on the same line"); + assert_equal(crash_files_db::release_tag("1.27.4") != crash_files_db::release_tag("1.28.0"), true, + "the next release line retries in the three-part form too"); // SRC-007 - overlapping registrations for the same path are independent; finishing one worker // must not erase the other worker's still-live crash claim. @@ -3667,6 +3577,438 @@ static void should_record_crashes() } } +#ifndef WINSTORE +// Where a test plants a report: named as the application's reports are, which is how one is known for its own, in a +// folder of the test's - never the application's, whose reports are the user's. +static core::file_path planted_crash_report_path() +{ + static int next = 0; + return test_temps.next_folder("crash-report") + .combine_file(std::format("{}-crash-20260101-000000-{}.txt", core::app_file_stem(), ++next)); +} + +#ifdef _WIN32 +// Windows reports in process and keeps no report for libdesktop to remove: a file a test plants there stays. +static constexpr bool crash_reports_are_removed = false; +#else +static constexpr bool crash_reports_are_removed = true; +#endif + +// What a run that was ended by a fatal signal leaves, as libdesktop reads it, for the next start to deal with. +static platform::crash_report crash_report_of_a_run(const std::string_view release, const bool reports = true) +{ + const auto now = core::utc_now(); + const auto seconds = static_cast(core::date_t::intervals_per_second); + + platform::crash_report report; + report.path = planted_crash_report_path(); + write_test_file(report.path, "a report, as far as the flow can tell"); + report.application = "Diffractor"; + report.process = 4200; + report.build_id = "8c7d00112233445566778899aabbccddeeff0011"; + report.started = now - 90 * seconds; + report.time = now - 5 * seconds; + report.signal = 11; + report.signal_name = "SIGSEGV"; + report.code = 1; + report.code_name = "SEGV_MAPERR"; + report.thread = 100; + report.thread_name = "thumbnail_decode"; + report.text = std::format("Release: {}\nBuild: 1316\nReports: {}\nVersion: {}.1316\nWindows: Test 64-bit release\n" + "Id: 0badf00d", + release, reports ? "yes" : "no", release); + report.work = {{100, std::format("decode thumbnail source\t{}", test_files_folder().combine_file("Test.jpg"))}, + {200, + std::format("queue_calc_perceptual_hashes\t{}", test_files_folder().combine_file("Small.jpg"))}}; + report.shareable = "libdesktop crash report 1\nsignal: 11 SIGSEGV\n-- backtrace\nthe frames\n-- end\n"; + report.complete = true; + return report; +} + +// The server, taken the place of: what it was sent, and what is in the zip it was sent. +namespace +{ + struct crash_server + { + int status = 200; + int posts = 0; + std::string message; + std::string version; + std::string build; + std::string subject; + std::string path; + std::string file_name; + std::vector entries; + + crash_server() + { + df::test_crash_post = [this](const platform::web_request& request) + { + ++posts; + path = request.path; + file_name = request.file_name; + + for (const auto& [name, value] : request.form_data) + { + if (name == "message") message = value; + else if (name == "diffractor") version = value; + else if (name == "build") build = value; + else if (name == "subject") subject = value; + } + + entries.clear(); + if (!request.file_path.is_empty()) + for (const auto& entry : df::zip_file::list(request.file_path)) entries.push_back(entry.filename); + + return platform::web_response{.status_code = status}; + }; + } + + ~crash_server() { df::test_crash_post = nullptr; } + crash_server(const crash_server&) = delete; + crash_server& operator=(const crash_server&) = delete; + }; + + // The log the restart rotated to diffractor.previous.log is not what a test is about unless it says so. + struct no_previous_log + { + core::file_path saved = platform::previous_log_path; + + no_previous_log() { platform::previous_log_path = {}; } + ~no_previous_log() { platform::previous_log_path = saved; } + no_previous_log(const no_previous_log&) = delete; + no_previous_log& operator=(const no_previous_log&) = delete; + }; +} + +static void should_record_the_files_a_crash_report_names() +{ + const auto db_path = test_temps.next_path(); + const auto build = "test-build-1"sv; + const auto first = test_files_folder().combine_file("Test.jpg"); + const auto second = test_files_folder().combine_file("Small.jpg"); + const auto third = test_files_folder().combine_file("Test90.jpg"); + + { + crash_files_db files(db_path, build); + + // The thread that faulted had the first open, another thread the second: what the faulting thread had is the + // cause, as it is when a crash is recorded in process. + assert_equal(1_z, files.record_reported({{first, 7}, {second, 8}}, 7), "what the faulting thread had open"); + assert_equal(true, files.is_known_crash_file(first), "is skipped at once, by the run that reads the report"); + assert_equal(false, files.is_known_crash_file(second), "and what another thread had open is not"); + assert_equal(0_z, files.record_reported({{first, 7}}, 7), "a file already recorded is not recorded again"); + } + + { + crash_files_db next(db_path, build); + assert_equal(true, next.is_known_crash_file(first), "and it is skipped by the next run too"); + assert_equal(1_z, next.skipped_file_count(), "the list keeps one line for it"); + + // The recovery callback's rule, which a thread with nothing open falls back to: all of what was open. + assert_equal(2_z, next.record_reported({{second, 8}, {third, 9}}, 7), "a thread with none open records all"); + assert_equal(0_z, next.record_reported({}, 7), "an empty report records nothing"); + } + + { + crash_files_db after(db_path, build); + assert_equal(3_z, after.skipped_file_count(), "all three are on the list"); + crash_files_db next_release(db_path, "test-build-2"sv); + assert_equal(0_z, next_release.skipped_file_count(), "which the next release line tries again"); + } +} + +static void should_record_the_crash_files_of_this_release_line_only() +{ + const auto db_path = test_temps.next_path(); + const auto release_tag = crash_files_db::release_tag(s_app_version); + const auto other_line = core::to_string(core::version(s_app_version).major + 1) + ".0"; + + { + crash_files_db files(db_path, release_tag); + const std::vector reports = {crash_report_of_a_run(other_line), crash_report_of_a_run(s_app_version)}; + assert_equal(1_z, df::record_reported_crash_files(files, reports), + "only the report of this release line records what it had open"); + assert_equal(true, files.is_known_crash_file(test_files_folder().combine_file("Test.jpg")), + "what the faulting thread had open"); + assert_equal(false, files.is_known_crash_file(test_files_folder().combine_file("Small.jpg")), + "and not what another thread had"); + } + + { + crash_files_db files(db_path, release_tag); + auto unsaid = crash_report_of_a_run(s_app_version); + unsaid.text.clear(); + assert_equal(0_z, df::record_reported_crash_files(files, {unsaid}), + "a report that names no release has no say in which files are skipped"); + + auto hostile = crash_report_of_a_run(s_app_version); + hostile.work = {{100, "no tab here"}, {100, "decode\tnot a path"}, {100, "\t"}}; + assert_equal(0_z, df::record_reported_crash_files(files, {hostile}), + "and work that names no file records none"); + } +} + +static void should_say_what_a_crash_report_may_tell_of_the_run() +{ + const auto saved_profile = command_line.profile_folder; + const auto saved_agent = command_line.agent; + const auto saved_network = df::network_allowed.load(); + const core::scope_exit restore([&] + { + command_line.profile_folder = saved_profile; + command_line.agent = saved_agent; + df::network_allowed = saved_network; + }); + + command_line.profile_folder.clear(); + command_line.agent.session = false; + df::network_allowed = true; + assert_equal(true, df::run_reports_to_diffractor(), "a run of the user's reports"); + + const auto run = df::read_crashed_run(df::crash_report_text()); + assert_equal(std::string(s_app_version), run.release, "the report names the release"); + assert_equal(std::string(g_app_build), run.build, "and the build"); + assert_equal(true, run.reports, "and that the run reports"); + assert_equal(true, df::crash_report_text().size() < platform::max_crash_report_text, "in the room there is for it"); + + command_line.profile_folder = "a profile of its own"; + assert_equal(false, df::run_reports_to_diffractor(), "a run with a profile of its own reports nothing"); + assert_equal(false, df::read_crashed_run(df::crash_report_text()).reports, "and says so in its report"); + command_line.profile_folder.clear(); + + command_line.agent.session = true; + df::network_allowed = false; + assert_equal(false, df::run_reports_to_diffractor(), "nor does an agent session without the network"); + df::network_allowed = true; + assert_equal(true, df::run_reports_to_diffractor(), "while one that was given it reports as any run does"); + + const auto none = df::read_crashed_run(""); + assert_equal(true, none.release.empty() && none.build.empty() && none.reports, + "no text names no run, and is not a report that was declined"); + assert_equal(false, df::read_crashed_run("Reports: no\nRelease: 1.0").reports, "though it can say none is sent"); +} + +static void should_decide_what_becomes_of_a_crash_report() +{ + using df::crash_report_fate; + const df::crashed_run reporting{.release = "127.4", .build = "1316", .reports = true}; + const df::crashed_run silent{.release = "127.4", .build = "1316", .reports = false}; + const df::crash_report_policy ready{.run_may_report = true, .user_allows = true, .online = true}; + + assert_equal(true, df::decide_crash_report_fate(reporting, ready) == crash_report_fate::send, "it is sent"); + assert_equal(true, df::decide_crash_report_fate(silent, ready) == crash_report_fate::remove, + "unless the run that crashed reported nothing, which Windows would not have either"); + + auto declined = ready; + declined.user_allows = false; + assert_equal(true, df::decide_crash_report_fate(reporting, declined) == crash_report_fate::remove, + "or the user has turned crash reports off, which drops it"); + + auto offline = ready; + offline.online = false; + assert_equal(true, df::decide_crash_report_fate(reporting, offline) == crash_report_fate::keep, + "or there is no network, which keeps it for a start that has"); + + // A run with a profile of its own, or an agent session with no network, has settings of its own that say nothing of + // what the user wants: the report waits for a run that is theirs, whatever those settings say. + auto borrowed = ready; + borrowed.run_may_report = false; + assert_equal(true, df::decide_crash_report_fate(reporting, borrowed) == crash_report_fate::keep, + "a run that may not report keeps it for one that may"); + borrowed.user_allows = false; + assert_equal(true, df::decide_crash_report_fate(reporting, borrowed) == crash_report_fate::keep, + "whatever its own setting says"); + assert_equal(true, df::decide_crash_report_fate(silent, borrowed) == crash_report_fate::remove, + "though a report no run could send is dropped by any"); +} + +static void should_send_a_crash_report_once_and_remove_it() +{ + const no_previous_log no_log; + const auto db_path = test_temps.next_path(); + crash_files_db files(db_path, crash_files_db::release_tag(s_app_version)); + const auto report = crash_report_of_a_run(s_app_version); + crash_server server; + + df::collect_crash_reports(files, {report}, {.run_may_report = true, .user_allows = true}); + assert_equal(true, files.is_known_crash_file(test_files_folder().combine_file("Test.jpg")), + "what the report says was open is skipped before anything is sent"); + assert_equal(0, server.posts, "and nothing is sent yet"); + + assert_equal(1_z, df::send_collected_crash_reports(), "the report is sent"); + assert_equal(1, server.posts, "to the server once"); + assert_equal("/crash", server.path, "at the address crashes go to"); + assert_equal("Diffractor CRASH report", server.subject, "under the subject of a crash"); + assert_equal("crash.zip", server.file_name, "as the zip a crash is"); + assert_equal(std::string(s_app_version), server.version, "naming the release that crashed"); + assert_equal("1316", server.build, "and its build"); + assert_equal(!crash_reports_are_removed, platform::exists(report.path), "and the report is gone once it is sent"); + + assert_equal(0_z, df::send_collected_crash_reports(), "a second start of the flow sends nothing"); + assert_equal(1, server.posts, "to nobody"); + + assert_equal(true, + server.message.find("Release: ") != std::string::npos && + server.message.find("Id: 0badf00d") != std::string::npos, + "the message carries what the run said of itself"); + assert_equal(true, server.message.find("Crash: SIGSEGV (SEGV_MAPERR) at 0x0") != std::string::npos, + "and what the signal was"); + assert_equal(true, server.message.find("Thread: thumbnail_decode") != std::string::npos, "on which thread"); + assert_equal(true, server.message.find("Running: 85 seconds") != std::string::npos, "after how long"); + assert_equal(true, server.message.find("Build id: 8c7d00112233445566778899aabbccddeeff0011") != std::string::npos, + "of which binary, so its symbols can be found"); + assert_equal(true, + server.message.find("Open file .jpg in decode thumbnail source (faulting thread)") != + std::string::npos, + "and the type of the file the faulting thread had open, and the stage"); + assert_equal(true, server.message.find("Open file .jpg in queue_calc_perceptual_hashes\n") != std::string::npos, + "and of the files the others had"); + assert_equal(true, + server.message.find("Test.jpg") == std::string::npos && + server.message.find(std::string(test_files_folder().text())) == std::string::npos, + "but never a file's name, for the report is uploaded"); + + // The log of the crashed run is not there to send once this run has rotated it away, and nothing stands in for it. + assert_equal(static_cast(1), server.entries.size(), "the zip holds the report alone"); + const auto date = report.time.date(); + assert_equal(std::format("Diffractor-{}-1316-{:04}{:02}{:02}-{:02}{:02}{:02}.crash.txt", s_app_version, date.year, + date.month, date.day, date.hour, date.minute, date.second), + server.entries.empty() ? std::string{} : server.entries.front(), + "named as a crash's minidump is, for the release, build and time that crashed"); +} + +static void should_send_the_log_of_the_crashed_run_with_its_report() +{ + const auto saved_previous = platform::previous_log_path; + const core::scope_exit restore([&] { platform::previous_log_path = saved_previous; }); + + const auto report = crash_report_of_a_run(s_app_version); + const auto log = test_temps.next_path(".log"); + write_test_file(log, "the log the restart rotated to diffractor.previous.log"); + platform::previous_log_path = log; + const auto logged = [&](const uint64_t when) + { + platform::set_file_attributes(log, when); + crash_server server; + auto copy = report; + copy.path = test_temps.next_path(".txt"); + write_test_file(copy.path, "a report"); + df::send_crash_reports({copy}, {.run_may_report = true, .user_allows = true, .online = true}); + return server.entries; + }; + + const auto during = logged(report.time._i - 3 * core::date_t::intervals_per_second); + assert_equal(static_cast(2), during.size(), "a log last written while the run lived goes too"); + assert_equal(true, std::ranges::find(during, "diffractor.log") != during.end(), + "as the log of the crash, which is what the run before the restart's was called"); + + assert_equal(static_cast(1), logged(report.time._i + 600 * core::date_t::intervals_per_second).size(), + "one that was written after it died is a later run's, and is not sent as its"); + assert_equal(static_cast(1), logged(report.started._i - 600 * core::date_t::intervals_per_second).size(), + "nor is one that was last written before it began"); +} + +static void should_drop_keep_and_retry_crash_reports_as_the_run_decides() +{ + const df::crash_report_policy ready{.run_may_report = true, .user_allows = true, .online = true}; + + // What the server says decides whether it is tried again: not a transfer that failed, nor a server that could not. + for (const auto& [status, sent, kept] : std::vector>{{200, 1, false}, + {204, 1, false}, + {0, 0, true}, + {500, 0, true}, + {503, 0, true}, + {400, 0, false}, + {404, 0, false}}) + { + crash_server server; + server.status = status; + const auto report = crash_report_of_a_run(s_app_version); + assert_equal(sent, df::send_crash_reports({report}, ready), std::format("status {} is sent or not", status)); + assert_equal(1, server.posts, "the server was asked", std::to_string(status)); + assert_equal(kept || !crash_reports_are_removed, platform::exists(report.path), + std::format("status {} keeps the report or not", status)); + platform::delete_file(report.path); + } + + auto declined = ready; + declined.user_allows = false; + auto offline = ready; + offline.online = false; + auto borrowed = ready; + borrowed.run_may_report = false; + + struct how + { + std::string_view what; + df::crash_report_policy policy; + bool reports; + bool kept; + }; + + for (const auto& [what, policy, reports, kept] : {how{"the user turned crash reports off", declined, true, false}, + how{"the run that crashed reported nothing", ready, false, false}, + how{"there is no network", offline, true, true}, + how{"this run is not one that reports", borrowed, true, true}}) + { + crash_server server; + const auto report = crash_report_of_a_run(s_app_version, reports); + assert_equal(static_cast(0), df::send_crash_reports({report}, policy), "nothing is sent", what); + assert_equal(0, server.posts, "the network is not asked", what); + assert_equal(kept || !crash_reports_are_removed, platform::exists(report.path), + "and the report is kept or dropped as it should be", what); + platform::delete_file(report.path); + } +} + +#ifndef _WIN32 +static void should_read_the_report_a_linux_run_left_and_send_it() +{ + const no_previous_log no_log; + const auto epoch_offset = static_cast(core::date_t::offset_1970 / core::date_t::intervals_per_second); + const auto now = static_cast(core::utc_now().to_seconds()) - epoch_offset; + const auto text = std::format("Release: {}\nBuild: 1316\nReports: yes\nVersion: {}.1316", s_app_version, + s_app_version); + const auto first = test_files_folder().combine_file("Test.jpg"); + const auto work = std::format("decode thumbnail source\t{}", first); + const std::string other_work = "scan\t/home/me/other.jpg"; + const auto planted = std::format( + "libdesktop crash report 1\napplication: Diffractor\nexecutable: /opt/diffractor/diffractor\n" + "kernel: Linux 6.1 x86_64\nbuild-id: 0123abcd\nload-base: 0x55d0c0000000\nstarted: {}\nprocess: 4242\n" + "time: {}\nuptime: 60\nsignal: 11 SIGSEGV\ncode: 1 SEGV_MAPERR\naddress: 0x0000000000000008\nthread: 4243\n" + "thread-name: thumbnail_decode\n-- text {}\n{}\n-- work 4243 {}\n{}\n-- work 4244 {}\n{}\n" + "-- backtrace\n./diffractor(+0x1234)[0x55d0c0001234]\n-- end\n", + now - 60, now, text.size(), text, work.size(), work, other_work.size(), other_work); + + const auto path = planted_crash_report_path(); + write_test_file(path, planted); + const auto report = platform::read_crash_report(path); + assert_equal(true, report.has_value(), "a report libdesktop wrote is read"); + if (!report) return; + + assert_equal(true, report->complete, "whole"); + assert_equal(4243, static_cast(report->thread), "it names the thread that faulted"); + assert_equal(static_cast(2), report->work.size(), "and the work in flight"); + + const auto db_path = test_temps.next_path(); + crash_files_db files(db_path, crash_files_db::release_tag(s_app_version)); + crash_server server; + df::collect_crash_reports(files, {*report}, {.run_may_report = true, .user_allows = true}); + assert_equal(true, files.is_known_crash_file(first), "the file the faulting thread had open is skipped"); + assert_equal(false, files.is_known_crash_file(core::file_path("/home/me/other.jpg")), + "and the one another thread had is not"); + + assert_equal(1_z, df::send_collected_crash_reports(), "the report is sent"); + assert_equal(1, server.posts, "once"); + assert_equal(std::string(s_app_version), server.version, "for the release the report names"); + assert_equal(true, server.message.find("Crash: SIGSEGV (SEGV_MAPERR) at 0x8") != std::string::npos, + "and says what happened"); + assert_equal(false, platform::exists(path), "and the report is removed, since it is the run's to remove"); +} +#endif +#endif + static duplicate_report_test_photo duplicate_report_photo(const std::string_view name, const uint64_t created_key, const uint64_t hash) { @@ -6976,49 +7318,6 @@ static void should_offer_library_types_for_collection_folders() } } -// The bars right-align their parts and give what is left to the title or the status. Short of room, -// a bar gives up what is optional, then narrows what can narrow, and then drops whole parts from the -// leading end - the trailing end, where the commands are, is the last to go, and the last part -// standing is clipped rather than lost. -static void should_arrange_a_bar_from_its_trailing_end() -{ - constexpr recti bounds(10, 0, 410, 40); - constexpr auto gap = 4; - const std::vector slots = { - {{100, 20}, 0, true}, // optional, like the thumbnail size - {{150, 30}, 80}, // narrows, like the filter box - {{120, 36}}, // fixed, like a toolbar - }; - - const auto roomy = arrange_bar(bounds, slots, gap); - assert_equal(true, roomy.slots[2] == recti(290, 2, 410, 38), "the last slot ends the bar, centred in it"); - assert_equal(true, roomy.slots[1] == recti(136, 5, 286, 35), "the one before it sits a gap to its left"); - assert_equal(true, roomy.slots[0] == recti(32, 10, 132, 30), "and so on, in declared order"); - assert_equal(true, roomy.remainder == recti(10, 0, 28, 40), "the leading end keeps what is left"); - - const auto tight = arrange_bar(recti(10, 0, 310, 40), slots, gap); - assert_equal(true, tight.slots[0].is_empty(), "an optional slot is the first given up"); - assert_equal(150, tight.slots[1].width(), "while the others still fit at their size"); - assert_equal(true, tight.slots[2] == recti(190, 2, 310, 38), "and the trailing slot has not moved"); - - const auto tighter = arrange_bar(recti(10, 0, 220, 40), slots, gap); - assert_equal(true, tighter.slots[0].is_empty(), "the optional slot stays given up"); - assert_equal(86, tighter.slots[1].width(), "a narrowing slot gives up width next"); - assert_equal(120, tighter.slots[2].width(), "before the trailing slot loses any"); - assert_equal(0, tighter.remainder.width(), "nothing is left for the status"); - - const auto cramped = arrange_bar(recti(10, 0, 150, 40), slots, gap); - assert_equal(true, cramped.slots[1].is_empty(), "past its minimum a leading slot goes whole"); - assert_equal(true, cramped.slots[2] == recti(30, 2, 150, 38), "so the trailing slot still fits whole"); - - const auto clipped = arrange_bar(recti(10, 0, 70, 40), slots, gap); - assert_equal(60, clipped.slots[2].width(), "a lone slot wider than the bar is cut to the bar"); - assert_equal(true, clipped.slots[2].right == 70, "from its leading end"); - - const auto empty = arrange_bar(bounds, {}, gap); - assert_equal(true, empty.remainder == bounds, "a bar with nothing declared is all remainder"); -} - // A run of a view's own commands short of room gives way from its leading end into a More menu, so the command // that ends it - here Movie's Render - stays on the bar; given the room again, the run shows whole. static void should_keep_a_short_status_bar_s_last_command() @@ -7060,41 +7359,12 @@ static void should_keep_a_short_status_bar_s_last_command() assert_equal(true, app->_bar_overflow.empty(), "given the room again, nothing is left over"); } -// The status bar starts from both ends. What a view starts it with is arranged from the leading end, -// in the room its trailing controls leave, by the same rules mirrored: short of room, the part -// furthest from the end it starts from goes first. A part with nothing to show takes no room, not -// even the gap beside it. -static void should_arrange_a_bar_from_its_leading_end() -{ - constexpr recti bounds(10, 0, 410, 40); - constexpr auto gap = 4; - const std::vector slots = { - {{120, 36}}, // a toolbar, like the one Items starts its status bar with - {{0, 0}}, // nothing to show - {{150, 30}}, // text, like the totals - }; - - const auto roomy = arrange_bar(bounds, slots, gap, bar_alignment::leading); - assert_equal(true, roomy.slots[0] == recti(10, 2, 130, 38), "the first slot starts the bar, centred in it"); - assert_equal(true, roomy.slots[1].is_empty(), "a slot with nothing to show is not placed"); - assert_equal(true, roomy.slots[2] == recti(134, 5, 284, 35), "so the next sits one gap after the first"); - assert_equal(true, roomy.remainder == recti(288, 0, 410, 40), "and the trailing end keeps what is left"); - - const auto cramped = arrange_bar(recti(10, 0, 200, 40), slots, gap, bar_alignment::leading); - assert_equal(true, cramped.slots[2].is_empty(), "short of room the slot furthest from the start goes"); - assert_equal(true, cramped.slots[0] == recti(10, 2, 130, 38), "while the first keeps its place"); - - const auto trailing = arrange_bar(bounds, slots, gap); - assert_equal(true, trailing.slots[1].is_empty(), "nor is one at the trailing end"); - assert_equal(true, trailing.slots[0] == recti(136, 2, 256, 38), "which leaves no gap for it either"); -} - // design.md "Navigation and search" specifies the address box as an editing session with a // committed address, a typed draft and a previewed completion. The two-stage Escape is the part a // user notices: losing it either throws away what they typed or traps them in the popup. static void should_run_an_address_editing_session() { - search_edit_session session; + ui::completion_session session; session.begin("c:\\photos"); assert_equal("c:\\photos", session.original_text(), "focusing snapshots the committed address"); @@ -7107,7 +7377,7 @@ static void should_run_an_address_editing_session() assert_equal("c:\\photos", session.original_text(), "typing does not disturb the committed address"); // Up and Down preview a completion without changing the draft. - session.preview("beach"); + session.preview(); assert_equal(true, session.is_previewing(), "a highlighted completion is previewing"); assert_equal("bea", session.typed_text(), "previewing leaves the draft alone"); @@ -7139,10 +7409,10 @@ static void should_run_an_address_editing_session() // refreshes completions, keeps the popup open, and retains address focus." static void should_accept_a_completion_without_running_it() { - search_edit_session session; + ui::completion_session session; session.begin("c:\\photos"); session.typed("bea"); - session.preview("beach"); + session.preview(); const auto accepted = session.accept(true, "beach "); assert_equal(true, accepted.handled, "tab with a highlighted completion is handled"); @@ -7155,11 +7425,11 @@ static void should_accept_a_completion_without_running_it() assert_equal("beach ", session.typed_text(), "the accepted completion becomes the draft"); assert_equal(false, session.is_previewing(), "accepting ends the preview"); - session.preview("beach huts"); + session.preview(); assert_equal("beach ", session.escape().edit_text, "escape after tab returns to the accepted draft"); // With nothing highlighted, Tab is not ours to handle - it must fall through to focus traversal. - search_edit_session untouched; + ui::completion_session untouched; untouched.begin("c:\\photos"); const auto ignored = untouched.accept(false, {}); assert_equal(false, ignored.handled, "tab without a completion is not handled"); @@ -7171,10 +7441,10 @@ static void should_accept_a_completion_without_running_it() // it for the address. The draft the user actually typed has to come back with them. static void should_restore_the_draft_when_a_previewing_session_ends() { - search_edit_session session; + ui::completion_session session; session.begin("c:\\photos"); session.typed("bea"); - session.preview("beach huts"); + session.preview(); const auto ended = session.end(); assert_equal(true, ended.set_edit_text, "ending while previewing puts the box back"); @@ -7182,16 +7452,16 @@ static void should_restore_the_draft_when_a_previewing_session_ends() assert_equal(false, session.is_previewing(), "the preview is over"); // Nothing to undo when no preview was showing: the box already holds what the user typed. - search_edit_session typed_only; + ui::completion_session typed_only; typed_only.begin("c:\\photos"); typed_only.typed("bea"); assert_equal(false, typed_only.end().set_edit_text, "ending without a preview leaves the box alone"); // And accepting a completion makes it the draft, so ending after that keeps it. - search_edit_session accepted; + ui::completion_session accepted; accepted.begin("c:\\photos"); accepted.typed("bea"); - accepted.preview("beach"); + accepted.preview(); accepted.accept(true, "beach "); assert_equal(false, accepted.end().set_edit_text, "an accepted completion is the draft and stays"); } @@ -7200,7 +7470,7 @@ static void should_restore_the_draft_when_a_previewing_session_ends() // the visible address." static void should_commit_the_highlighted_completion_or_the_visible_address() { - search_edit_session session; + ui::completion_session session; session.begin("c:\\photos"); session.typed("bea"); @@ -7209,7 +7479,7 @@ static void should_commit_the_highlighted_completion_or_the_visible_address() "enter commits the visible address when nothing is highlighted"); // A preview shows in the address box, so committing with no selection still runs what is visible. - session.preview("beach"); + session.preview(); assert_equal("beach", session.commit(false, {}, "beach"), "enter runs the address the user can see"); } @@ -7724,7 +7994,7 @@ static void should_deliver_address_portraits_without_replacing_the_prediction() as.drain_ui(); int repaints = 0; - const auto completes = make_search_auto_complete(state, [](std::string) {}, [&] { ++repaints; }); + const auto completes = make_search_auto_complete(state, [](const std::string&) {}, [&] { ++repaints; }); const auto run = [&] { std::shared_ptr row; @@ -8271,39 +8541,6 @@ static void should_report_movie_projects_as_json() assert_equal(2, projects[1]["unreadable_lines"][0]["line"].GetInt(), "by its number"); } -// -tool: takes name=value pairs, each read as the tool's schema types it, so a call from the command line -// reaches the tool with the arguments a client would send. -static void should_type_a_tool_call_s_arguments() -{ - constexpr auto schema = - R"({"type":"object","properties":{"path":{"type":"string"},"count":{"type":"integer"},"scale":{"type":"number"},"overwrite":{"type":"boolean"},"names":{"type":"array","items":{"type":"string"}},"checks":{"type":"object"}}})"sv; - - std::string error; - const auto arguments = tool_arguments_json(schema, - {"path=C:\\a b\\c=d.dfv", "count=3", "scale=0.5", "overwrite=yes", - "names=a.jpg,b.jpg", R"(checks={"Keep":true})", "other=7"}, - error); - assert_equal(std::string{}, error, "every pair reads"); - - rapidjson::Document json; - json.Parse(arguments.c_str()); - assert_equal(true, json.IsObject(), "the arguments are an object"); - assert_equal("C:\\a b\\c=d.dfv"s, std::string(json["path"].GetString()), "the first = ends the name"); - assert_equal(3, json["count"].GetInt(), "an integer"); - assert_equal(0.5, json["scale"].GetDouble(), "a number"); - assert_equal(true, json["overwrite"].GetBool(), "yes is true"); - assert_equal(2_z, static_cast(json["names"].Size()), "a list is split at its commas"); - assert_equal(true, json["checks"]["Keep"].GetBool(), "an object is given as JSON"); - assert_equal("7"s, std::string(json["other"].GetString()), "a name the schema has not is text, which it refuses"); - - error.clear(); - tool_arguments_json(schema, {"count=three"}, error); - assert_equal(false, error.empty(), "a number that is not one is refused"); - error.clear(); - tool_arguments_json(schema, {"overwrite"}, error); - assert_equal(false, error.empty(), "and a pair without its ="); -} - // An agent's Save in the Edit view was answered as soon as the window caught up: the dialog saying the save was under // way read as a question to answer, and wait_until_idle as idle, while the file was still being written. A dialog // showing work is waited out, and says what it waits on; one that asks is answered. @@ -8315,52 +8552,32 @@ static void should_wait_out_a_dialog_that_shows_work_under_way() bool is_canceled() const override { return false; } }; - const auto work_before = dialogs_showing_work().size(); - const auto asked_before = dialog_awaits_answer(); + const auto app = std::make_shared(); + diffractor_agent hooks(*app); + const auto host = std::make_shared(hooks, ui::agent_options{}, true); + const auto busy_before = host->busy().size(); + const auto asked_before = host->answerable_ui_open(); { const auto saving = make_dlg(ui::no_frame()); saving->_frame = std::make_shared(); saving->show_status(icon_index::save, "Saving photo.avif..."sv); - const auto work = dialogs_showing_work(); - assert_equal(work_before + 1, work.size(), "a status shows work under way"); - assert_equal("Saving photo.avif..."s, work.back(), "and says what it is"); - assert_equal(asked_before, dialog_awaits_answer(), "with nothing to answer"); + const auto busy = host->busy(); + assert_equal(busy_before + 1, busy.size(), "a status shows work under way"); + assert_equal("Saving photo.avif..."s, busy.back(), "and says what it is"); + assert_equal(asked_before, host->answerable_ui_open(), "with nothing to answer"); const auto asking = make_dlg(ui::no_frame()); asking->_frame = std::make_shared(); asking->show_controls({std::make_shared(asking->_frame)}, {44}, {44}); asking->list_as_open(); - assert_equal(true, dialog_awaits_answer(), "a dialog that asks is answered"); - assert_equal(work_before + 1, dialogs_showing_work().size(), "and is no work to wait out"); + assert_equal(true, host->answerable_ui_open(), "a dialog that asks is answered"); + assert_equal(busy_before + 1, host->busy().size(), "and is no work to wait out"); } - assert_equal(work_before, dialogs_showing_work().size(), "the work is not waited on once its dialog has gone"); - assert_equal(asked_before, dialog_awaits_answer(), "nor the question"); -} - -// What -mcp-ui and -mcp-allow ask of a session. What is not understood is reported, not guessed at, and nothing -// beyond reading is allowed unless asked for. -static void should_read_an_agent_session_s_options() -{ - const auto options = parse_agent_options("visible", "write, capture,dev"); - assert_equal(true, options.presence == agent_presence::visible, "the window on the desktop"); - assert_equal(true, options.allow.write && options.allow.capture && options.allow.dev, "each tier asked for"); - assert_equal(false, options.allow.network || options.allow.launch, "and no other"); - assert_equal(true, options.problems.empty(), "spaces round a tier are allowed"); - assert_equal(true, parse_agent_options({}, "launch").allow.launch, "opening other programs is a tier of its own"); - - const auto plain = parse_agent_options({}, {}); - assert_equal(true, plain.presence == agent_presence::none, "no window until a tool needs one"); - assert_equal(false, - plain.allow.write || plain.allow.capture || plain.allow.network || plain.allow.dev || - plain.allow.launch, - "reading alone"); - - const auto wrong = parse_agent_options("hidden", "write,everything"); - assert_equal(2_z, wrong.problems.size(), "what is not understood is reported"); - assert_equal(true, wrong.presence == agent_presence::none && wrong.allow.write, "and what is understood is kept"); + assert_equal(busy_before, host->busy().size(), "the work is not waited on once its dialog has gone"); + assert_equal(asked_before, host->answerable_ui_open(), "nor the question"); } // What an agent session writes to the settings lasts as long as it does: it reads what is kept, and the user's next @@ -8445,6 +8662,110 @@ static core::file_path write_tone_wave(const double seconds) return path; } +// The pointer a tutorial's script shows glides to where it is sent, eased as a hand moves a mouse; the first place it +// is sent is where it appears, with nothing to glide from. A click spreads a ring from the pointer's tip that fades out +// in a moment, and none is made for a pointer that is not shown. +static void should_glide_the_scripted_pointer_and_spread_a_ring_for_a_click() +{ + recording_script script; + assert_equal(false, script.current().pointer.shown, "no pointer is shown until a script sends one"); + assert_equal(false, script.current().ring(1.0, 48).has_value(), "and no ring"); + + script.pointer(pointi{100, 50}, 1.0, 2.0); + assert_equal(true, script.current().pointer.at(2.0) == pointi{100, 50}, "it appears where it is first sent"); + + script.pointer(pointi{300, 150}, 1.0, 3.0); + const auto view = script.current(); + assert_equal(true, view.pointer.at(2.9) == pointi{100, 50}, "it stays where it was until it is sent"); + assert_equal(true, view.pointer.at(3.5) == pointi{200, 100}, "and is half way when the glide is half done"); + assert_equal(true, view.pointer.at(4.0) == pointi{300, 150}, "and where it was sent when it is done"); + assert_equal(true, view.pointer.at(9.0) == pointi{300, 150}, "and stays"); + assert_equal(true, view.pointer.at(3.25).x < 150 && view.pointer.at(3.75).x > 250, "easing in and out"); + + script.click(5.0); + const auto clicked = script.current(); + assert_equal(false, clicked.ring(4.99, 48).has_value(), "a click has no ring before it is made"); + const auto early = clicked.ring(5.1, 48); + const auto late = clicked.ring(5.4, 48); + assert_equal(true, early.has_value() && late.has_value(), "it spreads a ring for a moment"); + + if (early && late) + { + assert_equal(true, early->center == pointi{300, 150}, "from the pointer's tip"); + assert_equal(true, late->radius > early->radius, "wider as it goes"); + assert_equal(true, late->opacity < early->opacity && late->opacity > 0.0, "and fainter"); + assert_equal(true, early->bounds().width() > early->radius * 2.0, "the bounds hold the whole ring"); + } + + assert_equal(false, clicked.ring(5.0 + click_ring_seconds, 48).has_value(), "and is gone when its time is up"); + + script.pointer(std::nullopt, 0.0, 6.0); + assert_equal(false, script.current().ring(5.1, 48).has_value(), "a hidden pointer makes no ring"); +} + +// The ring and the pointer are drawn over what is under them, and nowhere else, whatever the frame's edge. +static void should_draw_the_scripted_pointer_and_a_click_ring_into_a_frame() +{ + const auto frame = std::make_shared(); + frame->alloc(200, 120, core::texture_format::RGB); + frame->make_blank(); + + const auto sum = [&frame](const recti block) + { + auto total = 0; + + for (auto y = block.top; y < block.bottom; ++y) + { + for (auto x = block.left; x < block.right; ++x) + { + for (auto c = 0; c < 3; ++c) total += frame->pixels_line(y)[x * 4 + c]; + } + } + + return total; + }; + const auto green = [&frame](const int x, const int y) + { + return static_cast(frame->pixels_line(y)[x * 4 + 1]); + }; + + click_ring ring; + ring.center = {100, 60}; + ring.radius = 20.0; + ring.thickness = 4.0; + ring.opacity = 1.0; + draw_click_ring(*frame, ring); + assert_equal(true, sum({118, 58, 124, 62}) > 0, "the ring is drawn on its circle"); + assert_equal(0, sum({98, 58, 102, 62}), "and not inside it"); + assert_equal(0, sum({0, 0, 40, 20}), "nor far from it"); + + ring.center = {-10, 200}; + draw_click_ring(*frame, ring); + + frame->make_blank(); + draw_pointer_arrow(*frame, {20, 10}, 48); + assert_equal(true, green(22, 18) > 200, "the arrow's body is white"); + assert_equal(true, green(19, 14) > 0 && green(19, 14) < 100, "with a dark edge round it"); + assert_equal(0, sum({100, 80, 140, 110}), "and nothing else is drawn"); + + draw_pointer_arrow(*frame, {-5, -5}, 48); + draw_pointer_arrow(*frame, {195, 115}, 48); +} + +// The moments a script names are written beside its movie, one `` a line, ending with the movie's +// own end: what a narration is laid to. +static void should_write_the_moments_a_script_names_beside_its_movie() +{ + recording_script script; + script.mark("intro", 0.0); + script.mark("the second thing", 4.256); + + const auto movie = test_temps.next_path(".mp4"); + assert_equal(true, script.write_markers(movie, 9.5), "the markers are written"); + assert_equal("0.000\tintro\n4.256\tthe second thing\n9.500\tend\n"s, + read_test_file(screen_recording_markers_path(movie)), "a line for each, and the end"); +} + // A photo has no sound of its own; given a sound file, the movie carries that sound while the photo shows. The // render opens the sound apart from the picture, so asking for the sound first still leaves the photo to draw. static void should_render_a_clips_sound_file() @@ -8774,8 +9095,6 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) tests.add("Should skip existing Movie batch outputs"s, should_skip_existing_movie_batch_outputs); tests.add("Should render a Movie project only as written"s, should_render_a_movie_project_only_as_written); tests.add("Should report Movie projects as JSON"s, should_report_movie_projects_as_json); - tests.add("Should type a tool call's arguments"s, should_type_a_tool_call_s_arguments); - tests.add("Should read an agent session's options"s, should_read_an_agent_session_s_options); tests.add("Should wait out a dialog that shows work under way"s, should_wait_out_a_dialog_that_shows_work_under_way); tests.add("Should keep an agent session's settings to itself"s, should_keep_an_agent_session_s_settings_to_itself); @@ -8784,6 +9103,12 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) should_refuse_a_movie_output_claimed_during_render); tests.add("Should render a Movie clip's sound file"s, should_render_a_clips_sound_file); tests.add("Should render each Movie item as a Short"s, should_render_each_movie_item_as_a_short); + tests.add("Should glide a recording's scripted pointer and spread a ring for a click"s, + should_glide_the_scripted_pointer_and_spread_a_ring_for_a_click); + tests.add("Should draw a recording's scripted pointer and click ring into a frame"s, + should_draw_the_scripted_pointer_and_a_click_ring_into_a_frame); + tests.add("Should write a recording's markers beside its movie"s, + should_write_the_moments_a_script_names_beside_its_movie); tests.add("Should read a tutorial script"s, should_read_a_tutorial_script); tests.add("Should read a script's pointer and keyboard steps"s, should_read_a_script_s_pointer_and_keyboard_steps); tests.add("Should invoke link commands and selection shortcuts"s, @@ -8794,16 +9119,6 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) tests.add("Should honor no-indexing for collection updates"s, should_honor_no_indexing_for_collection_updates); tests.add("INI file settings should persist values"s, should_persist_to_ini_file); tests.add("Should drop damaged recent entries"s, should_drop_damaged_recent_entries); -#ifndef _WIN32 - // PLAT-010 - Linux INI writes published values before the file was durably replaced. - tests.add("Should commit Linux INI file settings after durable save"s, - should_commit_linux_ini_file_settings_after_durable_save); - // G21 review - unchanged settings values should not restage and fsync the whole file. - tests.add("Should skip unchanged Linux INI file settings"s, should_skip_unchanged_linux_ini_file_settings); - // G21 review - each settings save needs its own stage path. - tests.add("Should commit Linux INI file settings from owned stage"s, - should_commit_linux_ini_file_settings_from_owned_stage); -#endif tests.add("Should store an order an older build can read"s, should_store_an_order_an_older_build_can_read); tests.add("Should Rename with substitutions"s, should_rename_with_substitutions); tests.add("Should rename name token without extension"s, should_rename_name_token_without_extension); @@ -8892,9 +9207,6 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) should_prepare_shared_copies_under_their_own_names); tests.add("Should adjust item dates from snapshot"s, should_adjust_item_dates_from_snapshot); tests.add("Should round trip the environment mask"s, should_round_trip_the_environment_mask); -#ifdef _WIN32 - tests.add("Should classify MAPI results"s, should_classify_mapi_results); -#endif tests.add("Should detect duplicate import destinations"s, should_detect_duplicate_import_destinations); tests.add("Should revalidate import rows"s, should_revalidate_import_rows); tests.add("Should revalidate import sidecars"s, should_revalidate_import_sidecars); @@ -9055,9 +9367,7 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) tests.add("Should pause media while the options view shows"s, should_pause_media_while_the_options_view_shows); tests.add("Should ask before leaving options with changes"s, should_ask_before_leaving_options_with_changes); tests.add("Should offer library types for collection folders"s, should_offer_library_types_for_collection_folders); - tests.add("Should arrange a bar from its trailing end"s, should_arrange_a_bar_from_its_trailing_end); tests.add("Should keep a short status bar's last command"s, should_keep_a_short_status_bar_s_last_command); - tests.add("Should arrange a bar from its leading end"s, should_arrange_a_bar_from_its_leading_end); tests.add("Should summarise the selection for the status bar"s, should_summarise_the_selection_for_the_status_bar); // @@ -9135,6 +9445,24 @@ void register_app_tests(view_state& /*state*/, test_registry& tests) // Issue #256 - a collection folder lost a letter, and every folder after the first, at a restart. tests.add("Should keep collection folders across a restart"s, should_keep_collection_folders_across_a_restart); tests.add("Should record crashes"s, should_record_crashes); +#ifndef WINSTORE + // A run that was ended by a fatal signal (Linux) leaves a report, which the next start deals with. + tests.add("Should record the files a crash report names"s, should_record_the_files_a_crash_report_names); + tests.add("Should record the crash files of this release line only"s, + should_record_the_crash_files_of_this_release_line_only); + tests.add("Should say what a crash report may tell of the run"s, + should_say_what_a_crash_report_may_tell_of_the_run); + tests.add("Should decide what becomes of a crash report"s, should_decide_what_becomes_of_a_crash_report); + tests.add("Should send a crash report once and remove it"s, should_send_a_crash_report_once_and_remove_it); + tests.add("Should send the log of the crashed run with its report"s, + should_send_the_log_of_the_crashed_run_with_its_report); + tests.add("Should drop, keep and retry crash reports as the run decides"s, + should_drop_keep_and_retry_crash_reports_as_the_run_decides); +#ifndef _WIN32 + tests.add("Should read the report a Linux run left and send it"s, + should_read_the_report_a_linux_run_left_and_send_it); +#endif +#endif // APP-013 - bucket size is not an unset global photo index. tests.add("Should anchor duplicate report sets"s, should_anchor_duplicate_report_sets); // APP-014 - requested output errors are command failures, not stdout fallback. diff --git a/src/test_av.cpp b/src/test_av.cpp index 443e7942..a459b46b 100644 --- a/src/test_av.cpp +++ b/src/test_av.cpp @@ -21,7 +21,7 @@ #include "av_sound.h" #include "av_visualizer.h" #include "files.h" -#include "machine.h" +#include "lib64/machine.h" #include "model.h" #include "model_display.h" #include "model_faces.h" @@ -4595,18 +4595,20 @@ static void should_name_sid_notes_and_waveforms() // The Commodore 64 the media pane runs // -// Whether the machine's text screen shows the text, which is upper-case ASCII. -static bool c64_screen_shows(const machine& m, const std::string_view text) +// Whether the machine's text screen, at $0400, shows the text, which is upper-case ASCII. +static bool c64_screen_shows(const lib64::machine& m, const std::string_view text) { - const auto* const screen = m._state->RAM + 0x0400; + std::array screen{}; + for (size_t i = 0; i < screen.size(); ++i) screen[i] = m.peek(static_cast(0x0400 + i)); + const auto screen_code = [](const char c) { return static_cast(c >= 'A' && c <= 'Z' ? c - 'A' + 1 : c); }; - for (size_t at = 0; at + text.size() <= 1000; ++at) + for (size_t at = 0; at + text.size() <= screen.size(); ++at) { - if (std::equal(text.begin(), text.end(), screen + at, + if (std::equal(text.begin(), text.end(), screen.begin() + static_cast(at), [&](const char c, const uint8_t s) { return (s & 0x7F) == screen_code(c); })) return true; } @@ -4616,7 +4618,7 @@ static bool c64_screen_shows(const machine& m, const std::string_view text) // Runs a session's frames as its worker does while a program loads - unpaced and unheard, publishing every // eighth picture - until the screen shows the text or the frames run out. -static bool run_c64_until(c64_session& session, machine& m, const std::string_view text, const int frames) +static bool run_c64_until(c64_session& session, lib64::machine& m, const std::string_view text, const int frames) { std::vector pcm(c64_session::max_frame_samples); @@ -4653,7 +4655,7 @@ static void should_run_a_commodore_64_disks_program() ".d64"); c64_session session(path, c64_name("HELLO")); - machine m; + lib64::machine m; assert_equal(true, session.boot(m), "the disk boots"); m.set_render_enabled(true); assert_equal(true, run_c64_until(session, m, "HI FROM THE DISK", 1000), "the program the row names runs"); @@ -4666,7 +4668,7 @@ static void should_run_a_commodore_64_disks_program() picture && picture->dimensions() == sizei(c64_session::picture_width, c64_session::picture_height), "each the whole of the screen and its border"); - machine untouched; + lib64::machine untouched; assert_equal(false, c64_session(path, c64_name("GONE")).boot(untouched), "a name the disk does not hold"); assert_equal(false, c64_session(test_temps.next_path(".d64"), {}).boot(untouched), "an empty file"); } @@ -4679,7 +4681,7 @@ static void should_run_a_commodore_64_program_file_and_tape() { const auto path = write_c64_test_file(make_test_c64_program("HI FROM THE FILE"), ".prg"); c64_session session(path, {}); - machine m; + lib64::machine m; assert_equal(true, session.boot(m), "a program file boots"); assert_equal(true, run_c64_until(session, m, "HI FROM THE FILE", 1000), "and runs"); } @@ -4692,7 +4694,7 @@ static void should_run_a_commodore_64_program_file_and_tape() p00.insert(p00.end(), program.begin(), program.end()); c64_session session(write_c64_test_file(p00, ".p00"), c64_name("my tape game")); - machine m; + lib64::machine m; assert_equal(true, session.boot(m), "a P00 boots"); assert_equal(true, run_c64_until(session, m, "HI FROM THE P00", 1000), "and runs the program it wraps"); } @@ -4732,7 +4734,7 @@ static void should_run_a_commodore_64_program_file_and_tape() // Lower case in a stored name is PETSCII's graphics, which a typed name would fold away. c64_session session(path, c64_name("Second")); - machine m; + lib64::machine m; assert_equal(true, session.boot(m), "a tape boots"); assert_equal(true, run_c64_until(session, m, "HI FROM THE TAPE", 1000), "and runs the file the row names"); assert_equal(false, c64_session(path, c64_name("SECOND")).boot(m), "matched as stored, nothing folded"); @@ -4743,16 +4745,13 @@ static void should_run_a_commodore_64_program_file_and_tape() // has them, and the rest are left to the application. Keys are let go once the keyboard reports them up. static void should_drive_a_commodore_64_from_the_keyboard() { - uint8_t rows[2] = {}; - uint8_t cols[2] = {}; - assert_equal(1, c64_matrix_keys(U'A', rows, cols), "a letter is one key"); - assert_equal(true, rows[0] == 1 && cols[0] == 2, "where the C64 has A"); - assert_equal(2, c64_matrix_keys(platform::keys::F2, rows, cols), "F2 is the C64's F1 with shift"); - assert_equal(true, rows[0] == 1 && cols[0] == 7 && rows[1] == 0 && cols[1] == 4, "left shift, then F1"); - assert_equal(0, c64_matrix_keys(platform::keys::F12, rows, cols), "F12 is not the C64's"); + assert_equal(true, c64_key(U'A') == lib64::key::a, "a letter is the C64's"); + assert_equal(true, c64_key(platform::keys::F2) == lib64::key::f2, + "F2 is the C64's, not the letter its key code shares a value with"); + assert_equal(false, c64_key(platform::keys::F12).has_value(), "F12 is not the C64's"); c64_session session(write_c64_test_file(make_test_c64_program("READY"), ".prg"), {}); - machine m; + lib64::machine m; assert_equal(true, session.boot(m), "the machine boots"); std::vector pcm(c64_session::max_frame_samples); const auto step = [&] @@ -4761,7 +4760,7 @@ static void should_drive_a_commodore_64_from_the_keyboard() }; const auto key_down = [&m](const int row, const int col) { - return (m._state->key_matrix[row] & (1 << col)) == 0; + return m.key_held(row, col); }; c64_keyboard keyboard; @@ -4769,27 +4768,30 @@ static void should_drive_a_commodore_64_from_the_keyboard() assert_equal(false, keyboard.press(session, platform::keys::F12, false), "others are the application's"); assert_equal(true, keyboard.press(session, platform::keys::UP, false), "the arrows are the joystick"); assert_equal(true, keyboard.press(session, platform::keys::UP, true), "and their repeats are swallowed"); + assert_equal(true, keyboard.press(session, platform::keys::F2, false), "a key the C64 types shifted is taken"); step(); assert_equal(true, key_down(1, 2), "A is held on the machine"); - assert_equal(0, m._state->joystick2 & 0x01, "up is held on the joystick in port 2"); - assert_equal(0x1F, m._state->joystick1 & 0x1F, "and nothing in port 1"); + assert_equal(true, key_down(1, 7) && key_down(0, 4), "F2 holds the left shift and F1"); + assert_equal(true, (m.joystick(2) & lib64::joystick_up) != 0, "up is held on the joystick in port 2"); + assert_equal(0, static_cast(m.joystick(1)), "and nothing in port 1"); // Nothing is held on the test's own keyboard, so every key reads as let go. keyboard.sync(session); step(); assert_equal(false, key_down(1, 2), "A is let go"); - assert_equal(0x1F, m._state->joystick2 & 0x1F, "and so is up"); + assert_equal(false, key_down(1, 7) || key_down(0, 4), "and both of F2's"); + assert_equal(0, static_cast(m.joystick(2)), "and so is up"); session.joystick_port(1); assert_equal(true, keyboard.press(session, platform::keys::SPACE, false), "Space is fire"); step(); - assert_equal(0, m._state->joystick1 & 0x10, "fired in port 1 once it is chosen"); - assert_equal(0x1F, m._state->joystick2 & 0x1F, "and not in port 2"); + assert_equal(true, (m.joystick(1) & lib64::joystick_fire) != 0, "fired in port 1 once it is chosen"); + assert_equal(0, static_cast(m.joystick(2)), "and not in port 2"); assert_equal(true, key_down(7, 4), "and the C64's space bar, for a game that waits for SPACE"); keyboard.release_all(session); step(); - assert_equal(0x1F, m._state->joystick1 & 0x1F, "leaving lets every key go"); + assert_equal(0, static_cast(m.joystick(1)), "leaving lets every key go"); assert_equal(false, key_down(7, 4), "the space bar too"); } diff --git a/src/test_faces.cpp b/src/test_faces.cpp index 5c4c2f72..4d6145ab 100644 --- a/src/test_faces.cpp +++ b/src/test_faces.cpp @@ -1088,6 +1088,60 @@ static void should_put_away_the_faces_of_pictures_the_index_no_longer_holds() assert_equal(1u, search.progress().done, "with nothing left to read"sv); } +// docs/faces.md#31-turning-it-on-and-off: a kind turned on while face search is on puts away what it holds and loads +// it again, and the scan reads the collection afresh - also where a pass was already waiting to run. That pass, for the +// session that was put away, reads nothing; it must not forget the pass the new session asked for while it waited. +static void should_scan_for_a_kind_turned_on_while_a_pass_waits_to_run() +{ + const auto folder = test_temps.next_folder("faces-turn-on-again"); + platform::copy_file(test_files_folder().combine_file("Test.jpg"), test_temps.next_path_in(folder, ".jpg"), false, + false); + + // The faces queue's thread runs a pass when it gets to it, which may be after the database's has loaded the + // records: here the passes wait for the test, and every other task runs at once. + class waiting_scans final : public null_async_strategy + { + public: + std::deque> scans; + + void queue_async(const async_queue q, const std::function f) override + { + if (q == async_queue::faces) scans.push_back(f); + else f(); + } + }; + + waiting_scans as; + const location_cache locations; + index_state index(as, locations); + core::index_roots roots; + roots.folders.emplace(folder); + index.index_roots(roots); + index.index_folders(test_token); + index.cache_load_complete(); + index.scan_uncached(test_token); + + auto& search = index.faces(); + search.configure(true, false, false); + search.loaded(); + // What turning videos on does: resumes, which asks for a pass, then asks for the other kind... + search.pause(false); + search.turn_on(true, true); + // ...and what the database's task does once it has loaded the records: its pass finds the first still waiting. + search.loaded(); + search.start_scan(); + + while (!as.scans.empty()) + { + const auto scan = std::move(as.scans.front()); + as.scans.pop_front(); + scan(); + } + + assert_equal(1u, search.progress().eligible, "the collection's picture is counted"sv); + assert_equal(1u, search.progress().done, "and read by the pass the new session asked for"sv); +} + // A video of `frames` a second apiece - each a picture of `extent`, or grey where there is none - written as YUV4MPEG2, // which FFmpeg reads with no encoder, every frame a key frame. static void write_y4m(const core::file_path path, const std::vector& frames, @@ -1478,11 +1532,12 @@ static void should_refuse_invalid_face_csv_without_changing_the_book() const auto before = book.to_csv(); const auto generation = book.generation(); auto persisted = false; - book.persist_to([&](faces::book_write) { persisted = true; }); + book.persist_to([&](const faces::book_write&) { persisted = true; }); const auto header = legacy_face_header(3); const auto person = "person,10,Alice,,,,,,,,,\r\n"s; const auto path = core::windows_path_semantics ? "C:\\Photos\\one.jpg"sv : "/photos/one.jpg"sv; const auto face = std::format("face,,,{},0.1,0.2,0.3,0.4,0,", path); + const auto valid = header + person; for (const auto& bad : {person, "person,20,aLiCe,,,,,,,,,\r\n"s, "group,10,2,,,,,,,,,\r\n"s, "person,20,\"unterminated,,,,,,,,,\r\n"s, "alias,99,Former,,,,,,,,,\r\n"s, "alias,10,aLiCe,,,,,,,,,\r\n"s, face + "99,0,\r\n", face + ",0,99\r\n", @@ -1491,7 +1546,7 @@ static void should_refuse_invalid_face_csv_without_changing_the_book() std::format("face,,,{},0.1,0.2,-0.3,0.4,0,,0,\r\n", path), std::format("face,,,{},0.1,0.2,0.3,0.4,256,,0,\r\n", path)}) { - const auto result = book.import_csv(header + person + bad); + const auto result = book.import_csv(valid + bad); assert_equal(true, !result.ok && !result.error.empty(), "malformed or inconsistent CSV refused"sv); } for (const char version : {'1', '9'}) @@ -2208,6 +2263,7 @@ namespace const auto piece = std::max(1, count / (static_cast(threads) * 8)); std::atomic_size_t next = 0; std::vector pool; + pool.reserve(static_cast(threads)); for (auto t = 0; t < threads; ++t) pool.emplace_back([&] { @@ -2337,6 +2393,7 @@ static void should_make_the_same_overview_on_one_thread_as_on_several() { recognition_fixture f; std::vector ids; + ids.reserve(6); for (auto p = 0; p < 6; ++p) ids.push_back(f.book.create(std::format("Person {}", p))); for (auto k = 0; k < 400; ++k) { @@ -2531,7 +2588,7 @@ static void should_offer_the_one_face_of_a_picture_to_the_one_person_it_names() f.marks[f.path("rejected.jpg")] = {{f.left, 0, 0, false, {ann}}}; const auto read = [&](const core::file_path path) -> faces::picture_evidence { - const auto names = [](std::vector n) + const auto names = [](const std::vector& n) { return core::cache(core::combine(n)); }; @@ -4017,6 +4074,8 @@ void register_faces_tests(view_state& /*state*/, test_registry& tests) tests.add("Should keep faces in the store by picture"s, should_keep_faces_in_the_store_by_picture); tests.add("Should put away the faces of pictures the index no longer holds"s, should_put_away_the_faces_of_pictures_the_index_no_longer_holds); + tests.add("Should scan for a kind turned on while a pass waits to run"s, + should_scan_for_a_kind_turned_on_while_a_pass_waits_to_run); tests.add("Should read a video's faces from its key frames"s, should_read_a_videos_faces_from_its_key_frames); tests.add("Should tell the window of face scan progress a few times a second"s, should_tell_the_window_of_face_scan_progress_a_few_times_a_second); diff --git a/src/test_files.cpp b/src/test_files.cpp index 68bdd143..ac238933 100644 --- a/src/test_files.cpp +++ b/src/test_files.cpp @@ -10,7 +10,6 @@ #include "pch.h" #include "files.h" #include "crypto.h" -#include "libfiles/commodore.h" #include "libfiles/encode.h" #include "libfiles/exif.h" #include "libfiles/exif_listing.h" @@ -379,323 +378,6 @@ static void should_report_move_or_copy_collision_paths() platform::delete_items({}, {root}, false); } -#ifndef _WIN32 -static void should_report_linux_file_operation_errors() -{ - const platform::file_op_result collision{platform::file_op_result_code::ALREADY_EXISTS}; - const platform::file_op_result failure{platform::file_op_result_code::FAILED}; - assert_equal(true, collision.failed(), "an existing destination is a failure"); - assert_equal(false, collision.format_error().empty(), "a collision cannot look like an empty success message"); - assert_equal(false, failure.format_error().empty(), "an unspecified failure still has a diagnostic"); -} - -static void should_reject_linux_folder_file_collisions() -{ - const auto root = test_temps.next_folder("linux-folder-collision"); - const auto file = root.combine_file("occupied"); - write_test_file(file, "not a directory"); - - assert_equal(true, platform::create_folder(root.combine("occupied")).failed(), - "an existing file is not a successful mkdir"); - assert_equal("not a directory", read_test_file(file), "the colliding file is unchanged"); - - const auto link = root.combine("dangling"); - std::filesystem::create_directory_symlink(platform::to_stream_path(root.combine("missing")), - platform::to_stream_path(link)); - assert_equal(true, platform::create_folder(link).failed(), "a dangling symlink is not a directory"); - assert_equal(true, platform::create_folder(root.combine("directory")).success(), "a new directory is created"); - assert_equal(true, platform::create_folder(root.combine("directory")).success(), - "an existing directory is accepted"); -} - -static void should_preserve_linux_directory_move_on_unsupported_no_replace() -{ - const auto root = test_temps.next_folder("linux-directory-move"); - const auto source = root.combine("source"); - const auto destination = root.combine("destination"); - assert_equal(true, platform::create_folder(source).success(), "source directory exists"); - write_test_file(source.combine_file("original.txt"), "original"); - - platform::test_linux_move_file_failures({true, false}); - const core::scope_exit restore([] { platform::test_linux_clear_move_file_failures(); }); - const auto result = platform::move_file(source, destination); - assert_equal(true, result.failed(), "unsupported atomic directory rename is a reported failure"); - assert_equal("original", read_test_file(source.combine_file("original.txt")), "source is retained"); - assert_equal(false, platform::exists(destination), "an unsafe fallback did not publish a destination"); -} - -static void should_refuse_linux_copy_identity_overwrites() -{ - const auto root = test_temps.next_folder("linux-copy-identity"); - const auto source = root.combine_file("source.bin"); - const auto alias = root.combine_file("alias.bin"); - const core::blob bytes = {1, 2, 3, 4}; - platform::blob_save_to_file(bytes, source); - std::filesystem::create_hard_link(platform::to_stream_path(source), platform::to_stream_path(alias)); - - const auto same_path = platform::copy_file(source, source, false, false); - assert_equal(true, same_path.failed(), "copy to self fails"); - assert_equal(true, platform::blob_from_file(source) == bytes, "copy to self preserves source"); - - const auto hard_link = platform::copy_file(source, alias, false, false); - assert_equal(true, hard_link.failed(), "copy to hard-link alias fails"); - assert_equal(true, platform::blob_from_file(source) == bytes, "hard-link source bytes survive"); - assert_equal(true, platform::blob_from_file(alias) == bytes, "hard-link destination bytes survive"); -} - -static void should_report_linux_copy_flush_failures() -{ - const auto root = test_temps.next_folder("linux-copy-flush"); - const auto source = root.combine_file("source.bin"); - const auto destination = root.combine_file("destination.bin"); - const core::blob source_bytes = {9, 8, 7, 6, 5, 4}; - const core::blob original_destination = {1, 2, 3}; - platform::blob_save_to_file(source_bytes, source); - platform::blob_save_to_file(original_destination, destination); - - platform::linux_copy_file_test_failures partial; - partial.max_write_bytes = 2; - partial.interrupt_first_write = true; - platform::test_linux_copy_file_failures(partial); - const auto partial_result = platform::copy_file(source, root.combine_file("partial.bin"), true, false); - platform::test_linux_clear_copy_file_failures(); - assert_equal(true, partial_result.success(), "partial and interrupted writes complete"); - assert_equal(true, platform::blob_from_file(root.combine_file("partial.bin")) == source_bytes, - "partial write copy has every byte"); - - platform::linux_copy_file_test_failures write_failure; - write_failure.fail_write_after_calls = 0; - platform::test_linux_copy_file_failures(write_failure); - const auto write_result = platform::copy_file(source, destination, false, false); - platform::test_linux_clear_copy_file_failures(); - assert_equal(true, write_result.failed(), "write failure is reported"); - assert_equal(true, platform::blob_from_file(destination) == original_destination, - "write failure preserves prior destination"); - - platform::linux_copy_file_test_failures close_failure; - close_failure.fail_destination_close = true; - platform::test_linux_copy_file_failures(close_failure); - const auto close_result = platform::copy_file(source, destination, false, false); - platform::test_linux_clear_copy_file_failures(); - assert_equal(true, close_result.failed(), "late close failure is reported"); - assert_equal(true, platform::blob_from_file(destination) == original_destination, - "late close failure preserves prior destination"); -} - -static void should_claim_linux_auto_rename_destinations_atomically() -{ - const auto root = test_temps.next_folder("linux-auto-rename"); - const auto source_folder = root.combine("source"); - const auto target = root.combine("target"); - platform::create_folder(source_folder); - platform::create_folder(target); - - const auto source = source_folder.combine_file("photo.txt"); - const core::blob source_bytes = {7}; - const core::blob competing_bytes = {3}; - platform::blob_save_to_file(source_bytes, source); - - bool competed = false; - platform::test_linux_before_claim_file_path = [&](const core::file_path candidate) - { - if (!competed) - { - competed = true; - platform::blob_save_to_file(competing_bytes, candidate); - } - }; - - const auto result = platform::move_or_copy({source}, {}, target, false); - platform::test_linux_before_claim_file_path = {}; - - assert_equal(true, result.success(), "copy retries after a raced file candidate"); - assert_equal(1_z, result.created_files.files.size(), "one copied file is reported"); - assert_equal(true, result.created_files.files.front() != target.combine_file("photo.txt"), - "the raced name was not reported as copied"); - assert_equal(true, platform::blob_from_file(target.combine_file("photo.txt")) == competing_bytes, - "competing file bytes survive"); - assert_equal(true, platform::blob_from_file(result.created_files.files.front()) == source_bytes, - "reported file has source bytes"); - - const auto replace_source = source_folder.combine_file("replace.txt"); - const auto replace_target = target.combine_file("replace.txt"); - platform::blob_save_to_file(source_bytes, replace_source); - platform::blob_save_to_file(competing_bytes, replace_target); - const auto replace = platform::move_or_copy({replace_source}, {}, target, false, true); - assert_equal(true, replace.success(), "explicit replace still succeeds"); - assert_equal(true, platform::blob_from_file(replace_target) == source_bytes, "replace writes source bytes"); -} - -static void should_reject_linux_recursive_copy_into_descendant() -{ - const auto root = test_temps.next_folder("linux-descendant-copy"); - const auto source = root.combine("source"); - const auto child = source.combine("child"); - platform::create_folder(child); - platform::blob_save_to_file(core::blob{1}, source.combine_file("photo.txt")); - - const auto result = platform::move_or_copy({}, {source}, child, false); - assert_equal(true, result.failed(), "copy into descendant fails"); - assert_equal(false, platform::exists(child.combine("source")), "descendant target is not created"); - assert_equal(true, platform::exists(source.combine_file("photo.txt")), "source remains available"); -} - -static void should_delete_linux_directory_symlinks() -{ - const auto root = test_temps.next_folder("linux-delete-symlink"); - const auto source = root.combine("source"); - const auto target = root.combine("target"); - const auto link = source.combine("linked"); - platform::create_folder(source); - platform::create_folder(target); - platform::blob_save_to_file(core::blob{1}, source.combine_file("file.txt")); - platform::blob_save_to_file(core::blob{2}, target.combine_file("target.txt")); - std::filesystem::create_directory_symlink(platform::to_stream_path(target), platform::to_stream_path(link)); - - const auto result = platform::delete_items({}, {source}, false); - assert_equal(true, result.success(), std::format("delete succeeds ({})", result.format_error())); - assert_equal(false, platform::exists(source), "source folder is removed"); - assert_equal(true, platform::exists(target.combine_file("target.txt")), "symlink target survives"); -} - -static void should_move_or_copy_linux_directory_symlinks() -{ - const auto root = test_temps.next_folder("linux-copy-symlink"); - const auto source = root.combine("source"); - const auto target = root.combine("target"); - const auto link_target = root.combine("linked-target"); - platform::create_folder(source); - platform::create_folder(target); - platform::create_folder(link_target); - std::filesystem::create_directory_symlink(platform::to_stream_path(link_target), - platform::to_stream_path(source.combine("linked"))); - - const auto result = platform::move_or_copy({}, {source}, target, false); - assert_equal(true, result.success(), std::format("copy succeeds ({})", result.format_error())); - assert_equal(1_z, result.created_files.folders.size(), "one folder reported"); - const auto copied_link = result.created_files.folders.front().combine("linked"); - assert_equal(true, std::filesystem::is_symlink(platform::to_stream_path(copied_link)), - "directory symlink is recreated"); - assert_equal(platform::to_stream_path(link_target).string(), - std::filesystem::read_symlink(platform::to_stream_path(copied_link)).string(), - "link target spelling is preserved"); -} - -static void should_move_or_copy_into_its_own_folder_with_auto_rename() -{ - const auto root = test_temps.next_folder("linux-copy-self-parent"); - const auto file = root.combine_file("photo.txt"); - const auto folder = root.combine("album"); - platform::blob_save_to_file(core::blob{7}, file); - platform::create_folder(folder); - platform::blob_save_to_file(core::blob{8}, folder.combine_file("inside.txt")); - - const auto file_result = platform::move_or_copy({file}, {}, root, false); - assert_equal(true, file_result.success(), std::format("file copy succeeds ({})", file_result.format_error())); - assert_equal(1_z, file_result.created_files.files.size(), "one copied file reported"); - assert_equal(true, file_result.created_files.files.front() != file, "copy uses a new file name"); - assert_equal(true, platform::blob_from_file(file_result.created_files.files.front()) == core::blob{7}, - "copied file has the source bytes"); - - const auto folder_result = platform::move_or_copy({}, {folder}, root, false); - assert_equal(true, folder_result.success(), std::format("folder copy succeeds ({})", folder_result.format_error())); - assert_equal(1_z, folder_result.created_files.folders.size(), "one copied folder reported"); - assert_equal(true, folder_result.created_files.folders.front() != folder, "copy uses a new folder name"); - assert_equal(true, platform::exists(folder_result.created_files.folders.front().combine_file("inside.txt")), - "copied folder has the source contents"); -} - -static void should_move_or_copy_stop_on_inner_linux_folder_collision() -{ - const auto root = test_temps.next_folder("linux-inner-collision"); - const auto source = root.combine("album"); - const auto target = root.combine("target"); - platform::create_folder(source); - platform::create_folder(target); - platform::blob_save_to_file(core::blob{5}, source.combine_file("inside.txt")); - - bool competed = false; - platform::test_linux_before_copy_folder_file_path = [&](const core::file_path candidate) - { - if (!competed) - { - competed = true; - platform::blob_save_to_file(core::blob{6}, candidate); - } - }; - - const auto result = platform::move_or_copy({}, {source}, target, false); - platform::test_linux_before_copy_folder_file_path = {}; - - assert_equal(true, result.failed(), "inner collision fails the claimed tree"); - assert_equal(false, platform::exists(target.combine("album (2)")), "inner collision does not retry the top folder"); - assert_equal(true, platform::blob_from_file(target.combine("album").combine_file("inside.txt")) == core::blob{6}, - "competing inner file survives"); -} - -static void should_move_linux_no_replace_without_renameat_or_links() -{ - const auto root = test_temps.next_folder("linux-move-fallback"); - const auto source = root.combine_file("source.txt"); - const auto destination = root.combine_file("destination.txt"); - const core::blob bytes = {4, 3, 2}; - platform::blob_save_to_file(bytes, source); - - platform::test_linux_move_file_failures({true, true}); - const auto result = platform::move_file(source, destination, true); - platform::test_linux_clear_move_file_failures(); - - assert_equal(true, result.success(), std::format("fallback move succeeds ({})", result.format_error())); - assert_equal(false, platform::exists(source), "source is removed after the exclusive copy"); - assert_equal(true, platform::blob_from_file(destination) == bytes, "destination has source bytes"); -} - -static void should_refuse_or_preserve_linux_replace_permissions() -{ - const auto root = test_temps.next_folder("linux-copy-permissions"); - const auto source = root.combine_file("source.txt"); - const auto read_only = root.combine_file("read-only.txt"); - const auto private_file = root.combine_file("private.txt"); - const core::blob source_bytes = {9}; - const core::blob original_bytes = {1}; - platform::blob_save_to_file(source_bytes, source); - platform::blob_save_to_file(original_bytes, read_only); - platform::blob_save_to_file(original_bytes, private_file); - - namespace fs = std::filesystem; - fs::permissions(platform::to_stream_path(read_only), - fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read, fs::perm_options::replace); - const auto refused = platform::copy_file(source, read_only, false, false); - assert_equal(true, refused.failed(), "read-only destination refuses replace"); - assert_equal(true, platform::blob_from_file(read_only) == original_bytes, "read-only destination bytes survive"); - - fs::permissions(platform::to_stream_path(private_file), fs::perms::owner_read | fs::perms::owner_write, - fs::perm_options::replace); - const auto replaced = platform::copy_file(source, private_file, false, false); - assert_equal(true, replaced.success(), std::format("replace succeeds ({})", replaced.format_error())); - const auto mode = fs::status(platform::to_stream_path(private_file)).permissions() & fs::perms::all; - assert_equal(true, mode == (fs::perms::owner_read | fs::perms::owner_write), - "replace preserves destination permissions"); -} - -static void should_move_or_copy_reject_linux_destination_alias_inside_source() -{ - const auto root = test_temps.next_folder("linux-copy-alias-descendant"); - const auto source = root.combine("source"); - const auto nested = source.combine("a").combine("b"); - const auto target = root.combine("target-link"); - platform::create_folder(nested); - platform::blob_save_to_file(core::blob{1}, source.combine_file("top.txt")); - platform::blob_save_to_file(core::blob{2}, source.combine("a").combine_file("mid.txt")); - std::filesystem::create_directory_symlink(platform::to_stream_path(nested), platform::to_stream_path(target)); - - const auto result = platform::move_or_copy({}, {source}, target, false); - assert_equal(true, result.failed(), "alias into source is rejected"); - assert_equal(false, platform::exists(nested.combine("source")), "copy does not create output inside source"); - assert_equal(true, platform::exists(source.combine_file("top.txt")), "source remains available"); -} -#endif - static void should_fail_replace_when_flush_fails() { const auto result = platform::replacement_flush_result(false, "flush failed"); @@ -884,7 +566,7 @@ static void should_scan_d64() constexpr auto file_name = "Ace of Aces (Europe).D64"; const auto load_path = test_files_folder().combine("retro").combine_file(file_name); const auto loaded = platform::blob_from_file(load_path); - const auto contents = libfiles::list_c64_media({loaded.data(), loaded.size()}); + const auto contents = lib64::list_media({loaded.data(), loaded.size()}).value(); assert_equal(4_z, contents.rows.size(), "d64", file_name); assert_equal("147 \"ACE OF ACES+ \" PRG", contents.rows[0].text, "d64", file_name); @@ -2186,13 +1868,13 @@ static void should_reuse_jpeg_encoder_after_abandoned_encode() const auto surface = make_gradient_surface(32, 32); const auto dimensions = surface->dimensions(); - // start() leaves the encoder mid-compress, which is the state a throw out of jpeg_write_scanlines - // or a marker write hands back. - encoder.start(dimensions.cx, dimensions.cy, 1, {}, {}); + // start() leaves the encoder mid-compress, which is the state a failure in jpeg_write_scanlines or a marker + // write hands back. + assert_equal(true, static_cast(encoder.start(dimensions.cx, dimensions.cy, 1, {}, {})), "encode started"); - const auto encoded = encoder.encode(dimensions.cx, dimensions.cy, surface->pixels(), surface->stride(), 1, {}, {}); + const auto encoded = encoder.encode(libfiles_view(*surface, libfiles::pixel_format::bgrx8), {}, {}); - assert_equal(false, encoded.empty(), "encoder still usable after an abandoned encode"); + assert_equal(false, !encoded || encoded->data.empty(), "encoder still usable after an abandoned encode"); } // Offset of the start-of-scan marker, or 0 when there is none. @@ -2259,7 +1941,7 @@ static void should_refuse_an_over_budget_lossless_rotate() libfiles::jpeg_encoder encoder; libfiles::jpeg_transformer transformer; - assert_equal(true, transformer.read_header(image->data()), "header read"); + assert_equal(true, static_cast(transformer.read_header(image->data())), "header read"); assert_equal(static_cast(0), jpeg_frame(image->data()).working_bytes, "a baseline single-scan jpeg decodes a block at a time"); @@ -2298,7 +1980,7 @@ static void should_not_re_encode_a_rotate_refused_for_its_budget() const auto source = platform::blob_from_file(load_path); libfiles::jpeg_transformer transformer; - assert_equal(true, transformer.read_header({source.data(), source.size()}), "header read"); + assert_equal(true, static_cast(transformer.read_header({source.data(), source.size()})), "header read"); const sizei dimensions{static_cast(transformer.width()), static_cast(transformer.height())}; const auto rotate_bytes = transformer.coefficient_bytes() * 2; @@ -2390,7 +2072,8 @@ static void should_rotate_lossless_exif_dimensions() }; // clang-format on libfiles::jpeg_encoder encoder; - const auto source = encoder.encode(32, 16, surface->pixels(), surface->stride(), 1, metadata, {}); + auto encoded = encoder.encode(libfiles_view(*surface, libfiles::pixel_format::bgrx8), metadata, {}); + const auto source = encoded ? std::move(encoded->data) : std::vector{}; libfiles::jpeg_transformer transformer; libfiles::jpeg_encoder rotated_encoder; const auto rotated = turn_jpeg_losslessly(transformer, rotated_encoder, source, core::simple_transform::rot_90); @@ -4339,17 +4022,7 @@ namespace scan_parity std::string environment_variable(const char* const name) { -#ifdef _MSC_VER - char* value = nullptr; - size_t size = 0; - if (_dupenv_s(&value, &size, name) != 0 || !value) return {}; - std::string result(value); - free(value); - return result; -#else - const auto* const value = std::getenv(name); - return value ? value : ""; -#endif + return platform::environment_variable(name).value_or(""); } std::vector cut_points(const size_t size) @@ -4375,6 +4048,15 @@ namespace scan_parity if (k < 40) return 16 + static_cast(k * 2654435761ull % (head - 16)); return 16 + static_cast(k * 2654435761ull % (size - 16)); } + + // The records were taken on x86, in builds that fuse no multiply-adds: x86-64's baseline has no instruction for it, + // and MSVC fuses none unless told to. A record whose outcomes another processor, or fused multiply-adds, change is + // held to it there alone, and elsewhere logged, with what it was taken over checked. +#if (defined(_M_X64) || defined(_M_IX86) || defined(__x86_64__) || defined(__i386__)) && !defined(__FMA__) + constexpr bool as_recorded = true; +#else + constexpr bool as_recorded = false; +#endif } // A memory stream that does not lend its memory, so libfiles reads it through its window. @@ -5227,11 +4909,16 @@ namespace jpeg_sweep return o; } + // What every 64-bit build decodes alike: the outcome but for its pixels. + std::string describe_shape(const outcome& o) + { + return std::format("decoded {} yuv {} {}x{} format {} orientation {} colour {} {} bytes", o.decoded, o.yuv, + o.dimensions.cx, o.dimensions.cy, o.format, o.orientation, o.color_space, o.pixels.size()); + } + std::string describe(const outcome& o) { - return std::format("decoded {} yuv {} {}x{} format {} orientation {} colour {} {} bytes {:08x}", o.decoded, - o.yuv, o.dimensions.cx, o.dimensions.cy, o.format, o.orientation, o.color_space, - o.pixels.size(), core::crc32c(o.pixels.data(), o.pixels.size())); + return std::format("{} {:08x}", describe_shape(o), core::crc32c(o.pixels.data(), o.pixels.size())); } struct request @@ -5289,8 +4976,10 @@ static void should_decode_jpegs_as_jpeg_decoder_x_did() auto recorded_files = 0; auto recorded_outcomes = 0; std::string record; + std::string shape_record; - const auto decode = [&](const core::cspan bytes, const bool recorded, const std::vector& requests) + const auto decode = + [&](const core::cspan bytes, const bool recorded, const std::vector& requests, const bool whole) { for (const auto& r : requests) { @@ -5300,7 +4989,9 @@ static void should_decode_jpegs_as_jpeg_decoder_x_did() if (recorded) { - record += jpeg_sweep::describe(outcome) + "\n"; + const auto text = jpeg_sweep::describe(outcome); + record += text + "\n"; + shape_record += (whole ? text : jpeg_sweep::describe_shape(outcome)) + "\n"; ++recorded_outcomes; } } @@ -5309,34 +5000,51 @@ static void should_decode_jpegs_as_jpeg_decoder_x_did() for (auto& [name, bytes, recorded] : corpus) { if (recorded) ++recorded_files; - decode(bytes, recorded, whole_requests); + decode(bytes, recorded, whole_requests, true); // A small file is cheap to decode in full, so its parts are too. auto requests = part_requests; if (bytes.size() < 300 * 1024) requests.push_back({{0, 0}, false, decode_intent::display}); - for (const auto cut : scan_parity::cut_points(bytes.size())) decode({bytes.data(), cut}, recorded, requests); + for (const auto cut : scan_parity::cut_points(bytes.size())) + decode({bytes.data(), cut}, recorded, requests, false); for (uint64_t k = 0; k < 48; ++k) { const auto at = scan_parity::corruption_position(k, bytes.size()); const auto original = bytes[at]; bytes[at] = static_cast(k % 2 ? original ^ 0xFF : (k % 3 ? 0x00 : 0xFF)); - if (bytes[at] != original) decode(bytes, recorded, requests); + if (bytes[at] != original) decode(bytes, recorded, requests, false); bytes[at] = original; } } const auto checksum = core::crc32c(record.data(), record.size()); - core::log(__FUNCTION__, - std::format("{} files ({} recorded), {} decodes, {} decoded; record {:08x} over {} outcomes", - corpus.size(), recorded_files, decodes, decoded, checksum, recorded_outcomes)); + const auto shape_checksum = core::crc32c(shape_record.data(), shape_record.size()); + core::log( + __FUNCTION__, + std::format("{} files ({} recorded), {} decodes, {} decoded; record {:08x}, shape {:08x}, over {} outcomes", + corpus.size(), recorded_files, decodes, decoded, checksum, shape_checksum, recorded_outcomes)); assert_equal(true, recorded_files >= 10, "the fixtures hold JPEGs"); constexpr auto expected = sizeof(size_t) == 8 ? 0xc15126d4u : 0x7344b182u; assert_equal(4642, recorded_outcomes, "the sweep is the one the record was taken over"); - assert_equal(std::format("{:08x}", expected), std::format("{:08x}", checksum), - "every outcome is the one jpeg_decoder_x had before it moved to libfiles"); + + // What a corrupted byte decodes to depends on the processor: libjpeg-turbo's NEON and x86 kernels each treat the + // coefficients it makes, which no encoder writes, their own way, and on aarch64 11 outcomes differ in their pixels + // alone. Every 64-bit build holds each outcome's shape and every whole file's pixels, the builds the record was + // taken on everything. + if constexpr (sizeof(size_t) == 8) + { + assert_equal(std::format("{:08x}", 0x42a2fb7du), std::format("{:08x}", shape_checksum), + "every outcome decodes to the shape it did, and every whole file to its pixels"); + } + + if constexpr (scan_parity::as_recorded) + { + assert_equal(std::format("{:08x}", expected), std::format("{:08x}", checksum), + "every outcome is the one jpeg_decoder_x had before it moved to libfiles"); + } } // Diffractor's EXIF parser moved to libfiles. Before the switch both read every EXIF block the fixtures @@ -5781,14 +5489,17 @@ static void should_list_exif_as_libexif_did() "every row reads as libexif listed it"); } -// Diffractor's Commodore 64 listing moved to libfiles. Before the switch both listed every file in the -// fixtures and in DIFFRACTOR_SCAN_PARITY_CORPUS - lib64's test images among them - and 540 generated -// disks of every size, tapes, cartridges and programs, some with directories long enough for the -// listing's cap - whole, cut short and with single bytes corrupted - and agreed on every row's text and -// screen codes and on every pixel drawn: 53,196 comparisons over 631 files, with no difference. That -// comparison left a record of list_disk's outcomes for the fixtures and 54 generated files, the same on -// Windows x64 and x86 and on Linux. The sweep now holds libfiles to it, through the surface the disk -// control draws. +// The Commodore 64 listing is lib64's, made over the directory readers it loads files with. The sweep lists +// every file in the fixtures and in DIFFRACTOR_SCAN_PARITY_CORPUS - lib64's test images among them - and +// generated disks of every size, tapes, cartridges and programs, some with directories long enough for the +// listing's cap - whole, cut short and with single bytes corrupted - and holds every row's text and screen +// codes and every pixel drawn, through the surface the disk control draws, to a record of the fixtures and +// 54 generated files. Taken when lib64 took the listing over from libfiles, the record keeps libfiles' +// outcomes (themselves list_disk's) where the two agree, which is 8,254 of its 10,762, and differs only +// where lib64 reads as a drive does: 482 damaged disks end where their directory's chain names a sector its +// track does not have, rather than reading on; 2 tapes that say they use no entry list their first, which +// is what lib64 runs; and 2,024 listings holding graphics characters, a colon, a semicolon or an up arrow +// are drawn from the C64's character ROM, graphics included, rather than a font that left graphics blank. namespace commodore_sweep { // The colours the disk control draws with. @@ -5808,7 +5519,7 @@ namespace commodore_sweep outcome run(const core::cspan bytes) { outcome o; - const auto listing = libfiles::list_c64_media({bytes.data, bytes.size}); + const auto listing = lib64::list_media({bytes.data, bytes.size}).value(); for (const auto& row : listing.rows) { @@ -6131,7 +5842,7 @@ namespace commodore_sweep } } -static void should_list_commodore_media_as_list_disk_did() +static void should_list_commodore_media_as_recorded() { auto corpus = commodore_sweep::corpus(); const auto has_disk = std::ranges::any_of(corpus, [](const commodore_sweep::entry& e) @@ -6168,8 +5879,8 @@ static void should_list_commodore_media_as_list_disk_did() assert_equal(true, has_disk, "the fixtures hold a disk"); assert_equal(true, listed > 1000, "much of what is listed lists"); assert_equal(10762, recorded_outcomes, "the sweep is the one the record was taken over"); - assert_equal(std::format("{:08x}", 0xedcf99f2u), std::format("{:08x}", checksum), - "every listing is the one list_disk made before it moved to libfiles"); + assert_equal(std::format("{:08x}", 0xd7897582u), std::format("{:08x}", checksum), + "every listing is the one recorded when lib64 took the listing over"); } // A .sid file is described by its header alone: lib64 reads it, and the properties land where every @@ -6755,11 +6466,16 @@ namespace webp_sweep return o; } + // What every build decodes alike: the outcome but for its pixels. + std::string describe_shape(const outcome& o) + { + return std::format("threw {} null {} {}x{} format {} orientation {} cs {} {} bytes", o.threw, o.null, + o.dimensions.cx, o.dimensions.cy, o.format, o.orientation, o.color_space, o.rows.size()); + } + std::string describe(const outcome& o) { - return std::format("threw {} null {} {}x{} format {} orientation {} cs {} {} bytes {:08x}", o.threw, o.null, - o.dimensions.cx, o.dimensions.cy, o.format, o.orientation, o.color_space, o.rows.size(), - core::crc32c(o.rows.data(), o.rows.size())); + return std::format("{} {:08x}", describe_shape(o), core::crc32c(o.rows.data(), o.rows.size())); } uint8_t next_byte(uint32_t& seed) @@ -7035,6 +6751,7 @@ static void should_decode_webps_as_load_webp_did() auto decoded = 0; auto recorded_outcomes = 0; uint32_t checksum = 0; + uint32_t shape_checksum = 0; for (auto& e : corpus) { @@ -7051,19 +6768,33 @@ static void should_decode_webps_as_load_webp_did() const auto text = webp_sweep::describe(outcome); const uint32_t fold[] = {checksum, core::crc32c(text.data(), text.size())}; checksum = core::crc32c(fold, sizeof(fold)); + const auto shape = webp_sweep::describe_shape(outcome); + const uint32_t shape_fold[] = {shape_checksum, core::crc32c(shape.data(), shape.size())}; + shape_checksum = core::crc32c(shape_fold, sizeof(shape_fold)); ++recorded_outcomes; } }); } - core::log(__FUNCTION__, std::format("{} files ({} real), {} decodes, {} decoded; record {:08x} over {} outcomes", - corpus.size(), real_files, decodes, decoded, checksum, recorded_outcomes)); + core::log(__FUNCTION__, + std::format("{} files ({} real), {} decodes, {} decoded; record {:08x}, shape {:08x}, over {} outcomes", + corpus.size(), real_files, decodes, decoded, checksum, shape_checksum, recorded_outcomes)); assert_equal(true, real_files >= 1, "the fixtures hold a WebP"); assert_equal(true, decoded > 1000, "much of what is decoded decodes"); assert_equal(20331, recorded_outcomes, "the sweep is the one the record was taken over"); - assert_equal(std::format("{:08x}", 0xeab178fbu), std::format("{:08x}", checksum), - "every outcome is the one load_webp had, an animation's first frame aside"); + + // What a reduced decode's pixels are depends on the processor: libwebp's NEON rescaler rounds its fixed-point + // products as vqrdmulh does, unlike its C and x86 ones, and on aarch64 114 outcomes of one photo differ in their + // pixels alone. Every build holds each outcome's shape, the builds the record was taken on its pixels too. + assert_equal(std::format("{:08x}", 0x71668476u), std::format("{:08x}", shape_checksum), + "every outcome decodes to the shape it did"); + + if constexpr (scan_parity::as_recorded) + { + assert_equal(std::format("{:08x}", 0xeab178fbu), std::format("{:08x}", checksum), + "every outcome is the one load_webp had, an animation's first frame aside"); + } } // An animated WebP shows its first frame. Its picture is never written back over it, which would keep that @@ -7532,8 +7263,14 @@ static void should_decode_heifs_as_load_heif_did() assert_equal(true, real_files >= 2, "the fixtures hold HEIF and AVIF"); assert_equal(true, decoded > 1000, "much of what is decoded decodes"); assert_equal(2347, recorded_outcomes, "the sweep is the one the record was taken over"); - assert_equal(std::format("{:08x}", 0x2999784au), std::format("{:08x}", checksum), - "every outcome matches libheif 1.23.7's recovery record"); + + // Off x86 there are no SSE4.1 kernels to pin, and libheif turns YCbCr into RGB with multiply-adds GCC fuses where + // the processor has them, as aarch64 does: an x86-64 build with them fused gives 6a774e16. + if constexpr (scan_parity::as_recorded) + { + assert_equal(std::format("{:08x}", 0x2999784au), std::format("{:08x}", checksum), + "every outcome matches libheif 1.23.7's recovery record"); + } } // Diffractor's JPEG XL loader moved to libfiles. Before the switch both decoded every JPEG XL in the @@ -7897,8 +7634,14 @@ static void should_load_raws_as_load_raw_did() assert_equal(true, loaded > 100 && too_large > 100, "much of what is loaded loads, and much is refused for its size"); assert_equal(352, recorded_outcomes, "the sweep is the one the record was taken over"); - assert_equal(std::format("{:08x}", 0x0e50588fu), std::format("{:08x}", checksum), - "every outcome is the one recorded"); + + // LibRaw develops in floating point, whose multiply-adds GCC fuses where the processor has them, as aarch64 does: + // an x86-64 build with them fused gives ad020a9c. + if constexpr (scan_parity::as_recorded) + { + assert_equal(std::format("{:08x}", 0x0e50588fu), std::format("{:08x}", checksum), + "every outcome is the one recorded"); + } } // A raw file turned by its camera keeps its preview unturned, as the sensor saw it, and the preview takes @@ -8205,6 +7948,13 @@ namespace encode_sweep return std::format("{} bytes {:08x}", data.size(), core::crc32c(data.data(), data.size())); } + // The bytes an encoder made, or the reason it gave thrown, as attempt() records the encoders' failures. + std::vector encoded_or_thrown(libfiles::result encoded) + { + if (!encoded) throw std::runtime_error(std::string(encoded.message())); + return std::move(encoded->data); + } + // What an encoder made, or why it threw. template std::string attempt(F&& encode) { @@ -8571,8 +8321,9 @@ static void should_encode_as_diffractors_encoders_did() const auto between = make_surface(16, 16, texture_format::RGB, core::orientation::bottom_right); const auto encode_between = [&] { - return encoder.encode(16, 16, between->pixels(), between->stride(), - static_cast(core::orientation::bottom_right), {}, {}); + auto view = libfiles_view(*between, libfiles::pixel_format::bgrx8); + view.orientation = static_cast(core::orientation::bottom_right); + return encode_sweep::encoded_or_thrown(encoder.encode(view, {}, {})); }; // An encode started and abandoned, as a throw part way leaves one, and one refused for its metadata. @@ -8580,16 +8331,19 @@ static void should_encode_as_diffractors_encoders_did() const auto surface = make_surface(32, 32, texture_format::RGB); const auto abandoned = attempt([&] { - encoder.start(32, 32, static_cast(core::orientation::right_top), everything(), {}); + const auto started = encoder.start(32, 32, static_cast(core::orientation::right_top), + everything(), {}); + if (!started) throw std::runtime_error(std::string(started.message())); return core::blob{}; }); note("started and abandoned", abandoned); note("then encodes", attempt(encode_between)); note("refused", attempt([&] { - return encoder.encode(32, 32, surface->pixels(), surface->stride(), - static_cast(core::orientation::top_left), - exif_only(encode_sweep::padded(bare_exif, 65528)), {}); + auto view = libfiles_view(*surface, libfiles::pixel_format::bgrx8); + view.orientation = static_cast(core::orientation::top_left); + return encode_sweep::encoded_or_thrown( + encoder.encode(view, exif_only(encode_sweep::padded(bare_exif, 65528)), {})); })); note("then encodes", attempt(encode_between)); } @@ -8612,18 +8366,19 @@ static void should_encode_as_diffractors_encoders_did() { int64_t coefficients = 0; - try + // libjpeg's failure reads as it was thrown; a header cut short reads as none. + if (const auto header = transformer.read_header(jpeg); !header && header.error() != libfiles::error::truncated) { - const auto ok = transformer.read_header(jpeg); + note(name + " header", std::format("threw {}", header.message())); + } + else + { + const auto ok = static_cast(header); const auto d = ok ? sizei{static_cast(transformer.width()), static_cast(transformer.height())} : sizei{}; coefficients = ok ? transformer.coefficient_bytes() : 0; note(name + " header", std::format("{} {}x{} coefficients {}", ok, d.cx, d.cy, coefficients)); } - catch (const std::exception& e) - { - note(name + " header", std::format("threw {}", e.what())); - } for (auto t = 0; t < 8; ++t) { @@ -8671,8 +8426,9 @@ static void should_encode_as_diffractors_encoders_did() const libfiles::metadata_blocks& m, const int quality) { const auto surface = make_surface(cx, cy, format); - return encoder.encode(cx, cy, surface->pixels(), surface->stride(), - static_cast(core::orientation::top_left), m, {.quality = quality}); + auto view = libfiles_view(*surface, libfiles::pixel_format::bgrx8); + view.orientation = static_cast(core::orientation::top_left); + return encode_sweep::encoded_or_thrown(encoder.encode(view, m, {.quality = quality})); }; turn("made 32x32 camera exif", made(32, 32, texture_format::RGB, exif_only(camera_exif.clone()), 85), true); @@ -8747,7 +8503,7 @@ void register_files_tests(view_state& /*state*/, test_registry& tests) tests.add("Should write EXIF as libexif did"s, should_write_exif_as_libexif_did); tests.add("Should turn EXIF without rewriting it"s, should_turn_exif_without_rewriting_it); tests.add("Should list EXIF as libexif did"s, should_list_exif_as_libexif_did); - tests.add("Should list Commodore media as list_disk did"s, should_list_commodore_media_as_list_disk_did); + tests.add("Should list Commodore media as recorded"s, should_list_commodore_media_as_recorded); tests.add("Should scan a SID tune header"s, should_scan_a_sid_tune_header); tests.add("Should index a Commodore image by its listing"s, should_index_a_commodore_image_by_its_listing); tests.add("Should decode PNGs as load_png did"s, should_decode_pngs_as_load_png_did); @@ -8778,41 +8534,6 @@ void register_files_tests(view_state& /*state*/, test_registry& tests) tests.add("Should round trip zip entry dates"s, should_round_trip_zip_entry_dates); tests.add("Should create original before replace"s, should_create_original_before_replace); tests.add("Should report move or copy collision paths"s, should_report_move_or_copy_collision_paths); -#ifndef _WIN32 - // PLAT-007 - Linux replacement copy truncated source/destination aliases before reading. - tests.add("Should reject Linux folder file collisions"s, should_reject_linux_folder_file_collisions); - tests.add("Should report Linux file operation errors"s, should_report_linux_file_operation_errors); - tests.add("Should preserve Linux directory move on unsupported no replace"s, - should_preserve_linux_directory_move_on_unsupported_no_replace); - tests.add("Should refuse Linux copy identity overwrites"s, should_refuse_linux_copy_identity_overwrites); - // PLAT-007 - Linux copy ignored short writes and delayed close failures. - tests.add("Should report Linux copy flush failures"s, should_report_linux_copy_flush_failures); - // PLAT-008 - Linux auto-rename used a pre-check then an overwrite-capable copy. - tests.add("Should move or copy by claiming Linux auto rename destinations atomically"s, - should_claim_linux_auto_rename_destinations_atomically); - // PLAT-009 - Linux recursive folder copy could copy into its own destination. - tests.add("Should move or copy reject Linux recursive copy into descendant"s, - should_reject_linux_recursive_copy_into_descendant); - // G21 review - directory symlinks must be listed so delete can unlink them. - tests.add("Should delete Linux directory symlinks"s, should_delete_linux_directory_symlinks); - // G21 review - folder copy must not silently drop directory symlinks. - tests.add("Should move or copy Linux directory symlinks"s, should_move_or_copy_linux_directory_symlinks); - // G21 review - copying into the source's own parent should auto-rename, not fail on identity. - tests.add("Should move or copy into its own folder with auto rename"s, - should_move_or_copy_into_its_own_folder_with_auto_rename); - // G21 review - an inner collision belongs to the claimed tree, not the outer name picker. - tests.add("Should move or copy stop on inner Linux folder collision"s, - should_move_or_copy_stop_on_inner_linux_folder_collision); - // G21 review - filesystems without renameat2/link support still need a safe no-replace move. - tests.add("Should move Linux no replace without renameat or links"s, - should_move_linux_no_replace_without_renameat_or_links); - // G21 review - replacement copy must respect destination writeability and mode. - tests.add("Should refuse or preserve Linux replace permissions"s, - should_refuse_or_preserve_linux_replace_permissions); - // G21 review - containment checks must follow aliases into the source subtree. - tests.add("Should move or copy reject Linux destination alias inside source"s, - should_move_or_copy_reject_linux_destination_alias_inside_source); -#endif tests.add("Should fail replace when flush fails"s, should_fail_replace_when_flush_fails); #ifdef _WIN32 tests.add("Should cleanup failed update temps"s, should_cleanup_failed_update_temps); diff --git a/src/test_fixtures.cpp b/src/test_fixtures.cpp index 12f64d4c..1ac71f1b 100644 --- a/src/test_fixtures.cpp +++ b/src/test_fixtures.cpp @@ -72,7 +72,7 @@ file_update_result ff_turn(files& ff, const core::file_path path, const simple_t core::const_surface_ptr ff_shown_picture(files& ff, const core::file_path path) { - const auto surface = ff.load(path, false).to_surface(); + auto surface = ff.load(path, false).to_surface(); if (!is_valid(surface) || surface->orientation() == core::orientation::top_left) return surface; return surface->transform(to_simple_transform(surface->orientation())); } diff --git a/src/test_index.cpp b/src/test_index.cpp index 17db223e..fb202347 100644 --- a/src/test_index.cpp +++ b/src/test_index.cpp @@ -2133,6 +2133,11 @@ static void should_reload_thumb_after_scan() df::item_set items; items._items = {test_item, sony_item}; + // A scan is told by the time it stamps, and utc_now moves by the system tick - 15.6 ms on Windows - so the forced + // scan waits for the tick after the one build_index stamped. + for (const auto stamped = core::utc_now(); core::utc_now() == stamped;) + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + // Stage 1: a metadata refresh persists no thumbnail at all, so the item is still waiting on the // visible-item pass for one. const auto metadata_refreshed_initially = index.scan_items(items, false, false, false, false, test_token, true); @@ -2532,7 +2537,7 @@ static void should_request_a_re_query_only_when_a_folder_changed(shared_test_con assert_equal(true, platform::delete_items({removed}, {}, false).success(), "delete"); - index.queue_validate_changed_folders(std::move(touched)); + index.queue_validate_changed_folders(touched); assert_equal(true, as.run_next(async_queue::scan_folder), "validate ran"); assert_equal(true, as.was_invalidated(view_invalid::refresh_items), "a changed folder asks for the re-query"); } @@ -2561,7 +2566,7 @@ static void should_request_a_re_query_when_another_pass_published_the_change(sha core::unique_folders touched; touched.emplace(temp_folder); - index.queue_validate_changed_folders(std::move(touched)); + index.queue_validate_changed_folders(touched); // The scan of an item shown gets there first. assert_equal(true, index.validate_folder(temp_folder, true, core::utc_now()).was_updated, @@ -2603,7 +2608,7 @@ static void should_drop_deleted_items_from_a_search_with_no_folder(shared_test_c core::unique_folders touched; touched.emplace(removed.folder()); - index.queue_validate_changed_folders(std::move(touched)); + index.queue_validate_changed_folders(touched); assert_equal(1, count_search_results(index, search), "the deleted copy is gone from the list"); } @@ -2648,7 +2653,7 @@ static void should_drop_descendants_of_a_deleted_folder(shared_test_context& /*s core::unique_folders touched; touched.emplace(root); - index.queue_validate_changed_folders(std::move(touched)); + index.queue_validate_changed_folders(touched); assert_equal(1, count_search_results(index, search), "only the file outside the deleted branch survives"); } @@ -5486,7 +5491,7 @@ static void should_index_offline_placeholder() search_presence_mask::tag) != 0; // The shell property store also surfaces keywords and GPS for a placeholder (no hydration), which // the offline scan reads for free to help index non-downloaded files. - const std::string offline_tags(offline_md ? offline_md->tags.sv() : std::string_view{}); + [[maybe_unused]] const std::string offline_tags(offline_md ? offline_md->tags.sv() : std::string_view{}); const auto offline_has_gps = offline_md && offline_md->coordinate.is_valid(); [[maybe_unused]] const auto offline_gps_ok = offline_has_gps && std::abs(offline_md->coordinate.latitude() - 50.08806) < 0.01 && @@ -6316,7 +6321,7 @@ static void should_preserve_metadata_when_dehydrated() platform::test_offline_predicate = nullptr; const auto offline_md = item->metadata(); - const std::string offline_tags(offline_md ? offline_md->tags.sv() : std::string_view{}); + [[maybe_unused]] const std::string offline_tags(offline_md ? offline_md->tags.sv() : std::string_view{}); const auto offline_status = item->online_status(); const auto offline_has_crc = item->crc32c() != 0; diff --git a/src/test_media_edit.cpp b/src/test_media_edit.cpp index 430cc50a..1dad01ad 100644 --- a/src/test_media_edit.cpp +++ b/src/test_media_edit.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -579,10 +579,15 @@ static std::vector half_bright_jpeg(const sizei extent, const bool grey metadata.xmp = std::span(std::bit_cast(xmp.data()), xmp.size()); libfiles::jpeg_options options; options.quality = 95; - options.grayscale = grey; + libfiles::image_view view; + view.pixels = pixels.data(); + view.stride = static_cast(extent.cx) * channels; + view.width = extent.cx; + view.height = extent.cy; + view.format = grey ? libfiles::pixel_format::gray8 : libfiles::pixel_format::bgrx8; libfiles::jpeg_encoder encoder; - return encoder.encode(extent.cx, extent.cy, pixels.data(), static_cast(extent.cx) * channels, 1, metadata, - options); + auto encoded = encoder.encode(view, metadata, options); + return encoded ? std::move(encoded->data) : std::vector{}; } // An edited Ultra HDR JPEG keeps its gain map: the same picture as the photo, at a quarter of its size, so @@ -1238,7 +1243,7 @@ static core::file_path iptc_titled_jpeg() assert_equal(true, plan.ok(), "source planned"); libfiles::memory_stream out; - libfiles::write_updated(r, plan, out); + assert_equal(true, static_cast(libfiles::write_updated(r, plan, out)), "source written"); const auto& written = out.bytes(); assert_equal(true, platform::blob_save_to_file({written.data(), written.size()}, source), "source stored"); return source; @@ -1393,8 +1398,14 @@ static std::vector gradient_jpeg(const uint32_t width, const uint32_t h libfiles::embedded_metadata metadata; metadata.exif = exif; + libfiles::image_view view; + view.pixels = pixels.data(); + view.stride = static_cast(width) * 4; + view.width = static_cast(width); + view.height = static_cast(height); libfiles::jpeg_encoder encoder; - return encoder.encode(width, height, pixels.data(), size_t{width} * 4, 1, metadata, {}); + auto encoded = encoder.encode(view, metadata, {}); + return encoded ? std::move(encoded->data) : std::vector{}; } // A JPEG XL repacked from a JPEG turns as that JPEG would, and gives back the JPEG turned with it: by the orientation @@ -1405,7 +1416,8 @@ static void should_turn_a_jxl_repacked_from_a_jpeg_as_the_jpeg_would_turn() const auto repacked = [](const std::vector& jpeg) { const auto path = test_temps.next_path(".jxl"); - const auto jxl = libfiles::transcode_jpeg_to_jxl(jpeg).data; + auto repack = libfiles::transcode_jpeg_to_jxl(jpeg); + const auto jxl = repack ? std::move(repack->data) : std::vector{}; assert_equal(true, !jxl.empty() && platform::blob_save_to_file({jxl.data(), jxl.size()}, path), "repacked"); return path; }; diff --git a/src/test_metadata.cpp b/src/test_metadata.cpp index 24dce646..5c1989af 100644 --- a/src/test_metadata.cpp +++ b/src/test_metadata.cpp @@ -419,7 +419,7 @@ static void should_scan_tiff_camera_metadata() libfiles::xmp::meta xmp; xmp.set_property(libfiles::xmp::ns::tiff, "Model", "XMP camera"); - const auto packet = xmp.serialize(); + const auto packet = *xmp.serialize(); scanned.metadata.xmp.assign(packet.begin(), packet.end()); assert_equal("XMP camera"sv, scanned.to_props()->camera_model.sv(), "XMP still overrides native TIFF fields"); } @@ -3837,7 +3837,7 @@ namespace xmp_corpus std::string dump; }; - // A packet parses, or libfiles refuses it with its own error; anything else escaping is a fault. + // A packet parses, or libfiles refuses it with its own error; anything escaping is a fault. outcome parse(const std::string_view packet) { outcome result; @@ -3845,12 +3845,8 @@ namespace xmp_corpus try { libfiles::xmp::meta meta; - meta.parse(packet); - result.dump = dump(meta); - } - catch (const libfiles::xmp::error&) - { - result.refused = true; + if (meta.parse(packet)) result.dump = dump(meta); + else result.refused = true; } catch (const std::exception& e) { @@ -3914,17 +3910,7 @@ namespace xmp_corpus std::string environment_variable(const char* const name) { -#ifdef _MSC_VER - char* value = nullptr; - size_t size = 0; - if (_dupenv_s(&value, &size, name) != 0 || !value) return {}; - std::string result(value); - free(value); - return result; -#else - const auto* const value = std::getenv(name); - return value ? value : ""; -#endif + return platform::environment_variable(name).value_or(""); } std::vector corpus_files() @@ -4377,37 +4363,27 @@ static void should_read_back_every_xmp_packet_libfiles_writes() for (const auto& p : packets) { libfiles::xmp::meta meta; - - try - { - meta.parse(p.packet); - } - catch (...) - { - continue; - } + if (!meta.parse(p.packet)) continue; const auto written = xmp_corpus::dump(meta); for (const auto& f : forms) { - std::string text; + auto serialized = meta.serialize(f.options); - try - { - text = meta.serialize(f.options); - } - catch (const libfiles::xmp::error& e) + if (!serialized) { // A packet larger than the exact length cannot be written at it. if (!f.options.exact_packet_length) { - differences.push_back(std::format("{} ({}): not written: {}", p.label, f.name, e.what())); + differences.push_back( + std::format("{} ({}): not written: {}", p.label, f.name, serialized.message())); } continue; } + const auto text = std::move(*serialized); ++compared; const auto reread = xmp_corpus::parse(text); diff --git a/src/test_platform_linux.cpp b/src/test_platform_linux.cpp new file mode 100644 index 00000000..73e06e30 --- /dev/null +++ b/src/test_platform_linux.cpp @@ -0,0 +1,1283 @@ +// This file is part of the Diffractor photo and video organizer +// Copyright 2026 Zac Walker +// +// This Source Code Form is subject to the terms of the Mozilla Public +// License, v. 2.0. If a copy of the MPL was not distributed with this +// file, You can obtain one at https://mozilla.org/MPL/2.0/. + +// Purpose: Tests for Linux platform integration, the counterpart of test_platform_win.cpp, built on Linux alone: what +// Diffractor says where Delete moves items to the freedesktop.org Trash, the commands it leaves out where their service +// is a stand-in, Eject among them, how it finds and lists a drive where a drive is named by its mount point, and that +// its executable exports none of its static libraries' symbols; the file operations and settings saves libdesktop makes +// on Linux, some failed on purpose through its Linux test seams; and what only Linux builds, since only it has FFmpeg's +// encoders - the movie writer, AV1 by libaom and AAC in an MP4, read back through the application's own media reader +// and FFmpeg's, and the screen recorder that polls a window's own pixels, run over frames made here and asked for by +// the test as the UI thread. + +#include "pch.h" +#include "test.h" +#include "test_fixtures.h" +#include "test_runner.h" +#include "app_commands.h" +#include "app_text.h" +#include "app_util.h" +#include "ui_dialog.h" +#include "app.h" +#include "model_search.h" +#include "view_items.h" +#include "libdesktop/ui/test_support.h" +#include "libdesktop/platform/linux.h" +#include "app_record.h" +#include "av_format.h" +#include "av_movie_writer.h" +#include "model_movie.h" +#include "view_movie.h" + +extern "C" +{ +#include +#include +} + +namespace +{ + // Where Delete moves items to the freedesktop.org Trash, every text that says where an item went names the Trash, + // and none keeps the Recycle Bin or the Windows that recycles. + void should_say_trash_where_delete_goes_to_the_trash() + { + assert_equal(true, wastebasket_is_trash(platform::environment().family), + "this desktop's wastebasket is a Trash"); + + const std::pair texts[] = { + {&tt.import_replace_warning, &tt.import_replace_warning_trash}, + {&tt.options_confirm_del, &tt.options_confirm_del_trash}, + {&tt.sync_delete_warning, &tt.sync_delete_warning_trash}, + {&tt.delete_no_recycle_warning, &tt.delete_no_trash_warning}, + }; + + for (const auto& [recycle_bin, trash] : texts) + { + const auto& chosen = wastebasket_text(*recycle_bin, *trash); + assert_equal(true, &chosen == trash, "the Trash's words are the ones chosen"); + assert_equal(true, core::contains(chosen.sv(), "Trash"), "they name the Trash"); + assert_equal(false, core::contains(chosen.sv(), "recycle") || core::contains(chosen.sv(), "Windows"), + "and neither a Recycle Bin nor Windows"); + } + + // What the Trash cannot take - a network mount, a Windows drive under WSL, a memory file system - is not said to + // be on a network path, which would be wrong for two of the three. + assert_equal_strict("These items cannot be moved to the Trash. They will be permanently deleted and cannot be " + "recovered.", + wastebasket_text(tt.delete_no_recycle_warning, tt.delete_no_trash_warning).sv(), + "the delete that cannot be undone"); + + const auto& info = wastebasket_text(tt.delete_info_fmt, tt.delete_info_trash_fmt); + assert_equal(true, &info == &tt.delete_info_trash_fmt, "so is the Trash's account of what Delete will do"); + assert_equal_strict("photo.jpg will be moved to the Trash.", format_plural_text(info, "photo.jpg", 1, {}), + "one item"); + + const auto many = format_plural_text(info, "photo.jpg", 3, core::file_size(uint64_t{3 * 1024})); + assert_equal(true, core::starts(many, "3 items (") && core::ends(many, ") will be moved to the Trash."), + "and several, with their size"); + } + + // scan_drives lists removable drives on Linux as on Windows, so a command that ejected would offer them and fail: + // it is absent instead. + void should_offer_no_eject_where_the_platform_has_none() + { + assert_equal(false, platform::can_eject(), "Linux cannot eject a drive"); + + const auto app = std::make_shared(); + app->initialise_commands(); + app->create_toolbars(); + app->_app_frame = std::make_shared(); + app->_view = app->_view_items; + app->update_button_state(false); + + const auto eject = app->find_command(commands::tool_eject); + assert_equal(true, eject != nullptr, "Eject is a command of the application"); + if (!eject) return; + + assert_equal(false, eject->visible, "it is absent from the interface, not dimmed"); + assert_equal(false, eject->enable, "and nothing runs it"); + } + + // Printing, the desktop background, the properties sheet, scanning and mail are stand-ins on Linux, and Share + // without a share sheet is a mail draft: each command is absent rather than a button that does nothing. + void should_offer_no_command_whose_service_is_a_stand_in() + { + const auto app = std::make_shared(); + app->initialise_commands(); + app->create_toolbars(); + app->_app_frame = std::make_shared(); + app->_view = app->_view_items; + app->update_button_state(false); + + for (const auto id : {commands::print, commands::tool_desktop_background, commands::tool_file_properties, + commands::tool_scan, commands::tool_share}) + { + const auto command = app->find_command(id); + assert_equal(true, command != nullptr, "the command exists"); + if (!command) continue; + assert_equal(false, command->visible, "it is absent from the interface: " + command->text); + assert_equal(false, command->enable, "and nothing runs it: " + command->text); + } + } + + // The names the running executable defines in its dynamic symbol table, read from its own ELF file. + std::vector exported_symbols_of_this_executable() + { + std::ifstream file("/proc/self/exe", std::ios::binary); + const auto read_block = [&file](const uint64_t offset, const uint64_t size) + { + std::string block(size, '\0'); + file.seekg(static_cast(offset)); + file.read(block.data(), static_cast(size)); + return block; + }; + // Every target Diffractor builds for is little-endian. + const auto field = [](const std::string& block, const size_t offset, const size_t size) + { + uint64_t value = 0; + std::memcpy(&value, block.data() + offset, size); + return value; + }; + + const auto header = read_block(0, 64); + assert_equal("ELF", header.substr(1, 3), "an ELF executable"); + + const auto section_size = field(header, 58, 2); + const auto section_count = field(header, 60, 2); + const auto sections = read_block(field(header, 40, 8), section_size * section_count); + std::vector names; + size_t tables = 0; + + for (uint64_t i = 0; i < section_count; ++i) + { + const auto section = sections.substr(i * section_size, section_size); + if (field(section, 4, 4) != 11) continue; // SHT_DYNSYM + + const auto symbols = read_block(field(section, 24, 8), field(section, 32, 8)); + const auto strings_section = sections.substr(field(section, 40, 4) * section_size, section_size); + const auto strings = read_block(field(strings_section, 24, 8), field(strings_section, 32, 8)); + tables++; + + // The first entry is the null symbol; a section index of zero marks a name the executable imports. + for (size_t at = 24; at + 24 <= symbols.size(); at += 24) + { + if (field(symbols, at + 6, 2) != 0) names.emplace_back(strings.c_str() + field(symbols, at, 4)); + } + } + + assert_equal(1, static_cast(tables), "dynamic symbol tables in the executable"); + return names; + } + + // libpng, zlib, bzip2 and Brotli are linked statically and also named by the FreeType, libcurl and GLib the + // executable loads, which the linker exports a symbol for unless told not to. Each of those libraries then binds to + // Diffractor's copy, and libdecor's GTK plugin is refused on a desktop that draws no window frames itself. + void should_not_export_the_symbols_of_its_static_libraries() + { + std::string exported_by_libraries; + for (const auto& name : exported_symbols_of_this_executable()) + { + for (const auto library : + {"png_"sv, "jpeg_"sv, "inflate"sv, "deflate"sv, "BZ2_"sv, "Brotli"sv, "sqlite3_"sv, "lzma_"sv}) + { + if (name.starts_with(library)) exported_by_libraries += name + " "; + } + } + + assert_equal(""s, exported_by_libraries, "static library symbols the executable exports"); + } + + // A Linux drive is named by its mount point and every one starts with '/', so the drive a folder is on is the one + // whose path holds it: not the one its first character names, and not a neighbour whose name merely starts the same. + void should_find_the_drive_of_a_folder_by_its_path() + { + const auto drive = [](const std::string_view name, const std::string_view label) + { + platform::drive_t d; + d.name = name; + d.vol_name = label; + return d; + }; + + const auto labels = df::labelled_drives( + {drive("/", {}), drive("/media/zac/Backup", "Backup"), drive("/media/zac/Backup 2", "Spare"), + drive("/media/zac/Photos", "Photos"), drive("/mnt/data", "Data"), drive("/mnt/data/archive", "Archive")}); + assert_equal(5_z, labels.size(), "each drive with a label has its own entry, and the root has none"); + + const auto label_of = [&labels](const std::string_view folder) + { + for (const auto label : {"Backup", "Spare", "Photos", "Data", "Archive"}) + { + const auto search = df::search_t::parse(std::format("volume:{}", label)); + if (df::match_volume_label(folder, labels, search.terms().front())) return std::string(label); + } + + return std::string{}; + }; + + assert_equal_strict("Backup", label_of("/media/zac/Backup/photos/2024"), "a folder on a drive"); + assert_equal_strict("Backup", label_of("/media/zac/Backup"), "and the drive itself"); + assert_equal_strict("Photos", label_of("/media/zac/Photos/2024"), "a folder on another"); + assert_equal_strict("Spare", label_of("/media/zac/Backup 2/photos"), + "a drive whose name starts with another's"); + assert_equal_strict("", label_of("/media/zac/Backup-old/photos"), "a folder beside a drive is not on it"); + assert_equal_strict("", label_of("/media/zac/backup/photos"), "a path read as the file system reads it"); + assert_equal_strict("", label_of("/home/zac/Pictures"), "a folder on a drive that has no label"); + assert_equal_strict("Data", label_of("/mnt/data/raw"), "a folder on a drive that holds another"); + assert_equal_strict("Archive", label_of("/mnt/data/archive/2020"), "and one on the drive inside it"); + } + + // Import lists a card by its name, its label and what it holds. The desktop mounts a medium in a folder named for its + // label, so a name that is a path already says the label, and Import does not say it twice. + void should_name_a_medium_once_where_import_lists_it() + { + platform::drive_t card; + card.name = "/media/zac/EOS_DIGITAL"; + card.vol_name = "EOS_DIGITAL"; + card.used = core::file_size(uint64_t{3} * 1024 * 1024 * 1024); + + const auto text = describe_import_drive(card); + assert_equal(true, core::starts(text, card.name + " "), "the card is listed by its mount point"); + assert_equal(false, core::contains(std::string_view(text).substr(card.name.size()), card.vol_name), + "and its label is not said again"); + + card.name = "/mnt/camera"; + assert_equal(true, core::contains(describe_import_drive(card), card.vol_name), + "a label the name does not carry is still said"); + } +} + +namespace +{ + constexpr auto test_rate = 48000; + + // Four saturated quadrants - red, green, blue and white - with a dark square that moves along the foot, so no two + // frames are alike, and a colour has room to be read in the middle of each quadrant. Pixels are stored blue first. + core::surface_ptr make_test_frame(const sizei extent, const int step, const uint8_t background = 0) + { + const auto frame = std::make_shared(); + frame->alloc(extent, core::texture_format::RGB); + + for (auto y = 0; y < extent.cy; ++y) + { + auto* const line = frame->pixels_line(y); + + for (auto x = 0; x < extent.cx; ++x) + { + const auto right = x >= extent.cx / 2; + const auto lower = y >= extent.cy / 2; + uint8_t b = 0; + uint8_t g = 0; + uint8_t r = 0; + + if (background > 0) b = g = r = background; + else if (!right && !lower) r = 255; + else if (right && !lower) g = 255; + else if (!right && lower) b = 255; + else b = g = r = 255; + + auto* const pixel = line + static_cast(x) * 4; + pixel[0] = b; + pixel[1] = g; + pixel[2] = r; + pixel[3] = 0xff; + } + } + + const auto side = std::max(4, extent.cy / 10); + const auto left = (step * 3) % std::max(1, extent.cx - side); + + for (auto y = extent.cy - side - 2; y < extent.cy - 2; ++y) + { + for (auto x = left; x < left + side; ++x) + { + auto* const pixel = frame->pixels_line(y) + static_cast(x) * 4; + pixel[0] = pixel[1] = pixel[2] = 0x30; + } + } + + return frame; + } + + // `frames` stereo sample frames of a 440 Hz tone, loud enough that nothing would call it quiet, from `first`. + std::vector make_tone(const int64_t first, const int64_t frames) + { + std::vector samples(static_cast(frames) * 2); + + for (int64_t i = 0; i < frames; ++i) + { + const auto value = static_cast( + std::lround(10000.0 * std::sin(2.0 * M_PI * 440.0 * static_cast(first + i) / test_rate))); + samples[static_cast(i) * 2] = samples[static_cast(i) * 2 + 1] = value; + } + + return samples; + } + + struct movie_spec + { + sizei extent{320, 180}; + int frame_rate = 30; + int frames = 90; + int bitrate = 1500000; + bool with_audio = true; + }; + + platform::movie_writer_request request_for(const movie_spec& spec, const core::file_path& path) + { + platform::movie_writer_request request; + request.path = path; + request.extent = spec.extent; + request.frame_rate = spec.frame_rate; + request.video_bitrate = spec.bitrate; + request.with_audio = spec.with_audio; + request.sample_rate = test_rate; + request.channels = 2; + request.audio_bitrate = 192000; + return request; + } + + // The frames and sound of a render: each frame at its time, then the sound up to the next, counted from the sample + // the last chunk ended on. + bool write_movie(const platform::movie_writer_ptr& writer, const movie_spec& spec) + { + int64_t samples = 0; + + for (auto i = 0; i < spec.frames; ++i) + { + if (!writer->write_frame(make_test_frame(spec.extent, i), static_cast(i) / spec.frame_rate)) + { + return false; + } + + if (!spec.with_audio) continue; + + const auto next = static_cast( + std::llround(static_cast(i + 1) / spec.frame_rate * test_rate)); + const auto chunk = make_tone(samples, next - samples); + + if (!writer->write_audio(chunk.data(), chunk.size(), static_cast(samples) / test_rate)) + { + return false; + } + + samples = next; + } + + return true; + } + + // What an MP4 holds, as FFmpeg's own demuxer reads it, packet by packet. + struct movie_facts + { + bool opened = false; + std::string video_codec; + std::string audio_codec; + sizei extent; + int pixel_format = AV_PIX_FMT_NONE; + int color_primaries = 0; + int color_transfer = 0; + int color_space = 0; + int color_range = 0; + int video_packets = 0; + int audio_packets = 0; + int key_frames = 0; + // The most frames there are between one key frame and the next. + int longest_key_run = 0; + double video_seconds = 0.0; + double audio_seconds = 0.0; + int audio_rate = 0; + int audio_channels = 0; + }; + + movie_facts read_movie_facts(const core::file_path& path) + { + movie_facts facts; + AVFormatContext* format = nullptr; + + if (avformat_open_input(&format, path.str().c_str(), nullptr, nullptr) != 0) return facts; + + if (avformat_find_stream_info(format, nullptr) < 0) + { + avformat_close_input(&format); + return facts; + } + + facts.opened = true; + auto video_index = -1; + auto audio_index = -1; + + for (unsigned i = 0; i < format->nb_streams; ++i) + { + const auto* const parameters = format->streams[i]->codecpar; + + if (parameters->codec_type == AVMEDIA_TYPE_VIDEO) + { + video_index = static_cast(i); + facts.video_codec = avcodec_get_name(parameters->codec_id); + facts.extent = {parameters->width, parameters->height}; + facts.pixel_format = parameters->format; + facts.color_primaries = parameters->color_primaries; + facts.color_transfer = parameters->color_trc; + facts.color_space = parameters->color_space; + facts.color_range = parameters->color_range; + } + else if (parameters->codec_type == AVMEDIA_TYPE_AUDIO) + { + audio_index = static_cast(i); + facts.audio_codec = avcodec_get_name(parameters->codec_id); + facts.audio_rate = parameters->sample_rate; + facts.audio_channels = parameters->ch_layout.nb_channels; + } + } + + auto* packet = av_packet_alloc(); + auto since_key = 0; + + while (av_read_frame(format, packet) >= 0) + { + const auto index = packet->stream_index; + const auto base = av_q2d(format->streams[index]->time_base); + const auto end = (static_cast(packet->pts) + static_cast(packet->duration)) * base; + + if (index == video_index) + { + ++facts.video_packets; + facts.video_seconds = std::max(facts.video_seconds, end); + + if (packet->flags & AV_PKT_FLAG_KEY) + { + ++facts.key_frames; + since_key = 0; + } + + facts.longest_key_run = std::max(facts.longest_key_run, ++since_key); + } + else if (index == audio_index) + { + ++facts.audio_packets; + facts.audio_seconds = std::max(facts.audio_seconds, end); + } + + av_packet_unref(packet); + } + + av_packet_free(&packet); + avformat_close_input(&format); + return facts; + } + + // One channel of a pixel of a decoded picture, blue first. + int channel(const core::surface& picture, const int x, const int y, const int which) + { + return picture.pixels_line(y)[static_cast(x) * 4 + static_cast(which)]; + } + + // Whether a pixel is the colour that was drawn, within what an encoder and a 4:2:0 conversion leave of it. + bool is_colour(const core::surface& picture, const int x, const int y, const int red, const int green, + const int blue) + { + constexpr auto tolerance = 24; + return std::abs(channel(picture, x, y, 2) - red) <= tolerance && + std::abs(channel(picture, x, y, 1) - green) <= tolerance && + std::abs(channel(picture, x, y, 0) - blue) <= tolerance; + } + + // The UI thread, for a recording that asks it for frames: what is queued is run until `done`, or for `seconds`. + template void pump_ui(const double seconds, const Done& done) + { + const auto deadline = core::now() + seconds; + while (!done() && core::now() < deadline) platform::pump_ui_tasks(5); + } + + // The mean of one channel over a block, to read a small thing drawn small through an encoder. + double mean_channel(const core::surface& picture, const recti block, const int which) + { + auto total = 0.0; + + for (auto y = block.top; y < block.bottom; ++y) + { + for (auto x = block.left; x < block.right; ++x) total += channel(picture, x, y, which); + } + + return total / static_cast(block.width() * block.height()); + } +} + +// Linux has a writer where the system has none to ask, and a request that names no bitrate is written at the size +// Movie mixer would have asked for, which is what the Windows writer is given for the same movie. +static void should_offer_movie_writing_on_linux() +{ + assert_equal(true, df::can_write_movies(), "Render is offered"); + assert_equal(true, av_can_write_movies(), "by FFmpeg's own encoders"); + assert_equal(df::can_write_movies(), df::can_write_movies(), "and the answer is the same twice"); + + assert_equal(6220800, av_default_movie_bitrate({1920, 1080}, 30), + "HD at 30 is the 6.2 Mbit/s Movie mixer gives it"); + assert_equal(1000000, av_default_movie_bitrate({64, 64}, 30), "a tiny movie has Movie mixer's floor"); + assert_equal(60000000, av_default_movie_bitrate({7680, 4320}, 60), "a huge one its ceiling"); +} + +// What the Windows writer is held to: a movie with no size or no rate is refused, and what is refused leaves no file +// where the movie should be, which a render would otherwise report as written. +static void should_refuse_an_impossible_movie_on_linux() +{ + movie_spec spec; + spec.extent = {0, 0}; + const auto path = test_temps.next_path(".mp4"); + assert_equal(true, df::create_movie_writer(request_for(spec, path)) == nullptr, "a zero-sized movie is refused"); + assert_equal(false, platform::exists(path), "and no partial file is left behind"); + + spec.extent = {320, 180}; + spec.frame_rate = 0; + assert_equal(true, df::create_movie_writer(request_for(spec, path)) == nullptr, "a movie with no frame rate is"); + assert_equal(false, platform::exists(path), "and still leaves nothing behind"); + + const auto nowhere = test_temps.next_folder("no-such-folder").combine("missing").combine_file("movie.mp4"); + spec.frame_rate = 30; + assert_equal(true, df::create_movie_writer(request_for(spec, nowhere)) == nullptr, + "so is a folder that is not there"); +} + +// A movie written with picture and sound is AV1 and AAC in an MP4 that opens, plays and means what was drawn: its +// size, its length, its colours, its sound, and an index at the front. +static void should_write_a_movie_of_av1_and_aac() +{ + const movie_spec spec; + const auto path = test_temps.next_path(".mp4"); + const auto writer = df::create_movie_writer(request_for(spec, path)); + assert_equal(true, writer != nullptr, "a writer is made"); + if (!writer) return; + + assert_equal(true, write_movie(writer, spec), "frames and sound are accepted"); + assert_equal(true, writer->close(), "the movie is finished"); + assert_equal(true, platform::exists(path), "and is where it was asked to be"); + assert_equal(true, writer->last_error().empty(), "with no error to report"); + + const auto facts = read_movie_facts(path); + assert_equal(true, facts.opened, "the file opens"); + assert_equal("av1"s, facts.video_codec, "the picture is AV1"); + assert_equal("aac"s, facts.audio_codec, "the sound is AAC"); + assert_equal(true, facts.extent == spec.extent, "at the size drawn"); + assert_equal(static_cast(AV_PIX_FMT_YUV420P), facts.pixel_format, "in 8-bit 4:2:0"); + assert_equal(static_cast(AVCOL_PRI_BT709), facts.color_primaries, "tagged BT.709"); + assert_equal(static_cast(AVCOL_TRC_BT709), facts.color_transfer, "with its transfer"); + assert_equal(static_cast(AVCOL_SPC_BT709), facts.color_space, "and its matrix"); + assert_equal(static_cast(AVCOL_RANGE_MPEG), facts.color_range, "in limited range"); + assert_equal(spec.frames, facts.video_packets, "every frame is one packet of picture"); + assert_near(3.0, facts.video_seconds, 0.05, "the picture lasts as long as its frames"); + assert_near(3.0, facts.audio_seconds, 0.1, "and the sound as long as its samples"); + assert_equal(test_rate, facts.audio_rate, "the sound is at the rate asked"); + assert_equal(2, facts.audio_channels, "in stereo"); + assert_equal(true, facts.key_frames >= 2, "a key frame comes round again"); + assert_equal(true, facts.longest_key_run <= 2 * spec.frame_rate, "within two seconds"); + assert_equal(true, av_index_first(path), "and the index is before the media, so it plays as it downloads"); + + // What the application reads it as. + av_format_decoder decoder; + assert_equal(true, decoder.open(path, media_intent::playback), "the application opens the movie"); + decoder.init_streams(-1, -1, false, false, false); + const auto info = decoder.info(); + assert_equal(true, info.has_video && info.has_audio, "it has picture and sound"); + assert_equal("av1"s, std::string(info.video_codec.sv()), "AV1 to the application"); + assert_equal("aac"s, std::string(info.audio_codec.sv()), "and AAC"); + assert_equal(true, info.display_dimensions == spec.extent, "the size it was made at"); + assert_near(3.0, info.end - info.start, 0.1, "and the length"); + assert_near(30.0, info.video_frame_rate, 0.5, "at the rate"); + + // The first frame is the one drawn: the colours came through the conversion and the tag. + core::surface_ptr first; + assert_equal(true, decoder.extract_frame_at(first, spec.extent, 0.0), "the first frame is decoded"); + if (!first) return; + + const auto w = spec.extent.cx; + const auto h = spec.extent.cy; + assert_equal(true, is_colour(*first, w / 4, h / 4, 255, 0, 0), "red where it was red"); + assert_equal(true, is_colour(*first, w * 3 / 4, h / 4, 0, 255, 0), "green where it was green"); + assert_equal(true, is_colour(*first, w / 4, h * 3 / 4 - 8, 0, 0, 255), "blue where it was blue"); + assert_equal(true, is_colour(*first, w * 3 / 4, h * 3 / 4 - 8, 255, 255, 255), "and white where it was white"); + + // The sound is the tone: 440 Hz at 10000, not silence. + const auto pcm = decoder.extract_audio_pcm_range(test_rate, 1.0, 1.0); + auto peak = 0; + for (const auto sample : pcm) peak = std::max(peak, std::abs(static_cast(sample))); + assert_equal(true, peak > 8000 && peak < 12000, "the tone is heard at the level it was written"); +} + +// A writer that is let go without being finished, or asked to give up, leaves nothing at the path: not a partial +// movie, and not a movie that looks finished. One that was finished keeps its file whatever is done to it after. +static void should_leave_no_file_of_an_abandoned_movie() +{ + const movie_spec spec; + auto path = test_temps.next_path(".mp4"); + + { + const auto writer = df::create_movie_writer(request_for(spec, path)); + assert_equal(true, writer != nullptr && write_movie(writer, {{320, 180}, 30, 10}), "a few frames are written"); + assert_equal(true, platform::exists(path), "and a partial file is the writer's"); + writer->abandon(); + assert_equal(false, platform::exists(path), "abandoned, it is removed"); + writer->abandon(); + assert_equal(false, writer->write_frame(make_test_frame(spec.extent, 0), 0.0), "and nothing more is written"); + assert_equal(false, writer->close(), "nor finished"); + } + + assert_equal(false, platform::exists(path), "nothing is left once it is gone"); + + path = test_temps.next_path(".mp4"); + + { + const auto writer = df::create_movie_writer(request_for(spec, path)); + assert_equal(true, writer != nullptr && write_movie(writer, {{320, 180}, 30, 10}), "frames are written again"); + assert_equal(true, platform::exists(path), "to a partial file"); + } + + assert_equal(false, platform::exists(path), "which the writer removes when it is let go unfinished"); + + path = test_temps.next_path(".mp4"); + + { + const auto writer = df::create_movie_writer(request_for(spec, path)); + assert_equal(true, writer != nullptr && write_movie(writer, {{320, 180}, 30, 10}), "a movie is written"); + assert_equal(true, writer->close(), "and finished"); + writer->abandon(); + } + + assert_equal(true, platform::exists(path), "a finished movie is the caller's, whatever the writer does after"); + assert_equal(true, read_movie_facts(path).opened, "and plays"); +} + +// The times a caller gives are kept. A frame later than the next shows what came before it until then, as the +// Windows writer's sink does, so the movie is as long as its times and its sound stays in step; a frame that is not +// after the last is refused, and says why. +static void should_hold_a_picture_through_a_hole_in_the_times() +{ + movie_spec spec; + spec.with_audio = true; + const auto path = test_temps.next_path(".mp4"); + const auto writer = df::create_movie_writer(request_for(spec, path)); + assert_equal(true, writer != nullptr, "a writer is made"); + if (!writer) return; + + assert_equal(true, writer->write_frame(make_test_frame(spec.extent, 0), 0.0), "the first frame"); + assert_equal(true, writer->write_frame(make_test_frame(spec.extent, 1), 1.0 / 30), "the next"); + assert_equal(true, writer->write_frame(make_test_frame(spec.extent, 2), 5.0 / 30), "one three frames after it"); + assert_equal(false, writer->write_frame(make_test_frame(spec.extent, 3), 5.0 / 30), + "one at the same time is refused"); + assert_equal(false, writer->last_error().empty(), "and the writer says why"); + assert_equal(false, writer->write_frame(make_test_frame(spec.extent, 3), 2.0 / 30), "so is one before it"); + + // Sound for the first tenth of a second, then a pause, then sound again from half a second in. + const auto first = make_tone(0, test_rate / 10); + assert_equal(true, writer->write_audio(first.data(), first.size(), 0.0), "sound is accepted"); + const auto later = make_tone(test_rate / 2, test_rate / 10); + assert_equal(true, writer->write_audio(later.data(), later.size(), 0.5), "and sound after a pause"); + assert_equal(true, writer->close(), "the movie is finished"); + + const auto facts = read_movie_facts(path); + assert_equal(6, facts.video_packets, "the hole is six frames, not three"); + assert_near(6.0 / 30, facts.video_seconds, 0.01, "so the picture lasts to the last frame"); + assert_near(0.6, facts.audio_seconds, 0.05, "and the sound to the end of what it was given, the pause kept"); +} + +// Cancel abandons the writer: a render stopped part way leaves neither the movie nor the file it was staged in. +static void should_leave_no_file_of_a_cancelled_render() +{ + const auto folder = test_temps.next_folder("cancelled-render"); + + movie_render_request request; + request.clips = {make_movie_text("Cancelled", 2)}; + request.output = derive_movie_output(request.clips); + request.path = folder.combine_file("movie.mp4"); + + std::atomic_bool stop = false; + const auto control = std::make_shared(); + const auto result = render_movie_to_file(request, [&stop](const double) { stop = true; }, core::cancel_token(stop), + control); + + assert_equal(true, result.cancelled && !result.ok, "the render says it was cancelled"); + assert_equal(false, platform::exists(request.path), "no movie is left"); + assert_equal(0_z, platform::iterate_file_items(folder, true).files.size(), "nor the file it was staged in"); +} + +// What a platform that films a window's own pixels is asked: a frame at a steady rate, from the UI thread. Here the +// test is the UI thread, running what the recorder queues for it, and the window is made of frames drawn here, 321 by +// 201 so that the movie has to be even. +static void should_record_a_window_at_a_steady_rate() +{ + const auto path = test_temps.next_path(".mp4"); + + screen_recording_request request; + request.path = path; + request.seconds = 1.0; + request.draw_pointer = false; + // The window's client area starts at (10, 20) on the screen, so a script's point there is (100, 100) in it. + request.client_origin = [] + { + return pointi{10, 20}; + }; + + auto captures = 0; + const auto recording = start_window_recording(request, [&captures] + { return make_test_frame({321, 201}, captures++, 0x30); }); + assert_equal(true, recording != nullptr, "a recording starts"); + if (!recording) return; + + recording->pointer(pointi{110, 120}, 0.0); + recording->mark("first"); + + pump_ui(30.0, [&recording] { return recording->is_finished(); }); + + assert_equal(true, recording->is_finished(), "it finishes by itself once its length is written"); + recording->stop(); + platform::pump_ui_tasks(); + + const auto summary = recording->summary(); + assert_equal(true, summary.starts_with("Recorded"), "and says it recorded: " + summary); + assert_equal(true, captures >= 5, "the window was asked for as the clock went"); + + const auto facts = read_movie_facts(path); + assert_equal(true, facts.opened, "the movie opens"); + assert_equal("av1"s, facts.video_codec, "AV1"); + assert_equal(true, facts.extent == sizei{320, 200}, "of the window's even size"); + assert_equal(30, facts.video_packets, "a second at 30 frames a second is 30 frames"); + assert_near(1.0, facts.video_seconds, 0.05, "which last a second"); + assert_equal(0, facts.audio_packets, "with no sound"); + + // The markers are the moments named, and the movie's end. + const auto markers = read_test_file(screen_recording_markers_path(path)); + assert_equal(true, markers.find("\tfirst\n") != std::string::npos, "the markers name the moment marked"); + assert_equal(true, markers.ends_with("1.000\tend\n"), "and the end of the movie"); + + // The pointer the script showed is in the frames: a white arrow at its point, over the window's grey. + av_format_decoder decoder; + assert_equal(true, decoder.open(path, media_intent::playback), "the application opens the recording"); + decoder.init_streams(-1, -1, false, false, false); + core::surface_ptr middle; + assert_equal(true, decoder.extract_frame_at(middle, {320, 200}, 0.5), "a frame from the middle decodes"); + if (!middle) return; + + const auto arrow = mean_channel(*middle, {101, 103, 103, 107}, 1); + const auto beyond = mean_channel(*middle, {200, 103, 202, 107}, 1); + assert_equal(true, arrow > beyond + 40, "the arrow is white where the script pointed"); +} + +// A recording ends when it is told to, from the thread the window's own work is done on: the recorder is waiting on that +// thread for a frame when it is told, so stopping must not wait for the frame the thread is no longer there to give. +static void should_stop_a_recording_that_waits_for_the_ui_thread() +{ + const auto path = test_temps.next_path(".mp4"); + + screen_recording_request request; + request.path = path; + request.draw_pointer = false; + + const auto recording = start_window_recording(request, [] { return make_test_frame({160, 120}, 0, 0x30); }); + assert_equal(true, recording != nullptr, "a recording with no length starts"); + if (!recording) return; + + pump_ui(0.6, [&recording] { return recording->elapsed() > 0.5; }); + assert_equal(false, recording->is_finished(), "it goes on until it is stopped"); + assert_equal(true, recording->elapsed() > 0.2, "and its clock runs"); + + // The next frame the recorder asks for is never given: this thread is in stop. + const auto stopped_at = core::now(); + recording->stop(); + assert_equal(true, core::now() - stopped_at < 5.0, "stopping does not wait on the thread that stops it"); + recording->stop(); + assert_equal(true, recording->is_finished(), "it has finished"); + assert_equal(true, recording->summary().starts_with("Recorded"), "with what it recorded: " + recording->summary()); + + const auto facts = read_movie_facts(path); + assert_equal(true, facts.video_packets >= 10, "the second half of a second was written"); + assert_equal(true, platform::exists(screen_recording_markers_path(path)), "and its markers are beside it"); + platform::pump_ui_tasks(); +} + +// A window that gives no pixels is no window to record: the recording says so, and writes no movie. +static void should_report_a_recording_of_a_window_with_no_pixels() +{ + const auto path = test_temps.next_path(".mp4"); + + screen_recording_request request; + request.path = path; + const auto recording = start_window_recording(request, [] { return core::surface_ptr{}; }); + assert_equal(true, recording != nullptr, "a recording starts"); + if (!recording) return; + + pump_ui(30.0, [&recording] { return recording->is_finished(); }); + + recording->stop(); + assert_equal(true, recording->summary().starts_with("Recording failed"), + "it says it failed: " + recording->summary()); + assert_equal(false, platform::exists(path), "and no movie is written"); +} + +// The INI settings store's own saves, through libdesktop's Linux test seams. + +static void should_commit_linux_ini_file_settings_after_durable_save() +{ + const auto settings_folder = test_temps.folder().combine("linux-ini-settings"); + platform::create_folder(settings_folder); + const auto settings_path = settings_folder.combine_file("diffractor.ini"); + + auto settings = platform::create_ini_file_settings(settings_folder); + assert_equal(true, settings->write("test_section", "string_value", "original"), "initial write"); + + for (const auto failure : + {platform::linux_settings_test_failure::after_open, platform::linux_settings_test_failure::after_write, + platform::linux_settings_test_failure::before_replace}) + { + platform::test_linux_settings_failure(failure); + assert_equal(false, settings->write("test_section", "string_value", "updated"), "failed write reports false"); + platform::test_linux_settings_failure(platform::linux_settings_test_failure::none); + + std::string same_instance; + assert_equal(true, settings->read("test_section", "string_value", same_instance), + "same instance still has committed value"); + assert_equal("original", same_instance, "failed write does not publish uncommitted value"); + assert_equal(false, platform::exists(settings_folder.combine_file(".diffractor.ini.tmp")), + "failed write removes stage"); + + const auto reopened = platform::create_ini_file_settings(settings_folder); + std::string reopened_value; + assert_equal(true, reopened->read("test_section", "string_value", reopened_value), + "reopened settings read committed value"); + assert_equal("original", reopened_value, "failed write preserves on-disk value"); + assert_equal(true, platform::exists(settings_path), "settings file remains present"); + } + + assert_equal(true, settings->write("test_section", "string_value", "updated"), "write succeeds after failures"); + const auto reopened = platform::create_ini_file_settings(settings_folder); + std::string reopened_value; + assert_equal(true, reopened->read("test_section", "string_value", reopened_value), "reopened updated value"); + assert_equal("updated", reopened_value, "successful write reaches disk"); +} + +static void should_skip_unchanged_linux_ini_file_settings() +{ + const auto settings_folder = test_temps.folder().combine("linux-ini-unchanged"); + platform::create_folder(settings_folder); + auto settings = platform::create_ini_file_settings(settings_folder); + + platform::test_linux_reset_settings_save_count(); + assert_equal(true, settings->write("test_section", "string_value", "same"), "initial write"); + const auto saves_after_first = platform::test_linux_settings_save_count(); + assert_equal(true, saves_after_first > 0, "initial write saves"); + + assert_equal(true, settings->write("test_section", "string_value", "same"), "unchanged write succeeds"); + assert_equal(saves_after_first, platform::test_linux_settings_save_count(), "unchanged write does not save"); +} + +static void should_commit_linux_ini_file_settings_from_owned_stage() +{ + const auto settings_folder = test_temps.folder().combine("linux-ini-owned-stage"); + platform::create_folder(settings_folder); + auto first = platform::create_ini_file_settings(settings_folder); + auto second = platform::create_ini_file_settings(settings_folder); + + assert_equal(true, first->write("test_section", "string_value", "original"), "initial write"); + + bool nested = false; + platform::test_linux_before_settings_replace = [&] + { + if (nested) return; + nested = true; + platform::test_linux_before_settings_replace = {}; + assert_equal(true, second->write("test_section", "string_value", "second"), "nested write"); + }; + + const auto first_write = first->write("test_section", "string_value", "first"); + platform::test_linux_before_settings_replace = {}; + + assert_equal(true, first_write, "outer write succeeds with its own stage"); + const auto reopened = platform::create_ini_file_settings(settings_folder); + std::string value; + assert_equal(true, reopened->read("test_section", "string_value", value), "reopened setting"); + assert_equal("first", value, "outer complete write wins with complete bytes"); +} + +// File operations as Linux makes them, some through libdesktop's Linux test seams. + +static void should_report_linux_file_operation_errors() +{ + const platform::file_op_result collision{platform::file_op_result_code::ALREADY_EXISTS}; + const platform::file_op_result failure{platform::file_op_result_code::FAILED}; + assert_equal(true, collision.failed(), "an existing destination is a failure"); + assert_equal(false, collision.format_error().empty(), "a collision cannot look like an empty success message"); + assert_equal(false, failure.format_error().empty(), "an unspecified failure still has a diagnostic"); +} + +static void should_reject_linux_folder_file_collisions() +{ + const auto root = test_temps.next_folder("linux-folder-collision"); + const auto file = root.combine_file("occupied"); + write_test_file(file, "not a directory"); + + assert_equal(true, platform::create_folder(root.combine("occupied")).failed(), + "an existing file is not a successful mkdir"); + assert_equal("not a directory", read_test_file(file), "the colliding file is unchanged"); + + const auto link = root.combine("dangling"); + std::filesystem::create_directory_symlink(platform::to_stream_path(root.combine("missing")), + platform::to_stream_path(link)); + assert_equal(true, platform::create_folder(link).failed(), "a dangling symlink is not a directory"); + assert_equal(true, platform::create_folder(root.combine("directory")).success(), "a new directory is created"); + assert_equal(true, platform::create_folder(root.combine("directory")).success(), + "an existing directory is accepted"); +} + +static void should_preserve_linux_directory_move_on_unsupported_no_replace() +{ + const auto root = test_temps.next_folder("linux-directory-move"); + const auto source = root.combine("source"); + const auto destination = root.combine("destination"); + assert_equal(true, platform::create_folder(source).success(), "source directory exists"); + write_test_file(source.combine_file("original.txt"), "original"); + + platform::test_linux_move_file_failures({true, false}); + const core::scope_exit restore([] { platform::test_linux_clear_move_file_failures(); }); + const auto result = platform::move_file(source, destination); + assert_equal(true, result.failed(), "unsupported atomic directory rename is a reported failure"); + assert_equal("original", read_test_file(source.combine_file("original.txt")), "source is retained"); + assert_equal(false, platform::exists(destination), "an unsafe fallback did not publish a destination"); +} + +static void should_refuse_linux_copy_identity_overwrites() +{ + const auto root = test_temps.next_folder("linux-copy-identity"); + const auto source = root.combine_file("source.bin"); + const auto alias = root.combine_file("alias.bin"); + const core::blob bytes = {1, 2, 3, 4}; + platform::blob_save_to_file(bytes, source); + std::filesystem::create_hard_link(platform::to_stream_path(source), platform::to_stream_path(alias)); + + const auto same_path = platform::copy_file(source, source, false, false); + assert_equal(true, same_path.failed(), "copy to self fails"); + assert_equal(true, platform::blob_from_file(source) == bytes, "copy to self preserves source"); + + const auto hard_link = platform::copy_file(source, alias, false, false); + assert_equal(true, hard_link.failed(), "copy to hard-link alias fails"); + assert_equal(true, platform::blob_from_file(source) == bytes, "hard-link source bytes survive"); + assert_equal(true, platform::blob_from_file(alias) == bytes, "hard-link destination bytes survive"); +} + +static void should_report_linux_copy_flush_failures() +{ + const auto root = test_temps.next_folder("linux-copy-flush"); + const auto source = root.combine_file("source.bin"); + const auto destination = root.combine_file("destination.bin"); + const core::blob source_bytes = {9, 8, 7, 6, 5, 4}; + const core::blob original_destination = {1, 2, 3}; + platform::blob_save_to_file(source_bytes, source); + platform::blob_save_to_file(original_destination, destination); + + platform::linux_copy_file_test_failures partial; + partial.max_write_bytes = 2; + partial.interrupt_first_write = true; + platform::test_linux_copy_file_failures(partial); + const auto partial_result = platform::copy_file(source, root.combine_file("partial.bin"), true, false); + platform::test_linux_clear_copy_file_failures(); + assert_equal(true, partial_result.success(), "partial and interrupted writes complete"); + assert_equal(true, platform::blob_from_file(root.combine_file("partial.bin")) == source_bytes, + "partial write copy has every byte"); + + platform::linux_copy_file_test_failures write_failure; + write_failure.fail_write_after_calls = 0; + platform::test_linux_copy_file_failures(write_failure); + const auto write_result = platform::copy_file(source, destination, false, false); + platform::test_linux_clear_copy_file_failures(); + assert_equal(true, write_result.failed(), "write failure is reported"); + assert_equal(true, platform::blob_from_file(destination) == original_destination, + "write failure preserves prior destination"); + + platform::linux_copy_file_test_failures close_failure; + close_failure.fail_destination_close = true; + platform::test_linux_copy_file_failures(close_failure); + const auto close_result = platform::copy_file(source, destination, false, false); + platform::test_linux_clear_copy_file_failures(); + assert_equal(true, close_result.failed(), "late close failure is reported"); + assert_equal(true, platform::blob_from_file(destination) == original_destination, + "late close failure preserves prior destination"); +} + +static void should_claim_linux_auto_rename_destinations_atomically() +{ + const auto root = test_temps.next_folder("linux-auto-rename"); + const auto source_folder = root.combine("source"); + const auto target = root.combine("target"); + platform::create_folder(source_folder); + platform::create_folder(target); + + const auto source = source_folder.combine_file("photo.txt"); + const core::blob source_bytes = {7}; + const core::blob competing_bytes = {3}; + platform::blob_save_to_file(source_bytes, source); + + bool competed = false; + platform::test_linux_before_claim_file_path = [&](const core::file_path candidate) + { + if (!competed) + { + competed = true; + platform::blob_save_to_file(competing_bytes, candidate); + } + }; + + const auto result = platform::move_or_copy({source}, {}, target, false); + platform::test_linux_before_claim_file_path = {}; + + assert_equal(true, result.success(), "copy retries after a raced file candidate"); + assert_equal(1_z, result.created_files.files.size(), "one copied file is reported"); + assert_equal(true, result.created_files.files.front() != target.combine_file("photo.txt"), + "the raced name was not reported as copied"); + assert_equal(true, platform::blob_from_file(target.combine_file("photo.txt")) == competing_bytes, + "competing file bytes survive"); + assert_equal(true, platform::blob_from_file(result.created_files.files.front()) == source_bytes, + "reported file has source bytes"); + + const auto replace_source = source_folder.combine_file("replace.txt"); + const auto replace_target = target.combine_file("replace.txt"); + platform::blob_save_to_file(source_bytes, replace_source); + platform::blob_save_to_file(competing_bytes, replace_target); + const auto replace = platform::move_or_copy({replace_source}, {}, target, false, true); + assert_equal(true, replace.success(), "explicit replace still succeeds"); + assert_equal(true, platform::blob_from_file(replace_target) == source_bytes, "replace writes source bytes"); +} + +static void should_reject_linux_recursive_copy_into_descendant() +{ + const auto root = test_temps.next_folder("linux-descendant-copy"); + const auto source = root.combine("source"); + const auto child = source.combine("child"); + platform::create_folder(child); + platform::blob_save_to_file(core::blob{1}, source.combine_file("photo.txt")); + + const auto result = platform::move_or_copy({}, {source}, child, false); + assert_equal(true, result.failed(), "copy into descendant fails"); + assert_equal(false, platform::exists(child.combine("source")), "descendant target is not created"); + assert_equal(true, platform::exists(source.combine_file("photo.txt")), "source remains available"); +} + +static void should_delete_linux_directory_symlinks() +{ + const auto root = test_temps.next_folder("linux-delete-symlink"); + const auto source = root.combine("source"); + const auto target = root.combine("target"); + const auto link = source.combine("linked"); + platform::create_folder(source); + platform::create_folder(target); + platform::blob_save_to_file(core::blob{1}, source.combine_file("file.txt")); + platform::blob_save_to_file(core::blob{2}, target.combine_file("target.txt")); + std::filesystem::create_directory_symlink(platform::to_stream_path(target), platform::to_stream_path(link)); + + const auto result = platform::delete_items({}, {source}, false); + assert_equal(true, result.success(), std::format("delete succeeds ({})", result.format_error())); + assert_equal(false, platform::exists(source), "source folder is removed"); + assert_equal(true, platform::exists(target.combine_file("target.txt")), "symlink target survives"); +} + +static void should_move_or_copy_linux_directory_symlinks() +{ + const auto root = test_temps.next_folder("linux-copy-symlink"); + const auto source = root.combine("source"); + const auto target = root.combine("target"); + const auto link_target = root.combine("linked-target"); + platform::create_folder(source); + platform::create_folder(target); + platform::create_folder(link_target); + std::filesystem::create_directory_symlink(platform::to_stream_path(link_target), + platform::to_stream_path(source.combine("linked"))); + + const auto result = platform::move_or_copy({}, {source}, target, false); + assert_equal(true, result.success(), std::format("copy succeeds ({})", result.format_error())); + assert_equal(1_z, result.created_files.folders.size(), "one folder reported"); + const auto copied_link = result.created_files.folders.front().combine("linked"); + assert_equal(true, std::filesystem::is_symlink(platform::to_stream_path(copied_link)), + "directory symlink is recreated"); + assert_equal(platform::to_stream_path(link_target).string(), + std::filesystem::read_symlink(platform::to_stream_path(copied_link)).string(), + "link target spelling is preserved"); +} + +static void should_move_or_copy_into_its_own_folder_with_auto_rename() +{ + const auto root = test_temps.next_folder("linux-copy-self-parent"); + const auto file = root.combine_file("photo.txt"); + const auto folder = root.combine("album"); + platform::blob_save_to_file(core::blob{7}, file); + platform::create_folder(folder); + platform::blob_save_to_file(core::blob{8}, folder.combine_file("inside.txt")); + + const auto file_result = platform::move_or_copy({file}, {}, root, false); + assert_equal(true, file_result.success(), std::format("file copy succeeds ({})", file_result.format_error())); + assert_equal(1_z, file_result.created_files.files.size(), "one copied file reported"); + assert_equal(true, file_result.created_files.files.front() != file, "copy uses a new file name"); + assert_equal(true, platform::blob_from_file(file_result.created_files.files.front()) == core::blob{7}, + "copied file has the source bytes"); + + const auto folder_result = platform::move_or_copy({}, {folder}, root, false); + assert_equal(true, folder_result.success(), std::format("folder copy succeeds ({})", folder_result.format_error())); + assert_equal(1_z, folder_result.created_files.folders.size(), "one copied folder reported"); + assert_equal(true, folder_result.created_files.folders.front() != folder, "copy uses a new folder name"); + assert_equal(true, platform::exists(folder_result.created_files.folders.front().combine_file("inside.txt")), + "copied folder has the source contents"); +} + +static void should_move_or_copy_stop_on_inner_linux_folder_collision() +{ + const auto root = test_temps.next_folder("linux-inner-collision"); + const auto source = root.combine("album"); + const auto target = root.combine("target"); + platform::create_folder(source); + platform::create_folder(target); + platform::blob_save_to_file(core::blob{5}, source.combine_file("inside.txt")); + + bool competed = false; + platform::test_linux_before_copy_folder_file_path = [&](const core::file_path candidate) + { + if (!competed) + { + competed = true; + platform::blob_save_to_file(core::blob{6}, candidate); + } + }; + + const auto result = platform::move_or_copy({}, {source}, target, false); + platform::test_linux_before_copy_folder_file_path = {}; + + assert_equal(true, result.failed(), "inner collision fails the claimed tree"); + assert_equal(false, platform::exists(target.combine("album (2)")), "inner collision does not retry the top folder"); + assert_equal(true, platform::blob_from_file(target.combine("album").combine_file("inside.txt")) == core::blob{6}, + "competing inner file survives"); +} + +static void should_move_linux_no_replace_without_renameat_or_links() +{ + const auto root = test_temps.next_folder("linux-move-fallback"); + const auto source = root.combine_file("source.txt"); + const auto destination = root.combine_file("destination.txt"); + const core::blob bytes = {4, 3, 2}; + platform::blob_save_to_file(bytes, source); + + platform::test_linux_move_file_failures({true, true}); + const auto result = platform::move_file(source, destination, true); + platform::test_linux_clear_move_file_failures(); + + assert_equal(true, result.success(), std::format("fallback move succeeds ({})", result.format_error())); + assert_equal(false, platform::exists(source), "source is removed after the exclusive copy"); + assert_equal(true, platform::blob_from_file(destination) == bytes, "destination has source bytes"); +} + +static void should_refuse_or_preserve_linux_replace_permissions() +{ + const auto root = test_temps.next_folder("linux-copy-permissions"); + const auto source = root.combine_file("source.txt"); + const auto read_only = root.combine_file("read-only.txt"); + const auto private_file = root.combine_file("private.txt"); + const core::blob source_bytes = {9}; + const core::blob original_bytes = {1}; + platform::blob_save_to_file(source_bytes, source); + platform::blob_save_to_file(original_bytes, read_only); + platform::blob_save_to_file(original_bytes, private_file); + + namespace fs = std::filesystem; + fs::permissions(platform::to_stream_path(read_only), + fs::perms::owner_read | fs::perms::group_read | fs::perms::others_read, fs::perm_options::replace); + const auto refused = platform::copy_file(source, read_only, false, false); + assert_equal(true, refused.failed(), "read-only destination refuses replace"); + assert_equal(true, platform::blob_from_file(read_only) == original_bytes, "read-only destination bytes survive"); + + fs::permissions(platform::to_stream_path(private_file), fs::perms::owner_read | fs::perms::owner_write, + fs::perm_options::replace); + const auto replaced = platform::copy_file(source, private_file, false, false); + assert_equal(true, replaced.success(), std::format("replace succeeds ({})", replaced.format_error())); + const auto mode = fs::status(platform::to_stream_path(private_file)).permissions() & fs::perms::all; + assert_equal(true, mode == (fs::perms::owner_read | fs::perms::owner_write), + "replace preserves destination permissions"); +} + +static void should_move_or_copy_reject_linux_destination_alias_inside_source() +{ + const auto root = test_temps.next_folder("linux-copy-alias-descendant"); + const auto source = root.combine("source"); + const auto nested = source.combine("a").combine("b"); + const auto target = root.combine("target-link"); + platform::create_folder(nested); + platform::blob_save_to_file(core::blob{1}, source.combine_file("top.txt")); + platform::blob_save_to_file(core::blob{2}, source.combine("a").combine_file("mid.txt")); + std::filesystem::create_directory_symlink(platform::to_stream_path(nested), platform::to_stream_path(target)); + + const auto result = platform::move_or_copy({}, {source}, target, false); + assert_equal(true, result.failed(), "alias into source is rejected"); + assert_equal(false, platform::exists(nested.combine("source")), "copy does not create output inside source"); + assert_equal(true, platform::exists(source.combine_file("top.txt")), "source remains available"); +} + +void register_platform_linux_tests(view_state& /*state*/, test_registry& tests) +{ + tests.add("Should say Trash where Delete goes to the Trash"s, should_say_trash_where_delete_goes_to_the_trash); + tests.add("Should offer no eject where the platform has none"s, should_offer_no_eject_where_the_platform_has_none); + tests.add("Should offer no command whose service is a stand-in"s, + should_offer_no_command_whose_service_is_a_stand_in); + tests.add("Should not export the symbols of its static libraries"s, + should_not_export_the_symbols_of_its_static_libraries); + tests.add("Should find the drive of a folder by its path"s, should_find_the_drive_of_a_folder_by_its_path); + tests.add("Should name a medium once where Import lists it"s, should_name_a_medium_once_where_import_lists_it); + tests.add("Should offer movie writing on Linux"s, should_offer_movie_writing_on_linux); + tests.add("Should refuse an impossible movie on Linux"s, should_refuse_an_impossible_movie_on_linux); + tests.add("Should write a movie of AV1 and AAC"s, should_write_a_movie_of_av1_and_aac); + tests.add("Should leave no file of an abandoned movie"s, should_leave_no_file_of_an_abandoned_movie); + tests.add("Should hold a picture through a hole in the times"s, should_hold_a_picture_through_a_hole_in_the_times); + tests.add("Should leave no file of a cancelled render"s, should_leave_no_file_of_a_cancelled_render); + tests.add("Should record a window at a steady rate"s, should_record_a_window_at_a_steady_rate); + tests.add("Should stop a recording that waits for the UI thread"s, + should_stop_a_recording_that_waits_for_the_ui_thread); + tests.add("Should report a recording of a window with no pixels"s, + should_report_a_recording_of_a_window_with_no_pixels); + // PLAT-010 - Linux INI writes published values before the file was durably replaced. + tests.add("Should commit Linux INI file settings after durable save"s, + should_commit_linux_ini_file_settings_after_durable_save); + // G21 review - unchanged settings values should not restage and fsync the whole file. + tests.add("Should skip unchanged Linux INI file settings"s, should_skip_unchanged_linux_ini_file_settings); + // G21 review - each settings save needs its own stage path. + tests.add("Should commit Linux INI file settings from owned stage"s, + should_commit_linux_ini_file_settings_from_owned_stage); + // PLAT-007 - Linux replacement copy truncated source/destination aliases before reading. + tests.add("Should reject Linux folder file collisions"s, should_reject_linux_folder_file_collisions); + tests.add("Should report Linux file operation errors"s, should_report_linux_file_operation_errors); + tests.add("Should preserve Linux directory move on unsupported no replace"s, + should_preserve_linux_directory_move_on_unsupported_no_replace); + tests.add("Should refuse Linux copy identity overwrites"s, should_refuse_linux_copy_identity_overwrites); + // PLAT-007 - Linux copy ignored short writes and delayed close failures. + tests.add("Should report Linux copy flush failures"s, should_report_linux_copy_flush_failures); + // PLAT-008 - Linux auto-rename used a pre-check then an overwrite-capable copy. + tests.add("Should move or copy by claiming Linux auto rename destinations atomically"s, + should_claim_linux_auto_rename_destinations_atomically); + // PLAT-009 - Linux recursive folder copy could copy into its own destination. + tests.add("Should move or copy reject Linux recursive copy into descendant"s, + should_reject_linux_recursive_copy_into_descendant); + // G21 review - directory symlinks must be listed so delete can unlink them. + tests.add("Should delete Linux directory symlinks"s, should_delete_linux_directory_symlinks); + // G21 review - folder copy must not silently drop directory symlinks. + tests.add("Should move or copy Linux directory symlinks"s, should_move_or_copy_linux_directory_symlinks); + // G21 review - copying into the source's own parent should auto-rename, not fail on identity. + tests.add("Should move or copy into its own folder with auto rename"s, + should_move_or_copy_into_its_own_folder_with_auto_rename); + // G21 review - an inner collision belongs to the claimed tree, not the outer name picker. + tests.add("Should move or copy stop on inner Linux folder collision"s, + should_move_or_copy_stop_on_inner_linux_folder_collision); + // G21 review - filesystems without renameat2/link support still need a safe no-replace move. + tests.add("Should move Linux no replace without renameat or links"s, + should_move_linux_no_replace_without_renameat_or_links); + // G21 review - replacement copy must respect destination writeability and mode. + tests.add("Should refuse or preserve Linux replace permissions"s, + should_refuse_or_preserve_linux_replace_permissions); + // G21 review - containment checks must follow aliases into the source subtree. + tests.add("Should move or copy reject Linux destination alias inside source"s, + should_move_or_copy_reject_linux_destination_alias_inside_source); +} diff --git a/src/test_platform_win.cpp b/src/test_platform_win.cpp index b1ab6bb3..43dc5418 100644 --- a/src/test_platform_win.cpp +++ b/src/test_platform_win.cpp @@ -5,12 +5,13 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: Tests for Windows platform integration. These are the only tests whose subject is the -// operating system itself -- the application manifest, extended path syntax, DXGI device loss, adapter +// Purpose: Tests for Windows platform integration, the counterpart of test_platform_linux.cpp. These are the only +// tests whose subject is Windows itself -- the application manifest, extended path syntax, DXGI device loss, adapter // classification and the texture budget taken from it, the adapter the decode device is made on, texture // recycling, the crash-guard recovery session, the system font stack, the registry settings store, time zone -// conversion, the shell drag data object and the snap-layouts caption button. -// Keeping them here is what lets every other test file stay free of system headers. +// conversion, the shell drag data object, the snap-layouts caption button, the software renderer's window-sized +// buffer and the Recycle Bin's words. +// Keeping them here is what lets every other test file stay free of Windows headers. #include "pch.h" #include "libdesktop/platform/win32.h" @@ -19,6 +20,7 @@ #include "av_format.h" #include "test_fixtures.h" +#include "app_text.h" #include @@ -1506,16 +1508,24 @@ static void should_read_coherent_number_format_snapshots() assert_equal(",", platform::number_dec_sep(), "the separator belongs to the same refreshed snapshot"); } -static void should_bound_the_software_buffer_as_the_client_grows() +// The software renderer draws into one buffer as large as the window, kept while a drag of the window's edge stays +// within a step of it, and presents each frame once, and only the damage it repainted. +static void should_hold_a_window_sized_software_buffer_across_a_resize_drag() { - const auto probe = render::probe_software_tiling(); + const auto probe = render::probe_software_present(); - // Without this the assertion below would still pass if the buffer went back to tracking the - // window, which is the thing tiling exists to stop. - assert_equal(true, probe.grown_buffer_pixels < probe.grown_client_pixels / 4, - "the buffer stayed bounded while the client grew"); - assert_equal(probe.grown_client_pixels, probe.grown_writable_pixels, - "a grown client is writable to its new edges without reallocating the tile"); + assert_equal(1, probe.presents, "a frame is presented once"); + assert_equal(true, probe.presented_the_damage, "and what it presents is the damage"); + assert_equal(true, probe.kept_pixels_outside_damage, "a partial repaint keeps the pixels outside the damage"); + + assert_equal(0, probe.reallocations_growing_within_step, "a client grown within its buffer keeps it"); + assert_equal(0, probe.reallocations_shrinking_a_little, "and one shrunk a little"); + assert_equal(1, probe.reallocations_shrinking_to_half, "a client under half of it is worth a smaller buffer"); + assert_equal(1, probe.reallocations_growing_past_buffer, "and one grown past it needs a larger"); + assert_equal(true, probe.grown_buffer_pixels >= probe.grown_client_pixels, "the buffer is as large as the client"); + assert_equal(probe.grown_client_pixels, probe.grown_writable_pixels, "and writable to its new edges"); + + assert_equal(true, probe.repainted_client_into_fresh_buffer, "a fresh buffer is presented whole"); } static void should_translate_highlight_spans_to_utf16_clusters() @@ -1616,6 +1626,18 @@ static void should_snap_gpu_text_in_pixel_coordinates() "text callbacks report enabled snapping, identity transform and one pixel per DIP"); } +static void should_keep_the_recycle_bins_words_on_windows() +{ + // Windows keeps the text its translations are of; the Trash's is Linux's. + assert_equal(false, wastebasket_is_trash(platform::environment().family), "Windows' wastebasket is not a Trash"); + assert_equal(true, + &wastebasket_text(tt.delete_no_recycle_warning, tt.delete_no_trash_warning) == + &tt.delete_no_recycle_warning, + "so the warning is the one about a network path"); + assert_equal(true, &wastebasket_text(tt.delete_info_fmt, tt.delete_info_trash_fmt) == &tt.delete_info_fmt, + "and Delete says it will recycle when Windows can"); +} + static void should_refuse_an_impossible_movie() { // The probe is the whole of whether Render is offered, so an unstable answer would make the @@ -1640,6 +1662,14 @@ static void should_refuse_an_impossible_movie() assert_equal(false, platform::exists(request.path), "and still leaves nothing behind"); } +// The numbers are MAPI's own result codes, the email draft's answer on Windows. +static void should_classify_mapi_results() +{ + assert_equal(true, platform::classify_mapi_result(0) == platform::mail_result::sent, "MAPI success"); + assert_equal(true, platform::classify_mapi_result(1) == platform::mail_result::canceled, "MAPI user abort"); + assert_equal(true, platform::classify_mapi_result(3) == platform::mail_result::failed, "MAPI login failure"); +} + void register_platform_tests(view_state& /*state*/, test_registry& tests) { tests.add("Should preserve writability probe collisions"s, should_preserve_writability_probe_collisions); @@ -1705,8 +1735,8 @@ void register_platform_tests(view_state& /*state*/, test_registry& tests) should_answer_hit_tests_on_the_maximize_toolbar_button_as_the_caption_button); // PLAT-018 - coherent locale-format snapshots. tests.add("Should read coherent number format snapshots"s, should_read_coherent_number_format_snapshots); - tests.add("Should bound the software buffer as the client grows"s, - should_bound_the_software_buffer_as_the_client_grows); + tests.add("Should hold a window sized software buffer across a resize drag"s, + should_hold_a_window_sized_software_buffer_across_a_resize_drag); // UI-006 - Unicode highlights must be translated to the UTF-16 clusters DirectWrite draws. tests.add("Should translate highlight spans to utf16 clusters"s, should_translate_highlight_spans_to_utf16_clusters); @@ -1720,5 +1750,7 @@ void register_platform_tests(view_state& /*state*/, test_registry& tests) tests.add("Should gate native bubble alpha steps"s, should_gate_native_bubble_alpha_steps); // PLAT-016 - a missing font renderer is a degraded text outcome, not a null dereference. tests.add("Should handle unavailable font layout"s, should_handle_unavailable_font_layout); + tests.add("Should keep the Recycle Bin's words on Windows"s, should_keep_the_recycle_bins_words_on_windows); tests.add("Should refuse an impossible movie"s, should_refuse_an_impossible_movie); + tests.add("Should classify MAPI results"s, should_classify_mapi_results); } diff --git a/src/test_render.cpp b/src/test_render.cpp index 05ef1f0c..91ae18fc 100644 --- a/src/test_render.cpp +++ b/src/test_render.cpp @@ -5,11 +5,10 @@ // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: Tests for the rendering layer (render*, util_simd) -- software blends, YUV conversion for the software backend, packed-surface area downscaling, surface transforms (resize, rotate) and the drawn logo. +// Purpose: Tests for the rendering layer (render*) -- YUV conversion for the software backend, packed-surface area downscaling, surface transforms (resize, rotate) and the drawn logo. #include "pch.h" #include "test.h" -#include "libdesktop/core/simd.h" #include "av_format.h" #include "libdesktop/render/software.h" #include "test_fixtures.h" @@ -19,11 +18,6 @@ #include "ui_globe.h" #include "ui_panorama.h" -static uint8_t blend_opaque_channel(const uint8_t dest, const float src, const float alpha) -{ - return static_cast(std::clamp(static_cast(src * alpha + dest * (1.0f - alpha) + 0.5f), 0, 255)); -} - static void should_unpremultiply_surface_alpha() { core::surface surface; @@ -37,83 +31,6 @@ static void should_unpremultiply_surface_alpha() assert_equal(0xff336699u, surface.get_pixel(2, 0), "opaque pixels are unchanged"); } -static uint8_t blend_opaque_normalized_channel(const uint8_t dest, const float src, const float alpha) -{ - const auto value = src * alpha + (dest / 255.0f) * (1.0f - alpha); - return static_cast(std::clamp(static_cast(value * 255.0f + 0.5f), 0, 255)); -} - -static void should_match_simd_software_blends() -{ -#if defined(COMPILE_SIMD_INTRINSIC) - constexpr size_t max_pixels = 19; - alignas(16) std::array original{}; - alignas(16) std::array source{}; - alignas(16) std::array coverage{}; - - for (size_t i = 0; i < original.size(); ++i) original[i] = static_cast(i * 47u + 13u); - for (size_t i = 0; i < source.size(); ++i) source[i] = static_cast(i * 29u + 7u); - for (size_t i = 0; i < coverage.size(); ++i) coverage[i] = static_cast(i * 61u + 3u); - - constexpr std::array alphas = {0.0f, 0.13f, 0.5f, 0.87f, 1.0f}; - constexpr float sb = 37.0f; - constexpr float sg = 149.0f; - constexpr float sr = 231.0f; - - for (size_t count = 0; count <= max_pixels; ++count) - { - for (const auto alpha : alphas) - { - auto check = [&](auto&& scalar, auto&& simd, const std::string_view message) - { - auto expected = original; - auto actual = original; - for (size_t i = 0; i < count; ++i) scalar(expected.data() + i * 4, i); - const auto processed = simd(actual.data()); - assert_equal(count & ~size_t{3}, processed, message); - for (size_t i = processed; i < count; ++i) scalar(actual.data() + i * 4, i); - assert_equal(true, expected == actual, message); - }; - - auto blend_solid_pixel = [](uint8_t* dest, const float b, const float g, const float r, const float a) - { - dest[0] = blend_opaque_normalized_channel(dest[0], b, a); - dest[1] = blend_opaque_normalized_channel(dest[1], g, a); - dest[2] = blend_opaque_normalized_channel(dest[2], r, a); - dest[3] = 255; - }; - - check([&](uint8_t* dest, size_t) - { blend_solid_pixel(dest, sb / 255.0f, sg / 255.0f, sr / 255.0f, alpha); }, [&](uint8_t* dest) { - return blend_solid_opaque_sse2(dest, count, sb / 255.0f, sg / 255.0f, sr / 255.0f, alpha); - }, "SIMD solid blend"); - - check([&](uint8_t* dest, const size_t i) { - blend_solid_pixel(dest, sb / 255.0f, sg / 255.0f, sr / 255.0f, alpha * coverage[i] / 255.0f); - }, [&](uint8_t* dest) { - return blend_glyph_opaque_sse2(dest, coverage.data(), count, sb / 255.0f, sg / 255.0f, sr / 255.0f, - alpha); - }, "SIMD glyph blend"); - - for (const auto has_alpha : {false, true}) - { - check([&](uint8_t* dest, const size_t i) - { - const auto* src = source.data() + i * 4; - const auto pixel_alpha = (has_alpha ? src[3] / 255.0f : 1.0f) * alpha; - dest[0] = blend_opaque_channel(dest[0], src[0], pixel_alpha); - dest[1] = blend_opaque_channel(dest[1], src[1], pixel_alpha); - dest[2] = blend_opaque_channel(dest[2], src[2], pixel_alpha); - dest[3] = 255; - }, [&](uint8_t* dest) { - return blend_bgra_opaque_sse2(dest, source.data(), count, has_alpha, alpha); - }, "SIMD BGRA blend"); - } - } - } -#endif -} - // The CPU renderer and every CPU conversion map HDR through the cube the GPU samples, so the lookup has // to be the arithmetic of a trilinear texture sample: the signal scaled onto the samples, with 0 and // 65535 on the end samples, and the eight around it blended by distance. Each output channel is a @@ -1950,10 +1867,6 @@ static void should_keep_an_overlapped_month_selectable() void register_render_tests(view_state& /*state*/, test_registry& tests) { tests.add("Should unpremultiply surface alpha"s, should_unpremultiply_surface_alpha); -#if defined(COMPILE_SIMD_INTRINSIC) - // TEST-007 - registration follows the compiled assertion body. - tests.add("Should match SIMD software blends"s, should_match_simd_software_blends); -#endif tests.add("Should rasterise tiles identically to the whole surface"s, should_rasterise_tiles_identically_to_the_whole_surface); tests.add("Should rasterise one scene to one answer on every platform"s, diff --git a/src/test_runner.h b/src/test_runner.h index b6b2c620..977a0424 100644 --- a/src/test_runner.h +++ b/src/test_runner.h @@ -23,6 +23,7 @@ void register_media_edit_tests(view_state& state, test_registry& tests); void register_metadata_tests(view_state& state, test_registry& tests); void register_movie_tests(view_state& state, test_registry& tests); void register_platform_tests(view_state& state, test_registry& tests); +void register_platform_linux_tests(view_state& state, test_registry& tests); void register_render_tests(view_state& state, test_registry& tests); void register_search_tests(view_state& state, test_registry& tests); void register_text_tests(view_state& state, test_registry& tests); diff --git a/src/test_search.cpp b/src/test_search.cpp index e763bf67..35feaef4 100644 --- a/src/test_search.cpp +++ b/src/test_search.cpp @@ -865,26 +865,47 @@ static void should_not_call_a_cancelled_query_complete(shared_test_context& stc) static void should_match_volume_label() { - // Map a drive letter to a volume label so the volume: term can be matched - // deterministically without depending on the drives present on the machine. - core::hash_map labels; - labels['X'] = core::cache("Backup"); - - const auto exact = df::search_t::parse("volume:Backup"); - const auto& exact_term = exact.terms().front(); - - assert_equal(true, df::match_volume_label("X:\\photos\\2024", labels, exact_term), "match on drive X"); - assert_equal(true, df::match_volume_label("x:\\photos", labels, exact_term), "drive letter case-insensitive"); - assert_equal(false, df::match_volume_label("Y:\\photos", labels, exact_term), "different drive"); - assert_equal(false, df::match_volume_label("\\\\server\\share", labels, exact_term), - "unc path has no drive letter"); - - assert_equal(true, df::match_volume_label("X:\\x", labels, df::search_t::parse("volume:BACKUP").terms().front()), - "label case-insensitive"); - assert_equal(true, df::match_volume_label("X:\\x", labels, df::search_t::parse("volume:Back*").terms().front()), - "label wildcard"); - assert_equal(false, df::match_volume_label("X:\\x", labels, df::search_t::parse("volume:Other").terms().front()), - "non-matching label"); + // The drives are made up so the volume: term can be matched without depending on those this machine has. A drive + // is named by its path, as scan_drives names it: a letter's root on Windows, a mount point on Linux. + constexpr auto windows = core::windows_path_semantics; + const auto drive = [](const std::string_view name, const std::string_view label) + { + platform::drive_t d; + d.name = name; + d.vol_name = label; + return d; + }; + + const auto backup = drive(windows ? "X:\\" : "/media/zac/Backup", "Backup"); + const auto photos = drive(windows ? "Y:\\" : "/media/zac/Photos", "Photos"); + const auto system = drive(windows ? "C:\\" : "/", {}); + const auto labels = df::labelled_drives({system, backup, photos}); + assert_equal(2_z, labels.size(), "a drive with no label has none to match"); + + const auto on = [](const platform::drive_t& d, const std::string_view folder) + { + return std::string(core::folder_path(d.name).combine(folder).text().sv()); + }; + const auto volume = [&labels](const std::string_view folder, const std::string_view query) + { + const auto search = df::search_t::parse(std::format("volume:{}", query)); + return df::match_volume_label(folder, labels, search.terms().front()); + }; + + assert_equal(true, volume(on(backup, "photos/2024"), "Backup"), "match on the drive"); + assert_equal(true, volume(backup.name, "Backup"), "and on the drive itself"); + assert_equal(false, volume(on(photos, "photos"), "Backup"), "different drive"); + assert_equal(false, volume(on(system, "photos"), "Backup"), "a drive with no label"); + + if constexpr (windows) + { + assert_equal(true, volume("x:\\photos", "Backup"), "drive letter case-insensitive"); + assert_equal(false, volume("\\\\server\\share", "Backup"), "unc path has no drive letter"); + } + + assert_equal(true, volume(on(backup, "x"), "BACKUP"), "label case-insensitive"); + assert_equal(true, volume(on(backup, "x"), "Back*"), "label wildcard"); + assert_equal(false, volume(on(backup, "x"), "Other"), "non-matching label"); } static void should_match_date(const std::string_view query, const core::date_t d) diff --git a/src/test_util.cpp b/src/test_util.cpp index fc830fac..ce0844d1 100644 --- a/src/test_util.cpp +++ b/src/test_util.cpp @@ -46,6 +46,8 @@ static void should_name_files_after_the_application() assert_equal("diffractor"sv, core::app_file_stem(), "file stem"); assert_equal("diffractor.log"sv, platform::log_path.name(), "log"); assert_equal("diffractor.previous.log"sv, platform::previous_log_path.name(), "previous log"); + // The ID the desktop file, the AppStream metadata and the Flatpak in packaging/ carry; case matters to all three. + assert_equal_strict("com.diffractor.Diffractor"sv, core::app_id(), "application ID"); } static void should_complete_result_scope() @@ -666,7 +668,7 @@ static void should_convert_utf8() const auto round_tripped_utf16 = core::utf8_to_utf16(actual_utf8); assert_equal(1, static_cast(round_tripped_utf16.size()), std::format("icon round-trip UTF-16 length for 0x{:X}", icon_val)); - assert_equal(static_cast(icon_val), round_tripped_utf16[0], + assert_equal(static_cast(icon_val), static_cast(round_tripped_utf16[0]), std::format("icon round-trip code point for 0x{:X}", icon_val)); // Also verify str:: matches platform:: conversion @@ -1054,16 +1056,17 @@ static void should_parse_command_line() command_line_t cl_agent; cl_agent.parse(std::format("-mcp -mcp-ui:offscreen -MCP-ALLOW:write,capture \"{}\"", path3)); - assert_equal(true, cl_agent.agent, "an agent session"); - assert_equal("offscreen"sv, cl_agent.agent_ui, "where its window is"); - assert_equal("write,capture"sv, cl_agent.agent_allow, "what it may do beyond reading"); + assert_equal(true, cl_agent.agent.session, "an agent session"); + assert_equal("offscreen"s, cl_agent.agent.ui, "where its window is"); + assert_equal("write,capture"s, cl_agent.agent.allow, "what it may do beyond reading"); assert_equal(false, cl_agent.can_forward_file(), "an agent session is never handed to a running window"); command_line_t cl_tool; cl_tool.parse("-tool:movie_check \"projects=C:\\my movies\\trip.dfv\" skip_missing=true -no-gpu"); - assert_equal("movie_check"sv, cl_tool.tool, "a single tool call"); - assert_equal(2_z, cl_tool.tool_arguments.size(), "its arguments are the parts after it"); - assert_equal("projects=C:\\my movies\\trip.dfv"sv, cl_tool.tool_arguments.front(), "a quoted one keeps its space"); + assert_equal("movie_check"s, cl_tool.agent.tool, "a single tool call"); + assert_equal(2_z, cl_tool.agent.tool_arguments.size(), "its arguments are the parts after it"); + assert_equal("projects=C:\\my movies\\trip.dfv"s, cl_tool.agent.tool_arguments.front(), + "a quoted one keeps its space"); assert_equal(true, cl_tool.no_gpu, "and a switch among them still parses"); assert_equal(true, cl_tool.selection.is_empty(), "an argument naming a path is the tool's, not a file to open"); @@ -1207,22 +1210,29 @@ static void should_find_text() static void should_compare_versions() { - const core::version current_version(s_app_version); + const df::app_version current_version(s_app_version); assert_equal(s_app_version, current_version.to_string(), "Can parse and to_string current version"); - const core::version test_version1("123.45"); - const core::version test_version1b("123.45"); - const core::version test_version2("456.1"); + const df::app_version test_version1("1.23.45"); + const df::app_version test_version1b("1.23.45"); + const df::app_version test_version2("4.56.1"); - assert_equal("123.45", test_version1.to_string(), "Can parse and to_string test version 1"); - assert_equal("456.1", test_version2.to_string(), "Can parse and to_string test version 2"); + assert_equal("1.23.45", test_version1.to_string(), "Can parse and to_string test version 1"); + assert_equal("4.56.1", test_version2.to_string(), "Can parse and to_string test version 2"); assert_equal(true, test_version1 < test_version2, "Less op version"); assert_equal(false, test_version2 < test_version1, "Less op version"); assert_equal(false, test_version1 == test_version2, "== op version"); assert_equal(true, test_version1 == test_version1b, "== op version"); - assert_equal("457.1", (test_version2 + 1).to_string(), "+ op version"); + // The two-part form older builds and the update check use reads as the same version. + assert_equal("1.27.4", df::app_version("127.4").to_string(), "two-part version"); + assert_equal(true, df::app_version("127.4") == df::app_version("1.27.4"), "both forms are one version"); + assert_equal(true, df::app_version("127.5") > df::app_version("1.27.4"), "an offer in the old form is newer"); + assert_equal(true, df::app_version("1.28.0") > df::app_version("127.9"), "the next line is newer"); + assert_equal(true, df::app_version("1.27.4.1316") == df::app_version("1.27.4"), "a build is not the version"); + assert_equal(true, df::app_version("127.4.1316") == df::app_version("1.27.4"), "nor in the two-part form"); + assert_equal(127, df::app_version("1.27.4").line(), "the release line"); } // Verifies the append-only string interning table: one shared immutable copy per unique diff --git a/src/test_view.cpp b/src/test_view.cpp index cb04eb33..aa39f684 100644 --- a/src/test_view.cpp +++ b/src/test_view.cpp @@ -6195,16 +6195,20 @@ static void should_forward_checkbox_hits_to_visible_checked_child() checkbox->checked(false); assert_equal(false, checkbox->is_control_area({15, 25}, {}), "unchecked child is not interactive"); hit_test_context unchecked_ctx{{15, 25}, recti(0, 0, 200, 100)}; + // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks): a shared_ptr owns it; MSVC's count is opaque assert_equal(true, checkbox->controller_from_location(host, {15, 25}, {}, unchecked_ctx) == nullptr, "unchecked child receives no controller lookup"); + // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks) checkbox->checked(true); checkbox->collapse_child_when_unchecked(); checkbox->checked(false); assert_equal(false, checkbox->is_control_area({15, 25}, {}), "collapsed child is not interactive"); hit_test_context collapsed_ctx{{15, 25}, recti(0, 0, 200, 100)}; + // NOLINTBEGIN(clang-analyzer-cplusplus.NewDeleteLeaks): a shared_ptr owns it; MSVC's count is opaque assert_equal(true, checkbox->controller_from_location(host, {15, 25}, {}, collapsed_ctx) == nullptr, "collapsed child receives no controller lookup"); + // NOLINTEND(clang-analyzer-cplusplus.NewDeleteLeaks) } // Every layout of a task view enabled every control in its panel, so the options of a format not @@ -6868,6 +6872,7 @@ static void should_show_and_take_a_slider_value_in_tenths_as_seconds() slider.edit_change("1e999"); assert_equal(600, value, "and to a minute, however long the typed number"); + // NOLINTNEXTLINE(clang-analyzer-deadcode.DeadStores): the slider holds value by reference and shows it next value = 125; slider.show_bound_value(); assert_equal("12.5"sv, box->window_text(), "a value its owner sets shows in seconds"); @@ -9119,7 +9124,7 @@ static void should_start_a_commodore_cartridge() assert_equal(true, v.display->_c64 != nullptr, "Start starts the machine"); assert_equal(1_z, v.as.pending_worker_count(async_queue::emulator), "on the emulator's queue"); - libfiles::c64_listing blank; + lib64::media_listing blank; blank.rows.emplace_back().file_type = 0x99; assert_equal("PITFALL"sv, c64_cartridge_title(blank, "pitfall"), "a blank header gives way to the file's name"); } diff --git a/src/ui_c64.cpp b/src/ui_c64.cpp index 0a298a46..41b6e6a3 100644 --- a/src/ui_c64.cpp +++ b/src/ui_c64.cpp @@ -158,20 +158,18 @@ commodore_disk_control::commodore_disk_control(view_state& state, display_state_ _display(std::move(display)) { const auto& data = _display->_selected_item_data; - _listing = libfiles::list_c64_media({data.data(), data.size()}); + _listing = lib64::list_media({data.data(), data.size()}).value(); _cols = static_cast(_listing.columns); _rows = static_cast(_listing.rows.size()); const auto* const file_type = _display->_item1 ? _display->_item1->file_type() : nullptr; - const auto tape = file_type && file_type->extension == "t64"; const auto disk = file_type && file_type->has_trait(file_traits::disk_image); auto runnable = 0; for (const auto& row : _listing.rows) { - const auto runs = c64_row_runs(row.file_type, tape); - _runs.push_back(runs); - if (runs) ++runnable; + _runs.push_back(row.runs); + if (row.runs) ++runnable; } // A disk is chosen from by its rows. Anything else that holds just one thing to run starts it with a button. @@ -370,7 +368,7 @@ bool is_c64_cartridge(const file_type& type) return type.has_trait(file_traits::commodore) && core::icmp(type.extension, "crt") == 0; } -std::string c64_cartridge_title(const libfiles::c64_listing& listing, const std::string_view file_name) +std::string c64_cartridge_title(const lib64::media_listing& listing, const std::string_view file_name) { std::string title; @@ -604,11 +602,11 @@ c64_cartridge_control::c64_cartridge_control(view_state& state, display_state_pt _display(std::move(display)) { const auto& data = _display->_selected_item_data; - const auto listing = libfiles::list_c64_media({data.data(), data.size()}); + const auto listing = lib64::list_media({data.data(), data.size()}).value(); const auto name = _display->_item1 ? std::string(_display->_item1->path().file_name_without_extension()) : std::string{}; _title = c64_cartridge_title(listing, name); - if (listing.rows.size() == 1 && c64_row_runs(listing.rows.front().file_type, false)) _row = 0; + if (listing.rows.size() == 1 && listing.rows.front().runs) _row = 0; } sizei c64_cartridge_control::measure(render::measure_context& mc, const int width_limit) const diff --git a/src/ui_c64.h b/src/ui_c64.h index 62643ebb..9be37ce0 100644 --- a/src/ui_c64.h +++ b/src/ui_c64.h @@ -13,7 +13,7 @@ #include "ui_elements.h" #include "model_display.h" -#include "libfiles/commodore.h" +#include "lib64/listing.h" // The size the machine's picture is drawn at in space of avail: as large as fits, keeping its shape, and at a // whole multiple of its pixels when that gives up at most a fifth of the size, so they stay square and sharp. @@ -24,7 +24,7 @@ sizei fit_c64_picture(sizei avail, bool& whole); bool is_c64_cartridge(const file_type& type); // The title a cartridge's label carries: the name its header gives it, or the file's when that is blank. -std::string c64_cartridge_title(const libfiles::c64_listing& listing, std::string_view file_name); +std::string c64_cartridge_title(const lib64::media_listing& listing, std::string_view file_name); // Draws Commodore's own cartridge for the C64 and VIC-20 into r, standing as it goes into the machine and in its // shell's proportions, with the depth the sidebar's calendar gives its blocks: a black shell whose grip ridges cross @@ -71,7 +71,7 @@ class commodore_disk_control final : view_state& _state; display_state_ptr _display; - libfiles::c64_listing _listing; + lib64::media_listing _listing; int _cols = 0; int _rows = 0; // Whether each row names something the machine can start. diff --git a/src/ui_dialog.h b/src/ui_dialog.h index 1e80befe..5602b40e 100644 --- a/src/ui_dialog.h +++ b/src/ui_dialog.h @@ -1430,9 +1430,8 @@ namespace ui const auto r = center_rect(_text_extent, limit); _rect_text.set(bounds.left, r.top, bounds.right, r.top + _text_extent.cy); - int y_off = 4; + constexpr int y_off = 4; _rect_progress.set(bounds.left, r.bottom + y_off, bounds.right, r.bottom + y_off + 8); - if (_pos > 0) y_off += 16; _parent->invalidate(); } diff --git a/src/ui_music.cpp b/src/ui_music.cpp index 15b4e4f1..dd7adc03 100644 --- a/src/ui_music.cpp +++ b/src/ui_music.cpp @@ -36,6 +36,7 @@ view_elements_ptr make_media_transport(view_state& state, const display_state_pt scrubber_element::found_spans spans; }; + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): a shared_ptr owns it; MSVC's count is opaque scrubber->found_by([&state, display, cache = std::make_shared()] { const auto& item = display->is_one() ? display->_item1 : nullptr; diff --git a/src/ui_view.h b/src/ui_view.h index 8018361e..6b7a4ae8 100644 --- a/src/ui_view.h +++ b/src/ui_view.h @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -13,6 +13,7 @@ #pragma once +#include "libdesktop/ui/app_bars.h" #include "libdesktop/ui/controls.h" class view_host; @@ -48,28 +49,7 @@ namespace bubble_delay } } -struct pointer_dwell -{ - pointi origin; - uint64_t since = 0; - bool armed = false; - - void reset() { armed = false; } - - bool ready(const uint64_t now, const pointi position, const int tolerance, const uint32_t delay, - const bool follow_pointer = false) - { - const auto moved = std::abs(static_cast(position.x) - origin.x) > tolerance || - std::abs(static_cast(position.y) - origin.y) > tolerance; - if (!armed || now < since || (moved && !follow_pointer)) - { - origin = position; - since = now; - armed = true; - } - return now - since >= delay; - } -}; +using ui::pointer_dwell; using view_scroller = ui::scroller; using view_scroller_section = ui::scroller_section; diff --git a/src/util_crash_files_db.h b/src/util_crash_files_db.h index 12013ad2..f113ec96 100644 --- a/src/util_crash_files_db.h +++ b/src/util_crash_files_db.h @@ -1,12 +1,13 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public // License, v. 2.0. If a copy of the MPL was not distributed with this // file, You can obtain one at https://mozilla.org/MPL/2.0/. -// Purpose: Crash-loop protection. Records which media files were open when the process faulted so -// the next launch does not scan them again, and keeps that list bounded, attributed and recoverable. +// Purpose: Crash-loop protection. Records which media files were open when the process faulted - by the process +// itself, or where its crash is reported by the next start, from the report it left - so the next launch does not +// scan them again, and keeps that list bounded, attributed and recoverable. #pragma once @@ -17,6 +18,8 @@ class crash_files_db core::file_path path; std::string_view context; uint32_t thread_id = 0; + // The piece of the crash report's work that stands for this file, ended with it. + platform::crash_work_id work = 0; }; using open_file_id = uint64_t; @@ -30,6 +33,9 @@ class crash_files_db core::file_path _crash_files_path; std::string _release_tag; + // Whether the files open are also kept where a crash report reads them, for a process whose crash is reported + // by the next start rather than in process: only the process's own list does, which is not a test's. + bool _publish_open_files = false; path_set _crash_files; size_t _lines_on_disk = 0; @@ -62,17 +68,26 @@ class crash_files_db } public: + // A file a run that has ended had open when it crashed, as the report it left names it, and the thread that had it. + struct reported_open_file + { + core::file_path path; + uint32_t thread_id = 0; + }; + // Deliberately the release line and not the build or the point release. The build number changes // on every compile, so tagging with it retried every recorded file after almost any update and // handed the user the same crash again. Retrying once per release line is where a decoder fix - // actually reaches them, and costs at most one repeat crash per file. + // actually reaches them, and costs at most one repeat crash per file. 1.27.4 and 127.4 are one line, + // tagged 127 as lists written by the two-part builds are. static std::string release_tag(const std::string_view app_version) { - return core::to_string(core::version(app_version).major); + return core::to_string(df::app_version(app_version).line()); } - crash_files_db(const core::file_path path, const std::string_view release_tag) : - _crash_files_path(path), _release_tag(release_tag) + crash_files_db(const core::file_path path, const std::string_view release_tag, + const bool publish_open_files = false) : + _crash_files_path(path), _release_tag(release_tag), _publish_open_files(publish_open_files) { try { @@ -98,16 +113,26 @@ class crash_files_db open_file_id add_open(const core::file_path path, const std::string_view context) { + // Where a crash report reads it, for a fatal signal cannot ask this list, whose lock the faulting thread may + // hold. Made before the lock: nothing here may wait on it. + const auto work = _publish_open_files && platform::crash_reporting() + ? platform::add_crash_work(std::format("{}\t{}", context, path.str())) + : 0; + core::exclusive_lock lock(_mtx); const auto id = _next_open_file_id++; - _open_files[id] = {path, context, core::current_thread_id()}; + _open_files[id] = {path, context, core::current_thread_id(), work}; return id; } void remove_open(const open_file_id id) { core::exclusive_lock lock(_mtx); - _open_files.erase(id); + const auto found = _open_files.find(id); + if (found == _open_files.end()) return; + + platform::remove_crash_work(found->second.work); + _open_files.erase(found); } // The following two readers run from the crash / application-recovery handler @@ -187,6 +212,51 @@ class crash_files_db open.thread_id == faulting_thread ? " (faulting thread)" : "")); } } + + // Records what a run that has ended had open when it crashed, as the report it left names it: the files the + // thread that faulted had open, or every one where it had none, as flush_open_files chooses. Unlike it this runs + // in a process that goes on, so what it records is skipped from now on by this run as well as the next, and it + // belongs before any work starts, which is what reads the list. Answers how many files it recorded. + size_t record_reported(const std::vector& files, const uint32_t faulting_thread) + { + if (is_full()) return 0; + + const auto attributed = std::ranges::any_of(files, [faulting_thread](const auto& i) + { return i.thread_id == faulting_thread; }); + + auto room = max_entries - _lines_on_disk; + std::string appended; + size_t recorded = 0; + + for (const auto& [path, thread_id] : files) + { + if (room == 0) break; + if (attributed && thread_id != faulting_thread) continue; + if (path.is_empty() || _crash_files.contains(path)) continue; + + core::log(__FUNCTION__, std::format("Add file type to crash list {}", path.extension())); + appended += std::format("{}\t{}\n", _release_tag, path.str()); + _crash_files.emplace(path); + --room; + ++recorded; + } + + if (appended.empty()) return 0; + + // Appended, as flush_open_files does, so that a second crash cannot truncate away what earlier ones earned. + std::ofstream file(platform::to_stream_path(_crash_files_path), std::ios_base::app); + file << appended; + + // Skipped by this run all the same, but not on the disk for the next, which is stated. + if (!file) + { + core::log(__FUNCTION__, std::format("could not write {}", _crash_files_path.str())); + return recorded; + } + + _lines_on_disk += recorded; + return recorded; + } }; struct record_open_path @@ -204,7 +274,7 @@ struct record_open_path }; // Constructed on first use rather than as a global: the constructor resolves known folders and reads -// a file, and before WinMain a throw there would end the process with no log and no message box. +// a file, and before main a throw there would end the process with no log and no message box. crash_files_db& crash_files(); // Called from the crash handler and the shutdown path. diff --git a/src/util_spell.h b/src/util_spell.h index 6cb01590..4af7a448 100644 --- a/src/util_spell.h +++ b/src/util_spell.h @@ -96,7 +96,7 @@ class spell_check }; // Its constructor resolves known folders, probes the file system and may create the dictionaries -// directory. As a global that would run before WinMain, where a throw ends the process with nothing +// directory. As a global that would run before main, where a throw ends the process with nothing // logged and no message box; constructed on first use instead, inside the app's error handling. spell_check& spell(); diff --git a/src/view_batch.cpp b/src/view_batch.cpp index 0da94e78..f60a905a 100644 --- a/src/view_batch.cpp +++ b/src/view_batch.cpp @@ -714,7 +714,7 @@ void batch_tool_view::run_convert() { core::unique_folders written; written.emplace(write_folder); - s.item_index.queue_validate_changed_folders(std::move(written)); + s.item_index.queue_validate_changed_folders(written); } } catch (const std::exception& e) @@ -814,7 +814,7 @@ void batch_tool_view::run_updates(const icon_index icon, std::string title, std: // and a run that ended early still wrote everything it reported as written. if (!written.empty()) { - s.item_index.queue_validate_changed_folders(std::move(written)); + s.item_index.queue_validate_changed_folders(written); } session_change change{icon, title, {}}; diff --git a/src/view_edit.cpp b/src/view_edit.cpp index 6cbe1e9d..9fcd2836 100644 --- a/src/view_edit.cpp +++ b/src/view_edit.cpp @@ -2832,7 +2832,7 @@ void edit_view::save_av(const core::file_path src_path, const core::file_path ds { auto update_result = std::make_shared(); const auto cancelled = std::make_shared(false); - const auto dlg = make_dlg(owner); + auto dlg = make_dlg(owner); dlg->show_cancel_status(icon_index::save, str_format(tt.saving_file_name.sv(), dst_path.name()), [cancelled] { *cancelled = true; }); diff --git a/src/view_explore.cpp b/src/view_explore.cpp index fb16f176..e342e472 100644 --- a/src/view_explore.cpp +++ b/src/view_explore.cpp @@ -641,6 +641,7 @@ void explore_view::request_model() auto model = std::make_shared( df::build_explore_model(std::move(request), &locations)); + // NOLINTNEXTLINE(clang-analyzer-cplusplus.NewDeleteLeaks): a shared_ptr owns it; MSVC's count is opaque state.queue_ui([weak, model = std::move(model), generation]() mutable { if (const auto self = weak.lock()) self->model_built(std::move(model), generation); diff --git a/src/view_faces.cpp b/src/view_faces.cpp index ef20b3e7..4c7f45f6 100644 --- a/src/view_faces.cpp +++ b/src/view_faces.cpp @@ -1176,6 +1176,7 @@ void faces_view::build_rows() _people_selection.click(open, false, false, {}); } std::vector keys; + keys.reserve(_rows.size()); for (const auto& r : _rows) keys.push_back(r.key); const auto selected = _people_selection.size(); _people_selection.retain(keys); @@ -1368,6 +1369,8 @@ void faces_view::build_cells(const std::optional focus_face) const auto buttons = [editable](const bool name) { std::vector result; + // Room for both: GCC 13 takes the growth a second push_back may need for a write through null. + result.reserve(2); if (editable && name) result.push_back({heading_action::name}); if (editable) result.push_back({heading_action::hide}); return result; @@ -2943,6 +2946,7 @@ void faces_view::click_heading(const int index, const platform::key_state keys) _pane = pane::faces; std::vector chosen; + chosen.reserve(under.size()); for (const auto c : under) chosen.push_back(_cell_keys[c]); using choice = ui::list_selection::choice; _face_selection.choose(chosen, keys.control ? choice::add : choice::replace); @@ -3128,6 +3132,7 @@ void faces_view::end_marquee(const pointi loc) // A band that touches no face leaves the selection as it was, as an empty one does in Items; one that does takes // them as Items' does, or with Ctrl puts each in or out of the selection. std::vector chosen; + chosen.reserve(inside.size()); for (const auto c : inside) chosen.push_back(_cell_keys[c]); using choice = ui::list_selection::choice; _face_selection.choose(chosen, toggle ? choice::toggle : choice::replace); @@ -3438,7 +3443,6 @@ bool faces_view::key_down_groups(const char32_t key, const platform::key_state k const auto count = static_cast(_rows.size()); const auto focus = focus_row(); - auto next = focus; if (key == platform::keys::SPACE) { @@ -3448,7 +3452,7 @@ bool faces_view::key_down_groups(const char32_t key, const platform::key_state k } const auto page = std::max(1, groups_pane().height() / std::max(1, _row_height) - 1); - next = ui::step_list_cursor(focus, count, key, page, false); + auto next = ui::step_list_cursor(focus, count, key, page, false); if (next < 0) return false; const auto step = key == platform::keys::UP || key == platform::keys::PRIOR || key == platform::keys::END ? -1 : 1; while (next >= 0 && next < count && _rows[next].bounds.is_empty()) next += step; diff --git a/src/view_faces_actions.cpp b/src/view_faces_actions.cpp index 47b6270b..f5d92d61 100644 --- a/src/view_faces_actions.cpp +++ b/src/view_faces_actions.cpp @@ -154,8 +154,9 @@ namespace return; } - state.queue_async(async_queue::thumbnail_decode, [&state, spots = std::move(spots), edge, - tiles = std::move(tiles), done = std::move(done)]() mutable + state.queue_async(async_queue::thumbnail_decode, + [&state, spots = std::move(spots), edge, tiles = std::move(tiles), done = std::move(done), + function = __FUNCTION__]() mutable { files ff; for (size_t i = 0; i < spots.size() && !platform::is_closing; ++i) @@ -177,7 +178,7 @@ namespace } catch (const std::exception& e) { - core::log(__FUNCTION__, e.what()); + core::log(function, e.what()); } } @@ -376,6 +377,7 @@ namespace std::vector names_of(const std::vector& likely) { std::vector names; + names.reserve(likely.size()); for (const auto& p : likely) names.push_back(p.name); return names; } @@ -1056,18 +1058,18 @@ bool faces_view::offer_combine(const std::string_view from, const std::string_vi str_format(tt.faces_combine_fmt, source, target), tt.button_ok)) return true; _combining = true; - _state.queue_async(async_queue::work, - [weak = weak_from_this(), &book, &async = _state._async, generation, source, target] + _state.queue_async(async_queue::work, [weak = weak_from_this(), &book, &async = _state._async, generation, source, + target, function = __FUNCTION__] { auto edit = book.combine(source, target, generation); - async.queue_ui([weak, source, target, edit = std::move(edit)]() mutable + async.queue_ui([weak, source, target, edit = std::move(edit), function]() mutable { const auto self = weak.lock(); if (!self) return; self->_combining = false; if (!edit) { - core::log(__FUNCTION__, "Combine cancelled: person identities changed"); + core::log(function, "Combine cancelled: person identities changed"); if (self->_active && self->_host) make_dlg(self->_host->owner()) ->show_message(icon_index::person, tt.faces_combine_title, tt.faces_combine_changed); diff --git a/src/view_import.cpp b/src/view_import.cpp index ba533062..6db00c25 100644 --- a/src/view_import.cpp +++ b/src/view_import.cpp @@ -1,4 +1,4 @@ -// This file is part of the Diffractor photo and video organizer +// This file is part of the Diffractor photo and video organizer // Copyright 2026 Zac Walker // // This Source Code Form is subject to the terms of the Mozilla Public @@ -157,6 +157,7 @@ void import_view::populate_controls(const view_controls_host_ptr& result, const radio_group_scope); // A phone keeps its pictures: Import copies from one, whatever Move says. if (!src.device.id.empty()) check->child(std::make_shared(tt.import_device_copies)); + if (!src.device.unavailable.empty()) check->child(std::make_shared(src.device.unavailable)); controls.emplace_back(check); is_first_source = false; ++source_index; @@ -438,7 +439,8 @@ void import_view::run() set_margin(std::make_shared(confirm->_frame, icon_index::import, tt.command_import, format_collision_summary(collision_policy::replace, replace_count)))); - controls.emplace_back(set_margin(std::make_shared(tt.import_replace_warning))); + controls.emplace_back(set_margin(std::make_shared( + wastebasket_text(tt.import_replace_warning, tt.import_replace_warning_trash)))); controls.emplace_back(std::make_shared()); controls.emplace_back(std::make_shared(confirm->_frame, tt.collision_replace)); if (confirm->show_modal(controls) != ui::close_result::ok) return; @@ -604,7 +606,10 @@ void import_view::analyze() { if (files.empty()) { - fail(str_format(tt.import_device_empty_fmt.sv(), name)); + // A device that would not open lists nothing; say why rather than that it is empty. + fail(device->unavailable.empty() + ? str_format(tt.import_device_empty_fmt.sv(), name) + : str_format(tt.import_device_unavailable_fmt.sv(), name, device->unavailable)); return; } diff --git a/src/view_movie.cpp b/src/view_movie.cpp index d0634264..4e3fcfdd 100644 --- a/src/view_movie.cpp +++ b/src/view_movie.cpp @@ -17,6 +17,7 @@ #include "app_text.h" #include "app_util.h" #include "av_format.h" +#include "av_movie_writer.h" #include "av_sid.h" #include "files.h" #include "model_index.h" @@ -2452,7 +2453,7 @@ double movie_view::duration() const } // Whether this timeline can be rendered now. Whether this machine can render at all is the frame's to -// say: it asks on a worker at startup, because asking starts Media Foundation. +// say: it asks on a worker at startup, because asking may start the system's media framework. bool movie_view::can_render() const { return _movie_state.project.is_ready_to_render() && !_progress.active; @@ -5489,7 +5490,7 @@ movie_render_result render_movie_to_file(const movie_render_request& request, co writer_request.with_audio = std::any_of(clips.begin(), clips.end(), [](const movie_clip& c) { return c.has_sound_file() || (!c.is_photo && !c.is_text && !c.is_missing); }); - const auto writer = platform::create_movie_writer(writer_request); + const auto writer = df::create_movie_writer(writer_request); if (!writer) { diff --git a/src/view_options.cpp b/src/view_options.cpp index 1c21d39f..1a097e49 100644 --- a/src/view_options.cpp +++ b/src/view_options.cpp @@ -239,8 +239,10 @@ template static void visit_edited_options(const se visit(from.avif_lossless, to.avif_lossless); // Updates and advanced -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES visit(from.check_for_updates, to.check_for_updates); +#endif +#ifndef WINSTORE visit(from.send_crash_dumps, to.send_crash_dumps); #endif visit(from.use_gpu, to.use_gpu); @@ -496,7 +498,8 @@ view_controls_host_ptr options_view::controls(const ui::frame_ptr& owner) // Confirmations const auto confirmations = make_section(tt.options_confirmations_title); - confirmations->add(std::make_shared(frame, tt.options_confirm_del, s.confirm_deletions)); + const auto& confirm_deletions_text = wastebasket_text(tt.options_confirm_del, tt.options_confirm_del_trash); + confirmations->add(std::make_shared(frame, confirm_deletions_text, s.confirm_deletions)); confirmations->add(std::make_shared(frame, tt.options_confirm_rotate, s.confirm_rotations)); // Playback @@ -714,8 +717,10 @@ view_controls_host_ptr options_view::controls(const ui::frame_ptr& owner) // Advanced const auto advanced = make_section(tt.options_advanced); -#ifndef WINSTORE +#ifndef DIFFRACTOR_PACKAGE_UPDATES advanced->add(std::make_shared(frame, tt.options_check_for_update, s.check_for_updates)); +#endif +#ifndef WINSTORE advanced->add(std::make_shared(frame, tt.options_send_crash_reports, s.send_crash_dumps)); #endif advanced->add(std::make_shared(frame, tt.options_use_gpu, s.use_gpu)); diff --git a/src/view_sync.cpp b/src/view_sync.cpp index e5c23e11..e4bbdf65 100644 --- a/src/view_sync.cpp +++ b/src/view_sync.cpp @@ -20,8 +20,8 @@ // nothing and is reported as failed with the reason stated; the rows that still match still run, so // one changed file no longer discards a whole run. // -// Deletes here are permanent. platform::delete_file bypasses the Recycle Bin, and a remote UNC path -// has no Recycle Bin to bypass. That is why deletion is confirmed separately, with its permanence +// Deletes here are permanent. platform::delete_file bypasses the Recycle Bin and the Trash, and a remote location +// may have none to bypass. That is why deletion is confirmed separately, with its permanence // stated, even though every deletion is already a row the user read. #include "pch.h" @@ -311,8 +311,8 @@ void sync_view::run() { const auto confirm = make_dlg(_host->owner()); std::vector controls; - controls.emplace_back( - set_margin(std::make_shared(confirm->_frame, icon, title, tt.sync_delete_warning))); + const auto& warning = wastebasket_text(tt.sync_delete_warning, tt.sync_delete_warning_trash); + controls.emplace_back(set_margin(std::make_shared(confirm->_frame, icon, title, warning))); controls.emplace_back(set_margin(std::make_shared( str_format(tt.sync_delete_count_fmt.sv(), delete_local_count, delete_remote_count)))); controls.emplace_back(std::make_shared()); diff --git a/tools/check_translations.py b/tools/check_translations.py index ad284dd5..34a79336 100644 --- a/tools/check_translations.py +++ b/tools/check_translations.py @@ -25,7 +25,8 @@ * accelerator mismatches - a ``&`` that begins a word in the English source is a mnemonic marker (``&OK``, ``As &JPEG``), which dialog buttons press on Alt+letter. A translation may move the marker to a different - letter, but must keep exactly one and must not leave it dangling. A ``&`` + letter, but must keep exactly one, before the start of a word - inside one + (``A&nnuler``) it is shown as text - and must not leave it dangling. A ``&`` surrounded by spaces or inside a word is literal text (``Fitness & Workout``, ``R&B``) and translations may render it as the local "and". * quality mismatches in existing translations - objective, language-agnostic @@ -162,12 +163,24 @@ def placeholder_issues(src: str, got: str) -> list[str]: MNEMONIC_RE = re.compile(r"(?:^|(?<=\s))&(?=\w)") +def _word_character(c: str) -> bool: + # As ui::parse_mnemonic reads a word, every character beyond ASCII is part of one. + return not c.isascii() or c.isalnum() or c == "_" + + +def _marks_word_start(text: str, at: int) -> bool: + """Whether the ``&`` at ``at`` marks a letter by libdesktop's word_start rule, which Diffractor's labels use.""" + before_word = at == 0 or not _word_character(text[at - 1]) + return before_word and at + 1 < len(text) and _word_character(text[at + 1]) + + def accelerator_issues(src: str, got: str) -> list[str]: - """Mnemonic ``&`` markers dropped, duplicated or left dangling. + """Mnemonic ``&`` markers dropped, duplicated, left dangling or put inside a word. Only checked when the English source carries a mnemonic. A translation may move the marker to a different letter - that is the translator's job - but it - must keep exactly one, and it must sit before a character. + must keep exactly one, and it must sit before the first character of a word: + one inside a word (``A&nnuler``) marks nothing and is shown as text. Not checked: whether two commands in the same menu claim the same letter. That needs the menu grouping, which is not visible in a .po file. @@ -183,6 +196,8 @@ def accelerator_issues(src: str, got: str) -> list[str]: issues.append(f"accelerator mismatch: {expected} mnemonic '&' in source, {found} in translation") elif re.search(r"&(\s|$)", got): issues.append("accelerator marker '&' does not precede a character") + elif not all(_marks_word_start(got, i) for i, c in enumerate(got) if c == "&"): + issues.append("accelerator marker '&' is not at the start of a word, so it is shown as text") return issues @@ -651,11 +666,28 @@ def _words_header(platform_header: Path) -> Path: return platform_header.parent.parent / "core" / "strings.h" +# libdesktop declares platform::messages in platform/messages.h. A libdesktop from before it split +# platform/services.h into topic headers - an older pin - declares them there. +_PLATFORM_TEXT_HEADERS = ("messages.h", "services.h") + + +def _platform_text_in(platform_dir: Path) -> Path | None: + for name in _PLATFORM_TEXT_HEADERS: + candidate = platform_dir / name + if candidate.is_file(): + return candidate + return None + + def _platform_text_header() -> Path: - sibling = REPO_ROOT.parent / "libdesktop" / "include" / "libdesktop" / "platform" / "services.h" - if sibling.is_file(): + sibling = _platform_text_in(REPO_ROOT.parent / "libdesktop" / "include" / "libdesktop" / "platform") + if sibling is not None: return sibling - fetched = sorted(REPO_ROOT.glob("tmp/*/_deps/libdesktop-src/include/libdesktop/platform/services.h")) + fetched = sorted( + header + for header in map(_platform_text_in, REPO_ROOT.glob("tmp/*/_deps/libdesktop-src/include/libdesktop/platform")) + if header is not None + ) signatures = { (path.read_bytes(), _words_header(path).read_bytes()) for path in fetched @@ -663,7 +695,7 @@ def _platform_text_header() -> Path: if fetched and len(signatures) == 1: return fetched[0] raise ValueError( - "Cannot identify libdesktop's platform/services.h. Configure the build first or " + "Cannot identify the libdesktop header that declares platform::messages. Configure the build first or " "pass --platform-text-header with the header used by this build." ) @@ -721,7 +753,8 @@ def main(argv=None) -> int: ) parser.add_argument( "--platform-text-header", type=Path, - help="libdesktop/include/libdesktop/platform/services.h used by the build; otherwise " + help="the libdesktop header used by the build that declares platform::messages - " + "platform/messages.h, or platform/services.h before libdesktop split it; otherwise " "use the sibling checkout or an unambiguous fetched copy", ) parser.add_argument( diff --git a/tools/compare_ffmpeg_config.py b/tools/compare_ffmpeg_config.py index c0e4cb60..9898e17d 100644 --- a/tools/compare_ffmpeg_config.py +++ b/tools/compare_ffmpeg_config.py @@ -14,9 +14,10 @@ # in docs/third-party.md. # # The divergences that remain are real and expected -- the hardware accelerators, Media Foundation -# and SChannel are Windows-only by nature -- so the guard is not "no divergence" but "no divergence -# that has not been accounted for". The accepted set is checked in beside the Windows configuration, -# and any change to it fails until someone looks and re-records it. +# and SChannel are Windows-only by nature, and Linux alone writes movies with FFmpeg's own encoders -- +# so the guard is not "no divergence" but "no divergence that has not been accounted for". The accepted +# set is checked in beside the Windows configuration, and any change to it fails until someone looks and +# re-records it. # # python tools/compare_ffmpeg_config.py compare, and fail on an unaccounted difference # python tools/compare_ffmpeg_config.py --update re-record the accepted set @@ -47,6 +48,26 @@ DEFINE = re.compile(r"^#define\s+(CONFIG_[A-Z0-9_]+)\s+(\S+)") +# Linux writes movies with FFmpeg's own encoders - AV1 by libaom, AAC by FFmpeg's native encoder - where +# Windows asks Media Foundation, so Linux has these on and Windows, whose checked-in configuration has no +# encoder, does not: the two encoders, libaom, and the parts of libavcodec an encoder is made of (the +# audio frame queue and LPC the AAC encoder selects, and the encoder machinery and its frame threading +# that any encoder brings). docs/movie.md owns why, and docs/third-party.md the configure line, in +# cmake/vendored/FFmpeg.cmake. +MOVIE_WRITER = frozenset({ + "CONFIG_AAC_ENCODER", + "CONFIG_AUDIO_FRAME_QUEUE", + "CONFIG_ENCODERS", + "CONFIG_FRAME_THREAD_ENCODER", + "CONFIG_LIBAOM", + "CONFIG_LIBAOM_AV1_ENCODER", + "CONFIG_LPC", +}) + +# What a format is: a switch for a decoder, demuxer, encoder or muxer. One of these on a single platform +# is a format that platform reads or writes and the other does not, unless it is a movie writer's. +FORMAT = re.compile(r"^CONFIG_[A-Z0-9_]+_(DECODER|ENCODER|DEMUXER|MUXER)$") + # The documentation targets. Both configure lines pass --disable-doc, so nothing these control is # built on either platform, let alone compiled into Diffractor. They are nevertheless autodetected # rather than chosen: FFmpeg makes doc depend on the pages instead of the pages on doc, so each one @@ -59,6 +80,13 @@ "CONFIG_TXTPAGES", }) +# The timer libavutil/timer.h gives checkasm and FFmpeg's developers. configure turns on Linux's perf events for it on +# Arm alone, and nothing Diffractor calls reads that timer, so comparing an aarch64 build with the x64 configuration +# checked in for Windows would report the build machine's architecture as a difference in the product. +ARCHITECTURE = frozenset({ + "CONFIG_LINUX_PERF", +}) + def enabled_switches(directory: Path, headers: tuple[str, ...]) -> set[str]: """The CONFIG_* switches this configuration turns on, across all of its headers.""" @@ -76,7 +104,7 @@ def enabled_switches(directory: Path, headers: tuple[str, ...]) -> set[str]: for line in path.read_text(encoding="utf-8", errors="replace").splitlines(): match = DEFINE.match(line) - if match and match.group(2) != "0" and match.group(1) not in IGNORED: + if match and match.group(2) != "0" and match.group(1) not in IGNORED | ARCHITECTURE: enabled.add(match.group(1)) if not enabled: @@ -92,6 +120,17 @@ def divergence(windows: set[str], linux: set[str]) -> list[str]: ) +def is_movie_writer(line: str) -> bool: + """Whether a divergence line is one of those Linux has so that it can write movies.""" + side, name = line.split(" ", 1) + return side == "LINUX" and name in MOVIE_WRITER + + +def stray_formats(lines: list[str]) -> list[str]: + """The decoders, demuxers, encoders and muxers one platform has and the other does not, but for a movie writer's.""" + return [line for line in lines if FORMAT.match(line.split(" ", 1)[1]) and not is_movie_writer(line)] + + def read_baseline(path: Path) -> list[str]: lines = [] @@ -110,13 +149,26 @@ def write_baseline(path: Path, lines: list[str]) -> None: "# Generated by tools/compare_ffmpeg_config.py --update. Each line names the platform that", "# enables a switch the other does not. Read every line before re-recording: each should be", "# platform by nature -- the hardware accelerators, Media Foundation and SChannel on the", - "# Windows side, glibc's iconv on the Linux side. A decoder, demuxer, encoder or muxer here is", - "# a defect rather than a divergence, and so is anything that is merely a choice one side made.", + "# Windows side, glibc's iconv on the Linux side -- or the movie writer's, below. A decoder,", + "# demuxer, encoder or muxer anywhere else is a defect rather than a divergence, which the tool", + "# refuses to record, and so is anything that is merely a choice one side made.", "#", "# See docs/third-party.md, 'FFmpeg Configuration And Upgrade Checklist'.", "", ] - path.write_text("\n".join(header + lines) + "\n", encoding="utf-8") + writer = [line for line in lines if is_movie_writer(line)] + body = [line for line in lines if not is_movie_writer(line)] + + if writer: + body += [ + "", + "# The movie writer. Linux writes movies with FFmpeg's own encoders - AV1 by libaom, AAC by", + "# its native encoder - where Windows asks Media Foundation, whose encoders are the system's", + "# and not FFmpeg's. Each line is an encoder, libaom, or what the encoders are made of.", + "# docs/movie.md and docs/third-party.md say why.", + ] + writer + + path.write_text("\n".join(header + body) + "\n", encoding="utf-8") def main() -> int: @@ -134,6 +186,18 @@ def main() -> int: enabled_switches(args.linux, LINUX_HEADERS), ) + stray = stray_formats(current) + + if stray: + print("A format one platform has and the other does not, which is a defect and not a divergence:") + print() + for line in stray: + print(f" ! {line}") + print() + print("Make the two configure lines agree. Only the movie writer's encoders differ on purpose;") + print("a new one of those is named in MOVIE_WRITER, with docs/movie.md and docs/third-party.md.") + return 1 + if args.update: write_baseline(args.baseline, current) print(f"Recorded {len(current)} accepted divergence(s) in {args.baseline}") diff --git a/tools/dd.py b/tools/dd.py index fe04b154..3674d106 100644 --- a/tools/dd.py +++ b/tools/dd.py @@ -11,12 +11,15 @@ from __future__ import annotations import argparse +import hashlib import os import platform import re import shutil import subprocess import sys +import textwrap +import xml.etree.ElementTree as ElementTree from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent @@ -41,7 +44,6 @@ APT_DEPENDENCIES = [ "zlib1g-dev", "libpng-dev", - "libjpeg-dev", # virtual: resolves to libjpeg-turbo on Debian and Ubuntu "libsqlite3-dev", "libwebp-dev", "libarchive-dev", @@ -50,7 +52,7 @@ ] # libdesktop-render's window layer: Pango sets text, and SDL3, built from its pin, drives X11 and -# Wayland through these system libraries. The same list as .github/workflows/linux.yml installs. +# Wayland through these system libraries. .github/workflows/linux.yml installs them, then the platform's. APT_WINDOW_LAYER = [ "libpango1.0-dev", "libfontconfig-dev", @@ -76,6 +78,21 @@ "libudev-dev", ] +# libdesktop-platform's services on Linux, which the default build cannot do without either: the web client is the +# system's libcurl, pictures are decoded through libjpeg-turbo besides SDL3, SDL3 builds its PulseAudio, ALSA and +# PipeWire audio backends only where these development packages are installed, and a phone or camera is reached over +# MTP through libmtp, which speaks USB through libusb. .github/workflows/linux.yml installs them after the window +# layer's. +APT_PLATFORM_SERVICES = [ + "libcurl4-openssl-dev", # the web client; the build fails without it + "libjpeg-dev", # JPEG decoding; virtual, resolving to libjpeg-turbo on Debian and Ubuntu + "libpulse-dev", # SDL3's PulseAudio backend + "libasound2-dev", # SDL3's ALSA backend + "libpipewire-0.3-dev", # SDL3's PipeWire backend + "libmtp-dev", # portable devices over MTP + "libusb-1.0-0-dev", # libmtp's transport +] + def is_windows() -> bool: return platform.system() == "Windows" @@ -296,9 +313,10 @@ def cmd_setup(args: argparse.Namespace) -> None: sys.exit("setup currently understands apt only. Install the equivalents by hand:\n" f" toolchain: {' '.join(APT_TOOLCHAIN)}\n" f" window layer: {' '.join(APT_WINDOW_LAYER)}\n" + f" platform: {' '.join(APT_PLATFORM_SERVICES)}\n" f" dependencies: {' '.join(APT_DEPENDENCIES)}") - wanted = APT_TOOLCHAIN + APT_WINDOW_LAYER + APT_DEPENDENCIES + wanted = APT_TOOLCHAIN + APT_WINDOW_LAYER + APT_PLATFORM_SERVICES + APT_DEPENDENCIES missing = missing_apt_packages(wanted) say("") @@ -431,7 +449,7 @@ def cmd_linux(args: argparse.Namespace) -> None: # The packages the default build cannot do without; the bring-up conveniences are not needed. if shutil.which("dpkg-query"): - missing = missing_apt_packages(APT_TOOLCHAIN + APT_WINDOW_LAYER) + missing = missing_apt_packages(APT_TOOLCHAIN + APT_WINDOW_LAYER + APT_PLATFORM_SERVICES) if missing: sys.exit(f"Missing {' '.join(missing)}. Run './dd setup' in this Linux shell; it needs sudo.") @@ -482,12 +500,215 @@ def cmd_info(args: argparse.Namespace) -> None: say("") +# ------------------------------------------------------------------------------------------- +# Debian package +# ------------------------------------------------------------------------------------------- + +DEB_PACKAGE = "diffractor" + +# Libraries the binary loads while it runs rather than links, named by the stem of their soname. SDL3, built static +# from libdesktop's pin, loads its video and audio backends this way, and libdesktop loads libjpeg and the X screen +# saver extension; dpkg-shlibdeps sees only what is linked, so these are stated here. What a window and JPEG decoding +# need on X11 or Wayland is a dependency, the rest a recommendation. A library the binary does not name is skipped, +# so a backend SDL stops loading drops out by itself; KMSDRM, Vulkan, the tray and the rest SDL could load are +# neither, as Diffractor never asks for them. +DEB_RUNTIME_DEPENDS = ("libjpeg", "libX11", "libXext", "libXcursor", "libXi", "libXrandr", "libXfixes", "libXss", + "libxkbcommon", "libwayland-client", "libwayland-cursor", "libwayland-egl", "libEGL", + "libGLESv2", "libGL", "libasound") +DEB_RUNTIME_RECOMMENDS = ("libpulse", "libpipewire-0.3", "libdecor-0", "libdbus-1", "libXtst") + + +def app_version() -> str: + """The version the application reports: s_app_version and g_app_build in src/app.cpp.""" + text = (REPO_ROOT / "src" / "app.cpp").read_text(encoding="utf-8") + version = re.search(r's_app_version\s*=\s*"([0-9.]+)"', text) + build = re.search(r'g_app_build\s*=\s*"([0-9]+)"', text) + if not version or not build: + sys.exit("src/app.cpp has no s_app_version or g_app_build to version the package by") + return f"{version.group(1)}.{build.group(1)}" + + +def embedded_sonames(binary: Path) -> set[str]: + """The sonames written into the binary as strings: what it, and SDL inside it, hand to dlopen.""" + found = re.findall(rb"(? str: + return soname.split(".so", 1)[0] + + +def soname_packages(sonames: set[str], stems: tuple[str, ...], required: bool) -> list[str]: + """The packages that install, on this machine, the sonames whose stems are listed.""" + multiarch = subprocess.run(["dpkg-architecture", "-qDEB_HOST_MULTIARCH"], capture_output=True, text=True, + check=True).stdout.strip() + # dpkg records the path a package ships, the merged /usr one on current releases and /lib on older ones. + directories = (f"/usr/lib/{multiarch}", f"/lib/{multiarch}", "/usr/lib", "/lib") + + packages: list[str] = [] + for soname in sorted(s for s in sonames if soname_stem(s) in stems): + owner = None + for directory in directories: + query = subprocess.run(["dpkg", "-S", f"{directory}/{soname}"], capture_output=True, text=True) + if query.returncode == 0: + owner = query.stdout.split(":", 1)[0].strip() + break + if not owner: + message = f"{soname}, which the binary loads, is not installed here, so no package can be named for it" + if required: + sys.exit(message + ". Run './dd setup'.") + say(f" warning: {message}") + continue + if owner not in packages: + packages.append(owner) + return packages + + +def shlib_depends(binary: Path, work: Path) -> list[str]: + """What dpkg-shlibdeps says the linked libraries need: their packages, at the oldest versions that serve. + + It reads work/debian/control and expects the binary staged beneath work/debian/, as a source package + lays one out. + """ + (work / "debian" / "control").write_text( + f"Source: {DEB_PACKAGE}\n\nPackage: {DEB_PACKAGE}\nArchitecture: any\n", encoding="utf-8") + result = subprocess.run(["dpkg-shlibdeps", "-O", str(binary.relative_to(work))], cwd=work, capture_output=True, + text=True) + if result.stderr.strip(): + say(result.stderr.rstrip()) + if result.returncode != 0: + sys.exit("dpkg-shlibdeps failed; it comes with dpkg-dev, which build-essential installs") + line = next((text for text in result.stdout.splitlines() if text.startswith("shlibs:Depends=")), "") + return [item.strip() for item in line.partition("=")[2].split(",") if item.strip()] + + +def deb_description() -> str: + """The control file's description, from the AppStream metadata a software centre shows.""" + root = ElementTree.parse(REPO_ROOT / "packaging" / "linux" / "com.diffractor.Diffractor.metainfo.xml").getroot() + description = root.find("description") + lines = [" ".join((root.findtext("summary") or "").split())] + for block in description if description is not None else []: + if lines[1:]: + lines.append(" .") + if block.tag == "p": + lines += [" " + text for text in textwrap.wrap(" ".join((block.text or "").split()), 78)] + elif block.tag == "ul": + # Two spaces make a line verbatim, so each item stays a line of its own. + for item in block.findall("li"): + wrapped = textwrap.wrap(" ".join((item.text or "").split()), 74) + lines += [" - " + wrapped[0]] + [" " + text for text in wrapped[1:]] + return "\n".join(lines) + + +def cmd_deb(args: argparse.Namespace) -> None: + """Build the Release binary and package it as a .deb in the repository root, for the system it is built on.""" + if is_windows(): + if not shutil.which("wsl"): + sys.exit("dd deb needs WSL. Install it with 'wsl --install', then run './dd setup' inside it.") + sys.exit(run(["wsl", "--cd", str(REPO_ROOT), "--exec", "python3", "tools/dd.py", "deb", *args.rest], + check=False)) + + if not shutil.which("dpkg-deb") or not shutil.which("dpkg-shlibdeps"): + sys.exit("dd deb builds a Debian package and needs dpkg-dev: run './dd setup'.") + if args.config != "Release": + sys.exit("A package is made from the Release build; leave out --config.") + + cmd_build(args) + + version = app_version() + architecture = subprocess.run(["dpkg", "--print-architecture"], capture_output=True, text=True, + check=True).stdout.strip() + name = f"{DEB_PACKAGE}_{version}_{architecture}" + + # Staged on the build's own file system, where modes and links are kept, never on a mounted Windows drive. + work = build_dir(args) / "deb" + if work.exists(): + shutil.rmtree(work) + stage = work / "debian" / DEB_PACKAGE + run([find_cmake(), "--install", str(build_dir(args)), "--prefix", "/usr"], env={**os.environ, "DESTDIR": str(stage)}) + + binary = stage / "usr" / "lib" / "diffractor" / "diffractor" + if not binary.exists(): + sys.exit(f"cmake --install left no {binary}") + + # The debug information vendored libraries carry (FFmpeg's configure compiles with -g) goes beside the package, + # not in it. The symbol table stays, so a crash report still names functions, and the .debug file, which the + # binary names and whose build id it shares, resolves a tester's report to source lines. + debug = work / f"{name}.debug" + run(["objcopy", "--only-keep-debug", str(binary), str(debug)]) + run(["strip", "--strip-debug", str(binary)]) + run(["objcopy", f"--add-gnu-debuglink={debug}", str(binary)]) + + documents = stage / "usr" / "share" / "doc" / DEB_PACKAGE + documents.mkdir(parents=True, exist_ok=True) + (documents / "copyright").write_text( + "Format: https://www.debian.org/doc/packaging-manuals/copyright-format/1.0/\n" + "Upstream-Name: Diffractor\n" + "Source: https://github.com/ZacWalk/diffractor\n" + "\n" + "Files: *\n" + "Copyright: 2026 Zac Walker\n" + "License: MPL-2.0\n" + " Diffractor's licence, and the licences of the libraries it links statically, are in\n" + " /usr/share/licenses/com.diffractor.Diffractor/.\n", encoding="utf-8") + + sonames = embedded_sonames(binary) + # dpkg-shlibdeps finds the package's root by its DEBIAN directory. + control = stage / "DEBIAN" + control.mkdir() + depends = shlib_depends(binary, work) + named = {item.split(" ", 1)[0] for item in depends} + depends += [package for package in soname_packages(sonames, DEB_RUNTIME_DEPENDS, True) if package not in named] + named = {item.split(" ", 1)[0] for item in depends} + recommends = [package for package in soname_packages(sonames, DEB_RUNTIME_RECOMMENDS, False) + if package not in named] + + files = [path for path in sorted(stage.rglob("*")) if path.is_file() and not path.is_symlink()] + installed_kib = (sum(path.stat().st_size for path in files) + 1023) // 1024 + + fields = [ + f"Package: {DEB_PACKAGE}", + f"Version: {version}", + f"Architecture: {architecture}", + "Maintainer: Zac Walker <181544+ZacWalk@users.noreply.github.com>", + f"Installed-Size: {installed_kib}", + f"Depends: {', '.join(depends)}", + ] + if recommends: + fields.append(f"Recommends: {', '.join(recommends)}") + fields += [ + "Section: graphics", + "Priority: optional", + "Homepage: https://www.diffractor.com", + f"Description: {deb_description()}", + ] + (control / "control").write_text("\n".join(fields) + "\n", encoding="utf-8") + + (control / "md5sums").write_text("".join( + f"{hashlib.md5(path.read_bytes()).hexdigest()} {path.relative_to(stage).as_posix()}\n" for path in files), + encoding="utf-8") + + package = work / f"{name}.deb" + run(["dpkg-deb", "--build", "--root-owner-group", "-Zxz", str(stage), str(package)]) + target = REPO_ROOT / package.name + shutil.copyfile(package, target) + shutil.copyfile(debug, REPO_ROOT / debug.name) + + say("") + say((control / "control").read_text(encoding="utf-8")) + say(f"Built {target}") + say(f" and {REPO_ROOT / debug.name}, its debug information, for resolving crash reports") + say(f"Install it with: sudo apt install ./{package.name}") + + COMMANDS = { "setup": cmd_setup, "configure": cmd_configure, "build": cmd_build, "run": cmd_run, "linux": cmd_linux, + "deb": cmd_deb, "test": cmd_test, "clean": cmd_clean, "info": cmd_info, @@ -497,7 +718,7 @@ def cmd_info(args: argparse.Namespace) -> None: def main() -> None: parser = argparse.ArgumentParser(prog="dd", description="Diffractor build backend") parser.add_argument("command", choices=sorted(COMMANDS)) - parser.add_argument("--config", help="CMake build type (default: Debug; Release for linux)") + parser.add_argument("--config", help="CMake build type (default: Debug; Release for linux and deb)") parser.add_argument("--arch", default="x64", choices=sorted(VCVARS_ARCH), help="Windows target architecture (default: x64)") parser.add_argument("--winstore", action="store_true", help="build the Microsoft Store variant") @@ -521,8 +742,8 @@ def main() -> None: if not selected: parser.error(f"No tests selected by label {args.label!r}. Available label: headless.") - # Running the application to look at it wants the optimised build, as dd.ps1 run does. - args.config = args.config or ("Release" if args.command == "linux" else "Debug") + # Running the application to look at it wants the optimised build, as dd.ps1 run does, and a package ships it. + args.config = args.config or ("Release" if args.command in ("linux", "deb") else "Debug") # The Store variant is Release by definition; it is the Release configuration plus a define. if args.winstore: diff --git a/tools/generate_icon.py b/tools/generate_icon.py index bf770d53..e5ff03dd 100644 --- a/tools/generate_icon.py +++ b/tools/generate_icon.py @@ -46,4 +46,7 @@ def clipped_rect(left: int, top: int, right: int, bottom: int, paint: Paint) -> ROOT / "src/Res/logo.png": 60, ROOT / "src/Res/logo30.png": 30, ROOT / "src/Res/logo15.png": 15, + # The Linux package's icon theme sizes beside src/Res/app.png, which is its 512. + **{ROOT / f"packaging/linux/icons/hicolor/{size}x{size}/apps/com.diffractor.Diffractor.png": size + for size in (64, 128, 256)}, })) diff --git a/tools/sweep_mcp.py b/tools/sweep_mcp.py index c0bb598f..4d5fae19 100644 --- a/tools/sweep_mcp.py +++ b/tools/sweep_mcp.py @@ -25,8 +25,8 @@ sys.path.insert(0, os.path.dirname(os.path.abspath(__file__))) from test_mcp_session import Session, taken, text_of, write_png # noqa: E402 -# What acts outside the window - on the user's clipboard, desktop, drives or other programs, or the network - is not -# pressed, and the report says so. +# What acts outside the window - on the user's clipboard, desktop, folders, drives or other programs, or the network - +# is not pressed, and the report says so. OUTSIDE = { "browse_open_containingfolder": "opens the system's file browser", "browse_open_in_file_browser": "opens the system's file browser", @@ -34,6 +34,7 @@ "view_help": "opens a web browser", "options_help": "opens a web browser", "print": "prints through the system", + "import_run": "copies into the user's Pictures folder", "tool_burn": "burns a disc through the system", "tool_desktop_background": "sets the user's desktop background", "tool_eject": "ejects a drive", @@ -45,14 +46,15 @@ "edit_cut": "writes the user's clipboard", "edit_paste": "reads the user's clipboard", "edit_copy_item_path": "writes the user's clipboard", - "tool_delete": "sends files to the user's Recycle Bin", + "tool_delete": "sends files to the user's Recycle Bin or Trash", "info_check_for_updates": "reaches the network", "info_new_version": "installs another version", "exit": "ends the session", } -# Pressed once, at the end, as they change the window itself: its size, or the language every label is in. -WINDOW = ["view_minimize", "view_restore", "view_maximize", "view_restore"] +# Pressed once, at the end, as they change the window itself: its size, or the language every label is in. Restore is +# offered to a maximized window alone, as its caption button is, so a minimized one is maximized and then restored. +WINDOW = ["view_minimize", "view_maximize", "view_restore"] LANGUAGE_MENU = "menu_language" # The Open menus list the programs that open the file as well as the window's own commands: a row with no command of # the window's own opens another program, and is not pressed. @@ -260,6 +262,12 @@ def checked_options(self): return {c["name"]: bool(c.get("checked")) for c in listed if c["name"].startswith(OPTIONS) and c["name"] != "playback_menu"} + def changed_options(self): + """The options not as the sweep began, of those listed now: a state that hides one - Edit hides the sidebar's - + has it neither listed nor run, so it is left as it is.""" + now = self.checked_options() + return {name: now[name] for name, was in self.options.items() if name in now and now[name] != was} + def restore_options(self): """Puts the window's options back as they were when the sweep began: those it had on first, which turns off the others of a choice, then any still on that it did not have.""" @@ -267,15 +275,12 @@ def restore_options(self): self.options = self.checked_options() return for wanted in (True, False): - now = self.checked_options() - for name, was in self.options.items(): - if was == wanted and now.get(name) != was: + for name in self.changed_options(): + if self.options[name] == wanted: self.call("command_run", {"command": name}) self.close_modal() # One no command puts back - a choice none of whose options was on - is taken as it is now. - now = self.checked_options() - for name in [n for n, was in self.options.items() if now.get(n) != was]: - self.options[name] = now.get(name) + self.options.update(self.changed_options()) def filtering(self): """Whether the filter box holds anything - typed there, or set by a button that filters.""" @@ -320,8 +325,7 @@ def enter(self, state): def back_home(self): shown = self.close_modal() - if (self.signature(shown) != self.home or (self.options and self.checked_options() != self.options) or - self.filtering()): + if self.signature(shown) != self.home or (self.options and self.changed_options()) or self.filtering(): self.enter(self.state) def leave_unsaved(self, answer): diff --git a/tools/test_check_translations.py b/tools/test_check_translations.py index bf5b7c3b..46122b0c 100644 --- a/tools/test_check_translations.py +++ b/tools/test_check_translations.py @@ -1,4 +1,5 @@ -"""Registration checks must cover messages moved into libdesktop, not ignore them.""" +"""Registration checks must cover messages moved into libdesktop, not ignore them, and a translated +mnemonic must mark a letter.""" from pathlib import Path import tempfile @@ -15,7 +16,7 @@ def setUp(self): self.root = Path(self.temp.name) self.header = self.root / "app_text.h" self.impl = self.root / "app_text.cpp" - self.platform = self.root / "include" / "libdesktop" / "platform" / "services.h" + self.platform = self.root / "include" / "libdesktop" / "platform" / "messages.h" self.platform.parent.mkdir(parents=True) self.words = self.root / "include" / "libdesktop" / "core" / "strings.h" self.words.parent.mkdir(parents=True) @@ -99,14 +100,14 @@ def test_words_are_checked_against_their_shared_header(self): def test_fetched_header_discovery_rejects_ambiguous_builds(self): repo = self.root / "app" - first = repo / "tmp" / "win-build-x64" / "_deps" / "libdesktop-src" / "include" / "libdesktop" / "platform" / "services.h" + first = repo / "tmp" / "win-build-x64" / "_deps" / "libdesktop-src" / "include" / "libdesktop" / "platform" / "messages.h" first.parent.mkdir(parents=True) first.write_text('text_t shared = "Shared";\n', encoding="utf-8") (first.parent.parent / "core").mkdir() checker._words_header(first).write_text('text_t month = "Month";\n', encoding="utf-8") with patch.object(checker, "REPO_ROOT", repo): self.assertEqual(first, checker._platform_text_header()) - second = repo / "tmp" / "win-build-x86" / "_deps" / "libdesktop-src" / "include" / "libdesktop" / "platform" / "services.h" + second = repo / "tmp" / "win-build-x86" / "_deps" / "libdesktop-src" / "include" / "libdesktop" / "platform" / "messages.h" second.parent.mkdir(parents=True) second.write_text(first.read_text(encoding="utf-8"), encoding="utf-8") (second.parent.parent / "core").mkdir() @@ -114,6 +115,30 @@ def test_fetched_header_discovery_rejects_ambiguous_builds(self): with self.assertRaisesRegex(ValueError, "Cannot identify"): checker._platform_text_header() + def test_libdesktop_before_the_split_declares_the_messages_in_services(self): + repo = self.root / "app" + older = repo / "tmp" / "win-build-x64" / "_deps" / "libdesktop-src" / "include" / "libdesktop" / "platform" / "services.h" + older.parent.mkdir(parents=True) + older.write_text('text_t shared = "Shared";\n', encoding="utf-8") + (older.parent.parent / "core").mkdir() + checker._words_header(older).write_text('text_t month = "Month";\n', encoding="utf-8") + with patch.object(checker, "REPO_ROOT", repo): + self.assertEqual(older, checker._platform_text_header()) + + +class AcceleratorTests(unittest.TestCase): + def test_a_marker_may_move_to_the_start_of_any_word(self): + for src, got in (("&Cancel", "&Annuler"), ("As &AVIF", "Au &format AVIF"), ("&Analyze", "分析(&A)")): + self.assertEqual([], checker.accelerator_issues(src, got), got) + + def test_a_marker_inside_a_word_marks_nothing(self): + for src, got in (("&Cancel", "A&nnuler"), ("&Tag", "É&tiqueter"), ("&Open", "От&крыть")): + self.assertEqual( + ["accelerator marker '&' is not at the start of a word, so it is shown as text"], + checker.accelerator_issues(src, got), + got, + ) + if __name__ == "__main__": unittest.main() diff --git a/tools/test_mcp_session.py b/tools/test_mcp_session.py index 752e6f84..629abfbd 100644 --- a/tools/test_mcp_session.py +++ b/tools/test_mcp_session.py @@ -2,16 +2,16 @@ # Purpose: Drives an agent session (-mcp) end to end over its pipes, as an MCP client does: the handshake each era of # client uses, the tool list and what the session withholds, a Movie project checked without a window, the window made # out of sight by the first tool that needs it, the index searched, the window's controls listed and a menu opened, read -# and cancelled, a screenshot, task panels filled in and reviewed - fields a check box shows or enables among them - a -# place suggested from the photo taken nearest in time and proposed by Locate, a tool's argument refused, and the end of -# input ending the session. A second session, which may write, types a search into the address box as a user does, -# waits while a large photo is read and decoded, reads back a file Convert has just written, and meets the prompt -# Windows shows when Delete finds a file held open: listed with the dialogs, ending a wait, and cancelled. A third, over -# libfacedetection's sample photographs where a build has fetched them, turns face search on for photos and then -# videos, names faces, confirms one suggestion and rejects another, hides a face and shows it again, joins two people -# and separates them, saves the face book to a file, and reads the saved book into a fourth with a profile of its own, -# over the same photos renamed and copied. dd.ps1 test runs it against the program it built; give the program's path -# to run it by hand. +# and cancelled, a screenshot and the paints diagnostics counts, task panels filled in and reviewed - fields a check box +# shows or enables among them - a place suggested from the photo taken nearest in time and proposed by Locate, a tool's +# argument refused, and the end of input ending the session. A second session, which may write, types a search into the +# address box as a user does, waits while a large photo is read and decoded, reads back a file Convert has just written, +# and meets the prompt Windows shows when Delete finds a file held open: listed with the dialogs, ending a wait, and +# cancelled. A third, over libfacedetection's sample photographs where a build has fetched them, turns face search on +# for photos and then videos, names faces, confirms one suggestion and rejects another, hides a face and shows it again, +# joins two people and separates them, saves the face book to a file, and reads the saved book into a fourth with a +# profile of its own, over the same photos renamed and copied. dd.ps1 test runs it against the program it built; give +# the program's path to run it by hand. import base64 import glob @@ -202,8 +202,14 @@ def select(session, page, cells=None): args["cells"] = cells return session.call("faces_select", args).get("structuredContent", {}) + def find_listed(items, matches, what): + found = next((item for item in items if matches(item)), None) + if found is None: + raise AssertionError(f"{what} is not among the {len(items)} listed") + return found + def named_file(items, file): - return next(i for i in items if os.path.basename(i["file"]) == file) + return find_listed(items, lambda i: os.path.basename(i["file"]) == file, f"a face in {file}") def assign(session, name): # docs/faces.md#95-naming-a-face: the popup's search box is called by its title, as Copy to folder's is. @@ -252,7 +258,7 @@ def assign(session, name): "naming a face confirms only that face; similar photos are suggestions") # docs/faces.md#92-faces: a suggestion's third shortcut asks for the name of that face alone, offering at a # press nobody it is already shown as. - suggestion = next(i for i in person["items"] if i["member"] == "suggested") + suggestion = find_listed(person["items"], lambda i: i["member"] == "suggested", "a suggested face") shortcuts = suggestion.get("shortcuts", []) labels = [s.get("label") for s in shortcuts] check(labels == ["Confirm Ann", "Not Ann", "Name as someone else"], @@ -363,7 +369,8 @@ def assign(session, name): # A panel button scrolled out of sight is scrolled to and pressed in one call, as a user scrolls to it. session.call("window", {"width": 1100, "height": 640}) panel = session.call("ui_controls", {"scope": "panel"}).get("structuredContent", {}).get("controls", []) - delete = next(c for c in panel if c["id"] == "panel/button/Delete face data") + delete = find_listed(panel, lambda c: c["id"] == "panel/button/Delete face data", + "the Delete face data button") pressed = session.call("ui_act", {"id": delete["id"], "action": "press"}) asked = session.call("ui_state").get("structuredContent", {}).get("dialogs") or [] check(delete.get("scrolled_away") is True and any(d.get("title") == "Delete face data" for d in asked), @@ -526,6 +533,9 @@ def check(condition, what): "screenshot returns the window as a PNG, though it is out of sight") size = picture.get("structuredContent", {}) check(size.get("width", 0) > 200 and size.get("height", 0) > 200, f"at the window's size ({size})") + render = session.call("diagnostics").get("structuredContent", {}).get("render", {}) + paints = render.get("ui", {}).get("paints", 0) + check(paints > 0, f"diagnostics counts the window's paints ({paints}, {render.get('renderer')})") toolbar = {c.get("command"): c["bounds"] for c in controls if c["scope"] == "title"} check("explore" in toolbar and "faces" in toolbar and toolbar["explore"][0] < toolbar["faces"][0],