From b2ecec4d875ad8c23f42151410cb22a070a5d0c5 Mon Sep 17 00:00:00 2001 From: Brian Holman Date: Sat, 14 Nov 2026 01:43:46 -0700 Subject: [PATCH] Sync source edition with VCC Plus 3.7.0 build 63 --- EXPORT.json | 368 ++++++--- RELEASES.md | 41 +- docs/development/MCP_BANKED_PLAYTEST.md | 19 +- docs/development/MCP_DEBUG_EVIDENCE.md | 18 +- docs/media/capture-sounds/README.md | 31 + docs/media/capture-sounds/manifest.json | 24 + docs/media/capture-sounds/prepare.py | 40 + docs/media/capture-sounds/source/shutter.mp3 | Bin 0 -> 15600 bytes .../capture-sounds/source/tape-start.mp3 | Bin 0 -> 50712 bytes docs/white-paper-evidence.json | 4 +- .../macos/App/ArchiveInlinePreview.swift | 125 ++- .../macos/App/ArchiveLibraryCatalog.swift | 19 + .../macos/App/ArchiveLibraryReader.swift | 113 ++- platforms/macos/App/ArchiveLibraryView.swift | 154 +++- platforms/macos/App/CMOCBankedDebug.swift | 98 ++- .../macos/App/CMOCDevelopmentModel.swift | 1 + platforms/macos/App/CMOCSourceMap.swift | 72 +- platforms/macos/App/CoCoCapture.swift | 638 ++++++++++++++ platforms/macos/App/CoCoCaptureFeedback.swift | 22 + platforms/macos/App/CoCoVideoEncoder.swift | 300 +++++++ .../macos/App/CompanionLibraryAuthority.swift | 81 +- .../macos/App/CompanionLibraryTypes.swift | 9 +- platforms/macos/App/DiskControlsView.swift | 10 +- platforms/macos/App/InputHub.swift | 82 +- platforms/macos/App/InputSettings.swift | 58 +- platforms/macos/App/InterfaceValidation.swift | 41 +- platforms/macos/App/LibraryContinuity.swift | 205 +++++ platforms/macos/App/MCPCMOC.swift | 46 +- .../macos/App/MCPDebuggerInspection.swift | 2 + platforms/macos/App/MCPPlaytest.swift | 148 +++- platforms/macos/App/MachineInterface.swift | 2 + platforms/macos/App/MachineModel.swift | 57 +- platforms/macos/App/ManualLibraryView.swift | 295 ++++++- .../macos/App/SoftwareLibraryArtwork.swift | 41 +- .../macos/App/SoftwareLibraryCatalog.swift | 53 ++ .../macos/App/SoftwareLibraryLaunchPlan.swift | 70 +- .../macos/App/SoftwareLibraryLaunchView.swift | 47 +- .../macos/App/SoftwareLibraryManual.swift | 88 +- .../macos/App/SoftwareLibraryModel.swift | 298 ++++++- .../macos/App/SoftwareLibraryPersonal.swift | 564 +++++++++++++ .../App/SoftwareLibraryPersonalView.swift | 556 +++++++++++++ .../macos/App/SoftwareLibraryState.swift | 8 +- platforms/macos/App/SoftwareLibraryView.swift | 398 ++++++++- platforms/macos/App/VCCMacApp.swift | 45 +- platforms/macos/Bridge/VCCMachineController.h | 18 +- .../macos/Bridge/VCCMachineController.mm | 106 ++- .../macos/Companion/CompanionTransport.swift | 27 +- .../Resources/About/ThirdPartyNotices.txt | 13 + .../CaptureSounds/recording-start.wav | Bin 0 -> 45908 bytes .../Resources/CaptureSounds/screenshot.wav | Bin 0 -> 48886 bytes .../Resources/SourceProjectSetupPrompt.txt | 2 + .../macos/Tests/ArchiveReaderTests.swift | 101 +++ .../macos/Tests/BASICReferenceTests.swift | 16 + .../macos/Tests/CMOCSourceMapTests.swift | 313 ++++++- .../Tests/CartridgePersistenceTests.swift | 54 ++ platforms/macos/Tests/CoCoCaptureTests.swift | 779 ++++++++++++++++++ .../macos/Tests/CoCoVideoBudgetTests.swift | 110 +++ .../macos/Tests/CompanionLibraryTests.swift | 409 ++++++++- .../macos/Tests/DebuggerMMUBridgeTests.swift | 61 +- platforms/macos/Tests/InputTests.swift | 150 +++- .../macos/Tests/LibraryContinuityTests.swift | 324 ++++++++ .../Tests/MCPCallContextAccessTests.swift | 89 +- .../Tests/MCPDebuggerInspectionTests.swift | 1 + platforms/macos/Tests/MCPPlaytestTests.swift | 427 +++++++++- .../Tests/SoftwareLibraryBrowseTests.swift | 143 ++++ .../SoftwareLibraryLaunchPlanTests.swift | 63 ++ .../SoftwareLibraryMachineLaunchTests.swift | 60 +- .../Tests/SoftwareLibraryManualTests.swift | 19 + .../Tests/SoftwareLibraryPersonalTests.swift | 380 +++++++++ platforms/macos/Tests/StartupTests.swift | 36 +- platforms/macos/Tools/MCP/MCPProjectTools.h | 23 + platforms/macos/Tools/MCP/main.mm | 23 +- platforms/macos/Tools/MCP/test-helper.py | 52 ++ .../macos/Tools/Playtest/VideoWriter.swift | 60 ++ platforms/macos/Tools/Playtest/main.mm | 118 ++- .../macos/UITests/InteractionTests.swift | 537 +++++++++++- platforms/macos/VCC.xcodeproj/project.pbxproj | 67 +- src/core/MachineSession.cpp | 93 ++- src/core/MachineSession.h | 7 +- tests/core/BinaryChecks.cpp | 126 +++ tools/catalog/curation/related-archive.json | 165 ++++ tools/catalog/package.py | 27 +- tools/catalog/related_archive.py | 144 ++++ tools/catalog/rights.py | 234 ++++++ tools/catalog/submission_intake.py | 314 +++++++ tools/tests/test_build_content.py | 9 +- 86 files changed, 10519 insertions(+), 472 deletions(-) create mode 100644 docs/media/capture-sounds/README.md create mode 100644 docs/media/capture-sounds/manifest.json create mode 100644 docs/media/capture-sounds/prepare.py create mode 100644 docs/media/capture-sounds/source/shutter.mp3 create mode 100644 docs/media/capture-sounds/source/tape-start.mp3 create mode 100644 platforms/macos/App/CoCoCapture.swift create mode 100644 platforms/macos/App/CoCoCaptureFeedback.swift create mode 100644 platforms/macos/App/CoCoVideoEncoder.swift create mode 100644 platforms/macos/App/LibraryContinuity.swift create mode 100644 platforms/macos/App/SoftwareLibraryPersonal.swift create mode 100644 platforms/macos/App/SoftwareLibraryPersonalView.swift create mode 100644 platforms/macos/Resources/CaptureSounds/recording-start.wav create mode 100644 platforms/macos/Resources/CaptureSounds/screenshot.wav create mode 100644 platforms/macos/Tests/CoCoCaptureTests.swift create mode 100644 platforms/macos/Tests/CoCoVideoBudgetTests.swift create mode 100644 platforms/macos/Tests/LibraryContinuityTests.swift create mode 100644 platforms/macos/Tests/SoftwareLibraryPersonalTests.swift create mode 100644 platforms/macos/Tools/Playtest/VideoWriter.swift create mode 100644 tools/catalog/curation/related-archive.json create mode 100644 tools/catalog/related_archive.py create mode 100644 tools/catalog/rights.py create mode 100644 tools/catalog/submission_intake.py diff --git a/EXPORT.json b/EXPORT.json index 2a741a7..2b785ab 100644 --- a/EXPORT.json +++ b/EXPORT.json @@ -22,9 +22,9 @@ "sha256": "7c7f385dd5c84d440b6134a7c850024bb72b84742f83725abbdcb1b7d59d4935" }, "RELEASES.md": { - "bytes": 13336, + "bytes": 15659, "mode": "0644", - "sha256": "b1b5d13db9ea530571c69dac0b74794dcb9112fa56b9b9a08f7ef1e8b5d924e7" + "sha256": "42a0479de6257f8bc4c728792e7700cb655516f98190d04d5b92a7d344b05dd2" }, "docs/WHITE_PAPER_EVIDENCE.md": { "bytes": 2442, @@ -72,9 +72,9 @@ "sha256": "5b4746bc68ea2e93c5bb1f5d54aa063fb409557b6ba2b085118225a304ed841b" }, "docs/development/MCP_BANKED_PLAYTEST.md": { - "bytes": 23592, + "bytes": 24663, "mode": "0644", - "sha256": "fad90fcb7e5ca3670d803f02578e44e637b0b126f7716dc4198f253ea7eae3a6" + "sha256": "75f1b3c0977ffc536a0cb47f46f554c10c06a34d5b7a2a58458d997c1493c480" }, "docs/development/MCP_BUILD45_VALIDATION.md": { "bytes": 1836, @@ -87,9 +87,9 @@ "sha256": "1bd9f44f14ab8eabd289571834307ebc6ceb1fe3f81109fc5a2d8bf3857438c9" }, "docs/development/MCP_DEBUG_EVIDENCE.md": { - "bytes": 7817, + "bytes": 8707, "mode": "0644", - "sha256": "79fe80ae2c40808e6da821bae1d2de1aa4c18b5f7e24b3a40707fdd473cf086e" + "sha256": "ddb8e4979b5573cff809a6fda8c9b961fcbd3dfc0fd7f8bce4dcd1814782e2f4" }, "docs/development/MCP_PLAYTEST_MEDIA.md": { "bytes": 9578, @@ -206,6 +206,31 @@ "mode": "0644", "sha256": "a1bf3619e46be3b4ab0b2d12a837510e67aaff8681a8e59e1cc9a2624ab56d15" }, + "docs/media/capture-sounds/README.md": { + "bytes": 1925, + "mode": "0644", + "sha256": "260de63b84b7e93706a393f63d30485f272008e564cf383ca40ee19eb0745d6d" + }, + "docs/media/capture-sounds/manifest.json": { + "bytes": 638, + "mode": "0644", + "sha256": "96c3790ae573f7a41e5a04817afad917c7eb9dcde811bff83d5c37695d61f3c8" + }, + "docs/media/capture-sounds/prepare.py": { + "bytes": 1569, + "mode": "0644", + "sha256": "afc84c60362c71d2057a2a0d0421cfcd5e13703abec1495bee4b132ed7c27be8" + }, + "docs/media/capture-sounds/source/shutter.mp3": { + "bytes": 15600, + "mode": "0644", + "sha256": "e805680b4ee8a48bc537f266c866e74d60b076a76e52af3acbaacf77e8cb7392" + }, + "docs/media/capture-sounds/source/tape-start.mp3": { + "bytes": 50712, + "mode": "0644", + "sha256": "ebbbb9d82d0ff2f84d48ae8228a2f635fe45b7816583393e77d079034230eac7" + }, "docs/media/coco-sdc-label.svg": { "bytes": 22514, "mode": "0644", @@ -404,7 +429,7 @@ "docs/white-paper-evidence.json": { "bytes": 18421, "mode": "0644", - "sha256": "f0da3f3d4e67e756d0b51471b2917197d51ec39cb15cb6ff19268aab3ea19ade" + "sha256": "8ab1249e778db9435e9d270ecb5deb1320fc62c86e37670efbba48c621952f7e" }, "examples/assembly/Dispatch/layout.link": { "bytes": 35, @@ -892,24 +917,24 @@ "sha256": "f511eda02c28214698a7f9a29607aaaadda6f181664afbc4840530c93693d9b7" }, "platforms/macos/App/ArchiveInlinePreview.swift": { - "bytes": 11867, + "bytes": 17730, "mode": "0644", - "sha256": "40aa6fb9fef1dc8d1756547238709af3e937e8091eb083837e6996e69a6b0862" + "sha256": "b49bd88e80a680213d4001a75042cc64102c9628fc7eff9f64bcacb26c6570f4" }, "platforms/macos/App/ArchiveLibraryCatalog.swift": { - "bytes": 12730, + "bytes": 13857, "mode": "0644", - "sha256": "576b5d6c45497fc1db3a754493d9f8cc8d0badcf4f555dd14b7f6c13febfe103" + "sha256": "a1614683b1bf69f97f52562838546e94b0af4d91d028834b4588bedc1f58c359" }, "platforms/macos/App/ArchiveLibraryReader.swift": { - "bytes": 34330, + "bytes": 39990, "mode": "0644", - "sha256": "d2f32012a5afb7ae24ed49f6fbae9ef689ca8f633c404720a9fd950afd9b4f29" + "sha256": "b2a55f8497503c8b03724d5bbe3f15d4da96337650cbf9158696548f83f3b338" }, "platforms/macos/App/ArchiveLibraryView.swift": { - "bytes": 17166, + "bytes": 25459, "mode": "0644", - "sha256": "081b7bc6cd56ab3e37762ea96f40d062d843aa0dc93308834b36aa087fb698b8" + "sha256": "297c149956739c2b432146fbac299ef28454bb88d1980931d077bf27a80e1bad" }, "platforms/macos/App/AssemblyBuildService.swift": { "bytes": 18307, @@ -1007,9 +1032,9 @@ "sha256": "5ef71300a52836d36807ec3c49a9e577f2ba2962530c9bec71cfe900b49c5c02" }, "platforms/macos/App/CMOCBankedDebug.swift": { - "bytes": 16327, + "bytes": 20336, "mode": "0644", - "sha256": "cc8559bee949cc4ad2aa797cdd8b4672b13c8e48d3b647b3a113ca402de3153e" + "sha256": "8f90848c01ad6694228774e39c51853a25d6b40acc08b36b2e1184e84fc68861" }, "platforms/macos/App/CMOCBuildHistory.swift": { "bytes": 12696, @@ -1037,9 +1062,9 @@ "sha256": "962d3d6168c3e1cddb9eac1f8127dcb6734aa1cb95c17ff97c57ea80eda36059" }, "platforms/macos/App/CMOCDevelopmentModel.swift": { - "bytes": 100828, + "bytes": 100955, "mode": "0644", - "sha256": "a97ce09ac5518fa49290fe835b5f0b2339ba394ed8e8f876a84af38c5cefaf9d" + "sha256": "86f073b34b8e47df275c1e59197b70b2345085dc7ab72e144033c1604eaa1858" }, "platforms/macos/App/CMOCDevelopmentView.swift": { "bytes": 101176, @@ -1072,9 +1097,9 @@ "sha256": "8c38bb3feb3fd227dfee8333a86784881ad0fe88c5dbb5ff7abb9cc15250291d" }, "platforms/macos/App/CMOCSourceMap.swift": { - "bytes": 67364, + "bytes": 70070, "mode": "0644", - "sha256": "dd193224ed3ad463d842be2b500de10f19b9327d6e5acbb46fea95221a399396" + "sha256": "bb72550d188ca99c95576ef258563339185c70cd3361d2293547dfa3b6fe2bbb" }, "platforms/macos/App/CMOCVariableDebug.swift": { "bytes": 21531, @@ -1101,20 +1126,35 @@ "mode": "0644", "sha256": "27aeb59f9481ad9ace6280e47b3255ebfa0c1964dc8b0bacec56719fa681ddac" }, + "platforms/macos/App/CoCoCapture.swift": { + "bytes": 37122, + "mode": "0644", + "sha256": "b9a39361e9bc4f44cd830b1909f141f5b13b7bb87ea879a4f8947d7b6bcdaa8f" + }, + "platforms/macos/App/CoCoCaptureFeedback.swift": { + "bytes": 843, + "mode": "0644", + "sha256": "1b12afaf2495aec48ed6c779368d9db46111ccbae332c35ae59feb0411f41b96" + }, + "platforms/macos/App/CoCoVideoEncoder.swift": { + "bytes": 18480, + "mode": "0644", + "sha256": "90ae96fbf85bf5ec35ca57a311c7233dd302d568f19659f96b8421849596e7e9" + }, "platforms/macos/App/CocoKeyboard.swift": { "bytes": 7938, "mode": "0644", "sha256": "d9cc7a5eec1ee2d6136a488e45d4a20d25f64d71882db4fcd22551b207ed61d0" }, "platforms/macos/App/CompanionLibraryAuthority.swift": { - "bytes": 10400, + "bytes": 14642, "mode": "0644", - "sha256": "cad38dff8cb39a1e9f405937908e4f7037d7e7deaa6f993c9e1341ffcf1ba0c6" + "sha256": "6ebefd461fd70872252d81d05e44e385d36af2230688d05a3eac320eafbf97aa" }, "platforms/macos/App/CompanionLibraryTypes.swift": { - "bytes": 3555, + "bytes": 3855, "mode": "0644", - "sha256": "41ee0805ef73656c1d645feb7f3ac879cbcb0b7eac23d7dcfdd30ca5217b73d8" + "sha256": "5d36a9a6b1830ccbe099a94a6b9c4100f732329143437fc80b37a4dfeb0ca262" }, "platforms/macos/App/ConfigurationProfile.swift": { "bytes": 15465, @@ -1157,9 +1197,9 @@ "sha256": "356234ff0b44863a9c07835107a3d810d895d09209e9d8a3a82a21aff2a1dc10" }, "platforms/macos/App/DiskControlsView.swift": { - "bytes": 15818, + "bytes": 16013, "mode": "0644", - "sha256": "81d234df53ecb030e0d3548c90597c6c1f70c0c242f4a5081c70740ac52a76b9" + "sha256": "320b9c1f3274a6dda5548b6548452bf2cdc43522310b819e81b2f4e456e07299" }, "platforms/macos/App/DiskEditorFileTable.swift": { "bytes": 22121, @@ -1232,19 +1272,24 @@ "sha256": "c1d65d9b6e9250b9d924f0248640ded133c59452c8fbbace322d2db503c37508" }, "platforms/macos/App/InputHub.swift": { - "bytes": 10706, + "bytes": 13797, "mode": "0644", - "sha256": "e6dd053effa720b62778022b0bf80f0b3ce2bac76781889543c326229439476e" + "sha256": "3db07416bee8bf8e2f2659febf61b8e48d530b0a851b9a1bc9e09d5fc800d438" }, "platforms/macos/App/InputSettings.swift": { - "bytes": 4679, + "bytes": 7127, "mode": "0644", - "sha256": "820875bac5efb7e716a73937ad2f1d8ce6d9ae57fbeac13011fafac6620ad50d" + "sha256": "b946cc9e071ce31ecf0b37fa41dc53475d9aed0f26d03a802b51af20e9a14abd" }, "platforms/macos/App/InterfaceValidation.swift": { - "bytes": 26452, + "bytes": 29060, "mode": "0644", - "sha256": "44a386dda7db24d78af71236d05b3bd8585346c4219a718e1fb26881ed11bf60" + "sha256": "265dfdb6bc58d7f8b14175719ca0fa4ed410260e828113457c221c155bd48ba3" + }, + "platforms/macos/App/LibraryContinuity.swift": { + "bytes": 10423, + "mode": "0644", + "sha256": "f0d11b1e88912caac088913bbaa2bcb6122c6fd17ed11407c4338b2762fad6fa" }, "platforms/macos/App/MCPAccess.swift": { "bytes": 37089, @@ -1267,9 +1312,9 @@ "sha256": "b0379b3be3b2794bdbde5b33e70b33e422868e02b370925447b0b0976d95f154" }, "platforms/macos/App/MCPCMOC.swift": { - "bytes": 141217, + "bytes": 143524, "mode": "0644", - "sha256": "c89b3f354580fd0752c2231c7298ca7261d0f7729de141d34463be8299f86c83" + "sha256": "1078432a8cf8e0696c4c660f6d2b3cff11ff38eee36688f781aa8e652d3915c2" }, "platforms/macos/App/MCPCMOCGuest.swift": { "bytes": 11824, @@ -1292,9 +1337,9 @@ "sha256": "999e6589635a192a49de12ee56aea065d4e8a93edb1771d3e5ac0c43b70440d7" }, "platforms/macos/App/MCPDebuggerInspection.swift": { - "bytes": 4251, + "bytes": 4427, "mode": "0644", - "sha256": "36611cefca2f101cabb451cca46d955e6247db358d60a862def92cbed22d344d" + "sha256": "381aafa2c52aee69df5d46a9b0390d7af1ca9b7a7ab84e94d164568a3250c5df" }, "platforms/macos/App/MCPHelpIndex.swift": { "bytes": 4269, @@ -1307,9 +1352,9 @@ "sha256": "5af349cb795b7a852d3cea3ca6a251d21408d2c452f8b243f9ce83b5f77b1e82" }, "platforms/macos/App/MCPPlaytest.swift": { - "bytes": 63916, + "bytes": 73624, "mode": "0644", - "sha256": "d747568bca7cb46bc9ae24eac530ef6ef1b7b98fb0c6d5104798b8d6da2356ef" + "sha256": "7fdd7c5a17538961e70a0f4b5abdf1fd84a3c91a1e9775aeef2e5a22d3cadf2b" }, "platforms/macos/App/MCPTransport.swift": { "bytes": 6503, @@ -1317,9 +1362,9 @@ "sha256": "10e93f413d0e1d6401fb2a25e59a83c1f3d956818d86603117b5184202837424" }, "platforms/macos/App/MachineInterface.swift": { - "bytes": 27725, + "bytes": 27844, "mode": "0644", - "sha256": "6634d933fb3038f13c028f0607f7ea1758b32b7d240f044e70f81060948bff62" + "sha256": "70f24be5d0eb2abdc4e5a38f3cc010b3043eeb60510ff2185356bee2c1f04e2c" }, "platforms/macos/App/MachineMenuState.swift": { "bytes": 3227, @@ -1327,9 +1372,9 @@ "sha256": "8ea7ca3fa1ba23a23cac4f35636f184263af0031a87352ca9cd398987a657ca2" }, "platforms/macos/App/MachineModel.swift": { - "bytes": 175829, + "bytes": 178684, "mode": "0644", - "sha256": "7c2f69173168e8db8dc68ecf7f3c0c198af25c83cd455eb566bc2b605e291ff2" + "sha256": "d9282b4c5c4e15caf4c6dd770370edd7d7406553dbfc6775522b8240bfe14a04" }, "platforms/macos/App/MachineSettings.swift": { "bytes": 1020, @@ -1342,9 +1387,9 @@ "sha256": "4a51686c57196d8646ceb3c75f7246e8db0c03b77adb1c538c8f82508884eaaf" }, "platforms/macos/App/ManualLibraryView.swift": { - "bytes": 12943, + "bytes": 31716, "mode": "0644", - "sha256": "dc68b1a59f6029c4c4144f4ff25f0370e7b6effc15c4a7503cf9eeb2f81fb894" + "sha256": "040810c2da6d0f2bf880e4b6beef83bdd569c420e6afcff98dbdd621247eab10" }, "platforms/macos/App/ManualPageFind.swift": { "bytes": 7664, @@ -1402,14 +1447,14 @@ "sha256": "0e91eb0aaa9f811ca03fc5bf4bad205ec6f45687762194966669c06ebd78952c" }, "platforms/macos/App/SoftwareLibraryArtwork.swift": { - "bytes": 13059, + "bytes": 15908, "mode": "0644", - "sha256": "78a15b30c73fd31cf791cf37e404b7c724867e6e982c1da8666d1f571cae728a" + "sha256": "a2bd21ff49a0203174ba1b9b0fd2e92099cd42d61eb260039b7e35203d1f3389" }, "platforms/macos/App/SoftwareLibraryCatalog.swift": { - "bytes": 38043, + "bytes": 41077, "mode": "0644", - "sha256": "e8630a7baf5fd36788b0b49793debcfb751bb88ee9a2866fa4ac2728ab6a7522" + "sha256": "e662558d241ee0f3441ffe8d84afaac11088a7fbc698aeebd58f31d99ac36c47" }, "platforms/macos/App/SoftwareLibraryInstallFixture.swift": { "bytes": 21059, @@ -1422,24 +1467,34 @@ "sha256": "56d7b20a389ba657799e164a360ec0dce169d62738270a537116cd8a1aa72f7a" }, "platforms/macos/App/SoftwareLibraryLaunchPlan.swift": { - "bytes": 22655, + "bytes": 24927, "mode": "0644", - "sha256": "db6efdc9ac0054d12ac3253dbc32c0a6d6b737f53fc9162bbd19982de25494bf" + "sha256": "926924f65eea69c5bd236942dbbd4a1ce10cf0465e65b33241ec3642737a6a67" }, "platforms/macos/App/SoftwareLibraryLaunchView.swift": { - "bytes": 5722, + "bytes": 8220, "mode": "0644", - "sha256": "cce2d7bf7954fcc49f541652f3f680ffd90ee19043cfe4df2132678138e64c5c" + "sha256": "88d79ec55224f10526f13f769051ccaca3dcb1aa9b8b322453068e21ebae6758" }, "platforms/macos/App/SoftwareLibraryManual.swift": { - "bytes": 15932, + "bytes": 20922, "mode": "0644", - "sha256": "a837bc19897a93066ad5c33e4e2224450ac57e10a970e5912d370b79c76fda35" + "sha256": "0fee8fa02746dffab23b95424bef626a0bde5b3ba4677183ea8f73cc29ff524b" }, "platforms/macos/App/SoftwareLibraryModel.swift": { - "bytes": 39853, + "bytes": 54804, "mode": "0644", - "sha256": "2156480803dc8cf42a07ae0473ea7da154051c8e3199aea6a88125319021ec17" + "sha256": "fcd64eba7ce43dee54eef4fbcde378810cb09fcf11a604e873d5d0190f18a26f" + }, + "platforms/macos/App/SoftwareLibraryPersonal.swift": { + "bytes": 39547, + "mode": "0644", + "sha256": "d15153a9d9871e46bd58dff9103ee78b3bd994d4e7c67d35fb70e62cc2f67ee4" + }, + "platforms/macos/App/SoftwareLibraryPersonalView.swift": { + "bytes": 30745, + "mode": "0644", + "sha256": "16dc9d20b8e3ea1c2608ef34b416eebfe0775ed9fa73c082c2e42a5dfe631c85" }, "platforms/macos/App/SoftwareLibrarySourceImporter.swift": { "bytes": 17913, @@ -1447,14 +1502,14 @@ "sha256": "597f714262f25aae7d167ada48e28add06a1fed6869b2707c80160c2efe750d9" }, "platforms/macos/App/SoftwareLibraryState.swift": { - "bytes": 7629, + "bytes": 7912, "mode": "0644", - "sha256": "bc43d62ab42f21c6a31ae179bacd9411f5c465a2b2afddf1271f238712606cc4" + "sha256": "f8f484417e62dc4c27776dfe5988ef974eb4208b1e4ba69d5fbeac246e777142" }, "platforms/macos/App/SoftwareLibraryView.swift": { - "bytes": 45406, + "bytes": 65285, "mode": "0644", - "sha256": "da4469a919e5eb42f0cd7455e3e199c47ab7e7e84f1c0043e61b143fa1176625" + "sha256": "8a8dba255564fe7bb20b91b4425c4da3d479b8ae985e6c9ba50aa20690d31fdd" }, "platforms/macos/App/SourceFind.swift": { "bytes": 14533, @@ -1487,9 +1542,9 @@ "sha256": "d32b681f102350a140a83ba11e3f80558465c52b852b62aeaa8064c9143270ed" }, "platforms/macos/App/VCCMacApp.swift": { - "bytes": 33420, + "bytes": 36510, "mode": "0644", - "sha256": "5af5a988aede692b38ec53fa4d3b517baec331b400e8a2a36fb06d54773e20d9" + "sha256": "c2c53bb6ff6ee5127068d4c7b831e8427d2d48a0cd82338d2c48cfa70bb0d211" }, "platforms/macos/App/WindowPlacement.swift": { "bytes": 6519, @@ -1562,14 +1617,14 @@ "sha256": "f7d6758f52c19962380885b4ce7b7ba52c09f62ec5ce404299e28e7d9217c5cb" }, "platforms/macos/Bridge/VCCMachineController.h": { - "bytes": 32254, + "bytes": 33567, "mode": "0644", - "sha256": "1dffe55b4b91a64141c4f4ec8b607da871421dae2e2cea5932190e7af9a15ccf" + "sha256": "c9a171c8c85b3324621792feade0a3cbdbb8f352ebea8f3dde81a69d6d3b9946" }, "platforms/macos/Bridge/VCCMachineController.mm": { - "bytes": 141524, + "bytes": 147599, "mode": "0644", - "sha256": "f512f63dfb440a7b1234d2b8f4af919f9173df7282037853c77e3934e5977685" + "sha256": "8604e44d525ddc16da983de0fbc431181beb57a4348cc25e1e190d5578ac8015" }, "platforms/macos/Companion/CompanionDiskTransfer.swift": { "bytes": 1167, @@ -1577,9 +1632,9 @@ "sha256": "29f54f1af924bc5a72b39e792f0e9e80ff144035466233824d27cf791ad17aba" }, "platforms/macos/Companion/CompanionTransport.swift": { - "bytes": 25193, + "bytes": 26603, "mode": "0644", - "sha256": "747a4b0f25508df8d625d702496f140dfa61476b6c2fc021c84d7e2c49252576" + "sha256": "f6eb73c2e35108631c79373110e9eecc2964e4b6de6855eeb4663c6a17fb4c1f" }, "platforms/macos/Companion/CompanionValidation.swift": { "bytes": 4822, @@ -1632,9 +1687,9 @@ "sha256": "1b46d86b5ca8a78e22d50221e634ed8dbff5fa937ea24b32d5863cdc89fcbb4c" }, "platforms/macos/Resources/About/ThirdPartyNotices.txt": { - "bytes": 5535, + "bytes": 6278, "mode": "0644", - "sha256": "7c8267a0b0aed1084329491ef1b96b9f13f7e9aa1a538b2d9f01c43662662bd6" + "sha256": "d707d2a8024bbafaa124d5cb3a7f101e920e3d8ab00313213a508ea218f46db9" }, "platforms/macos/Resources/About/WindowsAbout.txt": { "bytes": 998, @@ -1686,6 +1741,16 @@ "mode": "0644", "sha256": "25937ec363954867dbbc86c0250e449ab3b17b6df02a70884eb9fc2f6e8f992d" }, + "platforms/macos/Resources/CaptureSounds/recording-start.wav": { + "bytes": 45908, + "mode": "0644", + "sha256": "5b5ba2407a84e39cf04018c64acb48b690089cd32cec193920dcbf2cb4080aa7" + }, + "platforms/macos/Resources/CaptureSounds/screenshot.wav": { + "bytes": 48886, + "mode": "0644", + "sha256": "38bce90df26042fa70bb0a5dc33a5759867e0440de0a7acd4b8942cbcbdf239d" + }, "platforms/macos/Resources/Hardware/cassette.pdf": { "bytes": 14745, "mode": "0644", @@ -2477,9 +2542,9 @@ "sha256": "32655b557a67ed8ef2429fdc2ae12f12c2445aa064b336b99dd887e4acb8c9df" }, "platforms/macos/Resources/SourceProjectSetupPrompt.txt": { - "bytes": 681, + "bytes": 1206, "mode": "0644", - "sha256": "64d0f7ae39d089eb9520466fbe7a2cdfe84d8e3de8eb1697a36950130899e73d" + "sha256": "c1bf087e8fb98ac1ecc4ab653cb6e4ba146c08bf0899f5a748f57a5a67cc18cb" }, "platforms/macos/Resources/StarterMedia/Blank Disk.dsk": { "bytes": 161280, @@ -2512,9 +2577,9 @@ "sha256": "d354e72f8c749b04dc97beb7f6be3d9c5c467f43347b376c13e8345a56c5d2c9" }, "platforms/macos/Tests/ArchiveReaderTests.swift": { - "bytes": 16223, + "bytes": 22971, "mode": "0644", - "sha256": "6fe405075ca2073d7e08bdb664fae67d2942979c3fafd7699efeb07fe47423d5" + "sha256": "67e42ce73be848711b4325e9c33349a4ae91e5d4e284ffd60ba8fa93465d4be6" }, "platforms/macos/Tests/AssemblyBuildServiceTests.swift": { "bytes": 13007, @@ -2537,9 +2602,9 @@ "sha256": "f7a99fccdf28e89f9eb1fa23dc5625f2f2852bcc75ab5563f7c75ddccf001a45" }, "platforms/macos/Tests/BASICReferenceTests.swift": { - "bytes": 35058, + "bytes": 36086, "mode": "0644", - "sha256": "da193b61dbd97e930d2aa350c8e5f49f62ac3c50a3dcdecc3e4f6f7197a88224" + "sha256": "3f4ff23588091b35bc845474e075dcc01bf85024be9a26857fdf39eea5469f91" }, "platforms/macos/Tests/BASICWorkspaceTests.swift": { "bytes": 32906, @@ -2632,9 +2697,9 @@ "sha256": "5ad14f4c620211c331c984fcd9e3a6eb4d34c01c348cef73a58cbe6e702af24e" }, "platforms/macos/Tests/CMOCSourceMapTests.swift": { - "bytes": 79239, + "bytes": 99755, "mode": "0644", - "sha256": "9d6dd01b851c0e4ad5572f492f1b177eb22b0b9beb55a49224c684047702b5e1" + "sha256": "5ec68e186f49e6e1f000317fbf142898ee4a410f71da7d238d7ee50cb7ec4df7" }, "platforms/macos/Tests/CMOCVariableDebugTests.swift": { "bytes": 41433, @@ -2662,19 +2727,29 @@ "sha256": "25aa309ba9f7333072a0909ba7b4c4afb60be3c7d75dd8490570ac55526d7c86" }, "platforms/macos/Tests/CartridgePersistenceTests.swift": { - "bytes": 26433, + "bytes": 30125, "mode": "0644", - "sha256": "cc40d5daa5537c8014c281bc16759a78ea13d5a764401645f77eec1e7787a5e4" + "sha256": "6112145659a56bed9f4e253f0df5648d388f8d55cae576a3afe2f87fc64745bb" }, "platforms/macos/Tests/CartridgeTests.mm": { "bytes": 16558, "mode": "0644", "sha256": "1a9ee88ad9ca233e1bf5a2fd6d08af6b41390e106212a6bc1d9462793a99c150" }, - "platforms/macos/Tests/CompanionLibraryTests.swift": { - "bytes": 5740, + "platforms/macos/Tests/CoCoCaptureTests.swift": { + "bytes": 53937, "mode": "0644", - "sha256": "05be728de65ea63b20d06df43622153963d76e807c9e4eb9999a880732eec15f" + "sha256": "039786a3b389231f020f1a5e565b561ff141c4162096fc3dfde5061fa2b84df6" + }, + "platforms/macos/Tests/CoCoVideoBudgetTests.swift": { + "bytes": 6267, + "mode": "0644", + "sha256": "772e2e5543ebb3eca796761bf31fc91ffd5b4e5e499cbad9162a9f85359df5e0" + }, + "platforms/macos/Tests/CompanionLibraryTests.swift": { + "bytes": 34864, + "mode": "0644", + "sha256": "6b74083f974f266d232d91d59d7c8d69ab17db553978a173752b070c85b3b339" }, "platforms/macos/Tests/CompanionStartupTests.swift": { "bytes": 3016, @@ -2702,9 +2777,9 @@ "sha256": "4c9b34e91a56c4a2b6d1404a82aff54616cbc553419926fb2484b70ecf6d9356" }, "platforms/macos/Tests/DebuggerMMUBridgeTests.swift": { - "bytes": 8386, + "bytes": 12806, "mode": "0644", - "sha256": "4d29d5d84079e561a89a23cc079abe3e753f9b6ffd58a9fb9ab18d3c614cf370" + "sha256": "ed11730344d55e56d267486f4d01ca2881295be1eb4c3f2975ee49e24dbec14d" }, "platforms/macos/Tests/DebuggerMemoryModelTests.swift": { "bytes": 5866, @@ -2902,34 +2977,39 @@ "sha256": "52efc5e07e18f781d34b27796a646f19b55c71fca943102f8043897dfada2542" }, "platforms/macos/Tests/InputTests.swift": { - "bytes": 19709, + "bytes": 29608, "mode": "0644", - "sha256": "9fa057bfd3c007ef619917ecec21b18085224a872828ee91bead670e47c41bea" + "sha256": "85261419d0d2ad113e909c70bbf87ceab1238baa24590afa5543e9ec67dfb65e" }, "platforms/macos/Tests/InterfaceTests.swift": { "bytes": 31328, "mode": "0644", "sha256": "bbde253bc363d171cb9698d265a77eec416d138319a9c2f436f81f8a0d0f8c35" }, + "platforms/macos/Tests/LibraryContinuityTests.swift": { + "bytes": 20376, + "mode": "0644", + "sha256": "5987b9b623fd737fc424cdf54d2df44fe361890387e8ad581e86a14a3d4e3d8f" + }, "platforms/macos/Tests/MCPArchiveAccessTests.swift": { "bytes": 6480, "mode": "0644", "sha256": "eb0bc1ed6da4e567afc3418ea292ed3f2e879528d4a46a8dfdd62ca99f78d8de" }, "platforms/macos/Tests/MCPCallContextAccessTests.swift": { - "bytes": 35768, + "bytes": 41657, "mode": "0644", - "sha256": "7018a9d03b0abf2b7c6e8d4f761f62ec9aba3ee3a4dabf3581b24317ee28ea61" + "sha256": "59d08f1a994cf7c876685b3b0a2b85222e1b0980aa5d7a06a598d203f4649b57" }, "platforms/macos/Tests/MCPDebuggerInspectionTests.swift": { - "bytes": 14009, + "bytes": 14065, "mode": "0644", - "sha256": "c497f8320f7a6964341cec13ea09ed62a1d4eead032f0b258e57275707b2ad19" + "sha256": "c378b4b3b605781e3e02903b3bf1ebda174bb8976488be471fde0b77ebb2716a" }, "platforms/macos/Tests/MCPPlaytestTests.swift": { - "bytes": 134554, + "bytes": 167266, "mode": "0644", - "sha256": "5747d44d65ee1cfd2d6fccae471513e92765bc349184c7cee09e616fbaec2da9" + "sha256": "59adea534014540eaf59eef98871179cd14f2c6049d5c619170f57837033cbeb" }, "platforms/macos/Tests/MCPProjectRefreshTests.swift": { "bytes": 17605, @@ -2987,9 +3067,9 @@ "sha256": "f97bdb49891728cd4884d56a4fa544aeb91d49f0091be89c301a1857e735d126" }, "platforms/macos/Tests/SoftwareLibraryBrowseTests.swift": { - "bytes": 22529, + "bytes": 33579, "mode": "0644", - "sha256": "ddac708066479e2d0f50aa0732a442f5e7a61caa50f8ea1f3efae2f4686f12eb" + "sha256": "9f0752e2cc416b7979f87e5444ebc9f01e7a670b3ed154bc0598d472ebba897f" }, "platforms/macos/Tests/SoftwareLibraryCuratedLaunchTests.swift": { "bytes": 17902, @@ -3002,19 +3082,24 @@ "sha256": "26c94028fbe3ad421b2fc1d173f9c147942a7ebe09df201c399f366428efb1fe" }, "platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift": { - "bytes": 16889, + "bytes": 21510, "mode": "0644", - "sha256": "7f86b0cfa4538aff03e06346038175229b423d2b27f590fe3787aa44b2e65268" + "sha256": "66ad7aba832e4f32efe3a8ecdea5dc54e53b815994db6f1fa9169a498d107564" }, "platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift": { - "bytes": 23901, + "bytes": 27163, "mode": "0644", - "sha256": "21053ce1c90567242811ae72860ae2c74f9598952d518fd37ce9c12c826d721b" + "sha256": "75fda217f2996c2d87f7784e0a0aba000303ac030671957ce8862aa99236acfe" }, "platforms/macos/Tests/SoftwareLibraryManualTests.swift": { - "bytes": 9575, + "bytes": 11045, "mode": "0644", - "sha256": "a8cb39a16209f5d4e50bf59d08e3d1a1e69beadc2ca408b190fa6a5c0dec75c8" + "sha256": "2db6776f141792edb63222efa82aafaedac6230a4cb3b8c57825bed691ebf4b6" + }, + "platforms/macos/Tests/SoftwareLibraryPersonalTests.swift": { + "bytes": 29119, + "mode": "0644", + "sha256": "467aecf71bf7bbcccc274093730a087f3b9e96ac4a27562749612007f2988af0" }, "platforms/macos/Tests/SoftwareLibraryPublishedGameTests.swift": { "bytes": 29275, @@ -3037,9 +3122,9 @@ "sha256": "15b8a2b63f510a9617bf7930f9d15907c152d60beaeb74a4b38719a1b4d4de93" }, "platforms/macos/Tests/StartupTests.swift": { - "bytes": 46268, + "bytes": 48662, "mode": "0644", - "sha256": "66fdad573aa6cef00e8c2f59bae630fca74e29d9f2efc07cf70c1533293bc55a" + "sha256": "3c8c32ffa3bf0198d1fa7ec247c984a0d163bbcfac9a73c187b590e44d83eec2" }, "platforms/macos/Tools/MCP/MCPGuestTools.h": { "bytes": 2219, @@ -3047,24 +3132,29 @@ "sha256": "85c13429e98581b679c8410b03724860fedf00de962de63bea3b19e165ec6a3c" }, "platforms/macos/Tools/MCP/MCPProjectTools.h": { - "bytes": 24058, + "bytes": 26711, "mode": "0644", - "sha256": "f41a931a11bc77464e260f973afd84820a619b6c30abacee343ba879bae40ec2" + "sha256": "c4a2a9effa9bd84bff23024ed7d52d7a133d9064599de6691408b9a715eaddfe" }, "platforms/macos/Tools/MCP/main.mm": { - "bytes": 34960, + "bytes": 37128, "mode": "0644", - "sha256": "433b87264f4bd7b29cc598f38a56e698e5cd5583a210ef2eb06b680184dcf3d7" + "sha256": "9df3bf0ba49604f2000fb7a04d7b40c9c054947ae6130c164c3d8b0c16e698e7" }, "platforms/macos/Tools/MCP/test-helper.py": { - "bytes": 69972, + "bytes": 75034, "mode": "0644", - "sha256": "ce1aca493fc34683852f112394b88606e4f27807f098ec3a785c4601a43b8d52" + "sha256": "a43b3b13f6d0255857010974f880a8ee2566e95a4c5499b8a4cf6eed37484266" + }, + "platforms/macos/Tools/Playtest/VideoWriter.swift": { + "bytes": 2866, + "mode": "0644", + "sha256": "e834117bfbd780f71c9447e7007a33725449320ee380d3b8c26ed3d7d4523c03" }, "platforms/macos/Tools/Playtest/main.mm": { - "bytes": 44495, + "bytes": 52461, "mode": "0644", - "sha256": "bea1178f6ac9bef7c8a0d43cabfa4cc1bcf623a471b2c3229d59b4cca2747eb7" + "sha256": "9b2ee92ed622d98bd189099c1cfe17046362f5d72f5b278a28460f1b946c58da" }, "platforms/macos/Tools/bundle-manual-library.py": { "bytes": 4772, @@ -3127,14 +3217,14 @@ "sha256": "2c86f35bc0d0d0f898583a4bc8f1dc5004ac065b2f55df41976cd50e90533c97" }, "platforms/macos/UITests/InteractionTests.swift": { - "bytes": 295365, + "bytes": 333203, "mode": "0644", - "sha256": "b45abb2d13fa0c7301230299f0459f966ab8869a5ca381dda1b74811ee2ab439" + "sha256": "1b526e1be1ab9095d7de9b4d66a68095eaa288c1b5ca2fdba3d6991bfd4d09c0" }, "platforms/macos/VCC.xcodeproj/project.pbxproj": { - "bytes": 175127, + "bytes": 180154, "mode": "0644", - "sha256": "e770d37c41d2b7ee1c746a347282ced40ebc2a2a3dc8d5abb0ad3e181ef1f868" + "sha256": "6cabd50774087899af4d3c844d1fa3e8101eb440b2e54dc809fd86bbd919812f" }, "platforms/macos/VCC.xcodeproj/xcshareddata/xcschemes/VCCCoreChecks.xcscheme": { "bytes": 2337, @@ -4732,14 +4822,14 @@ "sha256": "dc008ed868e23b19e58882fcb3897696ff28ec376ec485cd0d5bdd6870244ba9" }, "src/core/MachineSession.cpp": { - "bytes": 131652, + "bytes": 137442, "mode": "0644", - "sha256": "3e19e72ed3660dec9359895fbaf700bd8b5fae641fd4648da9da9f41bd279810" + "sha256": "d253f8e966d7d913563711665bce01aa4693b1d4334fab62488c283adc971ad1" }, "src/core/MachineSession.h": { - "bytes": 16328, + "bytes": 16666, "mode": "0644", - "sha256": "c87dbd2676fe3fa27ab84c1123c07f9ad12840cab41b868c27654b78a719a2b4" + "sha256": "945cb3fe310c8d897038c909ded74e9fe54fc96578410a80650ecf1db5693aa1" }, "src/core/OpCodeTables.h": { "bytes": 56014, @@ -5027,9 +5117,9 @@ "sha256": "49a23d1c1a021c5cab8a530ca080c898c28c612651b2af5941f61e0e453466eb" }, "tests/core/BinaryChecks.cpp": { - "bytes": 37625, + "bytes": 46917, "mode": "0644", - "sha256": "fd30c01d9d87a32040757daf386ece974e2da659cf9e4d5bf586820afe7178ef" + "sha256": "69809289deadbe7cec27ca7b7c282f5ed523f6e34e66d98482e088d8db838337" }, "tests/core/CoreChecks.cpp": { "bytes": 7237, @@ -5751,10 +5841,30 @@ "mode": "0644", "sha256": "ca694620918b35b5775f154262dd3318d90a57ca686ed8d42ecee66c6a0db48c" }, - "tools/catalog/package.py": { - "bytes": 14932, + "tools/catalog/curation/related-archive.json": { + "bytes": 7988, "mode": "0644", - "sha256": "3a4685c3598b25ff8bc43930a1a5d3b171ea4fffe8f3db8e71577c23237dfd2d" + "sha256": "787f225461fc3081f5b0fd68311a035528a71e056219ab9555258184560d9b69" + }, + "tools/catalog/package.py": { + "bytes": 16784, + "mode": "0644", + "sha256": "31b76c8eafd1d9e4ae083a7ebfbbe36dab6a9baabff25157a9ca8d1fcbe5e105" + }, + "tools/catalog/related_archive.py": { + "bytes": 8114, + "mode": "0644", + "sha256": "16bed094f7346c4795f89bf86bb5ae4b6660a55942f2c2c292e0ab89b7bf7d3f" + }, + "tools/catalog/rights.py": { + "bytes": 11795, + "mode": "0644", + "sha256": "edfc67673bd28a7129053a97423a82be0dac88d1f65400532d892db269b545ce" + }, + "tools/catalog/submission_intake.py": { + "bytes": 21224, + "mode": "0644", + "sha256": "f4282241dc524f77fc66515a714a9b0bee292b7fcfcbe938980cc37bfb787e4d" }, "tools/dependencies/fetch.py": { "bytes": 17751, @@ -5827,9 +5937,9 @@ "sha256": "b6d7c59f754e86e77346e6c14d6ecb695aa32b525b2c7ca55afb093af694756c" }, "tools/tests/test_build_content.py": { - "bytes": 14195, + "bytes": 14438, "mode": "0644", - "sha256": "9f54794ec5d3b33cc0237622b19af87284f132e94d8401872dc5b42babd38772" + "sha256": "0fd0139efcc700529931036c7e9cab83cf56004dce94b272fb7d291b92f65253" }, "tools/toolchain/build-coco-letters.py": { "bytes": 1886, @@ -5957,8 +6067,8 @@ "sha256": "e7062472943ca987e4d0b59b67af85637f6a031ea9595a9159f62fe8f2499cef" } }, - "policy_version": 6, - "recipe_sha256": "0e6716bb6afbf93f2064a5bd724ba6260fb13fe0ece36a4654b92f0b6156d3e7", + "policy_version": 7, + "recipe_sha256": "4f13c9841bf4d90e4fdd54d410df6bfdd1ba3b6bf75be14a88582d6e3043e8ee", "repository": "VCCPlus/VCCPlusOSS", "schema_version": 1, "source_history": "Independent distribution history; private Git metadata excluded" diff --git a/RELEASES.md b/RELEASES.md index 2e31f5d..7f87015 100644 --- a/RELEASES.md +++ b/RELEASES.md @@ -2,7 +2,46 @@ > VCC Plus OSS retains the shared emulator and development capabilities. This calendar also describes prepared software collections, the full manual library, and separately distributed companion applications. Those payloads are not bundled with the OSS source edition; compatible user-supplied content and external applications have their own preparation requirements. -Current version **3.6.2** +Current version **3.7.0** + +## 3.7.0 — Personal Libraries and CoCo Capture + +November 14, 2026 + +**Make the library your own.** Import privately owned software into Personal +Library with retained originals and separate writable working copies. Choose +standard categories, add your own cover image and review machine/media settings +and multiline loading commands. Personal titles lead unified search and category +results with clear Personal Library badges. The matching DriveWire app can use +supported personal disks on a real CoCo through the same local library; each +insertion receives an independent writable copy. + +**Pick up where you left off.** Software Library, Archive Library and each manual +remember their browsing or reading location. One manual bookmark list offers +All Books and This Book. Related Guides & References connect a software entry to +useful Archive walkthroughs, maps and other supporting documents, with source +credit and spoiler labels separate from the main manual. + +**Capture the CoCo.** New camera and video controls save the actual guest picture, +excluding Mac windows and System artwork. Screenshots use a remembered None, +five-second or ten-second timer. One Save To folder serves PNG screenshots and +MP4 movies, Desktop by default. Movies optionally include generated CoCo audio; +local capture cues never enter exported media. Stop/save decisions, retained +working movies and recovery protect interrupted recordings. + +**Help the collection grow.** Feedback opens the product-selected website form. +Software submission, contact verification and rights-holder permission lead to a +private review queue and deliberate catalog intake. Verified rights holders can +request withdrawal independently of whether a title remains on Color Computer +Archive. Private personal imports are never uploaded through this process. + +**Build and demonstrate new software.** Fresh C Assistant connections can record +bounded guest-only MP4 playtest clips, with optional audio and verified chunked +retrieval. Verified physical code overlays support bank-aware source inspection, +and larger generated assembly remains bounded without rejecting ordinary large +Make projects. Recording continues through cancelled confirmation dialogs, and +floppy controls remain steady during genuine disk activity while media-change +safeguards stay enforced. ## 3.6.2 — Curated Games and Personal Profiles diff --git a/docs/development/MCP_BANKED_PLAYTEST.md b/docs/development/MCP_BANKED_PLAYTEST.md index 948f9ae..8d7c7eb 100644 --- a/docs/development/MCP_BANKED_PLAYTEST.md +++ b/docs/development/MCP_BANKED_PLAYTEST.md @@ -58,6 +58,16 @@ just the value written to an MMU register. Installed RAM capacity is checked by the emulator. The packed binary's transfer address is `entryPoint`; it can belong to a loader outside the unpacked C modules. +Verification uses distinct evidence budgets: the manifest is at most 1 MiB; +retained compiler `.s` assembly is at most 32 MiB per file; other evidence files +(including listings, objects, linker maps, executable and raw images) are at most +8 MiB each. Unique retained evidence is capped at 128 MiB in total. Files are +verified in full against their hashes; oversized evidence is rejected rather +than truncated. Rejections identify the artifact path, observed size and byte +limit. Existing limits on manifest records, module/page ownership and listing +rows still apply. Large generated type records in assembly do not relax the +assembler-listing row limits or establish a source mapping by themselves. + Declare each linker section under one module. `codeSections` names executable, immutable sections; mutable data and BSS belong in `sections` with their real page assignments but are excluded from code guards. BSS needs no invented raw zeros. @@ -65,8 +75,13 @@ A pure BSS module may omit `image` entirely when `codeSections` is empty; its explicit page assignments and section ownership still apply. An initialized section cannot use that omission to skip object byte verification. Keep mutable bytes out of executable sections. Split modules when unrelated pages -need not remain mapped together. Different overlays may reuse a logical address -only with distinct physical ownership. +need not remain mapped together. Version 1 permits logical-address reuse with +distinct physical ownership. For code images that replace one another in the +same physical RAM, use the explicit version-2 +overlay group and owner contract. Runtime inspection +requires complete loaded-code proof of exactly one owner; declaration alone +does not establish residency. Build catalogs list static candidates, while a +paused inspection reports current verified ownership and a residency fingerprint. Hashes bind the declaration to one build. VCC Plus independently replays object relocations against the raw module bytes and verifies live RAM before publishing diff --git a/docs/development/MCP_DEBUG_EVIDENCE.md b/docs/development/MCP_DEBUG_EVIDENCE.md index 99d8a2d..5227fda 100644 --- a/docs/development/MCP_DEBUG_EVIDENCE.md +++ b/docs/development/MCP_DEBUG_EVIDENCE.md @@ -37,7 +37,11 @@ its `VCCDBG1` type/storage records; retaining compiler-generated `.s` permits verification of records too long for an assembler listing row. A useful Debug compile uses `-O0 -fno-omit-frame-pointer`; optimized builds can legitimately have fewer C statements or unavailable locals. No user Makefile is rewritten -merely to provide debugger metadata. +merely to provide debugger metadata. Banked evidence permits compiler `.s` files +up to 32 MiB while retaining 8 MiB limits for other evidence, the 1 MiB manifest +limit and the 128 MiB aggregate cap. Size failures name the artifact and exact +limit; hash, declared-output and symbolic-link checks still apply. No evidence +is truncated to make a source map appear verified. For example, a normal recipe can compile and link with: @@ -51,7 +55,11 @@ program.bin: obj/main.o This fragment only illustrates retained evidence; disk construction and launch commands remain the project's declared recipe. Packed, relocated or bank-switched -programs must supply the public version-1 [banked debug manifest](MCP_BANKED_PLAYTEST.md). +programs must supply the public [banked debug manifest](MCP_BANKED_PLAYTEST.md). +Version 1 preserves distinct physical ownership; version 2 supports explicitly +declared mutually exclusive code overlays. Discover +`banked_debug_manifest_versions` and `verified_code_overlays` through +`get_capabilities` before preparing that evidence. Its hashes, unpacked images, section ownership and actual physical page identities are required. It never falls back to a flat interpretation after verification fails. @@ -82,7 +90,11 @@ Locally configured watches retain their existing rules. `read_debug_memory` accepts only ranges advertised by that immutable snapshot, up to 256 bytes. Resume, input, step, restart, source/artifact changes and -connection revocation invalidate the applicable observation. Inspection performs +connection revocation invalidate the applicable observation. Owned memory and +call-context reads also compare a fresh complete capture, including verified +residency, registers, cycles and safe memory, even at the same field clock. +The residency fingerprint names a current proof rather than a monotonic guest +write counter; A→B→A still requires fresh capture validation. Inspection performs no guest expressions, register writes, memory writes or side-effecting I/O reads. A mismatched binary, object relocation, source identity or bank cannot produce a verified snapshot merely because a requested function name exists. diff --git a/docs/media/capture-sounds/README.md b/docs/media/capture-sounds/README.md new file mode 100644 index 0000000..3e3be81 --- /dev/null +++ b/docs/media/capture-sounds/README.md @@ -0,0 +1,31 @@ +# Capture feedback audio + +The two short cues play through NSSound on the Mac only. They never enter the +emulator audio mixer, generated PCM, MCP audio capture or recorded movies. +They are not controlled by the separate Include CoCo Audio in Video preference. + +Brian selected these effects on Pixabay. The same recordings are available from +their original creators on Freesound under **CC0 1.0**; the retained sources were +downloaded from the preview URLs linked by those original pages on November 13, +2026. These assets are public-domain dedications, separate from the GPL code and +the original VCC Plus artwork notice. + +| Cue | Original creator and source | Retained preview | +| --- | --- | --- | +| Screenshot | [iPhone Camera Capture.wav — pooky1](https://freesound.org/people/pooky1/sounds/431588/) | https://cdn.freesound.org/previews/431/431588_2339776-hq.mp3 | +| Recording start | [Tape start .wav — sophiehall3535](https://freesound.org/people/sophiehall3535/sounds/245927/) | https://cdn.freesound.org/previews/245/245927_4361022-hq.mp3 | + +Both source pages explicitly identify Creative Commons 0: +https://creativecommons.org/publicdomain/zero/1.0/ + +The selected Pixabay pages remain references: +https://pixabay.com/sound-effects/film-special-effects-iphone-camera-capture-6448/ +https://pixabay.com/sound-effects/film-special-effects-tape-start-85778/ + +`prepare.py` decodes the retained previews, extracts 1.62–2.14 seconds of the tape +recording to remove the long lead-in and later sounds, downmixes to mono 44.1 kHz +16-bit WAV, normalizes the peak to 0.35 and applies five-millisecond edge fades. +The full shutter preview is retained in its cue. Source and output SHA-256 values +are recorded in `manifest.json`. Run `python3 docs/media/capture-sounds/prepare.py` +with ffmpeg available to reproduce the bundled WAV files. Application builds use +the prepared WAV files and require no audio download or ffmpeg. diff --git a/docs/media/capture-sounds/manifest.json b/docs/media/capture-sounds/manifest.json new file mode 100644 index 0000000..29c8aff --- /dev/null +++ b/docs/media/capture-sounds/manifest.json @@ -0,0 +1,24 @@ +{ + "license": "CC0-1.0", + "reviewed": "2026-11-13", + "inputs": { + "shutter.mp3": { + "sha256": "e805680b4ee8a48bc537f266c866e74d60b076a76e52af3acbaacf77e8cb7392", + "bytes": 15600 + }, + "tape-start.mp3": { + "sha256": "ebbbb9d82d0ff2f84d48ae8228a2f635fe45b7816583393e77d079034230eac7", + "bytes": 50712 + } + }, + "outputs": { + "recording-start.wav": { + "sha256": "5b5ba2407a84e39cf04018c64acb48b690089cd32cec193920dcbf2cb4080aa7", + "bytes": 45908 + }, + "screenshot.wav": { + "sha256": "38bce90df26042fa70bb0a5dc33a5759867e0440de0a7acd4b8942cbcbdf239d", + "bytes": 48886 + } + } +} diff --git a/docs/media/capture-sounds/prepare.py b/docs/media/capture-sounds/prepare.py new file mode 100644 index 0000000..815ec47 --- /dev/null +++ b/docs/media/capture-sounds/prepare.py @@ -0,0 +1,40 @@ +#!/usr/bin/env python3 +"""Reproduce short host-only cues from the retained CC0 Freesound previews. + +Requires ffmpeg; not needed to build or run VCC Plus. +""" +from pathlib import Path +import hashlib +import json +import struct +import subprocess +import wave + +ROOT = Path(__file__).resolve().parents[3] +HERE = Path(__file__).resolve().parent +DEST = ROOT / "platforms/macos/Resources/CaptureSounds" +CLIPS = [("shutter.mp3", "screenshot.wav", None), + ("tape-start.mp3", "recording-start.wav", "atrim=start=1.62:end=2.14,asetpts=PTS-STARTPTS")] + + +def build(): + DEST.mkdir(parents=True, exist_ok=True) + for original, filename, trim in CLIPS: + command = ["ffmpeg", "-nostdin", "-v", "error", "-i", str(HERE / "source" / original)] + if trim: + command += ["-af", trim] + raw = subprocess.check_output(command + ["-ac", "1", "-ar", "44100", "-f", "f32le", "-"]) + values = struct.unpack("<" + "f" * (len(raw) // 4), raw) + peak = max(abs(v) for v in values) + scale = 0.35 / max(peak, 0.000001) + fade = 221 + samples = [round(v * scale * 32767 * min(1, i / fade, (len(values) - 1 - i) / fade)) + for i, v in enumerate(values)] + with wave.open(str(DEST / filename), "wb") as output: + output.setparams((1, 2, 44100, 0, "NONE", "not compressed")) + output.writeframes(struct.pack("<" + "h" * len(samples), *samples)) + print(filename, len(samples) / 44100, hashlib.sha256((DEST / filename).read_bytes()).hexdigest()) + + +if __name__ == "__main__": + build() diff --git a/docs/media/capture-sounds/source/shutter.mp3 b/docs/media/capture-sounds/source/shutter.mp3 new file mode 100644 index 0000000000000000000000000000000000000000..8ce1eafc83d411911bb8a59ca6c3c5a53238661f GIT binary patch literal 15600 zcmdU$bx>Tv^WYz_xGjrokj34C1jqu5OBPw&-Gc^;;1*mL4G`RddvJG`03jrJAch1& zV2^x%clW#huIm1~Pu14$n|)Ppx?fLsPtOecCfyGBzhLC-;dp-w>HUWm0Azju*x1;R zdl>H#xJT|D?R$*wvA)Oap0Imf-;;Jv{ypXQyt}9Up8k6#?peBL^Pb&%zTI-)nArqIm`V%{cg~9U36%KpGz-apeP#PzK{CVu(H7=rK zeeoxRuFhts3~@1}_{=(#CEQW#CZbx^9AS$bijvh*MLD`w&qO46(zqbL$;C%5l6J{t zg$dRlDF??ET)CuQ(VIva%p6Qvb)6N_Bbr*Cpus?&tew9)% zX@=>X2xG8Lz_0DNlC%sGDqa`#gYZ<1BPiTc)ATdEl?6CSQgd5$;>#drzZ8n3k2FyV z9Rs7wFy$#>xM;CI6Njc|pn+j!v0oYS8$?*Pn{fBfMeYTQ;e815uZGQz6`D*W%Fvpt z70nsT*U26}SvRmT;rf-L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-(|Kb~U z|CJi%5!YDz6Yl*|ND>cz6iO2tN@CiKzOY7gcYpo`rZeSE zA70){{{@C?%T+3ue&T$l*@P_k;wPE#)eUyHz^X4hjMB@>-}l z6yPc$u^iwzXONlXRJ*_QYMHHM((6X2WAG8{v$ckJ_)OqP1SDSRedBJX#8zJAb_6eO2L+ zrM62gcYq)h*NM5cT5;hDEBdg-^OzCB2;V!*;704^j+6iDYi1UN+Jsx7Rw`wpi^W#LAim9frev&L1XRL2r$ zqHNkO3`~kD8Dg5c?N}{G96;VqvM2NUDyniOwrUTjn;V^pXH>TE8!8ThMK|NzH-dy9;v zp9%lH{TgV`ndC0{^B2~gAsF?oNtdmT-dWH+2&4w)Tu~+r({`bgfpl~pjJ9+@yzW#! zv}%#5aCrz2@%x9jH|LG7m@pE(2ZiR({!95|IRPY4$w^%W6qeeL0APNdGZ51^4uXHD zLqhRIvF2${7_W$nunRZU9>tqx6MG(?v0}WM#8KP$B#i}Sal77}i-osjYAb+aG7{CI z5Ww)E^V3>TonbzixA=wz2&=7f&6@oou%^B zk9VqNZ`EE()2x2U*m=|Pu1;bGd9EES7jEAg<@a)W*{&<-GQ;8O52qCmyGLZ6)+h#- k`#Bj;YeN}3o%xtvw1%Cy+;5S5+I{nZTke0O$W2ZE2d%>K+yDRo literal 0 HcmV?d00001 diff --git a/docs/white-paper-evidence.json b/docs/white-paper-evidence.json index b26832b..a24ed78 100644 --- a/docs/white-paper-evidence.json +++ b/docs/white-paper-evidence.json @@ -230,7 +230,7 @@ }, { "path": "docs/development/MCP_BANKED_PLAYTEST.md", - "export_sha256": "fad90fcb7e5ca3670d803f02578e44e637b0b126f7716dc4198f253ea7eae3a6", + "export_sha256": "75f1b3c0977ffc536a0cb47f46f554c10c06a34d5b7a2a58458d997c1493c480", "selected_headings": [ { "heading": "Build evidence for packed programs", @@ -306,7 +306,7 @@ }, { "path": "docs/development/MCP_DEBUG_EVIDENCE.md", - "export_sha256": "79fe80ae2c40808e6da821bae1d2de1aa4c18b5f7e24b3a40707fdd473cf086e", + "export_sha256": "ddb8e4979b5573cff809a6fda8c9b961fcbd3dfc0fd7f8bce4dcd1814782e2f4", "selected_headings": [ { "heading": "Read the build evidence first", diff --git a/platforms/macos/App/ArchiveInlinePreview.swift b/platforms/macos/App/ArchiveInlinePreview.swift index a2a2fd9..f7744d8 100644 --- a/platforms/macos/App/ArchiveInlinePreview.swift +++ b/platforms/macos/App/ArchiveInlinePreview.swift @@ -140,12 +140,14 @@ enum ArchiveInlineContent: Sendable { struct ArchiveInlinePreview: View { let content: ArchiveInlineContent let title: String + var position: LibraryReadingPosition? = nil + var onPositionChange: (Double, Double, Double?) -> Void = { _,_,_ in } var body: some View { switch content { - case .image(let image): ArchiveInlineImage(image: image, title: title) - case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title) - case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title) + case .image(let image): ArchiveInlineImage(image: image, title: title, position: position, onPositionChange: onPositionChange) + case .text(let text): ArchiveInlineText(text: text, worksheet: false, title: title, position: position, onPositionChange: onPositionChange) + case .worksheet(let text): ArchiveInlineText(text: text, worksheet: true, title: title, position: position, onPositionChange: onPositionChange) } } } @@ -153,8 +155,14 @@ struct ArchiveInlinePreview: View { private struct ArchiveInlineImage: View { let image: CGImage let title: String - @State private var zoom = 0 + let position: LibraryReadingPosition? + let onPositionChange: (Double, Double, Double?) -> Void + @State private var zoom: Int + init(image: CGImage, title: String, position: LibraryReadingPosition?, onPositionChange: @escaping (Double, Double, Double?) -> Void) { + self.image = image; self.title = title; self.position = position; self.onPositionChange = onPositionChange + _zoom = State(initialValue: min(5,max(0,Int(log2(position?.zoom ?? 1))))) + } var body: some View { VStack(spacing: 0) { HStack { @@ -166,18 +174,77 @@ private struct ArchiveInlineImage: View { Spacer() }.padding(6) Divider() - GeometryReader { geometry in - let width = CGFloat(image.width), height = CGFloat(image.height) - let fit = min(1, min(geometry.size.width / width, geometry.size.height / height)) - let scale = fit * pow(2.0, CGFloat(zoom)) - ScrollView([.horizontal, .vertical]) { - Image(image, scale: 1, label: Text(title)) - .resizable() - .frame(width: width * scale, height: height * scale) - .accessibilityIdentifier("archive-inline-image") - .frame(minWidth: geometry.size.width, minHeight: geometry.size.height) - } + ArchiveImageSurface(image: image, title: title, zoom: zoom, initialPosition: position, onPositionChange: onPositionChange) + } + } +} + +private struct ArchiveImageSurface: NSViewRepresentable { + let image: CGImage + let title: String + let zoom: Int + let initialPosition: LibraryReadingPosition? + let onPositionChange: (Double, Double, Double?) -> Void + func makeCoordinator() -> Coordinator { Coordinator() } + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSScrollView() + scroll.hasHorizontalScroller = true; scroll.hasVerticalScroller = true + let imageView = NSImageView() + imageView.image = NSImage(cgImage: image, size: NSSize(width: image.width, height: image.height)) + imageView.imageScaling = .scaleAxesIndependently + imageView.setAccessibilityLabel(title) + imageView.setAccessibilityIdentifier("archive-inline-image") + let container = NSView() + container.addSubview(imageView) + scroll.documentView = container + context.coordinator.imageView = imageView + context.coordinator.scroll = scroll + scroll.contentView.postsBoundsChangedNotifications = true + context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() } + return scroll + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + let coordinator = context.coordinator + coordinator.onPositionChange = onPositionChange; coordinator.imageSize = NSSize(width: image.width, height: image.height) + coordinator.initialPosition = initialPosition; coordinator.zoom = zoom + DispatchQueue.main.async { [weak coordinator] in coordinator?.layout() } + } + final class Coordinator { + weak var scroll: NSScrollView? + weak var imageView: NSImageView? + var observer: NSObjectProtocol? + var imageSize = NSSize.zero + var initialPosition: LibraryReadingPosition? + var zoom = 0 + var restored = false + var layingOut = false + var viewport = NSSize.zero + var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in } + deinit { if let observer { NotificationCenter.default.removeObserver(observer) } } + func layout() { + guard let scroll, let image = scroll.documentView, imageSize.width > 0, + scroll.contentSize.width > 0, scroll.contentSize.height > 0 else { return } + layingOut = true + viewport = scroll.contentSize + let fit = min(1,min(scroll.contentSize.width/imageSize.width,scroll.contentSize.height/imageSize.height)) + let picture = NSSize(width:imageSize.width*fit*pow(2,Double(zoom)),height:imageSize.height*fit*pow(2,Double(zoom))) + let size = NSSize(width:max(scroll.contentSize.width,picture.width),height:max(scroll.contentSize.height,picture.height)) + image.setFrameSize(size) + imageView?.frame = NSRect(x:(size.width-picture.width)/2,y:(size.height-picture.height)/2,width:picture.width,height:picture.height) + if !restored { + restored = true + let target = NSPoint(x:(initialPosition?.horizontalOffset ?? 0)*max(0,size.width-scroll.contentSize.width),y:(initialPosition?.offset ?? 0)*max(0,size.height-scroll.contentSize.height)) + scroll.contentView.scroll(to: target); scroll.reflectScrolledClipView(scroll.contentView) } + layingOut = false + changed() + } + func changed() { + guard !layingOut, let scroll, let image = scroll.documentView else { return } + if viewport != scroll.contentSize { layout(); return } + let x = scroll.contentView.bounds.minX/max(1,image.bounds.width-scroll.contentSize.width) + let y = scroll.contentView.bounds.minY/max(1,image.bounds.height-scroll.contentSize.height) + onPositionChange(min(1,max(0,y)),min(1,max(0,x)),pow(2,Double(zoom))) } } } @@ -186,9 +253,15 @@ private struct ArchiveInlineText: NSViewRepresentable { let text: String let worksheet: Bool let title: String + let position: LibraryReadingPosition? + let onPositionChange: (Double, Double, Double?) -> Void + func makeCoordinator() -> Coordinator { Coordinator() } func makeNSView(context: Context) -> NSScrollView { let scroll = NSTextView.scrollableTextView() + scroll.contentView.postsBoundsChangedNotifications = true + context.coordinator.scroll = scroll + context.coordinator.observer = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: scroll.contentView, queue: .main) { [weak coordinator = context.coordinator] _ in coordinator?.changed() } guard let view = scroll.documentView as? NSTextView else { return scroll } view.isEditable = false view.isSelectable = true @@ -205,6 +278,7 @@ private struct ArchiveInlineText: NSViewRepresentable { func updateNSView(_ scroll: NSScrollView, context: Context) { guard let view = scroll.documentView as? NSTextView else { return } + context.coordinator.onPositionChange = onPositionChange view.setAccessibilityLabel(title) guard view.string != text else { return } view.string = text @@ -234,7 +308,24 @@ private struct ArchiveInlineText: NSViewRepresentable { view.textStorage?.addAttribute(.paragraphStyle, value: style, range: NSRange(location: 0, length: (text as NSString).length)) } view.setSelectedRange(NSRange(location: 0, length: 0)) - scroll.contentView.scroll(to: .zero) - scroll.reflectScrolledClipView(scroll.contentView) + let initial = position + DispatchQueue.main.async { [weak scroll] in + guard let scroll, let view = scroll.documentView as? NSTextView else { return } + view.layoutManager?.ensureLayout(for: view.textContainer!) + let point = NSPoint(x:(initial?.horizontalOffset ?? 0)*max(0,view.bounds.width-scroll.contentSize.width),y:(initial?.offset ?? 0)*max(0,view.bounds.height-scroll.contentSize.height)) + scroll.contentView.scroll(to: point); scroll.reflectScrolledClipView(scroll.contentView) + } + } + final class Coordinator { + weak var scroll: NSScrollView? + var observer: NSObjectProtocol? + var onPositionChange: (Double,Double,Double?) -> Void = { _,_,_ in } + deinit { if let observer { NotificationCenter.default.removeObserver(observer) } } + func changed() { + guard let scroll, let view = scroll.documentView else { return } + let y = scroll.contentView.bounds.minY/max(1,view.bounds.height-scroll.contentSize.height) + let x = scroll.contentView.bounds.minX/max(1,view.bounds.width-scroll.contentSize.width) + onPositionChange(min(1,max(0,y)),min(1,max(0,x)),nil) + } } } diff --git a/platforms/macos/App/ArchiveLibraryCatalog.swift b/platforms/macos/App/ArchiveLibraryCatalog.swift index 327e269..87e96ed 100644 --- a/platforms/macos/App/ArchiveLibraryCatalog.swift +++ b/platforms/macos/App/ArchiveLibraryCatalog.swift @@ -125,6 +125,25 @@ actor ArchiveLibraryCatalog { return try rows.map(document) } + func document(id: String) throws -> ArchiveDocument? { + guard Self.isSHA(id) else { return nil } + return try database().rows("SELECT * FROM document WHERE sha256=? LIMIT 1", [id]).first.map(document) + } + + /// Locate the exact title in the same deterministic order used by Browse. + /// Deep links must not depend on the title happening to be in its first batch. + func browseOffset(documentID: String, collection: String?, batchSize: Int) throws -> Int? { + guard (1...50).contains(batchSize), let target = try document(id: documentID) else { return nil } + let filter = try scope(collection) + let rows = try database().rows(""" + SELECT count(*) AS amount FROM document d WHERE 1=1 \(filter.sql) + AND (d.title COLLATE NOCASE < ? COLLATE NOCASE OR + (d.title COLLATE NOCASE = ? COLLATE NOCASE AND d.sha256 < ?)) + """, filter.values + [target.title, target.title, target.id]) + guard let amount = rows.first?["amount"].flatMap(Int.init), amount <= 250_000 else { return nil } + return (amount / batchSize) * batchSize + } + private static let compounds = ["module directory", "width 80", "width 40", "disk basic", "extended basic"] private func match(_ query: String) throws -> String { diff --git a/platforms/macos/App/ArchiveLibraryReader.swift b/platforms/macos/App/ArchiveLibraryReader.swift index fead9a8..0503d7f 100644 --- a/platforms/macos/App/ArchiveLibraryReader.swift +++ b/platforms/macos/App/ArchiveLibraryReader.swift @@ -313,6 +313,7 @@ final class ArchiveReaderModel: ObservableObject { @Published private(set) var progress: ArchiveReadProgress? @Published private(set) var error: String? @Published private(set) var page = 1 + @Published private(set) var inlineNavigationRevision = 0 @Published var find = "" { didSet { if find != oldValue { resetFind() } } } @Published private(set) var findMessage: String? @Published private(set) var isFinding = false @@ -323,12 +324,17 @@ final class ArchiveReaderModel: ObservableObject { private var localURL: URL? private var lastMatch: (page: Int, range: NSRange)? private var pendingPage = 1 + private var resumePending = false + private var lastCheckpoint = Date.distantPast + private var tracking: [NSObjectProtocol] = [] + private let continuity: LibraryContinuityStore? let remembersPage: Bool private let cache: ArchiveAssetCache private let catalog: ArchiveLibraryCatalog - init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared) { + init(remembersPage: Bool, cache: ArchiveAssetCache = .shared, catalog: ArchiveLibraryCatalog = .shared, continuity: LibraryContinuityStore? = nil) { self.remembersPage = remembersPage + self.continuity = remembersPage ? (continuity ?? .shared) : nil self.cache = cache self.catalog = catalog view.displayMode = .singlePageContinuous @@ -336,7 +342,9 @@ final class ArchiveReaderModel: ObservableObject { view.displaysPageBreaks = true view.setAccessibilityLabel("Archive PDF") } + deinit { for token in tracking { NotificationCenter.default.removeObserver(token) } } func stop() { + rememberPage(force: true) requestID = UUID(); request?.cancel(); request = nil; progress = nil resetFind() } @@ -350,12 +358,55 @@ final class ArchiveReaderModel: ObservableObject { cancelled = true } func retry(_ record: ArchiveDocument) { - open(record, page: pendingPage) + open(record, page: pendingPage, resumePosition: resumePending) } - private func rememberPage() { - if remembersPage, let referenceID { UserDefaults.standard.set(page, forKey: "archive-library.page." + referenceID) } + private func rememberPage(force: Bool = false) { + guard let continuity, let referenceID, document != nil || preview != nil, + force || Date().timeIntervalSince(lastCheckpoint) >= 1 else { return } + lastCheckpoint = Date() + var position = continuity.reading(for: "archive:" + referenceID) ?? LibraryReadingPosition(documentID: referenceID) + position.page = page + if let document, let destination = view.currentDestination, let destinationPage = destination.page { + let bounds = destinationPage.bounds(for: view.displayBox) + let index = document.index(for: destinationPage) + if index >= 0, index < document.pageCount { position.page = index + 1 } + if bounds.height > 0 { position.offset = min(1,max(0,(destination.point.y-bounds.minY)/bounds.height)) } + if bounds.width > 0 { position.horizontalOffset = min(1,max(0,(destination.point.x-bounds.minX)/bounds.width)) } + position.zoom = view.scaleFactor; position.autoScales = view.autoScales + } + continuity.setReading(position, for: "archive:" + referenceID) + } + static func savedPage(for id: String) -> Int { + LibraryContinuityStore.shared.reading(for: "archive:" + id)?.page ?? max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) + } + func savedPage(for id: String) -> Int { + continuity?.reading(for: "archive:" + id)?.page ?? max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) + } + var inlinePosition: LibraryReadingPosition? { + guard let referenceID, let value = continuity?.reading(for: "archive:" + referenceID), value.page == page else { return nil } + return value + } + func updateInlinePosition(offset: Double, horizontal: Double = 0, zoom: Double? = nil) { + guard let continuity, let referenceID else { return } + var position = LibraryReadingPosition(documentID: referenceID, page: page, offset: min(1,max(0,offset)), horizontalOffset: min(1,max(0,horizontal)), zoom: zoom) + position.autoScales = nil + continuity.setReading(position, for: "archive:" + referenceID) + } + private func trackPDFPosition() { + for token in tracking { NotificationCenter.default.removeObserver(token) } + tracking = [] + for name in [Notification.Name.PDFViewPageChanged, .PDFViewScaleChanged] { + tracking.append(NotificationCenter.default.addObserver(forName: name, object: view, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in self?.updatePage() } + }) + } + if let clip = view.documentView?.enclosingScrollView?.contentView { + clip.postsBoundsChangedNotifications = true + tracking.append(NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: clip, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in self?.rememberPage() } + }) + } } - static func savedPage(for id: String) -> Int { max(UserDefaults.standard.integer(forKey: "archive-library.page." + id), 1) } func updatePage() { guard let document, let current = view.currentPage, current.document === document else { return } let index = document.index(for: current) @@ -367,18 +418,32 @@ final class ArchiveReaderModel: ObservableObject { guard let document, number > 0, number <= document.pageCount, let target = document.page(at: number - 1) else { return } view.go(to: target); updatePage() } - func open(_ record: ArchiveDocument, page number: Int) { + func open(_ record: ArchiveDocument, page requestedNumber: Int, resumePosition: Bool = false) { + let number = resumePosition ? min(max(requestedNumber,1),record.pageCount ?? max(requestedNumber,1)) : requestedNumber if referenceID == record.id { - if document != nil { go(to: number); return } - if preview != nil && page == number { return } + if document != nil { + if !resumePosition || page != number { go(to: number) } + return + } + if preview != nil && page == number { + if !resumePosition { + continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: number), for: "archive:" + record.id) + // A deliberate same-section citation starts at that section, + // rather than keeping an already visible image/text viewport. + inlineNavigationRevision += 1 + } + return + } if progress != nil && (record.format == "pdf" || number == pendingPage) { pendingPage = number + resumePending = resumePosition return } } reset() referenceID = record.id - pendingPage = number + pendingPage = number; resumePending = resumePosition + let saved = resumePosition ? continuity?.reading(for: "archive:" + record.id) : nil let identity = requestID progress = .checking request = Task { @@ -396,13 +461,22 @@ final class ArchiveReaderModel: ObservableObject { if record.format == "pdf" { let parsed = await Task.detached(priority: .userInitiated) { PDFDocument(url: url) }.value try Task.checkCancellation() - let target = pendingPage - guard let parsed, !parsed.isLocked, target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page } + guard let parsed, !parsed.isLocked, parsed.pageCount > 0 else { throw ArchiveReaderError.page } + let target = resumePending ? min(max(pendingPage,1),parsed.pageCount) : pendingPage + guard target > 0, target <= parsed.pageCount else { throw ArchiveReaderError.page } localURL = url; document = parsed; view.document = parsed; view.autoScales = true; go(to: target) + if resumePending, let saved, saved.page == target, let page = parsed.page(at: target-1) { + if saved.autoScales == false, let zoom = saved.zoom { view.autoScales = false; view.scaleFactor = CGFloat(zoom) } + let bounds = page.bounds(for: view.displayBox) + view.go(to: PDFDestination(page: page, at: NSPoint(x: bounds.minX + saved.horizontalOffset*bounds.width, y: bounds.minY + saved.offset*bounds.height))) + } + trackPDFPosition(); rememberPage(force: true) } else { let content = try await ArchivePreviewDecoder.shared.read(url, format: record.format, number: number) try Task.checkCancellation() - page = number; preview = content; rememberPage() + page = number; preview = content + if !resumePending { continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: number), for: "archive:" + record.id) } + rememberPage(force: true) } default: guard let section = try await catalog.readerSection(documentID: record.id, number: number) else { @@ -411,7 +485,8 @@ final class ArchiveReaderModel: ObservableObject { try Task.checkCancellation() page = section.number; sectionLabel = section.label preview = record.format == "office-xls" ? .worksheet(section.text) : .text(section.text) - rememberPage() + if !resumePending { continuity?.setReading(LibraryReadingPosition(documentID: record.id, page: page), for: "archive:" + record.id) } + rememberPage(force: true) } progress = nil } catch { @@ -469,6 +544,7 @@ struct ArchiveReaderPane: View { @ObservedObject var reader: ArchiveReaderModel let requestedPage: Int let catalog: ArchiveLibraryCatalog + var resumesPosition = false @Environment(\.openWindow) private var openWindow @State private var examples: [ArchiveExample] = [] @State private var exampleError: String? @@ -551,8 +627,13 @@ struct ArchiveReaderPane: View { Spacer(minLength: 0) }.padding(8) } - ArchiveInlinePreview(content: preview, title: record.title) - .id(record.id + "/" + String(reader.page)) + let revision = reader.inlineNavigationRevision + ArchiveInlinePreview(content: preview, title: record.title, position: reader.inlinePosition, + onPositionChange: { y,x,zoom in + guard reader.inlineNavigationRevision == revision else { return } + reader.updateInlinePosition(offset: y, horizontal: x, zoom: zoom) + }) + .id(record.id + "/" + String(reader.page) + "/" + String(revision)) } else { VStack(spacing: 12) { if isCurrent, let progress = reader.progress { @@ -586,7 +667,7 @@ struct ArchiveReaderPane: View { .onChange(of: reader.page, initial: true) { _, value in pageField = String(value) } .task(id: hit?.id ?? record.id) { guard !Task.isCancelled else { return } - reader.open(record, page: requestedPage) + reader.open(record, page: requestedPage, resumePosition: resumesPosition) } .task(id: exampleKey) { examples = []; loadedExampleKey = nil; exampleError = nil; copies = nil diff --git a/platforms/macos/App/ArchiveLibraryView.swift b/platforms/macos/App/ArchiveLibraryView.swift index 123cfe4..2d0ab16 100644 --- a/platforms/macos/App/ArchiveLibraryView.swift +++ b/platforms/macos/App/ArchiveLibraryView.swift @@ -38,11 +38,26 @@ final class ArchiveLibraryQuery: ObservableObject { init(_ text: String = "") { self.text = text } } +private struct ArchiveVisibleRows: PreferenceKey { + static let defaultValue: [String: CGFloat] = [:] + static func reduce(value: inout [String: CGFloat], nextValue: () -> [String: CGFloat]) { value.merge(nextValue(), uniquingKeysWith: { _, last in last }) } +} + struct ArchiveLibraryView: View { - @AppStorage("archive-library.collection") private var collection = "" - @AppStorage("archive-library.browse-selection") private var browseID: String? - @AppStorage("archive-library.browse-offset") private var browseOffset = 0 - @AppStorage("archive-library.scope") private var localScope = false + @State private var collection = "" + @State private var browseID: String? + @State private var browseOffset = 0 + @State private var localScope = false + @ObservedObject private var navigation = ArchiveLibraryNavigation.shared + private let continuity: LibraryContinuityStore + @State private var browseTopID: String? + @State private var searchTopID: String? + @State private var restoreBrowseTop: String? + @State private var restoreSearchTop: String? + @State private var restoringSearchSelection = false + @State private var navigationDocument: ArchiveDocument? + @State private var navigationPage: Int? + @State private var navigationError: String? @State private var collections: [ArchiveCollection] = [] @State private var documents: [ArchiveDocument] = [] @State private var hits: [ArchiveHit] = [] @@ -66,20 +81,49 @@ struct ArchiveLibraryView: View { private let batch = 35 private let catalog: ArchiveLibraryCatalog - init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil) { - self.catalog = catalog - _browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog)) - _archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery()) - _searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: false, catalog: catalog)) + init(catalog: ArchiveLibraryCatalog = .shared, query: ArchiveLibraryQuery? = nil, searchReader: ArchiveReaderModel? = nil, + continuity suppliedContinuity: LibraryContinuityStore? = nil) { + let continuity = suppliedContinuity ?? .shared + self.catalog = catalog; self.continuity = continuity + let saved = continuity.browse(for: "archive-main") + let defaults = UserDefaults.standard + _collection = State(initialValue: saved?.scope ?? defaults.string(forKey: "archive-library.collection") ?? "") + _browseID = State(initialValue: saved?.filters["browseID"] ?? defaults.string(forKey: "archive-library.browse-selection")) + _browseOffset = State(initialValue: saved?.pageOffset ?? max(0, defaults.integer(forKey: "archive-library.browse-offset"))) + _localScope = State(initialValue: saved?.filters["localScope"].map { $0 == "true" } ?? defaults.bool(forKey: "archive-library.scope")) + _searchID = State(initialValue: saved?.filters["searchID"]) + _searchOffset = State(initialValue: Int(saved?.filters["searchOffset"] ?? "0") ?? 0) + _searchFolder = State(initialValue: saved?.filters["searchFolder"]) + _searchBrowseCollection = State(initialValue: saved?.filters["searchBrowseCollection"]) + _browseTopID = State(initialValue: saved?.filters["browseTop"]) + _searchTopID = State(initialValue: saved?.filters["searchTop"]) + _restoreBrowseTop = State(initialValue: saved?.filters["browseTop"]) + _restoreSearchTop = State(initialValue: saved?.filters["searchTop"]) + _restoringSearchSelection = State(initialValue: saved?.filters["searchID"] != nil) + _browseReader = StateObject(wrappedValue: ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity)) + _archiveQuery = StateObject(wrappedValue: query ?? ArchiveLibraryQuery(saved?.query ?? "")) + _searchReader = StateObject(wrappedValue: searchReader ?? ArchiveReaderModel(remembersPage: true, catalog: catalog, continuity: continuity)) } private var query: String { archiveQuery.text } private var searching: Bool { !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } - private var browseDocument: ArchiveDocument? { documents.first { $0.id == browseID } } + private var browseDocument: ArchiveDocument? { navigationDocument.flatMap { $0.id == browseID ? $0 : nil } ?? documents.first { $0.id == browseID } } private var hit: ArchiveHit? { hits.first { $0.id == searchID } } private var selected: ArchiveDocument? { searching ? hit?.document : browseDocument } private var reader: ArchiveReaderModel { searching ? searchReader : browseReader } - private var requestedPage: Int { searching ? (hit?.locationNumber ?? 1) : browseID.map(ArchiveReaderModel.savedPage) ?? 1 } + private var requestedPage: Int { + if searching { return restoringSearchSelection ? hit.map { searchReader.savedPage(for: $0.document.id) } ?? 1 : hit?.locationNumber ?? 1 } + return navigationPage ?? browseID.map { browseReader.savedPage(for: $0) } ?? 1 + } + private var browseState: LibraryBrowseState { + var state = LibraryBrowseState() + state.scope = collection; state.query = query; state.selectedID = searching ? searchID : browseID; state.pageOffset = browseOffset + state.filters = ["localScope": String(localScope), "searchOffset": String(searchOffset)] + for (key,value) in [("browseID",browseID),("searchID",searchID),("searchFolder",searchFolder),("searchBrowseCollection",searchBrowseCollection),("browseTop",browseTopID),("searchTop",searchTopID)] { + if let value { state.filters[key] = value } + } + return state + } private var sidebarPath: String { searching ? (searchFolder ?? collection) : collection } private var scopePath: String? { if searching, let searchFolder, !searchFolder.isEmpty { return searchFolder } @@ -106,29 +150,51 @@ struct ArchiveLibraryView: View { } .frame(minWidth: 430, minHeight: 320) .task(id: retry) { - do { let paths = try await catalog.collections(); try Task.checkCancellation(); collections = ArchiveCollection.tree(paths) } + do { + let paths = try await catalog.collections(); try Task.checkCancellation() + collections = ArchiveCollection.tree(paths) + let valid = Set(paths.flatMap { path -> [String] in + let parts = path.split(separator: "/") + guard !parts.isEmpty else { return [] } + return (1...parts.count).map { parts.prefix($0).joined(separator: "/") } + }) + if !collection.isEmpty, !valid.contains(collection) { + collection = ""; browseID = nil; browseOffset = 0 + } + } catch { if !Task.isCancelled { browseError = error.localizedDescription } } } .task(id: ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry)) { await loadBrowse() } .task(id: key) { await loadSearch(key) } + .task(id: navigation.request?.id) { if let request = navigation.request { await openRequested(request) } } + .onChange(of: browseState) { _, value in continuity.setBrowse(value, for: "archive-main") } .onChange(of: query) { old, new in + navigationError = nil if old.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && !new.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty { searchBrowseCollection = browseDocument?.collection if browseReader.progress != nil { browseReader.stop() } } + restoringSearchSelection = false; restoreSearchTop = nil searchID = nil; searchOffset = 0; compactReader = false; searchReader.reset() if !searching { searchBrowseCollection = nil; searchFolder = nil } } .onChange(of: localScope) { _, _ in searchOffset = 0; searchID = nil; compactReader = false; searchReader.reset() } .onChange(of: browseID) { _, id in + navigationError = nil + if id != navigationDocument?.id { navigationDocument = nil; navigationPage = nil } if id == nil { browseReader.reset() } else if !searching { compactReader = true } } .onChange(of: searchID) { _, id in + navigationError = nil + // Initial restoration sets State before observation starts. A later + // selection change (including keyboard arrows) is an explicit hit. + if id != nil { restoringSearchSelection = false } if id == nil { searchReader.reset() } else if searching { compactReader = true } } - .onDisappear { browseReader.stop(); searchReader.stop() } + .onDisappear { continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint(); browseReader.stop(); searchReader.stop() } + .onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in continuity.setBrowse(browseState, for: "archive-main"); continuity.checkpoint() } } private func header(narrow: Bool, sidebar side: Bool) -> some View { @@ -176,7 +242,7 @@ struct ArchiveLibraryView: View { } private func chooseCollection(_ path: String) { - showCollections = false + showCollections = false; navigationError = nil; navigationDocument = nil; navigationPage = nil; restoreBrowseTop = nil; restoreSearchTop = nil if searching { if path != sidebarPath { searchID = nil; searchReader.reset() } searchFolder = path; searchOffset = 0; localScope = !path.isEmpty; compactReader = false @@ -215,17 +281,25 @@ struct ArchiveLibraryView: View { } private var browseList: some View { + ScrollViewReader { proxy in List(selection: $browseID) { ForEach(documents) { doc in VStack(alignment: .leading, spacing: 3) { Text(doc.title).lineLimit(2) Text(doc.collection.replacingOccurrences(of: "/", with: " › ")).font(.caption).foregroundStyle(.secondary).lineLimit(1) - }.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id) + }.padding(.vertical, 2).frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(doc.id).id(doc.id) + .background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [doc.id: value.frame(in: .named("archive-browse")).minY]) }) .simultaneousGesture(TapGesture().onEnded { browseID = doc.id; compactReader = true }) } - }.accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list") + }.coordinateSpace(name: "archive-browse") + .onPreferenceChange(ArchiveVisibleRows.self) { rows in if !searching { browseTopID = topRow(rows) } } + .onChange(of: documents.map(\.id)) { _, ids in + if let target = restoreBrowseTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreBrowseTop = nil } + } + .accessibilityLabel("Browse Archive documents").accessibilityIdentifier("archive-browse-list") .onKeyPress(.return, action: readSelectedWithKeyboard) .overlay { if documents.isEmpty, !browseBusy { ContentUnavailableView("No documents in this collection", systemImage: "books.vertical") } } + } } private var groups: [ArchiveResultGroup] { @@ -237,27 +311,64 @@ struct ArchiveLibraryView: View { return ordered } private var resultsList: some View { + ScrollViewReader { proxy in List(selection: $searchID) { ForEach(groups) { group in Section { ForEach(group.hits) { result in HStack { Text(result.locator); if result.ocr { Text("OCR").font(.caption).foregroundStyle(.secondary) } } - .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id) - .simultaneousGesture(TapGesture().onEnded { searchID = result.id; compactReader = true }) + .frame(maxWidth: .infinity, alignment: .leading).contentShape(Rectangle()).tag(result.id).id(result.id) + .background(GeometryReader { value in Color.clear.preference(key: ArchiveVisibleRows.self, value: [result.id: value.frame(in: .named("archive-search")).minY]) }) + .simultaneousGesture(TapGesture().onEnded { restoringSearchSelection = false; restoreSearchTop = nil; searchID = result.id; compactReader = true }) } } header: { Text(group.document.title).lineLimit(3).textCase(nil) } } - }.accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list") + }.coordinateSpace(name: "archive-search") + .onPreferenceChange(ArchiveVisibleRows.self) { rows in if searching { searchTopID = topRow(rows) } } + .onChange(of: hits.map(\.id)) { _, ids in + if let target = restoreSearchTop, ids.contains(target) { proxy.scrollTo(target, anchor: .top); restoreSearchTop = nil } + } + .accessibilityLabel("Matching Archive pages").accessibilityIdentifier("archive-results-list") .onKeyPress(.return, action: readSelectedWithKeyboard) .overlay { if hits.isEmpty, !searchBusy { ContentUnavailableView("No matching pages", systemImage: "magnifyingglass") } } + } + } + private func topRow(_ positions: [String: CGFloat]) -> String? { + positions.filter { $0.value <= 0 }.max(by: { $0.value < $1.value })?.key ?? positions.min(by: { $0.value < $1.value })?.key } @ViewBuilder private var detail: some View { - if let selected { - ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog) + if let navigationError { + ContentUnavailableView("Reference unavailable", systemImage: "book.closed", description: Text(navigationError)) + } else if let selected { + ArchiveReaderPane(record: selected, hit: searching ? hit : nil, reader: reader, requestedPage: requestedPage, catalog: catalog, resumesPosition: searching ? restoringSearchSelection : navigationPage == nil) } else { ContentUnavailableView("Choose a document", systemImage: "book.pages", description: Text("Browse a collection or search the Archive.")) } } + private func openRequested(_ request: ArchiveLibraryOpenRequest) async { + do { + guard let record = try await catalog.document(id: request.documentID), + request.expectedSHA256 == nil || request.expectedSHA256 == record.id, + request.location.map({ $0 > 0 && $0 <= (record.pageCount ?? 1_000_000) }) != false else { + throw ArchiveLibraryError.input("This reference no longer matches the installed Archive index. The software selection has not changed.") + } + guard let offset = try await catalog.browseOffset(documentID: record.id, collection: record.collection, batchSize: batch) else { + throw ArchiveLibraryError.input("The reference could not be located in the installed Archive collection.") + } + try Task.checkCancellation() + guard navigation.request?.id == request.id else { return } + navigationError = nil; archiveQuery.text = ""; collection = record.collection; browseOffset = offset + navigationDocument = record; navigationPage = request.location; browseID = record.id + restoreBrowseTop = record.id; compactReader = true + browseReader.open(record, page: request.location ?? browseReader.savedPage(for: record.id), resumePosition: request.location == nil) + navigation.consumed(request.id) + } catch { + guard !Task.isCancelled, navigation.request?.id == request.id else { return } + navigationError = error.localizedDescription; compactReader = true; navigation.consumed(request.id) + } + } private func moveBatch(_ direction: Int) { + navigationError = nil; navigationDocument = nil; navigationPage = nil; restoringSearchSelection = false + restoreBrowseTop = nil; restoreSearchTop = nil if searching { searchOffset = max(0, searchOffset + direction * batch); searchID = nil } else { browseOffset = max(0, browseOffset + direction * batch); browseID = nil } } @@ -274,6 +385,7 @@ struct ArchiveLibraryView: View { let rows = try await catalog.browse(collection: collection.isEmpty ? nil : collection, limit: batch + 1, offset: browseOffset) try Task.checkCancellation() guard request == ArchiveBrowseRequest(collection: collection, offset: browseOffset, retry: retry) else { return } + if rows.isEmpty, browseOffset > 0 { browseOffset = 0; browseID = nil; browseBusy = false; return } documents = Array(rows.prefix(batch)); browseMore = rows.count > batch if !documents.contains(where: { $0.id == browseID }) { browseID = nil } browseBusy = false diff --git a/platforms/macos/App/CMOCBankedDebug.swift b/platforms/macos/App/CMOCBankedDebug.swift index 9820a7f..5b8272d 100644 --- a/platforms/macos/App/CMOCBankedDebug.swift +++ b/platforms/macos/App/CMOCBankedDebug.swift @@ -5,6 +5,14 @@ import Foundation /// declaration to one retained build; object relocation replay and live physical /// RAM comparisons provide the independent byte checks before debugging. struct CMOCBankedDebugLayout: Sendable { + struct OverlayIdentity: Codable, Equatable, Hashable, Sendable { + let group: String + let owner: String + } + struct OverlayGroup: Codable, Equatable, Sendable { + let id: String + let owners: [String] + } struct File: Decodable, Sendable { let path: String; let sha256: String } struct Page: Decodable, Equatable, Sendable { let logicalPage: Int; let physicalPage: Int } struct CodeGuard: Equatable, Sendable { let address: UInt16; let bytes: [UInt8] } @@ -33,6 +41,7 @@ struct CMOCBankedDebugLayout: Sendable { let bytes: [UInt8] let pages: [Page] let codeGuards: [CodeGuard] + var overlay: OverlayIdentity? = nil func physicalAddress(_ logical: Int) -> UInt32? { guard (0..<65536).contains(logical), let page = pages.first(where: { $0.logicalPage == logical / 8192 }) else { return nil } @@ -44,6 +53,7 @@ struct CMOCBankedDebugLayout: Sendable { } private struct ModuleRecord: Decodable { let id: String; let sections: [String]; let codeSections: [String]; let image: Image?; let pages: [Page] + let overlay: OverlayIdentity? } private struct Manifest: Decodable { let version: Int; let entryPoint: Int @@ -51,6 +61,7 @@ struct CMOCBankedDebugLayout: Sendable { let sources: [String: String]; let artifacts: [String: String] let modules: [ModuleRecord] let framebuffers: [Framebuffer]? + let overlayGroups: [OverlayGroup]? } let entryPoint: UInt16 let binarySHA256: String @@ -59,15 +70,21 @@ struct CMOCBankedDebugLayout: Sendable { let artifactHashes: [String: String] let modules: [Module] var framebuffers: [Framebuffer] = [] + var overlayGroups: [OverlayGroup] = [] func module(forSection name: String) -> Module? { modules.first { $0.sections.contains(name) } } func module(id: String) -> Module? { modules.first { $0.id == id } } + func permitsPhysicalOverlap(between first: String, and second: String) -> Bool { + guard first != second, let a = module(id: first)?.overlay, let b = module(id: second)?.overlay else { return false } + return a.group == b.group && a.owner != b.owner + } static func parse(data: Data, directory: URL, sources: [String: Data], binary: Data, binaryPath: String, diskPath: String? = nil, allowedOutputs: [String]) throws -> Self { func fail(_ text: String) -> CMOCSourceMap.Failure { .invalid("banked manifest: " + text) } guard data.count <= 1024 * 1024 else { throw fail("manifest exceeds 1 MB.") } // Bound recursive decoding before handing untrusted JSON to Decodable. - var pending: [(Any, Int)] = [(try JSONSerialization.jsonObject(with: data), 0)], nodes = 0 + let raw = try JSONSerialization.jsonObject(with: data) + var pending: [(Any, Int)] = [(raw, 0)], nodes = 0 while let (value, depth) = pending.popLast() { nodes += 1 guard depth <= 16, nodes <= 30000 else { throw fail("manifest nesting or record limit exceeded.") } @@ -75,9 +92,31 @@ struct CMOCBankedDebugLayout: Sendable { if let values = value as? [Any] { pending += values.map { ($0, depth + 1) } } } let manifest = try JSONDecoder().decode(Manifest.self, from: data) - guard manifest.version == 1, (0..<65536).contains(manifest.entryPoint), + guard [1, 2].contains(manifest.version), (0..<65536).contains(manifest.entryPoint), !manifest.modules.isEmpty, manifest.modules.count <= 256, manifest.artifacts.count <= 8192, sources.count <= 4096 else { throw fail("unsupported version or record count.") } + let groups = manifest.overlayGroups ?? [] + if manifest.version == 1 { + let object = raw as? [String: Any] + let records = object?["modules"] as? [[String: Any]] ?? [] + guard object?["overlayGroups"] == nil, records.allSatisfy({ $0["overlay"] == nil }) else { + throw fail("overlay declarations require manifest version 2.") + } + } else if manifest.overlayGroups == nil { + throw fail("version 2 requires an explicit overlayGroups array.") + } + guard groups.count <= 64, groups.reduce(0, { $0 + $1.owners.count }) <= 256 else { + throw fail("overlay group or owner count exceeds limits.") + } + func validIdentity(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 128 && !value.contains("\0") } + var declaredOwners: [String: Set] = [:] + for group in groups { + guard validIdentity(group.id), declaredOwners[group.id] == nil, group.owners.count >= 2, + group.owners.allSatisfy(validIdentity), Set(group.owners).count == group.owners.count else { + throw fail("overlay groups require unique bounded identities and at least two distinct owners.") + } + declaredOwners[group.id] = Set(group.owners) + } func path(_ value: String) throws { guard !value.isEmpty, value.utf8.count <= 4096, !value.hasPrefix("/"), !value.contains("\\"), !value.contains("\0"), !value.split(separator: "/", omittingEmptySubsequences: false).contains(where: { $0.isEmpty || $0 == "." || $0 == ".." }), @@ -96,14 +135,23 @@ struct CMOCBankedDebugLayout: Sendable { guard CMOCSourceMap.sha256(data) == digest else { throw fail("conflicting artifact hashes.") }; return data } let url = root.appendingPathComponent(name) - guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact paths must not traverse symbolic links.") } + guard url.resolvingSymlinksInPath().path == url.path else { throw fail("artifact \(name) must not traverse symbolic links.") } let info = try url.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) - guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 8 * 1024 * 1024 else { throw fail("artifact is not a bounded regular file.") } + guard info.isRegularFile == true, info.isSymbolicLink != true, let size = info.fileSize else { + throw fail("artifact \(name) is not a regular file with a known size.") + } + let limit = CMOCSourceMap.evidenceByteLimit(for: name) + guard size <= limit else { throw fail("artifact \(name) is \(size) bytes; its verification limit is \(limit) bytes.") } + guard size <= CMOCSourceMap.maximumVerificationBytes - total else { + throw fail("artifact \(name) would bring retained evidence to \(total + size) bytes; the aggregate limit is \(CMOCSourceMap.maximumVerificationBytes) bytes.") + } let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } - let value = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data() + let value = try handle.read(upToCount: limit + 1) ?? Data() + guard value.count == size, value.count <= limit else { + throw fail("artifact \(name) changed size while reading (observed \(value.count) bytes; expected \(size), limit \(limit)).") + } + guard CMOCSourceMap.sha256(value) == digest else { throw fail("artifact \(name) SHA-256 differs from the retained build manifest.") } total += value.count - guard value.count <= 8 * 1024 * 1024, total <= 128 * 1024 * 1024, - CMOCSourceMap.sha256(value) == digest else { throw fail("artifact changed or exceeds verification limits.") } loaded[name] = value; return value } guard manifest.sources == sources.mapValues(CMOCSourceMap.sha256) else { throw fail("source snapshot differs from the manifest.") } @@ -130,13 +178,27 @@ struct CMOCBankedDebugLayout: Sendable { } for (name, digest) in manifest.artifacts { _ = try read(name, digest: digest) } var modules: [Module] = [], ids = Set(), sections = Set() - var physical: [UInt32: String] = [:] + var physical: [UInt32: Set] = [:] + var overlayByModule: [String: OverlayIdentity] = [:] + func mayShare(_ address: UInt32, module: String, overlay: OverlayIdentity?) -> Bool { + (physical[address] ?? []).allSatisfy { previous in + if previous == module { return true } + guard let overlay, let other = overlayByModule[previous] else { return false } + return overlay.group == other.group && overlay.owner != other.owner + } + } for record in manifest.modules { guard !record.id.isEmpty, record.id.count <= 128, ids.insert(record.id).inserted, !record.sections.isEmpty, record.sections.count <= 256, Set(record.codeSections).count == record.codeSections.count, Set(record.codeSections).isSubset(of: Set(record.sections)), !record.pages.isEmpty, record.pages.count <= 8 else { throw fail("invalid or repeated module identity.") } + if let overlay = record.overlay { + guard declaredOwners[overlay.group]?.contains(overlay.owner) == true else { + throw fail("module \(record.id) names an undeclared overlay group or owner.") + } + overlayByModule[record.id] = overlay + } for section in record.sections { guard !section.isEmpty, section.count <= 256, !section.contains(where: \.isWhitespace), sections.insert(section).inserted else { throw fail("section has ambiguous module ownership.") } } @@ -181,14 +243,14 @@ struct CMOCBankedDebugLayout: Sendable { } let module = Module(id: record.id, sections: record.sections, codeSections: record.codeSections, logicalAddress: logicalAddress, bytes: moduleBytes, pages: record.pages, - codeGuards: guards.sorted { $0.address < $1.address }) + codeGuards: guards.sorted { $0.address < $1.address }, overlay: record.overlay) var imagePhysical = Set() for logical in module.logicalAddress..<(module.logicalAddress + moduleBytes.count) { guard let address = module.physicalAddress(logical), imagePhysical.insert(address).inserted, - physical[address] == nil || physical[address] == module.id else { + mayShare(address, module: module.id, overlay: module.overlay) else { throw fail("module images overlap physical RAM or lack a page identity.") } - physical[address] = module.id + physical[address, default: []].insert(module.id) } // BSS has no image bytes, but its storage must still have one // physical owner. Initialized non-code data follows the same rule. @@ -198,15 +260,23 @@ struct CMOCBankedDebugLayout: Sendable { for placement in matching where placement.length > 0 { for logical in placement.address..<(placement.address + placement.length) { guard let address = module.physicalAddress(logical), - physical[address] == nil || physical[address] == module.id else { + mayShare(address, module: module.id, overlay: module.overlay) else { throw fail("module storage overlaps another module's physical RAM or lacks a page identity.") } - physical[address] = module.id + physical[address, default: []].insert(module.id) } } } modules.append(module) } + for group in groups { + for owner in group.owners { + let members = modules.filter { $0.overlay == OverlayIdentity(group: group.id, owner: owner) } + guard !members.isEmpty, members.contains(where: { !$0.codeGuards.isEmpty }) else { + throw fail("overlay owner \(group.id)/\(owner) needs at least one code-bearing module.") + } + } + } // A compressed transport can enter through its loader, outside every // eventual source module. Bind this entry to the delivered DECB trailer. guard try CMOCSourceMap.decbEntryPoint(binary) == UInt16(manifest.entryPoint) else { throw fail("entry point differs from the delivered executable.") } @@ -235,6 +305,6 @@ struct CMOCBankedDebugLayout: Sendable { } return Self(entryPoint: UInt16(manifest.entryPoint), binarySHA256: manifest.binary.sha256, linkMap: linkMap, sourceHashes: manifest.sources, artifactHashes: manifest.artifacts, - modules: modules, framebuffers: buffers) + modules: modules, framebuffers: buffers, overlayGroups: groups) } } diff --git a/platforms/macos/App/CMOCDevelopmentModel.swift b/platforms/macos/App/CMOCDevelopmentModel.swift index ec33114..4006380 100644 --- a/platforms/macos/App/CMOCDevelopmentModel.swift +++ b/platforms/macos/App/CMOCDevelopmentModel.swift @@ -1510,6 +1510,7 @@ final class CMOCDevelopmentModel: ObservableObject { pausedDebugSnapshot = snapshot; pausedInputEpoch = epoch let sameStop = previousEpoch == epoch && previousSnapshot?.machine.programCounter == address && previousSnapshot?.machine.debuggerMappingFingerprint == snapshot.machine.debuggerMappingFingerprint && + previousSnapshot?.machine.debuggerResidencyFingerprint == snapshot.machine.debuggerResidencyFingerprint && previousSnapshot?.registers["U"] == snapshot.registers["U"] && previousSnapshot?.registers["S"] == snapshot.registers["S"] && previousSnapshot?.logicalMemory == snapshot.logicalMemory && diff --git a/platforms/macos/App/CMOCSourceMap.swift b/platforms/macos/App/CMOCSourceMap.swift index 6f6c311..43d4767 100644 --- a/platforms/macos/App/CMOCSourceMap.swift +++ b/platforms/macos/App/CMOCSourceMap.swift @@ -20,6 +20,10 @@ struct CMOCSourceMap: Sendable { return (items, values.count, items.count != values.count) } + struct EvidenceAddress: Hashable { + let module: String? + let physical: UInt32 + } struct Instruction: Equatable, Sendable { let sourceLine: Int // one-based C source line let address: UInt16 @@ -52,6 +56,19 @@ struct CMOCSourceMap: Sendable { Self.sha256(source) == provenance.sourceSHA256 && Self.sha256(binary) == provenance.binarySHA256 } static func sha256(_ data: Data) -> String { SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined() } + // Generated assembly may contain full compiler type records and data tables; + // it has a larger byte budget than object/listing/map/executable evidence. + // Banked verification retains one aggregate cap across unique files. + static let maximumVerificationBytes = 128 * 1024 * 1024 + static func evidenceByteLimit(for path: String) -> Int { + (path as NSString).pathExtension.lowercased() == "s" ? 32 * 1024 * 1024 : 8 * 1024 * 1024 + } + static func validateEvidenceSize(_ count: Int, path: String) throws { + let limit = evidenceByteLimit(for: path) + guard count <= limit else { + throw Failure.invalid("artifact \(path) is \(count) bytes; its verification limit is \(limit) bytes.") + } + } static func decbEntryPoint(_ data: Data) throws -> UInt16 { try BinaryImage(data).entry } /// The caller must build all artifacts together from an immutable source @@ -61,8 +78,9 @@ struct CMOCSourceMap: Sendable { sourceAliases: [String] = [], objectAliases: [String] = [], strictIdentities: Bool = false, allowEmpty: Bool = false, bankedLayout: CMOCBankedDebugLayout? = nil) throws -> Self { - for data in [source, listing, object, linkMap, binary] { - guard data.count <= 8 * 1024 * 1024 else { throw Failure.invalid("an artifact exceeds 8 MB.") } + for (name, data) in [(sourceName, source), (String(objectName.dropLast(2)) + ".lst", listing), + (objectName, object), ("linker map", linkMap), ("executable", binary)] { + try validateEvidenceSize(data.count, path: name) } guard let sourceText = String(data: source, encoding: .utf8), !sourceText.contains("\0"), !sourceName.isEmpty, !objectName.isEmpty else { throw Failure.invalid("invalid source identity or encoding.") } @@ -75,7 +93,7 @@ struct CMOCSourceMap: Sendable { let linePattern = try NSRegularExpression(pattern: #"^\* Line (.+):([0-9]+)(?::.*)?$"#) let functionPattern = try NSRegularExpression(pattern: #"^\* FUNCTION .+: defined at (.+):([0-9]+)$"#) var sectionName: String?, sourceLine: Int?, instructions: [Instruction] = [] - var seenAddresses = Set() + var seenAddresses = Set() for text in listingLines { let octets = Array(text.utf8) guard octets.count >= 22, octets[21] == 32 else { continue } @@ -121,7 +139,8 @@ struct CMOCSourceMap: Sendable { } let address = UInt16(section.base + offset) let identity = bankedLayout?.module(forSection: sectionName)?.physicalAddress(Int(address)) ?? UInt32(address) - guard seenAddresses.insert(identity).inserted else { throw Failure.invalid("duplicate instruction addresses in the listing.") } + let qualified = EvidenceAddress(module: bankedLayout?.module(forSection: sectionName)?.id, physical: identity) + guard seenAddresses.insert(qualified).inserted else { throw Failure.invalid("duplicate instruction addresses in the listing module.") } instructions.append(Instruction(sourceLine: sourceLine, address: address, bytes: Array(final[offset..<(offset + originalBytes.count)]), assembly: trimmed, moduleID: bankedLayout?.module(forSection: sectionName)?.id, @@ -715,7 +734,7 @@ struct CMOCProjectSourceMap: Sendable { throw CMOCSourceMap.Failure.invalid("source identities must be canonical project-relative paths.") } } - var instructions: [Instruction] = [], addresses = Set(), occupied = Set() + var instructions: [Instruction] = [], addresses = Set(), occupied = Set() var entry: UInt16?, objectHashes: [String: String] = [:], listingHashes: [String: String] = [:] var executableSymbols: [ExecutableSymbol] = [], flatCodeGuards: [CodeGuard] = [] let marker = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#) @@ -763,13 +782,15 @@ struct CMOCProjectSourceMap: Sendable { if let entry, entry != map.entryPoint { throw CMOCSourceMap.Failure.invalid("inconsistent entry points.") } entry = map.entryPoint for item in map.instructions { - guard addresses.insert(item.physicalAddress ?? UInt32(item.address)).inserted else { + let startIdentity = CMOCSourceMap.EvidenceAddress(module: item.moduleID, physical: item.physicalAddress ?? UInt32(item.address)) + guard addresses.insert(startIdentity).inserted else { throw CMOCSourceMap.Failure.invalid("two source locations claim the same instruction address.") } for index in item.bytes.indices { let address = Int(item.address) + index let identity = item.moduleID.flatMap { bankedLayout?.module(id: $0)?.physicalAddress(address) } ?? UInt32(address) - guard address < 65536, occupied.insert(identity).inserted else { + let qualified = CMOCSourceMap.EvidenceAddress(module: item.moduleID, physical: identity) + guard address < 65536, occupied.insert(qualified).inserted else { throw CMOCSourceMap.Failure.invalid("overlapping source instruction ranges.") } } @@ -824,7 +845,7 @@ extension CMOCProjectSourceMap { func projected(physicalPages: [Int: Int]) -> Self { guard let bankedLayout else { return self } let active = Set(bankedLayout.modules.filter { module in - module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } + module.overlay == nil && module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } }.map(\.id)) return projected(activeModuleIDs: active) } @@ -835,13 +856,30 @@ extension CMOCProjectSourceMap { func projected(physicalPages: [Int: Int], memory: Data, available: Data) -> Self { guard let bankedLayout else { return self } guard memory.count == 65536, available.count == 65536 else { return projected(activeModuleIDs: []) } + func mapped(_ module: CMOCBankedDebugLayout.Module) -> Bool { + module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } + } + func codeMatches(_ module: CMOCBankedDebugLayout.Module) -> Bool { + mapped(module) && module.codeGuards.allSatisfy { guardRange in + let start = Int(guardRange.address), end = start + guardRange.bytes.count + return end <= memory.count && available[start..() + for group in bankedLayout.overlayGroups { + let matches = group.owners.filter { owner in + let identity = CMOCBankedDebugLayout.OverlayIdentity(group: group.id, owner: owner) + let code = bankedLayout.modules.filter { $0.overlay == identity && !$0.codeGuards.isEmpty } + return !code.isEmpty && code.allSatisfy(codeMatches) + } + if matches.count == 1 { + selectedOwners.insert(.init(group: group.id, owner: matches[0])) + } + } let active = Set(bankedLayout.modules.filter { module in - module.pages.allSatisfy { physicalPages[$0.logicalPage] == $0.physicalPage } && - module.codeGuards.allSatisfy { guardRange in - let start = Int(guardRange.address), end = start + guardRange.bytes.count - return end <= memory.count && available[start.. URL { + for n in 0..<10_000 { + let target = folder.appendingPathComponent(name + (n == 0 ? "" : "-\(n)")).appendingPathExtension(ext) + if renamex_np(temporary.path, target.path, UInt32(RENAME_EXCL)) == 0 { return target } + if errno != EEXIST { throw NSError(domain: NSPOSIXErrorDomain, code: Int(errno)) } + } + throw CoCoRecordingError.message("A unique capture filename could not be reserved.") + } + static func stamp(_ date: Date = Date()) -> String { + let f = DateFormatter(); f.locale = Locale(identifier: "en_US_POSIX"); f.dateFormat = "yyyy-MM-dd HH-mm-ss" + return f.string(from: date) + } + static func save(_ capture: ScreenCapture, folder: URL) throws -> URL { + try self.folder(folder) + let temp = folder.appendingPathComponent(".vcc-screen-\(UUID().uuidString).png") + defer { try? FileManager.default.removeItem(at: temp) } + try capture.save(to: temp) + return try promote(temp, folder: folder, name: "VCC Plus Screen " + stamp(), extension: "png") + } +} + +@MainActor final class CoCoCapturePreferences: ObservableObject { + enum Destination: String { case desktop, documents, other } + @Published private(set) var folder: URL + @Published private(set) var preparingDestination = false + @Published private(set) var timerSeconds: Int + @Published var includeVideoAudio: Bool { didSet { defaults.set(includeVideoAudio, forKey: "capture.video.includeAudio") } } + var screenshots: URL { folder } + var recordings: URL { folder } + private let defaults: UserDefaults + private let fallbackRoot: URL? + private let makeBookmark: @Sendable (URL) throws -> Data + private var selectionRevision: UInt64 = 0 + private var scopes: [URL] = [] + var desktop: URL { fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0] } + var documents: URL { fallbackRoot?.appendingPathComponent("Documents", isDirectory: true) ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] } + var destination: Destination { + if folder.standardizedFileURL == desktop.standardizedFileURL { return .desktop } + if folder.standardizedFileURL == documents.standardizedFileURL { return .documents } + return .other + } + init(defaults: UserDefaults, fallbackRoot: URL? = nil, + makeBookmark: @escaping @Sendable (URL) throws -> Data = { url in + try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) + }) { + self.defaults = defaults; self.fallbackRoot = fallbackRoot; self.makeBookmark = makeBookmark + let desktop = fallbackRoot ?? FileManager.default.urls(for: .desktopDirectory, in: .userDomainMask)[0] + let documents = fallbackRoot?.appendingPathComponent("Documents", isDirectory: true) + ?? FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0] + let stored = defaults.string(forKey: "capture.destination").flatMap(Destination.init(rawValue:)) + let timer = defaults.integer(forKey: "capture.timer.seconds") + timerSeconds = [0, 5, 10].contains(timer) ? timer : 0 + includeVideoAudio = defaults.object(forKey: "capture.video.includeAudio") as? Bool ?? true + if stored == .desktop || stored == .documents { + // Built-in choices are logical locations, not security bookmarks. + // Neither selection nor restore touches a cloud-backed directory. + folder = stored == .documents ? documents : desktop + } else { + func resolve(_ key: String) -> URL? { + guard let data = defaults.data(forKey: key) else { return nil } + var stale = false + guard let url = try? URL(resolvingBookmarkData: data, options: [.withSecurityScope, .withoutUI], + relativeTo: nil, bookmarkDataIsStale: &stale), url.isFileURL else { return nil } + return url + } + let shared = resolve("capture.folder.shared") + var legacy: (url: URL, bookmark: Data)? + if shared == nil { + for key in ["capture.folder.screenshots", "capture.folder.recordings"] { + if let url = resolve(key), let bookmark = defaults.data(forKey: key) { + legacy = (url, bookmark); break + } + } + } + folder = shared ?? legacy?.url ?? desktop + if let legacy { defaults.set(legacy.bookmark, forKey: "capture.folder.shared") } + if folder.standardizedFileURL == desktop.standardizedFileURL { + if shared != nil || legacy != nil { defaults.set(Destination.desktop.rawValue, forKey: "capture.destination") } + } else if folder.standardizedFileURL == documents.standardizedFileURL { + defaults.set(Destination.documents.rawValue, forKey: "capture.destination") + } else if shared != nil || legacy != nil { + defaults.set(Destination.other.rawValue, forKey: "capture.destination") + if folder.startAccessingSecurityScopedResource() { scopes.append(folder) } + } + } + } + func setTimerSeconds(_ seconds: Int) { + guard [0, 5, 10].contains(seconds) else { return } + timerSeconds = seconds; defaults.set(seconds, forKey: "capture.timer.seconds") + } + private func beginChoice() -> UInt64 { + selectionRevision &+= 1; preparingDestination = false + return selectionRevision + } + func setFolder(_ url: URL) async throws { + try await prepareFolder(url, revision: beginChoice()) + } + private func prepareFolder(_ url: URL, revision: UInt64) async throws { + guard url.isFileURL else { throw CoCoRecordingError.message("Choose a local capture folder.") } + guard revision == selectionRevision else { throw CancellationError() } + // Selecting a built-in through Other Location has the same logical + // semantics and never creates an unnecessary security bookmark. + if url.standardizedFileURL == desktop.standardizedFileURL { setDestination(.desktop); return } + if url.standardizedFileURL == documents.standardizedFileURL { setDestination(.documents); return } + preparingDestination = true + let makeBookmark = makeBookmark + do { + let grant = try await Task.detached(priority: .userInitiated) { + let data = try makeBookmark(url) + return (data, url.startAccessingSecurityScopedResource()) + }.value + guard revision == selectionRevision else { + if grant.1 { Task.detached(priority: .utility) { url.stopAccessingSecurityScopedResource() } } + throw CancellationError() + } + // Keep old grants while an in-flight movie still owns its folder. + if grant.1 { scopes.append(url) } + defaults.set(grant.0, forKey: "capture.folder.shared") + defaults.set(Destination.other.rawValue, forKey: "capture.destination") + folder = url; preparingDestination = false + } catch { + guard revision == selectionRevision else { throw CancellationError() } + preparingDestination = false; throw error + } + } + func setDestination(_ value: Destination) { + if value == .other { choose(); return } + _ = beginChoice() + folder = value == .desktop ? desktop : documents + defaults.set(value.rawValue, forKey: "capture.destination") + } + func choose() { + let revision = beginChoice() + let panel = NSOpenPanel(); panel.title = "Save Screenshots and Videos To" + panel.canChooseDirectories = true; panel.canChooseFiles = false; panel.canCreateDirectories = true + panel.directoryURL = folder + panel.begin { [weak self] response in + guard let self, revision == self.selectionRevision, response == .OK, let url = panel.url else { return } + Task { + do { try await self.prepareFolder(url, revision: revision) } + catch is CancellationError { } + catch { NSAlert(error: error).runModal() } + } + } + } +} + +struct CoCoRecordingRecovery: Codable, Identifiable { + let id: UUID + let created: Date + let directory: URL + var working: URL { directory.appendingPathComponent("Working.mov") } +} +private struct CoCoRecoveryDocument: Codable { + var version = 1 + var recordings: [CoCoRecordingRecovery] +} + +/// Owns recording transport independently of AppKit's modal/main run loop. +/// UI progress is observational: it never clocks or drains the movie pipeline. +private actor CoCoRecordingSession { + struct Completion: Sendable { let movie: URL?; let error: String? } + private let controller: VCCMachineController + private let encoder: CoCoVideoEncoder + private let includeAudio: Bool + private let folder: URL + private let failed: @Sendable (String) -> Void + private let replies = DispatchQueue(label: "com.brianholman.vccplus.capture-replies", qos: .userInitiated) + private var pump: Task? + private var finalization: Task? + private var capacityCheck: Task? + private var failureMessage: String? + private var started = false + + init(controller: VCCMachineController, encoder: CoCoVideoEncoder, includeAudio: Bool, folder: URL, + failed: @escaping @Sendable (String) -> Void) { + self.controller = controller; self.encoder = encoder; self.includeAudio = includeAudio + self.folder = folder; self.failed = failed + } + func start() async throws -> TimeInterval { + let snapshot = await withCheckedContinuation { continuation in + controller.beginVideoCapture(replyQueue: replies) { continuation.resume(returning: $0) } + } + if let message = snapshot.errorMessage { throw CoCoRecordingError.message(message) } + started = true + let origin = ProcessInfo.processInfo.systemUptime + encoder.failure = { [weak self] message in Task { await self?.fail(message) } } + pump = Task { [weak self] in guard let self else { return }; await self.run() } + return origin + } + private func packets(finish: Bool) async -> ([CoCoVideoFrame], String?) { + let includeAudio = includeAudio + return await withCheckedContinuation { continuation in + controller.takeVideoCapture(finish: finish, replyQueue: replies) { packets, error in + continuation.resume(returning: (packets.map { + CoCoCaptureCoordinator.videoFrame(pixels: $0.pixels, area: $0.activeArea, + audio: $0.samples, sampleOffset: Int64($0.sampleOffset), includeAudio: includeAudio) + }, error)) + } + } + } + private func run() async { + var nextCapacityCheck: TimeInterval = 0 + while !Task.isCancelled { + let result = await packets(finish: false) + // Cancellation cannot discard bytes already drained by this pull. + encoder.append(result.0) + if let message = result.1 { fail(message); return } + guard !Task.isCancelled else { return } + let now = ProcessInfo.processInfo.systemUptime + if now >= nextCapacityCheck { + nextCapacityCheck = now + 5; checkCapacity() + } + do { try await Task.sleep(for: .milliseconds(16)) } catch { return } + } + } + private func checkCapacity() { + guard capacityCheck == nil, finalization == nil else { return } + let folder = folder + capacityCheck = Task { [weak self] in + let free = await Task.detached(priority: .utility) { + try? folder.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage + }.value + await self?.acceptCapacity(free) + } + } + private func acceptCapacity(_ free: Int64?) { + capacityCheck = nil + guard finalization == nil, let free, free < 256 * 1024 * 1024 else { return } + fail("Recording stopped because the destination is low on space. The working movie is retained.") + } + private func fail(_ message: String) { + guard failureMessage == nil else { return } + failureMessage = message + _ = beginFinalization() + failed(message) + } + private func beginFinalization() -> Task { + if let finalization { return finalization } + let draining = pump; pump = nil; draining?.cancel() + let final = Task { [self] in + // One owner waits for the in-flight pull, takes the final tail and + // finishes the writer. User Stop and failures share this result. + await draining?.value + if started { + let tail = await packets(finish: true) + encoder.append(tail.0) + if failureMessage == nil { failureMessage = tail.1 } + } + let result: Result = await withCheckedContinuation { continuation in + encoder.finish { continuation.resume(returning: $0) } + } + switch result { + case .success(let url): return Completion(movie: url, error: failureMessage) + case .failure(let error): return Completion(movie: nil, error: failureMessage ?? error.localizedDescription) + } + } + finalization = final + return final + } + func finish(failure: String? = nil) async -> Completion { + if let failure { fail(failure) } + return await beginFinalization().value + } + func currentFailure() -> String? { failureMessage } +} + +@MainActor final class CoCoCaptureCoordinator: ObservableObject { + enum State: Equatable { case idle, starting, recording, finishing } + @Published private(set) var state: State = .idle + @Published private(set) var countdown: Int? + @Published private(set) var elapsed: TimeInterval = 0 + @Published private(set) var saving = false + @Published var error: String? + @Published private(set) var saved: URL? + @Published private(set) var recoveries: [CoCoRecordingRecovery] = [] + @Published var settingsShown = false + let preferences: CoCoCapturePreferences + private weak var machine: MachineModel? + private let controller: VCCMachineController + private var countdownTask: Task? + private var recordingTask: Task? + private var pendingImage: ScreenCapture? + private var session: CoCoRecordingSession? + private var recovery: CoCoRecordingRecovery? + private var start = ProcessInfo.processInfo.systemUptime + private var recoveryURL: URL + private var canWriteRecovery = true + private let feedback: (CoCoCaptureFeedback.Cue) -> Void + var active: Bool { state != .idle } + var recording: Bool { state == .recording } + lazy var menuState = CoCoCaptureMenuState(self) + + init(machine: MachineModel, controller: VCCMachineController, defaults: UserDefaults, directory: URL, + feedback: ((CoCoCaptureFeedback.Cue) -> Void)? = nil) { + self.machine = machine; self.controller = controller + self.feedback = feedback ?? CoCoCaptureFeedback.play + #if VCC_UI_TESTING + let root = ProcessInfo.processInfo.environment["VCC_CAPTURE_TEST_DIRECTORY"].map { URL(fileURLWithPath: $0, isDirectory: true) } ?? directory.appendingPathComponent("Captures") + preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + #else + preferences = CoCoCapturePreferences(defaults: defaults) + #endif + recoveryURL = directory.appendingPathComponent("CaptureRecovery.json") + if let data = try? Data(contentsOf: recoveryURL) { + do { + guard data.count <= 1_048_576 else { throw CoCoRecordingError.message("The recording recovery record is too large.") } + let document = try JSONDecoder().decode(CoCoRecoveryDocument.self, from: data) + guard document.version == 1 else { throw CoCoRecordingError.message("A newer recording recovery version has been preserved.") } + let records = document.recordings + guard records.allSatisfy({ $0.directory.isFileURL && $0.directory.lastPathComponent == ".vcc-recording-" + $0.id.uuidString }) else { + throw CoCoRecordingError.message("The recording recovery record is invalid.") + } + recoveries = records + } catch { self.error = "Recording recovery data was preserved but could not be read: \(error.localizedDescription)"; canWriteRecovery = false } + } + } + + /// The camera is the action; selecting menu options only changes preferences. + func capture() { + if preferences.timerSeconds == 0 { captureNow() } else { delay(preferences.timerSeconds) } + } + func captureNow() { + guard !saving, pendingImage == nil, countdown == nil, let machine else { return } + do { + pendingImage = try ScreenCapture(pixels: machine.pixels, area: machine.activeVideoRect) + feedback(.screenshot) + savePending() + } + catch { self.error = error.localizedDescription } + } + private func savePending() { + guard let image = pendingImage else { return } + saving = true; error = nil + let folder = preferences.screenshots + Task { + defer { saving = false } + do { + saved = try await Task.detached(priority: .userInitiated) { try CoCoCaptureFiles.save(image, folder: folder) }.value + pendingImage = nil + } catch { self.error = error.localizedDescription } + } + } + func saveImageAs() { + guard let image = pendingImage, !saving else { return } + let panel = NSSavePanel(); panel.title = "Save Captured CoCo Screen"; panel.allowedContentTypes = [.png] + panel.nameFieldStringValue = "VCC Plus Screen " + CoCoCaptureFiles.stamp() + ".png" + panel.begin { [weak self] result in + guard let self, result == .OK, let url = panel.url else { return } + self.saving = true + Task { [self] in + defer { self.saving = false } + do { + try await Task.detached { try image.save(to: url) }.value + self.pendingImage = nil; self.saved = url; self.error = nil + } catch { self.error = error.localizedDescription } + } + } + } + func discardImage() { guard !saving else { return }; pendingImage = nil; error = nil } + var hasPendingImage: Bool { pendingImage != nil } + func delay(_ seconds: Int) { + guard [5, 10].contains(seconds), !saving, pendingImage == nil else { return } + cancelCountdown(); countdown = seconds + countdownTask = Task { [weak self] in + for remaining in stride(from: seconds, through: 1, by: -1) { + guard let self, !Task.isCancelled else { return }; countdown = remaining + do { try await Task.sleep(for: .seconds(1)) } catch { return } + } + guard let self, !Task.isCancelled else { return }; countdown = nil; captureNow() + } + } + func cancelCountdown() { countdownTask?.cancel(); countdownTask = nil; countdown = nil } + + func startRecording() { + guard state == .idle, let machine, machine.pixels != nil else { return } + if machine.settings.fastForward { + error = "Turn off fast-forward before recording video. No machine setting has been changed."; return + } + guard canWriteRecovery else { error = "Resolve the preserved recording recovery record before starting another movie."; return } + state = .starting; error = nil + let includeAudio = preferences.includeVideoAudio + let folder = preferences.recordings + Task { [self] in + do { + let entry = CoCoRecordingRecovery(id: UUID(), created: Date(), directory: folder.appendingPathComponent(".vcc-recording-" + UUID().uuidString)) + // Directory identity is tied to its recovery ID; never clean a user folder. + let record = CoCoRecordingRecovery(id: entry.id, created: entry.created, + directory: folder.appendingPathComponent(".vcc-recording-" + entry.id.uuidString, isDirectory: true)) + let newEncoder = try await Task.detached { try CoCoCaptureFiles.folder(record.directory); return try CoCoVideoEncoder(workingURL: record.working) }.value + let backend = CoCoRecordingSession(controller: controller, encoder: newEncoder, + includeAudio: includeAudio, folder: folder) { [weak self] message in + Task { @MainActor in + guard let self, self.recovery?.id == record.id else { return } + self.error = message + await self.stopRecording(failed: true) + } + } + session = backend + recovery = record; recoveries.append(record); try await persistRecovery() + let origin = try await backend.start() + state = .recording; start = origin; elapsed = ProcessInfo.processInfo.systemUptime - origin + let startupFailure = await backend.currentFailure() + // A failure notification can finish this session while the + // status query suspends us. Never publish a stale success cue + // or resurrect its progress task after that finalization. + guard recovery?.id == record.id, state == .recording else { return } + if let startupFailure { + error = startupFailure; await stopRecording(failed: true); return + } + feedback(.recordingStarted) + recordingTask = Task { [weak self] in + while !Task.isCancelled { + guard let self, state == .recording else { return } + elapsed = ProcessInfo.processInfo.systemUptime - start + do { try await Task.sleep(for: .milliseconds(250)) } catch { return } + } + } + } catch { + self.error = error.localizedDescription + // Even a failed bridge start may own a writer. Recovery and + // quit must wait until that writer has finished its last work. + state = .finishing + if let session { _ = await session.finish(failure: self.error) } + session = nil; recovery = nil; state = .idle + } + } + } + /// Keep the recording clock and packet duration unchanged for silent video. + /// Only emulated PCM is selected here; host shutter/start cues never enter it. + nonisolated static func videoFrame(pixels: Data, area: CGRect, audio: Data, sampleOffset: Int64, includeAudio: Bool) -> CoCoVideoFrame { + CoCoVideoFrame(pixels: pixels, area: area, audio: includeAudio ? audio : Data(count: audio.count), sampleOffset: sampleOffset) + } + func stopRecording(failed: Bool = false) async { + guard state == .recording, let session, let record = recovery else { return } + state = .finishing + recordingTask?.cancel(); recordingTask = nil + let result = await session.finish(failure: failed ? (error ?? "Recording stopped with an error. The working movie is retained.") : nil) + if let message = result.error { error = message } + do { + if !failed, result.error == nil, let movie = result.movie { + try await complete(record, movie: movie, folder: record.directory.deletingLastPathComponent()) + } + } catch { self.error = error.localizedDescription } + self.session = nil; recovery = nil; state = .idle + } + func recover(_ record: CoCoRecordingRecovery) { + guard state == .idle else { return }; state = .finishing; error = nil + Task { + defer { state = .idle } + do { try await complete(record, movie: record.working, folder: preferences.recordings) } + catch { self.error = "Recovery did not complete. Retained files are unchanged. \(error.localizedDescription)" } + } + } + private func complete(_ record: CoCoRecordingRecovery, movie: URL, folder: URL) async throws { + let final = try await Task.detached(priority: .userInitiated) { + try CoCoCaptureFiles.folder(folder) + let temp = folder.appendingPathComponent(".vcc-finish-" + UUID().uuidString + ".mp4") + do { + try await CoCoVideoEncoder.exportMP4(from: movie, to: temp) + return try CoCoCaptureFiles.promote(temp, folder: folder, name: "VCC Plus Video " + CoCoCaptureFiles.stamp(record.created), extension: "mp4") + } catch { try? FileManager.default.removeItem(at: temp); throw error } + }.value + saved = final + recoveries.removeAll { $0.id == record.id }; try await persistRecovery() + // Only this verified owned working file/directory is removed. + try? FileManager.default.removeItem(at: record.working) + _ = rmdir(record.directory.path) // Never remove unexpected files added to it. + } + private func persistRecovery() async throws { + guard canWriteRecovery else { throw CoCoRecordingError.message("Recovery data is read-only until repaired.") } + let records = recoveries, url = recoveryURL + try await Task.detached(priority: .utility) { + try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) + try JSONEncoder().encode(CoCoRecoveryDocument(recordings: records)).write(to: url, options: .atomic) + }.value + } + func stopBeforeReplacingMachine() async -> Bool { + cancelCountdown() + guard active else { return true } + guard state == .recording else { error = "Wait for the recording to finish."; return false } + let alert = NSAlert(); alert.messageText = "Stop and save the CoCo movie first?" + alert.informativeText = "Changing the machine ends this recording. Existing media safeguards still apply." + alert.addButton(withTitle: "Cancel"); alert.addButton(withTitle: "Stop and Continue") + guard alert.runModal() == .alertSecondButtonReturn else { return false } + let id = recovery?.id + await stopRecording(); return state == .idle && !recoveries.contains { $0.id == id } + } +} + +/// Native menus observe transitions, not per-frame/elapsed-time notifications. +@MainActor final class CoCoCaptureMenuState: ObservableObject { + @Published private(set) var state: CoCoCaptureCoordinator.State + @Published private(set) var countdown = false + private var tokens: Set = [] + init(_ capture: CoCoCaptureCoordinator) { + state = capture.state + capture.$state.removeDuplicates().sink { [weak self] in self?.state = $0 }.store(in: &tokens) + capture.$countdown.map { $0 != nil }.removeDuplicates().sink { [weak self] in self?.countdown = $0 }.store(in: &tokens) + } +} + +struct CoCoCaptureControls: View { + @ObservedObject var capture: CoCoCaptureCoordinator + @ObservedObject var machine: MachineModel + @ObservedObject private var preferences: CoCoCapturePreferences + init(capture: CoCoCaptureCoordinator, machine: MachineModel) { + self.capture = capture; self.machine = machine; preferences = capture.preferences + } + @Environment(\.accessibilityReduceMotion) private var reduceMotion + var body: some View { + HStack(spacing: 4) { + Button { capture.capture() } label: { Image(systemName: "camera").frame(width: 28, height: 28) } + .help(preferences.timerSeconds == 0 ? "Capture CoCo Screen" : "Capture CoCo Screen after \(preferences.timerSeconds) seconds").accessibilityLabel("Capture CoCo Screen") + .accessibilityIdentifier("capture-now") + .disabled(machine.pixels == nil || capture.countdown != nil || capture.saving || capture.hasPendingImage) + Menu { + CoCoCaptureOptions(preferences: preferences) + if capture.countdown != nil { Button("Cancel Capture", action: capture.cancelCountdown) } + Divider(); Button("Capture Settings…") { capture.settingsShown = true } + } label: { Image(systemName: "chevron.down").frame(width: 14, height: 28) } + .menuStyle(.borderlessButton).menuIndicator(.hidden).fixedSize().help("Screenshot and video options") + .accessibilityLabel("Screenshot and video options").accessibilityIdentifier("capture-options") + Button { + if capture.recording { Task { await capture.stopRecording() } } else { capture.startRecording() } + } label: { + Image(systemName: capture.recording ? "stop.circle.fill" : "video") + .foregroundStyle(capture.recording ? Color.red : Color.primary) + .symbolEffect(.pulse, options: .repeating, isActive: capture.recording && !reduceMotion) + .frame(width: 28, height: 28) + }.help(capture.recording ? "Stop Recording" : (preferences.includeVideoAudio ? "Record CoCo Video with CoCo audio, even when local playback is muted" : "Record CoCo Video without audio")) + .accessibilityLabel(capture.recording ? "Stop Recording" : "Record CoCo Video") + .accessibilityIdentifier("capture-record") + .disabled((!capture.recording && machine.pixels == nil) || capture.state == .starting || capture.state == .finishing) + if let seconds = capture.countdown { + Button("\(seconds)s · Cancel", action: capture.cancelCountdown).font(.caption).help("Cancel Capture") + .accessibilityIdentifier("capture-countdown-cancel") + } else if capture.active { + Text(capture.state == .finishing ? "Finishing…" : String(format: "%02d:%02d", Int(capture.elapsed)/60, Int(capture.elapsed)%60)) + .font(.caption.monospacedDigit()).frame(minWidth: 42) + } + if capture.error != nil || !capture.recoveries.isEmpty && !capture.active { + Button { capture.settingsShown = true } label: { Image(systemName: "exclamationmark.circle").foregroundStyle(.orange) } + .help(capture.error ?? "Retained recording available — open Capture Settings") + .accessibilityLabel("Capture status and recovery") + } else if let saved = capture.saved { + Button { NSWorkspace.shared.activateFileViewerSelecting([saved]) } label: { Image(systemName: "checkmark.circle") } + .help("Saved \(saved.lastPathComponent) — Show in Finder").accessibilityLabel("Show saved capture in Finder") + } + }.buttonStyle(.borderless) + .sheet(isPresented: $capture.settingsShown) { CoCoCaptureSettings(capture: capture, preferences: capture.preferences) } + } +} + +/// One shared options view keeps the header menu and settings sheet consistent. +struct CoCoCaptureOptions: View { + @ObservedObject var preferences: CoCoCapturePreferences + var body: some View { + Section("Save Screenshots and Videos To") { + Toggle("Desktop", isOn: Binding(get: { preferences.destination == .desktop }, set: { _ in preferences.setDestination(.desktop) })) + .accessibilityIdentifier("capture-destination-desktop") + Toggle("Documents", isOn: Binding(get: { preferences.destination == .documents }, set: { _ in preferences.setDestination(.documents) })) + .accessibilityIdentifier("capture-destination-documents") + Button(action: preferences.choose) { + if preferences.destination == .other { Label("Other Location…", systemImage: "checkmark") } + else { Text("Other Location…") } + }.accessibilityIdentifier("capture-destination-other") + if preferences.destination == .other { Text(preferences.folder.lastPathComponent).font(.caption) } + } + Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) { + Text("None").tag(0) + Text("5 Seconds").tag(5) + Text("10 Seconds").tag(10) + }.pickerStyle(.inline).accessibilityIdentifier("capture-timer") + Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio) + .accessibilityIdentifier("capture-video-audio") + } +} + +struct CoCoCaptureSettings: View { + @ObservedObject var capture: CoCoCaptureCoordinator + @ObservedObject var preferences: CoCoCapturePreferences + @Environment(\.dismiss) private var dismiss + var body: some View { + VStack(alignment: .leading, spacing: 16) { + Text("CoCo Capture").font(.title2.bold()) + Text("Captures include only the CoCo picture. System artwork, Mac windows and the desktop are excluded. Include CoCo Audio in Video controls the movie’s sound, even when local playback is muted. Shutter and recording-start cues are never recorded.") + VStack(alignment: .leading, spacing: 8) { + Text("Save Screenshots and Videos To").font(.headline) + Picker("Save to", selection: Binding(get: { preferences.destination }, set: preferences.setDestination)) { + Text("Desktop").tag(CoCoCapturePreferences.Destination.desktop) + Text("Documents").tag(CoCoCapturePreferences.Destination.documents) + Text("Other Location…").tag(CoCoCapturePreferences.Destination.other) + }.accessibilityIdentifier("capture-settings-destination") + Text(preferences.folder.path).font(.caption).textSelection(.enabled).lineLimit(2) + if preferences.preparingDestination { + Label("Preparing capture folder…", systemImage: "hourglass").font(.caption) + .accessibilityIdentifier("capture-settings-preparing-folder") + } + HStack { Button("Other Location…", action: preferences.choose); Button("Show in Finder") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: preferences.folder.path) } } + Picker("Screenshot Timer", selection: Binding(get: { preferences.timerSeconds }, set: preferences.setTimerSeconds)) { + Text("None").tag(0); Text("5 Seconds").tag(5); Text("10 Seconds").tag(10) + }.accessibilityIdentifier("capture-settings-timer") + Toggle("Include CoCo Audio in Video", isOn: $preferences.includeVideoAudio) + .accessibilityIdentifier("capture-settings-video-audio") + Text("The camera button uses the selected timer. Video recording starts immediately. Audio choices apply to the next recording.") + .font(.caption).fixedSize(horizontal: false, vertical: true) + } + if !capture.recoveries.isEmpty { + Divider(); Text("Retained Recordings").font(.headline) + ForEach(capture.recoveries) { record in + HStack { Text(record.created.formatted()); Button("Recover MP4") { capture.recover(record) }.disabled(capture.active) + Button("Show Files") { NSWorkspace.shared.selectFile(nil, inFileViewerRootedAtPath: record.directory.path) } } + } + Text("Interrupted movies may contain only completed fragments. Working files remain until a verified MP4 is saved.").font(.caption) + } + if let error = capture.error { Text(error).foregroundStyle(.red).textSelection(.enabled) } + if capture.hasPendingImage { + HStack { Button("Save Captured Image As…", action: capture.saveImageAs); Button("Discard Captured Image", action: capture.discardImage) }.disabled(capture.saving) + } + HStack { Spacer(); Button("Done") { dismiss() }.keyboardShortcut(.defaultAction) } + }.padding(24).frame(width: 520) + } +} diff --git a/platforms/macos/App/CoCoCaptureFeedback.swift b/platforms/macos/App/CoCoCaptureFeedback.swift new file mode 100644 index 0000000..7d7b36c --- /dev/null +++ b/platforms/macos/App/CoCoCaptureFeedback.swift @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit + +/// Host feedback has no connection to the emulator's generated PCM or either +/// video/playtest capture path. No microphone or system-output recording is used. +@MainActor enum CoCoCaptureFeedback { + enum Cue: Equatable { case screenshot, recordingStarted } + + private static let shutter = sound("screenshot") + private static let recording = sound("recording-start") + + private static func sound(_ name: String) -> NSSound? { + guard let url = Bundle.main.url(forResource: name, withExtension: "wav", subdirectory: "CaptureSounds") else { return nil } + return NSSound(contentsOf: url, byReference: false) + } + + static func play(_ cue: Cue) { + let sound = cue == .screenshot ? shutter : recording + sound?.stop() + sound?.play() + } +} diff --git a/platforms/macos/App/CoCoVideoEncoder.swift b/platforms/macos/App/CoCoVideoEncoder.swift new file mode 100644 index 0000000..eb6682b --- /dev/null +++ b/platforms/macos/App/CoCoVideoEncoder.swift @@ -0,0 +1,300 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import AVFoundation +import CoreGraphics +import CoreVideo +import AudioToolbox + +/// Only emulator pixels and generated stereo PCM enter this boundary. There is +/// deliberately no host-window, microphone, or screen-recording API here. +struct CoCoVideoFrame: Sendable { + var pixels: Data + var area: CGRect + var audio: Data // packed, interleaved Float32 stereo, 44,100 sample frames/sec + var sampleOffset: Int64 +} + +enum CoCoRecordingError: LocalizedError { + case message(String) + var errorDescription: String? { if case let .message(s) = self { return s }; return nil } +} + +/// Serial, bounded writer. Working MOV fragments remain available after a +/// failure; only a verified MP4 completion permits their owner to clean up. +final class CoCoVideoEncoder: @unchecked Sendable { + static let width = 1280, height = 960 + static let rate: Int32 = 44_100 + let workingURL: URL + private let queue = DispatchQueue(label: "com.brianholman.vccplus.video-encoder", qos: .userInitiated) + private let writer: AVAssetWriter + private let video: AVAssetWriterInput + private let audio: AVAssetWriterInput + private let adaptor: AVAssetWriterInputPixelBufferAdaptor + private var audioFormat: CMAudioFormatDescription? + private var images: [(Data, CGRect, Int64)] = [] + private var sounds: [(Data, Int64)] = [] + private var queuedSamples = 0 + private var lastVideoTick: Int64 = -1 + private var previousPicture: (Data, CGRect)? + private var lastAudioEnd: Int64 = 0 + private var finalSample: Int64 = 0 + private var finishing = false, draining = false, failed = false + private var finishReplies: [(Result) -> Void] = [] + private var finishResult: Result? + private var closingWriter = false + private var failureError: Error? + private let ingressLock = NSLock() + private var accepting = true + private var retainedFrames = 0, retainedSamples = 0 + var failure: (@Sendable (String) -> Void)? + /// Read-only AVFoundation lifecycle evidence; a finish reply promises this + /// terminal state, including when a failed movie is retained for recovery. + var writerIsTerminal: Bool { [.completed, .failed, .cancelled].contains(writer.status) } + + init(workingURL: URL) throws { + self.workingURL = workingURL + writer = try AVAssetWriter(outputURL: workingURL, fileType: .mov) + writer.movieFragmentInterval = CMTime(seconds: 10, preferredTimescale: 600) + writer.initialMovieFragmentInterval = CMTime(seconds: 1, preferredTimescale: 600) + video = AVAssetWriterInput(mediaType: .video, outputSettings: [ + AVVideoCodecKey: AVVideoCodecType.h264, AVVideoWidthKey: Self.width, + AVVideoHeightKey: Self.height, AVVideoCompressionPropertiesKey: [ + AVVideoAverageBitRateKey: 4_000_000, AVVideoExpectedSourceFrameRateKey: 60, + AVVideoMaxKeyFrameIntervalKey: 60, AVVideoAllowFrameReorderingKey: false]]) + audio = AVAssetWriterInput(mediaType: .audio, outputSettings: [ + AVFormatIDKey: kAudioFormatMPEG4AAC, AVSampleRateKey: 48_000, + AVNumberOfChannelsKey: 2, AVEncoderBitRateKey: 160_000]) + video.expectsMediaDataInRealTime = true; audio.expectsMediaDataInRealTime = true + adaptor = AVAssetWriterInputPixelBufferAdaptor(assetWriterInput: video, + sourcePixelBufferAttributes: [kCVPixelBufferPixelFormatTypeKey as String: kCVPixelFormatType_32BGRA, + kCVPixelBufferWidthKey as String: Self.width, kCVPixelBufferHeightKey as String: Self.height, + kCVPixelBufferCGImageCompatibilityKey as String: true, + kCVPixelBufferCGBitmapContextCompatibilityKey as String: true]) + guard writer.canAdd(video), writer.canAdd(audio) else { throw CoCoRecordingError.message("The native video/audio encoder is unavailable.") } + writer.add(video); writer.add(audio) + var format = AudioStreamBasicDescription(mSampleRate: Double(Self.rate), mFormatID: kAudioFormatLinearPCM, + mFormatFlags: kAudioFormatFlagIsFloat | kAudioFormatFlagIsPacked, + mBytesPerPacket: 8, mFramesPerPacket: 1, mBytesPerFrame: 8, mChannelsPerFrame: 2, + mBitsPerChannel: 32, mReserved: 0) + guard CMAudioFormatDescriptionCreate(allocator: kCFAllocatorDefault, asbd: &format, + layoutSize: 0, layout: nil, magicCookieSize: 0, magicCookie: nil, + extensions: nil, formatDescriptionOut: &audioFormat) == noErr, + writer.startWriting() else { throw writer.error ?? CoCoRecordingError.message("The recording could not start.") } + writer.startSession(atSourceTime: .zero) + } + + func append(_ frames: [CoCoVideoFrame]) { + let samples = frames.reduce(0) { $0 + $1.audio.count / 8 } + ingressLock.lock() + guard accepting else { ingressLock.unlock(); return } + guard retainedFrames + frames.count <= 12, retainedSamples + samples <= Int(Self.rate) * 2 else { + accepting = false; ingressLock.unlock() + queue.async { [self] in fail(CoCoRecordingError.message("The recorder reached its bounded input limit. The working movie has been retained.")) } + return + } + retainedFrames += frames.count; retainedSamples += samples + ingressLock.unlock() + queue.async { [self] in + guard !failed, !finishing else { return } + do { + for frame in frames { + guard frame.pixels.count == 640 * 480 * 4, frame.audio.count % 8 == 0, + frame.sampleOffset >= lastAudioEnd else { + throw CoCoRecordingError.message("The recording input lost its frame/audio ordering.") + } + let gap = frame.sampleOffset - lastAudioEnd + guard gap <= Int64(Self.rate) * 2 else { throw CoCoRecordingError.message("The recording input was interrupted. The working movie has been retained.") } + if gap > 0 { + ingressLock.lock() + let allowed = retainedSamples + Int(gap) <= Int(Self.rate) * 2 + if allowed { retainedSamples += Int(gap) } + ingressLock.unlock() + guard allowed else { throw CoCoRecordingError.message("The recorder reached its bounded audio limit.") } + sounds.append((Data(count: Int(gap) * 8), lastAudioEnd)); queuedSamples += Int(gap) + } + if !frame.audio.isEmpty { sounds.append((frame.audio, frame.sampleOffset)); queuedSamples += frame.audio.count / 8 } + lastAudioEnd = frame.sampleOffset + Int64(frame.audio.count / 8) + finalSample = max(finalSample, lastAudioEnd) + let tick = frame.sampleOffset * 60 / Int64(Self.rate) + if tick > lastVideoTick { + let duplicates = Int(tick - lastVideoTick - 1) + if duplicates > 0 { + ingressLock.lock() + let allowed = retainedFrames + duplicates <= 12 + if allowed { retainedFrames += duplicates } + ingressLock.unlock() + guard allowed else { throw CoCoRecordingError.message("The recording frame clock was interrupted. The working movie is retained.") } + let held = previousPicture ?? (frame.pixels, frame.area) + for t in (lastVideoTick + 1)..) -> Void) { + ingressLock.lock(); accepting = false; ingressLock.unlock() + queue.async { [self] in + if let finishResult { completion(finishResult); return } + finishReplies.append(completion) + guard !finishing, !failed else { return } + finishing = true; drain() + } + } + + /// A disposable producer advances faster than wall time. Its own worker may + /// await this acknowledgement rather than overflowing the unchanged bounded + /// ingress queue. The application recorder continues using nonblocking append. + func whenDrained(_ completion: @escaping @Sendable (Result) -> Void) { + let deadline = ProcessInfo.processInfo.systemUptime + 10 + func check() { + queue.async { [self] in + if failed { completion(.failure(writer.error ?? CoCoRecordingError.message("The video writer stopped."))); return } + ingressLock.lock() + let empty = retainedFrames == 0 && retainedSamples == 0 + ingressLock.unlock() + if empty { completion(.success(())) } + else if ProcessInfo.processInfo.systemUptime >= deadline { + let error = CoCoRecordingError.message("The video writer did not drain within its deadline.") + fail(error); completion(.failure(error)) + } else { queue.asyncAfter(deadline: .now() + .milliseconds(5), execute: check) } + } + } + check() + } + + private func drain() { + guard !failed else { return } + do { + while !images.isEmpty && video.isReadyForMoreMediaData { + let image = images.removeFirst() + let pixel = try Self.pixelBuffer(image.0, area: image.1, pool: adaptor.pixelBufferPool) + guard adaptor.append(pixel, withPresentationTime: CMTime(value: image.2, timescale: 60)) else { + throw writer.error ?? CoCoRecordingError.message("A video frame could not be written.") + } + release(frames: 1, samples: 0) + } + while !sounds.isEmpty && audio.isReadyForMoreMediaData { + let sound = sounds.removeFirst(); queuedSamples -= sound.0.count / 8 + let sample = try audioSample(sound.0, offset: sound.1) + guard audio.append(sample) else { throw writer.error ?? CoCoRecordingError.message("CoCo sound could not be written.") } + release(frames: 0, samples: sound.0.count / 8) + } + if writer.status == .failed { throw writer.error ?? CoCoRecordingError.message("The movie writer stopped.") } + if images.isEmpty && sounds.isEmpty { + if finishing, !closingWriter { + closingWriter = true + writer.endSession(atSourceTime: CMTime(value: max(finalSample, 735), timescale: Self.rate)) + video.markAsFinished(); audio.markAsFinished() + writer.finishWriting { [self] in + queue.async { [self] in + if let failureError { finishAll(.failure(failureError)) } + else if writer.status == .completed { finishAll(.success(workingURL)) } + else { finishAll(.failure(writer.error ?? CoCoRecordingError.message("The working movie could not be finalized."))) } + } + } + } + } else if !draining { + draining = true + queue.asyncAfter(deadline: .now() + .milliseconds(5)) { [self] in draining = false; drain() } + } + } catch { fail(error) } + } + + private func fail(_ error: Error) { + guard !failed else { return }; failed = true + failureError = error + ingressLock.lock(); accepting = false; retainedFrames = 0; retainedSamples = 0; ingressLock.unlock() + images.removeAll(); sounds.removeAll(); queuedSamples = 0 + // Finishing what the framework can retain is preferable to cancelling + // and deleting fragments. Every Stop waits for that closure, including + // Stop arriving after the failure callback or during another Stop. + if closingWriter { + // The existing AVFoundation callback owns the terminal result. + } else if writer.status == .writing { + closingWriter = true + video.markAsFinished(); audio.markAsFinished() + writer.finishWriting { [self] in queue.async { [self] in finishAll(.failure(error)) } } + } else { finishAll(.failure(error)) } + failure?(error.localizedDescription) + } + private func finishAll(_ result: Result) { + guard finishResult == nil else { return } + finishResult = result + let replies = finishReplies; finishReplies.removeAll() + for reply in replies { reply(result) } + } + private func release(frames: Int, samples: Int) { + ingressLock.lock(); retainedFrames -= frames; retainedSamples -= samples; ingressLock.unlock() + } + + private func audioSample(_ data: Data, offset: Int64) throws -> CMSampleBuffer { + var block: CMBlockBuffer? + guard CMBlockBufferCreateWithMemoryBlock(allocator: kCFAllocatorDefault, memoryBlock: nil, + blockLength: data.count, blockAllocator: kCFAllocatorDefault, customBlockSource: nil, + offsetToData: 0, dataLength: data.count, flags: 0, blockBufferOut: &block) == kCMBlockBufferNoErr, + let block else { throw CoCoRecordingError.message("Audio buffer allocation failed.") } + let copied = data.withUnsafeBytes { CMBlockBufferReplaceDataBytes(with: $0.baseAddress!, blockBuffer: block, offsetIntoDestination: 0, dataLength: data.count) } + var time = CMSampleTimingInfo(duration: CMTime(value: 1, timescale: Self.rate), + presentationTimeStamp: CMTime(value: offset, timescale: Self.rate), decodeTimeStamp: .invalid) + var sample: CMSampleBuffer? + guard copied == noErr, CMSampleBufferCreateReady(allocator: kCFAllocatorDefault, + dataBuffer: block, formatDescription: audioFormat, sampleCount: data.count / 8, + sampleTimingEntryCount: 1, sampleTimingArray: &time, sampleSizeEntryCount: 0, + sampleSizeArray: nil, sampleBufferOut: &sample) == noErr, let sample else { + throw CoCoRecordingError.message("The CoCo audio sample could not be prepared.") + } + return sample + } + + static func pixelBuffer(_ bytes: Data, area: CGRect, pool: CVPixelBufferPool?) throws -> CVPixelBuffer { + guard bytes.count == 640 * 480 * 4 else { throw CoCoRecordingError.message("No complete CoCo picture is available.") } + guard [area.minX, area.minY, area.width, area.height].allSatisfy(\.isFinite) else { + throw CoCoRecordingError.message("The recording picture dimensions are invalid.") + } + let bounds = CGRect(x: 0, y: 0, width: 640, height: 480) + let rect = area.intersection(bounds).integral + guard !rect.isEmpty, !rect.isNull, let pool else { throw CoCoRecordingError.message("The recording picture dimensions are invalid.") } + var buffer: CVPixelBuffer? + guard CVPixelBufferPoolCreatePixelBuffer(nil, pool, &buffer) == kCVReturnSuccess, let buffer else { throw CoCoRecordingError.message("A video pixel buffer could not be allocated.") } + CVPixelBufferLockBaseAddress(buffer, []); defer { CVPixelBufferUnlockBaseAddress(buffer, []) } + let color = CGColorSpace(name: CGColorSpace.sRGB)! + guard let source = CGDataProvider(data: bytes as CFData), + let image = CGImage(width: 640, height: 480, bitsPerComponent: 8, bitsPerPixel: 32, + bytesPerRow: 640 * 4, space: color, + bitmapInfo: CGBitmapInfo(rawValue: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue), + provider: source, decode: nil, shouldInterpolate: false, intent: .defaultIntent)?.cropping(to: rect), + let context = CGContext(data: CVPixelBufferGetBaseAddress(buffer), width: width, height: height, + bitsPerComponent: 8, bytesPerRow: CVPixelBufferGetBytesPerRow(buffer), space: color, + bitmapInfo: CGImageAlphaInfo.noneSkipFirst.rawValue | CGBitmapInfo.byteOrder32Little.rawValue) else { + throw CoCoRecordingError.message("The CoCo picture could not be rendered for video.") + } + context.setFillColor(CGColor(gray: 0, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + let scale = min(CGFloat(width) / rect.width, CGFloat(height) / rect.height) + let size = CGSize(width: rect.width * scale, height: rect.height * scale) + context.interpolationQuality = .none + context.draw(image, in: CGRect(x: (CGFloat(width)-size.width)/2, y: (CGFloat(height)-size.height)/2, width: size.width, height: size.height)) + return buffer + } + + static func exportMP4(from source: URL, to destination: URL) async throws { + guard !FileManager.default.fileExists(atPath: destination.path), + let export = AVAssetExportSession(asset: AVURLAsset(url: source), presetName: AVAssetExportPresetPassthrough), + export.supportedFileTypes.contains(.mp4) else { throw CoCoRecordingError.message("The retained movie cannot be converted to this MP4 destination.") } + export.outputURL = destination; export.outputFileType = .mp4 + await export.export() + guard export.status == .completed else { throw export.error ?? CoCoRecordingError.message("MP4 completion failed; the working movie has been retained.") } + let asset = AVURLAsset(url: destination) + guard try await !asset.loadTracks(withMediaType: .video).isEmpty, + try await !asset.loadTracks(withMediaType: .audio).isEmpty, + try await asset.load(.duration).seconds > 0 else { throw CoCoRecordingError.message("The completed movie did not contain playable video and audio.") } + } +} diff --git a/platforms/macos/App/CompanionLibraryAuthority.swift b/platforms/macos/App/CompanionLibraryAuthority.swift index 25f826a..32d5b36 100644 --- a/platforms/macos/App/CompanionLibraryAuthority.swift +++ b/platforms/macos/App/CompanionLibraryAuthority.swift @@ -18,8 +18,19 @@ final class CompanionLibraryAuthority { try Task.checkCancellation() try await Task.sleep(nanoseconds: 50_000_000) } - guard let catalog = model.catalog else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") } - let disks = catalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1) + guard model.catalog != nil || !model.personalEntries.isEmpty else { throw failure(model.error ?? "VCC Plus's Software Library is unavailable.") } + let available = model.combinedCatalog.companionDisks(includingOwnedTitles: request.ownedTitlesVersion == 1, + includingPersonalTitles: request.personalTitlesVersion == 1) + let privateDisks = Set(model.personalEntries.filter { entry in + entry.files.contains { $0.kind == "disk" && Self.diskMember($0.path) } + }.map(\.releaseID)) + // The emulator accepts additional disk containers that this real-CoCo + // handoff cannot offer. Keep those entries in VCC Plus's own library. + let disks = SoftwareLibraryCatalog(titles: available.titles.compactMap { title in + let releases = title.releases.filter { !$0.isPersonal || privateDisks.contains($0.id) } + return releases.isEmpty ? nil : .init(id: title.id, name: title.name, + identityStatus: title.identityStatus, releases: releases) + }, metadata: available.metadata) func release() throws -> SoftwareLibraryRelease { guard let id = request.releaseID, let value = disks.releases.first(where: { $0.id == id }) else { throw failure("Choose a disk edition from VCC Plus's catalog.") @@ -45,6 +56,7 @@ final class CompanionLibraryAuthority { return .init(snapshot: snapshot(disks)) case .install: let selected = try release() + if selected.isPersonal { return try await installStatus(selected, catalog: disks) } guard model.installingReleaseID == nil || model.installingReleaseID == selected.id else { throw failure("VCC Plus is already installing another title. Let it finish or cancel it there.") } @@ -59,6 +71,7 @@ final class CompanionLibraryAuthority { return .init(snapshot: snapshot(disks), isInstalling: model.installingReleaseID == selected.id) case .removeInstallation: let selected = try release() + guard !selected.isPersonal else { throw failure("Manage or remove this private entry in VCC Plus's Personal Library. DriveWire disk copies are separate from its retained files.") } await model.removeInstallation(selected.id) if let message = model.installationErrors[selected.id] { throw failure(message) } return .init(snapshot: snapshot(disks)) @@ -89,6 +102,13 @@ final class CompanionLibraryAuthority { return .init(assetData: data) } guard asset.isManual else { throw failure("Choose a manual or instructions asset.") } + if asset.matchStatus == "personal", let local = asset.manualURL, local.isFileURL { + try await Task.detached(priority: .userInitiated) { + try SoftwareLibraryLocalAsset.validate(asset, url: local, + maximumBytes: local.pathExtension.lowercased() == "txt" ? 1024 * 1024 : 512 * 1024 * 1024) + }.value + return .init(assetFileURL: local) + } let local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, directory: model.state.directory.appendingPathComponent("Manuals", isDirectory: true)) return .init(assetFileURL: local) @@ -98,12 +118,29 @@ final class CompanionLibraryAuthority { private func failure(_ message: String) -> CompanionLibraryFailure { .init(message: message) } private func snapshot(_ catalog: SoftwareLibraryCatalog) -> CompanionLibrarySnapshot { let titleIDs = Set(catalog.titles.map(\.id)), releaseIDs = Set(catalog.releases.map(\.id)) + let personal = model.personalEntries.filter { releaseIDs.contains($0.releaseID) }.map { + $0.receipt(in: model.personalDirectory($0)) + }.map { SoftwareLibraryState.Installation(releaseID: $0.releaseID, packageSHA256: $0.packageSHA256, + installedAt: $0.installedAt, workingDirectory: $0.workingDirectory) } return .init(catalog: catalog, favorites: model.state.favoriteTitleIDs.intersection(titleIDs), preferredReleaseIDs: model.state.preferredReleaseIDs.filter { titleIDs.contains($0.key) && releaseIDs.contains($0.value) }, - installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) }) + installations: model.state.installedReleases.values.filter { releaseIDs.contains($0.releaseID) && !$0.releaseID.hasPrefix("personal:") } + personal) } private func installedReceipt(_ release: SoftwareLibraryRelease) async throws -> SoftwareLibraryInstallationReceipt { + if release.isPersonal { + // Reload the store to reject entries hidden since the catalog snapshot. + let entries = try await model.personalStore.entries() + guard let entry = entries.first(where: { + $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 + }) else { throw failure("This private disk entry is no longer available. Open Personal Library in VCC Plus.") } + let directory = model.personalDirectory(entry) + for location in [directory.deletingLastPathComponent(), directory, directory.appendingPathComponent("Working")] { + let values = try location.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard values.isDirectory == true, values.isSymbolicLink != true else { throw failure("The private disk location is not a safe directory. Its retained files were preserved.") } + } + return entry.receipt(in: directory) + } let receipts = try await model.installer.recoverInstallations() guard let receipt = receipts.first(where: { $0.releaseID == release.id && $0.packageSHA256 == release.packageSHA256 }) else { throw failure("Install this disk edition in VCC Plus first.") @@ -111,6 +148,10 @@ final class CompanionLibraryAuthority { return receipt } private func installStatus(_ release: SoftwareLibraryRelease, catalog: SoftwareLibraryCatalog) async throws -> CompanionLibraryResponse { + if release.isPersonal { + let receipt = try await installedReceipt(release) + return .init(snapshot: snapshot(catalog), receipt: receipt, isInstalling: false) + } if let message = model.installationErrors[release.id] { throw failure(message) } let active = model.installingReleaseID == release.id return .init(snapshot: snapshot(catalog), progress: active ? model.installProgress : nil, @@ -127,16 +168,19 @@ final class CompanionLibraryAuthority { nonisolated private static func exportDisk(receipt: SoftwareLibraryInstallationReceipt, member: String, destination: URL) throws -> URL { guard diskMember(member), receipt.relativeFiles.contains(member) else { throw CompanionLibraryFailure(message: "Invalid disk member.") } let root = receipt.workingDirectory.standardizedFileURL - var source = root - for component in member.split(separator: "/") { - source.appendPathComponent(String(component)) - let values = try source.resourceValues(forKeys: [.isSymbolicLinkKey]) - guard values.isSymbolicLink != true else { throw CompanionLibraryFailure(message: "The disk path contains a symbolic link.") } + guard root.isFileURL else { throw CompanionLibraryFailure(message: "Invalid installation location.") } + // Resolve members relative to opened directories so a swapped symlink + // cannot redirect an intermediate path outside the working tree. + var directory = open(root.path, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard directory >= 0 else { throw CompanionLibraryFailure(message: "The disk working directory could not be read safely.") } + defer { close(directory) } + let components = member.split(separator: "/").map(String.init) + for component in components.dropLast() { + let next = openat(directory, component, O_RDONLY | O_DIRECTORY | O_NOFOLLOW | O_CLOEXEC) + guard next >= 0 else { throw CompanionLibraryFailure(message: "The disk path contains an unavailable directory or symbolic link.") } + close(directory); directory = next } - guard source.resolvingSymlinksInPath().path.hasPrefix(root.resolvingSymlinksInPath().path + "/") else { - throw CompanionLibraryFailure(message: "The disk path leaves its installation.") - } - let descriptor = open(source.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + let descriptor = openat(directory, components.last!, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) guard descriptor >= 0 else { throw CompanionLibraryFailure(message: "The installed disk could not be read.") } let handle = FileHandle(fileDescriptor: descriptor, closeOnDealloc: true) defer { try? handle.close() } @@ -146,12 +190,21 @@ final class CompanionLibraryAuthority { throw CompanionLibraryFailure(message: "Choose a floppy image within the 16 MiB limit.") } let data = try handle.read(upToCount: 16 * 1024 * 1024 + 1) ?? Data() - guard data.count == Int(info.st_size) else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") } + var after = stat() + guard data.count == Int(info.st_size), fstat(descriptor, &after) == 0, + info.st_size == after.st_size, info.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, + info.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, + info.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec, + info.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw CompanionLibraryFailure(message: "The installed disk changed while being read.") } try FileManager.default.createDirectory(at: destination, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) + let destinationValues = try destination.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard destinationValues.isDirectory == true, destinationValues.isSymbolicLink != true else { + throw CompanionLibraryFailure(message: "The DriveWire disk-copy location is not a safe directory.") + } let folder = destination.appendingPathComponent(UUID().uuidString, isDirectory: true) try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) do { - let copy = folder.appendingPathComponent(source.lastPathComponent) + let copy = folder.appendingPathComponent(components.last!) try data.write(to: copy, options: .atomic) return copy } catch { try? FileManager.default.removeItem(at: folder); throw error } diff --git a/platforms/macos/App/CompanionLibraryTypes.swift b/platforms/macos/App/CompanionLibraryTypes.swift index 5daf3ac..2b23959 100644 --- a/platforms/macos/App/CompanionLibraryTypes.swift +++ b/platforms/macos/App/CompanionLibraryTypes.swift @@ -21,6 +21,8 @@ struct CompanionLibraryRequest: Codable, Sendable { var enabled: Bool? = nil // Missing in old clients: do not send project titles to an Archive-only UI. var ownedTitlesVersion: Int? = 1 + // Older clients cannot identify private entries safely. Missing decodes as nil. + var personalTitlesVersion: Int? = 1 } struct CompanionLibraryResponse: Codable, Sendable { @@ -83,12 +85,13 @@ extension SoftwareLibraryCatalog { /// Filter both releases and their containing title: alternate cartridge/tape /// editions never leak through the edition picker in a disk-only client. var companionDisksOnly: Self { - companionDisks(includingOwnedTitles: true) + companionDisks(includingOwnedTitles: true, includingPersonalTitles: true) } - func companionDisks(includingOwnedTitles: Bool) -> Self { + func companionDisks(includingOwnedTitles: Bool, includingPersonalTitles: Bool = false) -> Self { Self(titles: titles.compactMap { title in let releases = title.releases.filter { - $0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null) + (includingPersonalTitles || (!title.id.hasPrefix("personal:") && !$0.isPersonal)) && + $0.mediaType == "disk" && (includingOwnedTitles || $0.metadata["owned_game"] == .null) } return releases.isEmpty ? nil : SoftwareLibraryTitle(id: title.id, name: title.name, identityStatus: title.identityStatus, releases: releases) diff --git a/platforms/macos/App/DiskControlsView.swift b/platforms/macos/App/DiskControlsView.swift index b3cc89d..24d79bb 100644 --- a/platforms/macos/App/DiskControlsView.swift +++ b/platforms/macos/App/DiskControlsView.swift @@ -62,7 +62,7 @@ struct DiskControlsView: View { SecondaryCard { VStack(alignment: .leading, spacing: 10) { Label("Choose a disk ROM to enable the FD-502 controller", systemImage: "info.circle") - SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM).disabled(machine.diskBusy) + SecondaryAction(title: "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM) } } } else if !machine.diskConnected { @@ -86,7 +86,6 @@ struct DiskControlsView: View { } Spacer() SecondaryAction(title: machine.diskEnabled ? "Change Disk ROM…" : "Choose Disk ROM…", systemImage: "folder", action: machine.openDiskROM) - .disabled(machine.diskBusy) } if machine.diskEnabled { HStack { @@ -99,7 +98,7 @@ struct DiskControlsView: View { } }.font(.caption).foregroundStyle(.secondary) SecondaryAction(title: "Disable Controller…", systemImage: "minus.circle", action: machine.disableDisks) - .disabled(machine.dirtyDisks || machine.diskBusy) + .disabled(machine.dirtyDisks) .accessibilityLabel("Disable floppy controller") Text("Disabling ejects all four disks and cold-restarts the CoCo. Save or discard pending changes first.") .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) @@ -194,7 +193,10 @@ private struct DiskDriveRow: View { .sheet(item: $copySource) { source in VCCDriveWireTransferView(machine: machine, drive: index, sourceName: source.name, sourceEpoch: source.epoch) } - .disabled(machine.diskBusy) + // Guest sector transfers change busy many times per second. Keep browsing, + // menus and controls stable; commands recheck controller idleness on its + // serialized worker before changing media. Host-save/editor locks above + // and each disk's unsaved/protection guards still disable unsafe actions. } private var newDiskMenu: some View { Menu { diff --git a/platforms/macos/App/InputHub.swift b/platforms/macos/App/InputHub.swift index 7e2d37b..95178b8 100644 --- a/platforms/macos/App/InputHub.swift +++ b/platforms/macos/App/InputHub.swift @@ -18,9 +18,22 @@ struct InputDiagnosticObservation { @MainActor final class InputHub: ObservableObject { @Published var settings: InputSettings { didSet { - guard settings != oldValue else { return } - release(); epoch &+= 1 - do { try store.save(settings); error = nil } catch { self.error = "Could not save input settings: \(error.localizedDescription)" } + guard !normalizingSettings else { return } + let previousPolicy = automaticRightController + if !applyingAutomaticSettings, settings.right != oldValue.right { automaticRightController = false } + // Normalize this one user edit before releasing/routing/persisting it. + // @Published can reenter this observer during normalization; only the + // outer edit releases input, advances the epoch and persists settings. + let assigned = settings.assigningSoleController(devices.map(\.id), automaticRight: automaticRightController) + if settings != assigned { + normalizingSettings = true + settings = assigned + normalizingSettings = false + } + if settings.right.source == .controller, !settings.right.device.isEmpty { automaticRightController = false } + guard settings != oldValue || previousPolicy != automaticRightController else { return } + if settings != oldValue { release(); epoch &+= 1 } + saveSettings() } } @Published private(set) var devices: [ControllerReading] = [] @Published private(set) var preview = [JoystickSample(), JoystickSample()] @@ -29,7 +42,11 @@ final class InputHub: ObservableObject { var acceptsInput: () -> Bool = { false } private let store: InputSettingsStore private let controller: VCCMachineController - private let hardware: ControllerDevices + private let hardware: ControllerDevices? + private let controllerReadings: (() -> [ControllerReading])? + private var automaticRightController = false + private var applyingAutomaticSettings = false + private var normalizingSettings = false private var timer: Timer? private var routing = InputRouting() private var last: [JoystickSample] = [] @@ -40,20 +57,49 @@ final class InputHub: ObservableObject { private var lastDisplayAcceptsInput: Bool? private var submitted: [JoystickSample]? private var submittedInterfaces: [JoystickInterface]? - init(controller: VCCMachineController, store: InputSettingsStore = .standard) { - self.controller = controller; self.store = store; hardware = ControllerDevices() - do { settings = try store.load() } catch { + init(controller: VCCMachineController, store: InputSettingsStore = .standard, + controllerReadings: (() -> [ControllerReading])? = nil, automaticallyPoll: Bool = true) { + self.controller = controller; self.store = store + self.controllerReadings = controllerReadings + hardware = controllerReadings == nil ? ControllerDevices() : nil + do { + let saved = try store.loadState() + settings = saved.settings; automaticRightController = saved.automaticRightController + } catch { settings = InputSettings(); self.error = "Could not read input settings: \(error.localizedDescription)" } - timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in - MainActor.assumeIsolated { self?.poll() } - } + if automaticallyPoll { + timer = Timer.scheduledTimer(withTimeInterval: 1 / 60, repeats: true) { [weak self] _ in + MainActor.assumeIsolated { self?.poll() } + } #if VCC_UI_TESTING // Keep the authored preview moving even during native menu tracking. if let timer { RunLoop.main.add(timer, forMode: .common) } #endif + } } deinit { timer?.invalidate() } + private func saveSettings() { + do { try store.save(settings, automaticRightController: automaticRightController); error = nil } + catch { self.error = "Could not save input settings: \(error.localizedDescription)" } + } + /// Built-in reset is explicit; personal profile inputs never inherit the + /// fresh-install controller-discovery policy from this Mac's settings store. + func applyProfileSettings(_ value: InputSettings) { applySettings(value, automaticRight: false) } + /// Library hints can fill unused ports without turning an unchanged fresh + /// Right fallback into an explicit user choice. + func applyLibrarySettings(_ value: InputSettings) { + applySettings(value, automaticRight: automaticRightController && value.right == settings.right) + } + func restoreDefaultSettings() { applySettings(.freshDefaults, automaticRight: true) } + private func applySettings(_ value: InputSettings, automaticRight: Bool) { + let previous = settings, previousPolicy = automaticRightController + automaticRightController = automaticRight + applyingAutomaticSettings = true + settings = value + applyingAutomaticSettings = false + if settings == previous, automaticRightController != previousPolicy { saveSettings() } + } func swap() { var next = settings; next.right = settings.left; next.left = settings.right; settings = next } func key(_ code: UInt16, down: Bool) -> Bool { routing.key(code, down: down, settings: settings) @@ -73,17 +119,27 @@ final class InputHub: ObservableObject { lastPollUptime = nil; lastApplicationActive = nil; lastDisplayAcceptsInput = nil submit([JoystickSample(), JoystickSample()]) } - private func poll() { + func poll() { + let readings: [ControllerReading] + if let controllerReadings { readings = controllerReadings() } + else { #if VCC_UI_TESTING // Exercise the real preview/selection views with changing input even // when no physical controller is attached to the test Mac. let phase = ProcessInfo.processInfo.systemUptime - let readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller", + readings = [ControllerReading(id: "ui-fixture", name: "Authored test controller", x: sin(phase), y: cos(phase), rx: sin(phase * 2), ry: cos(phase * 2))] #else - let readings = hardware.read() + readings = hardware?.read() ?? [] #endif + } if devices != readings { devices = readings } + let assigned = settings.assigningSoleController(readings.map(\.id), automaticRight: automaticRightController) + if assigned != settings { + applyingAutomaticSettings = true + settings = assigned + applyingAutomaticSettings = false + } let displayAcceptsInput = acceptsInput(), applicationActive = NSApp.isActive let active = displayAcceptsInput && applicationActive lastPollUptime = ProcessInfo.processInfo.systemUptime diff --git a/platforms/macos/App/InputSettings.swift b/platforms/macos/App/InputSettings.swift index 1c3ad9a..24ee259 100644 --- a/platforms/macos/App/InputSettings.swift +++ b/platforms/macos/App/InputSettings.swift @@ -35,6 +35,24 @@ struct InputSettings: Codable, Equatable { get { port == 0 ? right : left } set { if port == 0 { right = newValue } else { left = newValue } } } + /// An unassigned Controller source can adopt an unambiguous connection. + /// A remembered device remains authoritative even while disconnected. + static var freshDefaults: Self { + var value = Self(); value.right.source = .mouse + return value + } + func assigningSoleController(_ deviceIDs: [String], automaticRight: Bool = false) -> Self { + guard deviceIDs.count == 1, let device = deviceIDs.first, + !device.isEmpty, device.count < 1024 else { return self } + var result = self + if automaticRight, result.right.source == .mouse, result.right.device.isEmpty { + result.right.source = .controller + } + for port in 0..<2 where result[port].source == .controller && result[port].device.isEmpty { + result[port].device = device + } + return result + } func validated() throws -> Self { for p in [right, left] { guard p.deadZone.isFinite, (0...0.5).contains(p.deadZone), @@ -46,16 +64,48 @@ struct InputSettings: Codable, Equatable { } } struct InputSettingsStore { + struct State { + let settings: InputSettings + let automaticRightController: Bool + } + /// Keep the existing flat settings document/profile contract. This optional + /// store-only marker distinguishes a fresh fallback from a person's choice. + private struct Record: Codable { + let settings: InputSettings + let automaticRightController: Bool + private enum Keys: String, CodingKey { case automaticRightController } + init(settings: InputSettings, automaticRightController: Bool) { + self.settings = settings; self.automaticRightController = automaticRightController + } + init(from decoder: Decoder) throws { + settings = try InputSettings(from: decoder) + automaticRightController = try decoder.container(keyedBy: Keys.self) + .decodeIfPresent(Bool.self, forKey: .automaticRightController) ?? false + } + func encode(to encoder: Encoder) throws { + try settings.encode(to: encoder) + if automaticRightController { + var fields = encoder.container(keyedBy: Keys.self) + try fields.encode(true, forKey: .automaticRightController) + } + } + } let url: URL static let standard = InputSettingsStore(url: AppIdentity.supportDirectory.appendingPathComponent("InputSettings.json")) func load() throws -> InputSettings { - guard FileManager.default.fileExists(atPath: url.path) else { return InputSettings() } - return try JSONDecoder().decode(InputSettings.self, from: Data(contentsOf: url)).validated() + try loadState().settings } - func save(_ value: InputSettings) throws { + func loadState() throws -> State { + guard FileManager.default.fileExists(atPath: url.path) else { + return State(settings: .freshDefaults, automaticRightController: true) + } + let record = try JSONDecoder().decode(Record.self, from: Data(contentsOf: url)) + return State(settings: try record.settings.validated(), automaticRightController: record.automaticRightController) + } + func save(_ value: InputSettings, automaticRightController: Bool = false) throws { _ = try value.validated() try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true) - try JSONEncoder().encode(value).write(to: url, options: .atomic) + try JSONEncoder().encode(Record(settings: value, automaticRightController: automaticRightController)).write(to: url, options: .atomic) } } struct JoystickSample: Equatable { diff --git a/platforms/macos/App/InterfaceValidation.swift b/platforms/macos/App/InterfaceValidation.swift index 2e157a5..851cd59 100644 --- a/platforms/macos/App/InterfaceValidation.swift +++ b/platforms/macos/App/InterfaceValidation.swift @@ -18,9 +18,40 @@ final class InterfaceValidation { private let controller = VCCMachineController() private var measurement: Task? private let suite: String + private let retainsRelaunchFixture: Bool init() throws { + #if VCC_UI_TESTING + if let path = ProcessInfo.processInfo.environment["VCC_CONTINUITY_TEST_ROOT"] { + let candidate = URL(fileURLWithPath: path).standardizedFileURL + let temporary = FileManager.default.temporaryDirectory.standardizedFileURL.resolvingSymlinksInPath() + // XCTest's runner is sandboxed and owns a different temporary root + // from the tested app. Permit precisely that runner's tmp directory, + // never its Documents directory or an arbitrary supplied parent. + let userHome = URL(fileURLWithPath: NSHomeDirectoryForUser(NSUserName()) ?? NSHomeDirectory()) + let runnerTemporary = userHome.appendingPathComponent("Library/Containers/com.brianholman.vccplus.mac.uitests.xctrunner/Data/tmp") + .standardizedFileURL.resolvingSymlinksInPath() + let prefix = "VCCContinuityRelaunch-" + let token = String(candidate.lastPathComponent.dropFirst(prefix.count)) + let values = try candidate.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard candidate.lastPathComponent.hasPrefix(prefix), UUID(uuidString: token) != nil, + [temporary.path, runnerTemporary.path].contains(candidate.deletingLastPathComponent().resolvingSymlinksInPath().path), + values.isDirectory == true, values.isSymbolicLink != true, + try String(contentsOf: candidate.appendingPathComponent("fixture-owner"), encoding: .utf8) == token else { + throw CocoaError(.fileReadNoPermission) + } + directory = candidate + suite = prefix + token + retainsRelaunchFixture = true + } else { + directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString) + suite = "VCCInterfaceUI-" + UUID().uuidString + retainsRelaunchFixture = false + } + #else directory = FileManager.default.temporaryDirectory.appendingPathComponent("vcc-interface-ui-" + UUID().uuidString) suite = "VCCInterfaceUI-" + UUID().uuidString + retainsRelaunchFixture = false + #endif defaults = UserDefaults(suiteName: suite)! // Ordinary interaction tests represent a returning user; the dedicated // first-use test exercises a fresh guide history through real commands. @@ -51,7 +82,12 @@ final class InterfaceValidation { try Data(repeating: 0,count:161280).write(to:kit.appendingPathComponent(name)) } if let resource = Bundle.main.url(forResource: "Blank OS9 Header", withExtension: "bin") { - try FileManager.default.copyItem(at: resource, to: kit.appendingPathComponent("Blank OS9 Header.bin")) + let destination = kit.appendingPathComponent("Blank OS9 Header.bin") + if retainsRelaunchFixture && FileManager.default.fileExists(atPath: destination.path) { + guard try Data(contentsOf: destination) == Data(contentsOf: resource) else { throw CocoaError(.fileReadCorruptFile) } + } else { + try FileManager.default.copyItem(at: resource, to: destination) + } } try Data([0x55,0x55,0x3c]).write(to:kit.appendingPathComponent("Hello World.cas")) } @@ -398,6 +434,9 @@ final class InterfaceValidation { } func cleanUp() { measurement?.cancel() + // Only the UI runner that owns the explicit one-test fixture removes it. + // A second app process must be able to read the first process's state. + guard !retainsRelaunchFixture else { return } defaults.removePersistentDomain(forName: suite) try? FileManager.default.removeItem(at: directory) } diff --git a/platforms/macos/App/LibraryContinuity.swift b/platforms/macos/App/LibraryContinuity.swift new file mode 100644 index 0000000..7644218 --- /dev/null +++ b/platforms/macos/App/LibraryContinuity.swift @@ -0,0 +1,205 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Combine +import Foundation + +/// Browsing/reading choices are personal state, not part of either shipped catalog. +struct LibraryBrowseState: Codable, Equatable, Sendable { + var scope = "" + var query = "" + var filters: [String: String] = [:] + var selectedID: String? + var selectedEditionID: String? + var topVisibleID: String? + var offset: Double = 0 + var pageOffset = 0 +} + +struct LibraryReadingPosition: Codable, Equatable, Sendable { + var documentID: String + var relativePath: String? = nil + var page = 1 + var anchor: String? = nil + var offset: Double = 0 + var horizontalOffset: Double = 0 + var zoom: Double? = nil + var autoScales: Bool? = nil + var readingOrder: Int? = nil +} + +struct ManualBookmark: Codable, Equatable, Identifiable, Sendable { + let id: UUID + let bookID: String + var bookTitle: String + var sectionTitle: String + var position: LibraryReadingPosition + var label: String? + let createdAt: Date + var updatedAt: Date + var locationChanged: Bool? = nil + var displayName: String { label.flatMap { $0.isEmpty ? nil : $0 } ?? sectionTitle } + var locationKey: String { bookID + "/" + (position.relativePath ?? "") + "#" + (position.anchor ?? "offset-\(Int(position.offset * 10_000))") } +} + +@MainActor +final class LibraryContinuityStore: ObservableObject { + private(set) static var shared: LibraryContinuityStore = { + #if VCC_UI_TESTING + return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityUITest-" + UUID().uuidString)) + #else + if CommandLine.arguments.contains("--interface-validation") || CommandLine.arguments.contains("--validate-startup") { + return LibraryContinuityStore(directory: FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityValidation-" + UUID().uuidString)) + } + return LibraryContinuityStore(directory: AppIdentity.supportDirectory) + #endif + }() + /// Called by the app delegate after selecting its normal or isolated support root. + static func configureShared(directory: URL) { + guard shared.fileURL.deletingLastPathComponent() != directory else { return } + shared = LibraryContinuityStore(directory: directory) + } + private struct Document: Codable, Sendable { + var version = 1 + var browse: [String: LibraryBrowseState] = [:] + var reading: [String: LibraryReadingPosition] = [:] + var bookmarks: [ManualBookmark] = [] + } + @Published private(set) var bookmarks: [ManualBookmark] = [] + @Published private(set) var saveError: String? + private var document = Document() + private var maySave = true + private var revision = 0 + private var pendingSave: Task? + private let queue = DispatchQueue(label: "com.brianholman.vccplus.library-continuity", qos: .utility) + let fileURL: URL + + init(directory: URL) { + fileURL = directory.appendingPathComponent("LibraryContinuity.json") + guard FileManager.default.fileExists(atPath: fileURL.path) else { return } + do { + let handle = try FileHandle(forReadingFrom: fileURL) + defer { try? handle.close() } + let bytes = try handle.read(upToCount: 8 * 1024 * 1024 + 1) ?? Data() + guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid } + let decoded = try JSONDecoder().decode(Document.self, from: bytes) + guard decoded.version == 1, decoded.browse.count <= 256, + decoded.reading.count <= 20_000, decoded.bookmarks.count <= 5_000, + decoded.browse.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }), + decoded.reading.allSatisfy({ Self.validID($0.key) && Self.valid($0.value) }), + decoded.bookmarks.allSatisfy({ Self.valid($0.position) && Self.validID($0.bookID) }), + Set(decoded.bookmarks.map(\.id)).count == decoded.bookmarks.count else { throw Failure.invalid } + document = decoded + bookmarks = decoded.bookmarks + } catch { + maySave = false + saveError = "Saved library positions and bookmarks could not be read. The original file has been preserved at \(fileURL.path). \(error.localizedDescription)" + } + } + + func browse(for key: String) -> LibraryBrowseState? { document.browse[key] } + func reading(for key: String) -> LibraryReadingPosition? { document.reading[key] } + func setBrowse(_ value: LibraryBrowseState, for key: String) { + guard maySave, Self.validID(key), Self.valid(value), document.browse[key] != value else { return } + document.browse[key] = value; scheduleSave() + } + func setReading(_ value: LibraryReadingPosition, for key: String) { + guard maySave, Self.validID(key), Self.valid(value), document.reading[key] != value else { return } + document.reading[key] = value; scheduleSave() + } + @discardableResult + func addBookmark(bookID: String, bookTitle: String, sectionTitle: String, position: LibraryReadingPosition) -> ManualBookmark? { + guard maySave, Self.validID(bookID), Self.valid(position), bookmarks.count < 5_000 else { return nil } + let candidate = ManualBookmark(id: UUID(), bookID: bookID, bookTitle: String(bookTitle.prefix(512)), + sectionTitle: String(sectionTitle.prefix(1024)), position: position, createdAt: Date(), updatedAt: Date()) + if let existing = bookmarks.first(where: { $0.locationKey == candidate.locationKey }) { return existing } + bookmarks.append(candidate); document.bookmarks = bookmarks; scheduleSave(); return candidate + } + func renameBookmark(_ id: UUID, label: String) { + guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }) else { return } + bookmarks[index].label = String(label.trimmingCharacters(in: .whitespacesAndNewlines).prefix(512)) + bookmarks[index].updatedAt = Date(); document.bookmarks = bookmarks; scheduleSave() + } + func removeBookmark(_ id: UUID) { + guard maySave else { return } + bookmarks.removeAll { $0.id == id }; document.bookmarks = bookmarks; scheduleSave() + } + func markBookmarkLocationChanged(_ id: UUID, changed: Bool) { + guard maySave, let index = bookmarks.firstIndex(where: { $0.id == id }), bookmarks[index].locationChanged != changed else { return } + bookmarks[index].locationChanged = changed + document.bookmarks = bookmarks; scheduleSave() + } + func flush() async { + pendingSave?.cancel(); pendingSave = nil + guard maySave else { return } + await withCheckedContinuation { continuation in write { continuation.resume() } } + } + /// Queue the latest checkpoint without a main-thread or emulator wait. + func checkpoint() { + pendingSave?.cancel(); pendingSave = nil + if maySave { write() } + } + private func scheduleSave() { + revision += 1 + pendingSave?.cancel() + pendingSave = Task { [weak self] in + do { try await Task.sleep(for: .milliseconds(300)) } catch { return } + guard let self, !Task.isCancelled else { return } + self.write() + } + } + private func write(completion: (@Sendable () -> Void)? = nil) { + let value = document, destination = fileURL, generation = revision + queue.async { [weak self] in + let message: String? + do { + let encoder = JSONEncoder(); encoder.outputFormatting = [.sortedKeys] + let bytes = try encoder.encode(value) + guard bytes.count <= 8 * 1024 * 1024 else { throw Failure.invalid } + try FileManager.default.createDirectory(at: destination.deletingLastPathComponent(), withIntermediateDirectories: true) + try bytes.write(to: destination, options: .atomic) + message = nil + } catch { message = "Library positions and bookmarks could not be saved: \(error.localizedDescription)" } + Task { @MainActor [weak self] in + guard let self, self.revision == generation else { return } + self.saveError = message + } + completion?() + } + } + private static func validID(_ value: String) -> Bool { !value.isEmpty && value.utf8.count <= 4096 && !value.contains("\0") } + private static func valid(_ state: LibraryBrowseState) -> Bool { + state.scope.utf8.count <= 4096 && state.query.count <= 256 && state.filters.count <= 32 + && state.filters.allSatisfy { $0.key.count <= 128 && $0.value.count <= 4096 } + && state.offset.isFinite && state.offset >= 0 && (0...250_000).contains(state.pageOffset) + } + private static func valid(_ position: LibraryReadingPosition) -> Bool { + validID(position.documentID) && position.page > 0 && position.page <= 1_000_000 + && position.offset.isFinite && (0...1).contains(position.offset) + && position.horizontalOffset.isFinite && (0...1).contains(position.horizontalOffset) + && position.zoom.map { $0.isFinite && $0 > 0 && $0 <= 100 } != false + && position.relativePath.map { !$0.hasPrefix("/") && !$0.split(separator: "/").contains("..") && !$0.contains("\0") } != false + && position.anchor.map { $0.count <= 2048 && !$0.contains("\0") } != false + } + private enum Failure: LocalizedError { + case invalid + var errorDescription: String? { "The continuity file is damaged or uses an unsupported version." } + } +} + +struct ArchiveLibraryOpenRequest: Equatable, Sendable { + let id = UUID() + let documentID: String + let location: Int? + let expectedSHA256: String? +} + +/// A request is retained until the Archive window appears, so opening its window +/// and requesting an exact document do not depend on notification timing. +@MainActor +final class ArchiveLibraryNavigation: ObservableObject { + static let shared = ArchiveLibraryNavigation() + @Published private(set) var request: ArchiveLibraryOpenRequest? + func open(documentID: String, location: Int? = nil, expectedSHA256: String? = nil) { + request = ArchiveLibraryOpenRequest(documentID: documentID, location: location, expectedSHA256: expectedSHA256) + } + func consumed(_ id: UUID) { if request?.id == id { request = nil } } +} diff --git a/platforms/macos/App/MCPCMOC.swift b/platforms/macos/App/MCPCMOC.swift index 7efd70f..1ce550c 100644 --- a/platforms/macos/App/MCPCMOC.swift +++ b/platforms/macos/App/MCPCMOC.swift @@ -607,7 +607,7 @@ final class MCPCMOC: ObservableObject { try FileManager.default.createDirectory(at: dir, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) do { let server = try MCPTransport(handler: handler) - let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 11, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true, + let bytes = try JSONSerialization.data(withJSONObject: ["token": secret, "kind": "cmoc", "toolset": 12, "playtestVideo": approvedPlaytests, "playtestMedia": approvedPlaytests, "playtestCallContext": approvedPlaytests, "projectRefresh": true, "projectDiagnostics": true, "playtestAudio": approvedPlaytests, "playtestProcessors": approvedPlaytests, "playtestJoysticks": approvedPlaytests, "customMake": scope.customMake, "playtest": approvedPlaytests, "canPropose": true, "socket": server.unixPath, "port": Int(server.port), "version": 1]) return (server, try MCPGrantFile(create: destination, data: bytes)) } catch { try? FileManager.default.removeItem(at: dir); throw error } @@ -698,13 +698,15 @@ final class MCPCMOC: ObservableObject { if let latestRefreshID, let record = refreshRecords[latestRefreshID] { fields["refresh"] = projectRefreshFields(record) } result = fields case "get_capabilities" where args.isEmpty: - result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS", + result = ["tools": Self.tools + (callContextApproved ? ["get_call_context"] : []) + (playtestMediaApproved ? ["list_playtest_media", "exchange_playtest_media"] : []) + (playtestsApproved ? ["list_playtest_disks", "start_playtest", "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest"] : []), "playtest_media_exchange": playtestMediaApproved, "playtest_media_drive": "FD0", "playtest_media_maximum_disks": 9, "playtest_media_maximum_disk_bytes": 512 * 1024, "call_context": callContextApproved, "call_context_maximum_stack_bytes": 64, "input_diagnostics": true, "playtest_joystick_input": playtestsApproved, "playtest_joystick_interfaces": playtestsApproved ? ["standard"] : [], "playtest_joystick_axis_min": 0, "playtest_joystick_axis_max": 16383, "playtest_joystick_axis_center": 8191, "owned_playtests": playtestsApproved, "async_playtest_start": playtestsApproved, "retained_playtest_disks": playtestsApproved, "period_key": playtestsApproved, "graphics_buffer_capture": playtestsApproved, "custom_gime_canvases": playtestsApproved, "source_only_debugging": playtestsApproved, "verified_flat_debugging": playtestsApproved, "video_capture": playtestsApproved, "video_capture_maximum_fields": 3600, "video_capture_maximum_clips": 4, "video_capture_maximum_bytes": 64 * 1024 * 1024, "video_capture_retained_maximum_bytes": 256 * 1024 * 1024, "video_capture_chunk_maximum_bytes": 65536, "video_capture_guest_only": true, "video_capture_optional_audio": true, "video_capture_ui_cues": false, "audio_capture": playtestsApproved, "audio_capture_maximum_fields": 120, "audio_capture_maximum_clips": 16, "audio_capture_maximum_bytes": 4 * 1024 * 1024, "build_diagnostics": true, "project_refresh": true, "input_status": refreshProblem ?? "approved", "changed_input_paths": Array(observedInputChanges.prefix(128)).map(\.path), "changed_input_paths_total": observedInputChanges.count, "changed_input_paths_truncated": observedInputChanges.count > 128, "kind": "cmoc", "app": "VCC Plus OSS", "mutation_request_limit": MCPPlaytest.mutationRequestLimit, "stop_retention_exempt": true, "playtest_processors": playtestsApproved ? ["MC6809", "HD6309"] : [], "playtest_default_processor": "MC6809", "playtest_processor_selection": playtestsApproved, "app_version": Bundle.main.object(forInfoDictionaryKey: "CFBundleShortVersionString") as? String ?? "unknown", "app_build": Bundle.main.object(forInfoDictionaryKey: "CFBundleVersion") as? String ?? "unknown", "project_id": id, "revision": revision, - "entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1] + "entry": scope.entry, "target": "CoCo Disk BASIC", "build_recipe": scope.customMake ? "approved_make" : scope.helloDisk ? "installed_hello_disk" : "bundled_cmoc", "files": scope.paths, "headers": Self.headers, "session_id": owner.uuidString, "version": 1, + "banked_debug_manifest_versions": [1, 2], "verified_code_overlays": true, + "overlay_residency_evidence": "complete_mapped_code_bytes"] if scope.customMake { var facts = result facts["recipe_id"] = approvedRecipeID @@ -832,7 +834,7 @@ final class MCPCMOC: ObservableObject { case "start_playtest": guard playtestsApproved else { throw problem("access_denied") } result = try await startPlaytest(args, model: model, owner: owner) - case "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "restart_playtest", "stop_playtest", "exchange_playtest_media": + case "playtest_input", "get_playtest_input", "playtest_debug", "capture_playtest", "capture_playtest_graphics", "capture_playtest_audio", "start_playtest_video", "stop_playtest_video", "read_playtest_video", "restart_playtest", "stop_playtest", "exchange_playtest_media": if tool == "stop_playtest", playtestsApproved, args.count == 2, let runID = args["run_id"] as? String, let request = args["request_id"] as? String, (1...128).contains(request.utf8.count), @@ -848,7 +850,7 @@ final class MCPCMOC: ObservableObject { owned.artifactID == artifact.value.id.uuidString, !playtestBusy else { throw problem("stale_run") } playtestBusy = true defer { playtestBusy = false } - if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input"].contains(tool) { ownedInspection = nil } + if !["capture_playtest", "capture_playtest_graphics", "get_playtest_input", "start_playtest_video", "stop_playtest_video", "read_playtest_video"].contains(tool) { ownedInspection = nil } var request = args if tool == "playtest_debug" { guard Set(args.keys).isSubset(of: ["run_id", "request_id", "action", "function", "stop_kind"]), let action = args["action"] as? String else { throw problem("invalid_arguments") } @@ -1070,8 +1072,12 @@ final class MCPCMOC: ObservableObject { modules = layout.modules.compactMap { module in let code = module.codeGuards guard !code.isEmpty else { return nil } - return ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }, + var definition: [String: Any] = ["id": module.id, "pages": module.pages.map { ["logical_page": $0.logicalPage, "physical_page": $0.physicalPage] }, "guards": code.map { ["address": Int($0.address), "bytes_base64": Data($0.bytes).base64EncodedString()] }] + if let overlay = module.overlay { + definition["overlay_group"] = overlay.group; definition["overlay_owner"] = overlay.owner + } + return definition } } else { flatGuards = map.flatCodeGuards.map(\.workerFields) @@ -1215,15 +1221,16 @@ final class MCPCMOC: ObservableObject { guard ownsPlaytest(owned, artifact: artifact, owner: owner), capture["processor"] as? String == owned.processor.rawValue, capture["paused"] as? Bool == true, capture["attached"] as? Bool == true, - let clock = capture["field_clock"] as? Int else { throw problem("verified_pause_required") } + let clock = capture["field_clock"] as? Int, + let captureFingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("verified_pause_required") } if tool == "get_call_context" { guard callContextApproved, Set(arguments.keys) == ["run_id", "snapshot_id"], let previous = ownedInspection, previous.run == owned.runID, arguments["snapshot_id"] as? String == previous.id, - previous.clock == clock, previous.fingerprint == Self.ownedCaptureFingerprint(capture), + previous.clock == clock, previous.fingerprint == captureFingerprint, var context = previous.callContext else { throw problem("stale_or_unavailable_call_context") } for key in ["run_id", "snapshot_id", "artifact_id", "project_id", "revision", "processor", "requested_processor", - "execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision"] { + "execution_mode", "md_register", "field_clock", "boot", "stop_kind", "mapping_fingerprint", "program_revision", "residency_fingerprint", "overlay_residency"] { context[key] = previous.fields[key] ?? NSNull() } return context @@ -1231,6 +1238,7 @@ final class MCPCMOC: ObservableObject { if tool == "read_debug_memory" { guard arguments.count == 4, let previous = ownedInspection, previous.run == owned.runID, previous.clock == clock, arguments["snapshot_id"] as? String == previous.id, + previous.fingerprint == captureFingerprint, let address = int(arguments["address"]), let count = int(arguments["count"]), (1...256).contains(count), address >= 0, address <= 0xff00 - count, previous.ranges.contains(where: { $0.contains(address) && address + count <= $0.upperBound }) else { throw problem("stale_or_unavailable_memory") } @@ -1249,6 +1257,10 @@ final class MCPCMOC: ObservableObject { let (verifiedMap, verifiedMetadata, variableError) = try await debugMetadata(artifact) guard ownsPlaytest(owned, artifact: artifact, owner: owner) else { throw problem("stale_run") } let map = verifiedMap.projected(physicalPages: pages, memory: memory, available: available) + if verifiedMap.bankedLayout?.overlayGroups.isEmpty == false { + guard let residency = capture["residency_fingerprint"] as? String, UInt64(residency) != nil, + residency != "0" else { throw problem("overlay_residency_unavailable") } + } let metadata = verifiedMetadata?.projected(physicalPages: pages, memory: memory, available: available) let shared = Set(scope?.paths ?? []) let point = map.instruction(at: address).flatMap { shared.contains($0.sourcePath) ? $0 : nil } @@ -1328,6 +1340,16 @@ final class MCPCMOC: ObservableObject { "globals": globals.items, "globals_total": globals.total, "globals_truncated": globals.truncated, "mapping_fingerprint": capture["mapping_fingerprint"] as Any? ?? NSNull(), "program_revision": capture["program_revision"] as Any? ?? NSNull(), + "residency_fingerprint": capture["residency_fingerprint"] as Any? ?? "0", + "overlay_residency": map.bankedLayout?.overlayGroups.map { group in + let activeOwners = Set(map.bankedLayout!.modules.compactMap { module -> String? in + guard map.activeModuleIDs?.contains(module.id) == true, let overlay = module.overlay, + overlay.group == group.id else { return nil } + return overlay.owner + }) + return ["group": group.id, "owner": activeOwners.count == 1 ? activeOwners.first! as Any : NSNull(), + "status": activeOwners.count == 1 ? "verified" : "unavailable"] as [String: Any] + } ?? [], "physical_pages": rawPages, "symbol_stop": symbols.count == 1 ? symbolCatalog.items.first as Any? ?? NSNull() : NSNull(), "symbols_at_pc": symbolCatalog.items, "symbols_at_pc_total": symbolCatalog.total, "symbols_at_pc_truncated": symbolCatalog.truncated, @@ -1335,11 +1357,10 @@ final class MCPCMOC: ObservableObject { "source_debugging": ["status": metadata == nil ? "source_only" : "verified", "source_map": "verified", "variables": metadata == nil ? "unavailable" : "verified"], "watch_status": metadata == nil ? String((variableError ?? "Typed C metadata is unavailable; verified code inspection remains available.").prefix(2000)) : "Verified globals; C frame locals are unavailable for owned entry and instruction stops.", "memory_ranges": ranges.map { ["address": $0.lowerBound, "count": $0.count] }] - guard let fingerprint = Self.ownedCaptureFingerprint(capture) else { throw problem("invalid_worker_capture") } let context = callContextApproved ? CMOCOwnedCallContext.capture(map: map, metadata: metadata, pc: address, s: stackPointer, u: framePointer, memory: memory, available: available, physicalPages: pages, sharedPaths: shared) : nil - ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, fingerprint, context) + ownedInspection = (snapshot, owned.runID, clock, memory, ranges, fields, captureFingerprint, context) return fields } @@ -1351,6 +1372,7 @@ final class MCPCMOC: ObservableObject { guard keys.allSatisfy({ capture[$0] != nil }) else { return nil } var state = Dictionary(uniqueKeysWithValues: keys.map { ($0, capture[$0]!) }) state["md_register"] = capture["md_register"] ?? NSNull() + state["residency_fingerprint"] = capture["residency_fingerprint"] ?? "0" guard JSONSerialization.isValidJSONObject(state), let bytes = try? JSONSerialization.data(withJSONObject: state, options: [.sortedKeys]) else { return nil } return CMOCSourceMap.sha256(bytes) @@ -1850,7 +1872,7 @@ private struct MCPCMOCConsent: View { if !host.active { Toggle("Allow Disposable Playtests", isOn: $host.allowPlaytests) if host.allowPlaytests { - Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest and uses no microphone. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout) + Text("Allow the assistant to launch this project's built disk or resume a retained test disk in a separate 512 KB 6809 or 6309 CoCo, hold key combinations and standard joystick axes and buttons, read input diagnostics, capture its screen, declared graphics buffers and guest audio, record bounded MP4 gameplay clips with optional CoCo audio, inspect verified program stops and shared data, read up to 64 bytes at the paused test guest’s stack pointer with caller and argument interpretations only when verified, and restart its own writable test disks. Reviewed additional disk products can be inserted or ejected in the paused, idle test drive without a reset or advancing time; each private writable copy is retained. The guest controls 6309 execution mode. Audio capture advances the test guest. Mac windows, microphone and capture feedback cues are excluded. Retained originals and your current CoCo and media are preserved. Access ends when this connection or build changes.").font(.callout) } if host.allowPlaytests, let media = model.project?.configuration.playtestDisks, !media.isEmpty { Text("Additional playtest disks: " + media.joined(separator: ", ")).font(.callout).textSelection(.enabled) diff --git a/platforms/macos/App/MCPDebuggerInspection.swift b/platforms/macos/App/MCPDebuggerInspection.swift index 962f869..b50fd06 100644 --- a/platforms/macos/App/MCPDebuggerInspection.swift +++ b/platforms/macos/App/MCPDebuggerInspection.swift @@ -35,6 +35,7 @@ struct MCPDebuggerInspection { fields["source_stop"] = sourceStop as Any? ?? NSNull() fields["watches"] = watches fields["watch_status"] = watchStatus + fields["residency_fingerprint"] = String(state.debuggerResidencyFingerprint) fields["memory_ranges"] = memory.map { ["address": $0.range.lowerBound, "count": $0.range.count] } self.fields = fields } @@ -42,6 +43,7 @@ struct MCPDebuggerInspection { static func sameProgram(_ state: VCCMachineSnapshot, _ expected: VCCMachineSnapshot) -> Bool { state.assistantDeviceBlockers.isEmpty && state.generation == expected.generation && state.debuggerProgramRevision == expected.debuggerProgramRevision && + state.debuggerResidencyFingerprint == expected.debuggerResidencyFingerprint && state.debuggerMappingFingerprint == expected.debuggerMappingFingerprint && state.use6309 == expected.use6309 } diff --git a/platforms/macos/App/MCPPlaytest.swift b/platforms/macos/App/MCPPlaytest.swift index e3b8853..f8a2c73 100644 --- a/platforms/macos/App/MCPPlaytest.swift +++ b/platforms/macos/App/MCPPlaytest.swift @@ -366,6 +366,10 @@ final class MCPPlaytest { static let audioFieldLimit = 120 static let audioCaptureLimit = 16 static let audioByteLimit = 4 * 1024 * 1024 + static let videoFieldLimit = 3600 + static let videoClipLimit = 4 + static let videoByteLimit = 64 * 1024 * 1024 + static let videoRetainedByteLimit = 256 * 1024 * 1024 private static let maximumAudioClipBytes = 44 + 131_072 * 4 let runID: String let projectID: String @@ -394,6 +398,88 @@ final class MCPPlaytest { private var audioCapturesAccepted = 0 private var audioBytesRetained = 0 private var stopRequestID: String? + private var videoDirectories: [String: URL] = [:] + private var completedVideos: [String: [String: Any]] = [:] + private var videoBytesRetained = 0 + private var currentVideoID: String? + private var videoIsRecording = false + private var videoStopRequestIDs: [String: String] = [:] + private struct VideoFileIdentity: Equatable, Sendable { + let device: UInt64, inode: UInt64 + let size: Int + let seconds: Int64, nanos: Int64 + init(_ info: stat) { + device = UInt64(info.st_dev); inode = UInt64(info.st_ino); size = Int(info.st_size) + seconds = Int64(info.st_mtimespec.tv_sec); nanos = Int64(info.st_mtimespec.tv_nsec) + } + } + private var videoFileIdentities: [String: VideoFileIdentity] = [:] + private let videoArtifactWillVerify: (@Sendable (URL) throws -> Void)? + + private func retainVideoMetadata(_ result: [String: Any]) async throws { + guard let metadata = (result["video"] ?? result["video_recording"]) as? [String: Any] else { return } + videoIsRecording = metadata["status"] as? String == "recording" + guard metadata["completed"] as? Bool == true else { return } + guard let id = metadata["clip_id"] as? String, let directory = videoDirectories[id] else { throw Self.failure("invalid_playtest_video") } + if completedVideos[id] != nil { return } + let url = directory.appendingPathComponent("Clip.mp4") + let expectedCount = (metadata["byte_count"] as? NSNumber)?.intValue + let expectedHash = metadata["sha256"] as? String + let willVerify = videoArtifactWillVerify + let identity = try await Task.detached { + try willVerify?(url) + let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { throw Self.failure("invalid_playtest_video") } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close() } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, + (1...Self.videoByteLimit).contains(Int(info.st_size)), Int(info.st_size) == expectedCount else { + throw Self.failure("invalid_playtest_video") + } + let identity = VideoFileIdentity(info) + let bytes = try handle.read(upToCount: identity.size + 1) ?? Data() + guard bytes.count == identity.size, CMOCProject.sha256(bytes) == expectedHash, + fstat(fd, &info) == 0, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") } + return identity + }.value + guard let count = expectedCount, videoBytesRetained <= Self.videoRetainedByteLimit - count else { throw Self.failure("playtest_video_retention_limit") } + videoBytesRetained += count; completedVideos[id] = metadata; videoFileIdentities[id] = identity + } + + private func readVideo(_ arguments: [String: Any]) async throws -> [String: Any] { + guard Set(arguments.keys).isSubset(of: ["run_id", "clip_id", "offset", "limit"]), + let id = arguments["clip_id"] as? String, let metadata = completedVideos[id], let directory = videoDirectories[id], + let total = (metadata["byte_count"] as? NSNumber)?.intValue, + let identity = videoFileIdentities[id] else { throw Self.failure("playtest_video_unavailable") } + func integer(_ value: Any?, fallback: Int, range: ClosedRange) throws -> Int { + guard let value else { return fallback } + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite, + number.doubleValue == Double(number.intValue), range.contains(number.intValue) else { throw Self.failure("invalid_arguments") } + return number.intValue + } + let offset = try integer(arguments["offset"], fallback: 0, range: 0...total) + let limit = try integer(arguments["limit"], fallback: 65536, range: 1...65536) + let url = directory.appendingPathComponent("Clip.mp4") + let data = try await Task.detached { + let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC | O_NONBLOCK) + guard fd >= 0 else { throw Self.failure("invalid_playtest_video") } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close() } + var info = stat() + guard fstat(fd, &info) == 0, info.st_mode & S_IFMT == S_IFREG, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") } + try handle.seek(toOffset: UInt64(offset)) + let count = min(limit, total - offset) + let bytes = try handle.read(upToCount: count) ?? Data() + guard bytes.count == count, fstat(fd, &info) == 0, VideoFileIdentity(info) == identity else { throw Self.failure("invalid_playtest_video") } + return bytes + }.value + guard valid else { throw Self.failure("stale_run") } + var result = metadata + result["video_chunk_base64"] = data.base64EncodedString(); result["offset"] = offset + result["next_offset"] = offset + data.count; result["eof"] = offset + data.count == total + return scoped(result) + } private struct MediumState { let source: MCPPlaytestMedium @@ -413,11 +499,13 @@ final class MCPPlaytest { private init(worker: Worker, projectID: String, revision: Int, artifactID: String, retentionDirectory: URL, diskProvenance: MCPPlaytestDiskStore.Provenance, resumedDiskID: String?, runID: String, - processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?) { + processor: MCPPlaytestProcessor, media: [MCPPlaytestMedium]?, + videoArtifactWillVerify: (@Sendable (URL) throws -> Void)?) { self.runID = runID self.worker = worker; self.projectID = projectID; self.revision = revision; self.artifactID = artifactID self.retentionDirectory = retentionDirectory; self.diskProvenance = diskProvenance; self.resumedDiskID = resumedDiskID self.processor = processor + self.videoArtifactWillVerify = videoArtifactWillVerify if let media { self.media = Dictionary(uniqueKeysWithValues: media.map { ($0.id, MediumState(source: $0, data: $0.data)) }) self.mediaOrder = media.map(\.id); self.mountedMediaID = media.first?.id @@ -429,7 +517,8 @@ final class MCPPlaytest { modules: [[String: Any]] = [], stopAt: UInt16? = nil, stopModule: String? = nil, flatGuards: [[String: Any]] = [], cpu: String = "6809", helperURL: URL? = nil, retentionDirectory: URL? = nil, diskProvenance: MCPPlaytestDiskStore.Provenance? = nil, resumedDiskID: String? = nil, graphicsBuffers: [[String: Any]] = [], runID: String = UUID().uuidString, - media: [MCPPlaytestMedium]? = nil) async throws -> MCPPlaytest { + media: [MCPPlaytestMedium]? = nil, + videoArtifactWillVerify: (@Sendable (URL) throws -> Void)? = nil) async throws -> MCPPlaytest { guard let reservedID = UUID(uuidString: runID) else { throw failure("invalid_playtest_run_id") } guard systemROM.count == 32768, diskROM.count == 8192, !disk.isEmpty, disk.count <= 512 * 1024, ["6809", "6309"].contains(cpu), bootCommands.utf8.count <= 256 else { throw failure("invalid_playtest_artifact") } @@ -472,7 +561,7 @@ final class MCPPlaytest { let test = MCPPlaytest(worker: worker, projectID: projectID, revision: revision, artifactID: artifactID, retentionDirectory: retentionDirectory ?? AppIdentity.supportDirectory.appendingPathComponent("Development Runs/Assistant Playtests"), diskProvenance: provenance, resumedDiskID: resumedDiskID.map { UUID(uuidString: $0)!.uuidString }, runID: reservedID.uuidString, - processor: cpu == "6309" ? .hd6309 : .mc6809, media: media) + processor: cpu == "6309" ? .hd6309 : .mc6809, media: media, videoArtifactWillVerify: videoArtifactWillVerify) var setup: [String: Any] = ["op": "init", "system_rom": systemROM.base64EncodedString(), "disk_rom": diskROM.base64EncodedString(), "disk": disk.base64EncodedString(), "boot_keys": paste.chords.map { NSNumber(value: $0) }, "modules": modules, "cpu": cpu, @@ -550,6 +639,10 @@ final class MCPPlaytest { throw Self.failure("playtest_disk_export_failed") } exportedDisk = Data(data); exportedStatus = result + // Video is an independent artifact. A missing or corrupt movie may + // never prevent retention of the guest's writable disk bytes. + do { try await retainVideoMetadata(result) } + catch { exportedStatus?["video_retention_error"] = "The video artifact could not be verified; disk retention continues." } } guard let data = exportedDisk else { throw Self.failure("playtest_disk_export_failed") } do { @@ -695,6 +788,8 @@ final class MCPPlaytest { do { result = try await worker.request(["op": "stop"]) try receiveMediaExport(result) + do { try await retainVideoMetadata(result) } + catch { result["video_retention_error"] = "The video artifact could not be verified; disk retention continues." } } catch let error as WorkerTransportFailure { // A failed swap pipe cannot have advanced a paused guest. // Every candidate copy is already frozen in the host; retain @@ -771,6 +866,7 @@ final class MCPPlaytest { if exportedDisk != nil { return scoped(["status": "retention_pending", "disk_retained": false]) } let result = try await worker.request(["op": "capture"]) guard valid else { throw Self.failure("stale_run") } + try await retainVideoMetadata(result) return scoped(result) } if tool == "get_playtest_input" { @@ -779,8 +875,9 @@ final class MCPPlaytest { guard valid else { throw Self.failure("stale_run") } return scoped(result) } + if tool == "read_playtest_video" { return try await readVideo(arguments) } guard let requestID = arguments["request_id"] as? String, (1...64).contains(requestID.utf8.count), - ["playtest_input", "restart_playtest", "stop_playtest", "playtest_debug", "capture_playtest_audio", "exchange_playtest_media"].contains(tool) else { throw Self.failure("invalid_arguments") } + ["playtest_input", "restart_playtest", "stop_playtest", "playtest_debug", "capture_playtest_audio", "exchange_playtest_media", "start_playtest_video", "stop_playtest_video"].contains(tool) else { throw Self.failure("invalid_arguments") } let signature = try JSONSerialization.data(withJSONObject: ["tool": tool, "arguments": arguments], options: [.sortedKeys]) if let (prior, reason) = mediaFailures[requestID] { guard signature == prior else { throw Self.failure("request_conflict") } @@ -793,11 +890,15 @@ final class MCPPlaytest { if tool == "stop_playtest", let stopRequestID, requestID != stopRequestID { throw Self.failure("request_conflict: retry the original stop request_id") } + if tool == "stop_playtest_video", let clip = currentVideoID, + let prior = videoStopRequestIDs[clip], prior != requestID { + throw Self.failure("request_conflict: retry the original video stop request_id") + } guard exportedDisk == nil || tool == "stop_playtest" else { throw Self.failure("playtest_retention_pending") } guard !finished else { throw Self.failure("stale_run") } // Cleanup has its own single cached receipt and must remain possible // after any execution/audio budget is exhausted. - guard tool == "stop_playtest" || mutationRequestsAccepted < Self.mutationRequestLimit || accepted[requestID] != nil else { + guard ["stop_playtest", "stop_playtest_video"].contains(tool) || mutationRequestsAccepted < Self.mutationRequestLimit || accepted[requestID] != nil else { throw Self.failure("playtest_request_limit") } if tool == "exchange_playtest_media" { @@ -843,6 +944,31 @@ final class MCPPlaytest { } var request: [String: Any] switch tool { + case "start_playtest_video": + guard Set(arguments.keys).isSubset(of: ["run_id", "request_id", "include_audio", "max_fields"]) else { throw Self.failure("invalid_arguments") } + guard !videoIsRecording else { throw Self.failure("playtest_video_active") } + let includeAudio: Bool + if let value = arguments["include_audio"] { + guard let number = value as? NSNumber, CFGetTypeID(number) == CFBooleanGetTypeID() else { throw Self.failure("invalid_arguments") } + includeAudio = number.boolValue + } else { includeAudio = true } + let maximum: Int + if let value = arguments["max_fields"] { + guard let number = value as? NSNumber, CFGetTypeID(number) != CFBooleanGetTypeID(), number.doubleValue.isFinite, + number.doubleValue == Double(number.intValue), (1...Self.videoFieldLimit).contains(number.intValue) else { throw Self.failure("invalid_arguments") } + maximum = number.intValue + } else { maximum = 1800 } + guard videoDirectories.count < Self.videoClipLimit, videoBytesRetained <= Self.videoRetainedByteLimit - Self.videoByteLimit else { + throw Self.failure("playtest_video_capture_limit") + } + let id = UUID().uuidString + let directory = retentionDirectory.appendingPathComponent("Videos", isDirectory: true).appendingPathComponent(runID, isDirectory: true).appendingPathComponent(id, isDirectory: true) + try await Task.detached { try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) }.value + videoDirectories[id] = directory; currentVideoID = id + request = ["op": "video_start", "clip_id": id, "directory": directory.path, "include_audio": includeAudio, "max_fields": maximum] + case "stop_playtest_video": + guard arguments.count == 2, currentVideoID != nil else { throw Self.failure("playtest_video_unavailable") } + request = ["op": "video_stop"] case "capture_playtest_audio": guard arguments.count == 3, let n = arguments["fields"] as? NSNumber, CFGetTypeID(n) != CFBooleanGetTypeID(), n.doubleValue.isFinite, @@ -892,6 +1018,7 @@ final class MCPPlaytest { } case "restart_playtest": guard arguments.count == 2 else { throw Self.failure("invalid_arguments") } + guard !videoIsRecording else { throw Self.failure("playtest_video_active: stop the recording before restarting") } request = ["op": "restart"] default: guard arguments.count == 2 else { throw Self.failure("invalid_arguments") } @@ -900,7 +1027,8 @@ final class MCPPlaytest { // Reserve the identity before execution. An interrupted operation must // never be retried as a new input sequence with the same request ID. if tool == "stop_playtest" { stopRequestID = requestID } - if tool != "stop_playtest" { mutationRequestsAccepted += 1 } + if tool == "stop_playtest_video", let clip = currentVideoID { videoStopRequestIDs[clip] = requestID } + if !["stop_playtest", "stop_playtest_video"].contains(tool) { mutationRequestsAccepted += 1 } if tool == "capture_playtest_audio" { audioCapturesAccepted += 1 } accepted[requestID] = (signature, scoped(["request_id": requestID, "status": "interrupted"])) if tool == "stop_playtest" { @@ -920,6 +1048,7 @@ final class MCPPlaytest { lastSafeMediaExport = nil var result = try await worker.request(request) guard valid else { throw Self.failure("stale_run") } + try await retainVideoMetadata(result) if tool == "capture_playtest_audio" { guard let encoded = result["audio_wav_base64"] as? String, let wav = Data(base64Encoded: encoded), (44...Self.maximumAudioClipBytes).contains(wav.count), @@ -963,6 +1092,7 @@ final class MCPPlaytest { if let operation = request["op"] as? String, ["continue", "step", "stop_at"].contains(operation) { lastSafeMediaExport = nil } let result = try await worker.request(request) guard valid else { throw Self.failure("stale_run") } + try await retainVideoMetadata(result) return scoped(result) } @@ -975,6 +1105,12 @@ final class MCPPlaytest { result["mutation_requests_used"] = mutationRequestsAccepted result["remaining_mutation_requests"] = max(0, Self.mutationRequestLimit - mutationRequestsAccepted) result["stop_retention_exempt"] = true + result["video_stop_retention_exempt"] = true + result["video_clip_limit"] = Self.videoClipLimit + result["remaining_video_clips"] = max(0, Self.videoClipLimit - videoDirectories.count) + result["video_byte_limit"] = Self.videoByteLimit + result["video_retained_byte_limit"] = Self.videoRetainedByteLimit + result["remaining_video_bytes"] = max(0, Self.videoRetainedByteLimit - videoBytesRetained) result["audio_capture_limit"] = Self.audioCaptureLimit result["remaining_audio_captures"] = max(0, Self.audioCaptureLimit - audioCapturesAccepted) result["audio_byte_limit"] = Self.audioByteLimit diff --git a/platforms/macos/App/MachineInterface.swift b/platforms/macos/App/MachineInterface.swift index 0c7a25f..e21bef1 100644 --- a/platforms/macos/App/MachineInterface.swift +++ b/platforms/macos/App/MachineInterface.swift @@ -59,6 +59,8 @@ struct MachineView: View { .frame(maxWidth: 440, maxHeight: 42) }.buttonStyle(.plain).help("Open Machine Settings for processor and memory") Spacer(minLength: 24) + CoCoCaptureControls(capture: machine.captures, machine: machine) + Spacer(minLength: 12) Button { openWindow(id: "machine-settings") } label: { HardwareBadge(name: machine.use6309 ? "hitachi" : "motorola", label: machine.use6309 ? "Hitachi 6309" : "Motorola 6809").frame(width: 44, height: 44) }.buttonStyle(.plain).help("Open Machine Settings for processor and memory") diff --git a/platforms/macos/App/MachineModel.swift b/platforms/macos/App/MachineModel.swift index 52da57a..dd8a549 100644 --- a/platforms/macos/App/MachineModel.swift +++ b/platforms/macos/App/MachineModel.swift @@ -352,10 +352,11 @@ final class MachineModel: ObservableObject { private let automaticDiskWriter: @Sendable (Data, URL, Data) async throws -> Void private let diskStore: DiskAssignmentStore private let inputStore: InputSettingsStore + private let inputControllerReadings: (() -> [ControllerReading])? lazy var printer = PrinterModel(controller: controller) private var existingInputHub: InputHub? lazy var input: InputHub = { - let hub = InputHub(controller: controller, store: inputStore) + let hub = InputHub(controller: controller, store: inputStore, controllerReadings: inputControllerReadings) existingInputHub = hub return hub }() @@ -386,10 +387,13 @@ final class MachineModel: ObservableObject { private var mediaPromptOpen = false let recentMedia: RecentMedia let displayPreferences: DisplayPreferences + lazy var captures = CoCoCaptureCoordinator(machine: self, controller: controller, defaults: displayDefaults, + directory: diskStore.url.deletingLastPathComponent()) private var screenshotInProgress = false private let controller: VCCMachineController init(diskStore: DiskAssignmentStore = .standard, controller: VCCMachineController = VCCMachineController(), displayDefaults: UserDefaults = .standard, inputStore: InputSettingsStore = .standard, startupStore: StartupStore? = nil, + inputControllerReadings: (() -> [ControllerReading])? = nil, restoreMediaOnLaunch: Bool = true, automaticHardDiskWriter: @escaping @Sendable (Data, Int, URL, String) async throws -> String = { patches, length, url, expected in try await Task.detached(priority: .utility) { try HardDiskFiles.saveAutomatically(patches, length: length, to: url, expected: expected) }.value @@ -403,6 +407,7 @@ final class MachineModel: ObservableObject { self.starterShellDiskURL = startupStore?.directory.resolvingSymlinksInPath() .appendingPathComponent("Starter Media/NitrOS-9 L2 V3.3.0.vhd").standardizedFileURL self.inputStore = inputStore + self.inputControllerReadings = inputControllerReadings self.displayDefaults = displayDefaults videoOutput = DisplayOutput.remembered(in: displayDefaults) let rememberedSettings = MachineSettings.remembered(in: displayDefaults) @@ -522,7 +527,7 @@ final class MachineModel: ObservableObject { // Shared by both presentations. The profile transaction already pauses the // worker, drains automatic writes and rejects any unsaved media atomically. @discardableResult func restoreAppDefaults() async -> Bool { - await loadSystemProfile(.diskBasic) + await loadSystemProfile(.diskBasic, resetInput: true) } func systemProfileUnavailableReason(_ kind: SystemProfile) -> String? { guard let startupStore else { return StartupStore.Failure.unavailable.localizedDescription } @@ -537,11 +542,15 @@ final class MachineModel: ObservableObject { }.value } @discardableResult func loadSystemProfile(_ kind: SystemProfile) async -> Bool { + await loadSystemProfile(kind, resetInput: false) + } + @discardableResult private func loadSystemProfile(_ kind: SystemProfile, resetInput: Bool) async -> Bool { guard !busy, !diskSaving, state != .closed else { return false } await loadProfile(preparing: { [startupStore] in guard let startupStore else { throw StartupStore.Failure.unavailable } return try await Task.detached(priority: .userInitiated) { try startupStore.systemProfile(kind) }.value - }, startRunning: true, builtInNitros9: kind == .nitros9) + }, startRunning: true, builtInNitros9: kind == .nitros9, + preserveInput: !resetInput, resetInput: resetInput) let succeeded = profileError == nil && fileError == nil if succeeded { guideRequest = GuideRequest(profile: kind) } return succeeded @@ -1080,6 +1089,9 @@ final class MachineModel: ObservableObject { // checks active disk writes and recordings again on its serial queue. func applyMachineSettings(_ value: MachineSettings) { guard !busy, !diskSaving, state != .closed, value.valid else { return } + if captures.active && (value.fastForward || value.use6309 != settings.use6309 || value.ram != settings.ram) { + Task { if await captures.stopBeforeReplacingMachine() { applyMachineSettings(value) } }; return + } command({ controller.configureMachine(use6309: value.use6309, ram: value.ram, overclock: value.overclock, frameInterval: value.frameInterval, fastForward: value.fastForward, completion: $0) }, onSuccess: { [self] in @@ -1111,6 +1123,10 @@ final class MachineModel: ObservableObject { } } func installROM(_ data: Data, url: URL) { + if captures.active { + Task { if await captures.stopBeforeReplacingMachine() { installROM(data, url: url) } else { busy = false } }; return + } + captures.cancelCountdown() busy = true; inputEpoch += 1 controller.loadROM(data, use6309: use6309) { [weak self] snapshot in MainActor.assumeIsolated { @@ -1761,6 +1777,9 @@ final class MachineModel: ObservableObject { var definition: [String: Any] = ["id": module.id, "pages": module.pages.map { ["logicalPage": $0.logicalPage, "physicalPage": $0.physicalPage] }, "addresses": code.map { NSNumber(value: $0.address) }, "bytes": code.map { Data($0.bytes) }] + if let overlay = module.overlay { + definition["overlay_group"] = overlay.group; definition["overlay_owner"] = overlay.owner + } if let pointModules { definition["breakpoints"] = addresses.filter { pointModules[$0]?.contains(module.id) == true }.map { NSNumber(value: $0) } } @@ -1846,6 +1865,7 @@ final class MachineModel: ObservableObject { debuggerCommand({ controller.debuggerStepBankedSource(mode: mode, addresses: addresses, locations: locations, bytes: bytes, moduleIdentifiers: moduleIdentifiers, generation: expected.generation, programRevision: expected.debuggerProgramRevision, mappingFingerprint: expected.debuggerMappingFingerprint, + residencyFingerprint: expected.debuggerResidencyFingerprint, programCounter: expected.programCounter, completion: $0) }, completion: completion) return } @@ -1891,8 +1911,8 @@ final class MachineModel: ObservableObject { func debuggerWriteMemory(address: UInt16, data: Data, completion: @escaping () -> Void) { debuggerCommand({ controller.debuggerWriteMemory(address: address, data: data, completion: $0) }, completion: completion) } - func softReset() { command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } - func reset() { command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } + func softReset() { captures.cancelCountdown(); command(controller.softReset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } + func reset() { captures.cancelCountdown(); command(controller.reset, onSuccess: { [self] in binaryName = nil; deniedShellGeneration = nil }) } func poll() { guard !polling, !busy, state != .closed else { return } polling = true @@ -2373,8 +2393,11 @@ extension MachineModel { await loadProfile(preparing: { profile }, startRunning: false) } @discardableResult private func loadProfile(preparing: () async throws -> ConfigurationProfile, startRunning: Bool, - builtInNitros9: Bool = false, afterStart: (() async throws -> Void)? = nil) async -> Bool { + builtInNitros9: Bool = false, preserveInput: Bool = false, resetInput: Bool = false, + libraryInputs: Bool = false, + afterStart: (() async throws -> Void)? = nil) async -> Bool { guard !busy, state != .closed else { return false } + guard await captures.stopBeforeReplacingMachine() else { return false } var committed = false guideRequest = nil busy = true; inputEpoch += 1; profileError = nil; fileError = nil @@ -2428,7 +2451,11 @@ extension MachineModel { } } nextHardSave = .distantPast; savedHardFlushRequests = hardFlushRequests - volume = profile.volume; input.settings = profile.input + volume = profile.volume + if resetInput { input.restoreDefaultSettings() } + else if preserveInput { input.release() } + else if libraryInputs { input.applyLibrarySettings(profile.input) } + else { input.applyProfileSettings(profile.input) } _ = await applyDriveWireDefault(builtInNitros9) rememberStartup() loadedProfileConfiguration = profileConfiguration @@ -2609,6 +2636,7 @@ extension MachineModel { let capture: ScreenCapture do { capture = try ScreenCapture(pixels: pixels, area: activeVideoRect) } catch { fileError = error.localizedDescription; return } + CoCoCaptureFeedback.play(.screenshot) screenshotInProgress = true; fileError = nil let panel = NSSavePanel() panel.title = "Save CoCo Screen" @@ -2685,6 +2713,15 @@ extension MachineModel { case .diskBasic: profile.media.rom = try firmware("disk11.rom", fallback: diskAssignments.rom) layout.slots[plan.controllerSlot].kind = .floppy + case .hardDriveBasic: + // An arbitrary active disk ROM may be Disk BASIC rather than RGB-DOS. + // Only recognized starter firmware can supply a missing bundled ROM; + // editable profile names and the presence of a hard disk prove nothing. + let knownRGBDOS = usageProfile == .hardDriveBasic || usageProfile == .nitros9 + profile.media.rom = try firmware(SystemProfile.hardDriveBasic.diskROMName, + fallback: knownRGBDOS ? diskAssignments.rom : nil) + layout.slots[plan.controllerSlot].kind = .floppy + layout.slots[plan.controllerSlot == 1 ? 2 : 1].kind = .hardDisk case .cocoSDC: let priorROM = cartridgeAssignments.slots.first { $0.kind == .sdc }?.url layout.slots[plan.controllerSlot] = .init(kind: .sdc, url: try firmware("sdcdos.rom", fallback: priorROM), @@ -2692,6 +2729,7 @@ extension MachineModel { } profile.media.cartridges = layout profile.media.hardDisks = HardDiskAssignments() + for (drive, url) in plan.hardDiskURLs { profile.media.hardDisks?.drives[drive] = .init(url: url, writeProtected: false) } for (drive, url) in plan.floppyURLs { profile.media.drives[drive] = .init(url: url, writeProtected: false) } profile.cassette = plan.cassetteURL; profile.fastCassette = plan.cassetteURL != nil profile.bootNitros9 = nil @@ -2720,7 +2758,7 @@ extension MachineModel { let applied = await loadProfile(preparing: { try await Task.detached(priority: .userInitiated) { try prepared.plan.validateMedia() }.value return prepared.profile - }, startRunning: true, afterStart: { [self] in + }, startRunning: true, libraryInputs: true, afterStart: { [self] in do { try Task.checkCancellation() if prepared.plan.cassetteURL != nil && !prepared.plan.commands.isEmpty { @@ -2769,7 +2807,8 @@ extension MachineModel { guard canLaunchLibrarySoftware else { throw ProfileFailure.message("Wait for the current machine operation to finish.") } _ = try await Task.detached(priority: .userInitiated) { try PreparedProfile.read(profile) }.value try Task.checkCancellation() - let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9) + let applied = await loadProfile(preparing: { profile }, startRunning: true, builtInNitros9: profile == libraryReturnToNitros9, + libraryInputs: true) guard applied, profileError == nil else { throw ProfileFailure.message(profileError ?? "The previous setup could not be restored.") } libraryReturnToNitros9 = nil } diff --git a/platforms/macos/App/ManualLibraryView.swift b/platforms/macos/App/ManualLibraryView.swift index 224ea50..2af1594 100644 --- a/platforms/macos/App/ManualLibraryView.swift +++ b/platforms/macos/App/ManualLibraryView.swift @@ -100,33 +100,157 @@ struct ManualLibraryContent { } } +private final class ManualContinuityBridge: NSObject, WKScriptMessageHandler { + weak var reader: ManualReader? + func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) { + guard message.frameInfo.isMainFrame else { return } + Task { @MainActor [weak self] in self?.reader?.receivedPosition(message.body) } + } +} + @MainActor final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { let webView: WKWebView let content: ManualLibraryContent? lazy var pageFind = ManualPageFind(webView: webView) private var searchNavigation: WKNavigation? + let continuity: LibraryContinuityStore? + private let scrollBridge = ManualContinuityBridge() + private var restorePosition: LibraryReadingPosition? + private var navigationRevision = 0 + @Published private(set) var currentBookID: String? + @Published private(set) var currentBookTitle = "" + @Published private(set) var currentSectionTitle = "" + @Published private(set) var currentPosition: LibraryReadingPosition? + @Published private(set) var bookmarkMessage: String? + @Published private var changedBookmarkIDs: Set = [] + private var restoringBookmarkID: UUID? var openExample: ((String) -> Void)? @Published private(set) var canGoBack = false @Published private(set) var canGoForward = false @Published private(set) var error: String? - init(content: ManualLibraryContent? = .bundled) { + init(content: ManualLibraryContent? = .bundled, continuity: LibraryContinuityStore? = nil) { self.content = content + self.continuity = continuity ?? (content?.root == ManualLibraryContent.bundled?.root ? .shared : nil) let configuration = WKWebViewConfiguration() configuration.websiteDataStore = .nonPersistent() webView = WKWebView(frame: .zero, configuration: configuration) super.init() + scrollBridge.reader = self + webView.configuration.userContentController.add(scrollBridge, name: "libraryPosition") + webView.configuration.userContentController.addUserScript(WKUserScript(source: Self.positionScript, injectionTime: .atDocumentEnd, forMainFrameOnly: true)) webView.navigationDelegate = self webView.allowsBackForwardNavigationGestures = true webView.publisher(for: \.canGoBack).receive(on: RunLoop.main).assign(to: &$canGoBack) webView.publisher(for: \.canGoForward).receive(on: RunLoop.main).assign(to: &$canGoForward) } - func showHome() { - loadPage(content?.home) + func showHome() { loadPage(content?.home) } + + func resume() { + guard webView.url == nil else { return } + if let position = continuity?.reading(for: "manual-last"), let path = position.relativePath, + let content, content.relativePath(for: content.root.appendingPathComponent(path)) != nil { + loadPage(content.root.appendingPathComponent(path), restore: position) + } else { showHome() } } + var hasCurrentBookmark: Bool { + guard let book = currentBookID, let position = currentPosition else { return false } + return continuity?.bookmarks.contains { + $0.bookID == book && $0.position.relativePath == position.relativePath && $0.position.anchor == position.anchor + && (position.anchor != nil || Int($0.position.offset * 10_000) == Int(position.offset * 10_000)) + } == true + } + func bookmarkCurrentLocation() { + guard continuity != nil, !webView.isLoading, let url = webView.url else { return } + let revision = navigationRevision + // The periodic scroll checkpoint deliberately runs infrequently. A + // deliberate bookmark must ask the loaded page for its location now. + Task { [weak self] in + guard let self else { return } + do { + let value = try await webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()") + guard navigationRevision == revision, webView.url == url, !webView.isLoading, + let object = value as? [String: Any], object["href"] as? String == url.absoluteString else { return } + receivedPosition(object) + guard let book = currentBookID, let position = currentPosition else { return } + let existing = hasCurrentBookmark + _ = continuity?.addBookmark(bookID: book, bookTitle: currentBookTitle, sectionTitle: currentSectionTitle, position: position) + bookmarkMessage = existing ? "This location is already bookmarked." : "Bookmark saved." + } catch { + guard navigationRevision == revision, webView.url == url else { return } + bookmarkMessage = "This location could not be bookmarked. Try again after the page finishes loading." + } + } + } + func openBookmark(_ bookmark: ManualBookmark, fromBookStart: Bool = false) { + guard let content else { return } + let home = bookmark.bookID.hasPrefix("toolchain-reference:") ? "toolchain-reference/index.html" : bookmark.bookID + "/template.html" + let path = fromBookStart ? home : bookmark.position.relativePath ?? "" + let url = content.root.appendingPathComponent(path) + guard content.relativePath(for: url) != nil else { + error = "This bookmark's page is no longer in the bundled book. The bookmark has been preserved." + return + } + loadPage(url, restore: fromBookStart ? nil : bookmark.position) + restoringBookmarkID = fromBookStart ? nil : bookmark.id + } + func bookmarkAvailable(_ bookmark: ManualBookmark) -> Bool { + guard let content, let path = bookmark.position.relativePath else { return false } + return bookmark.locationChanged != true && !changedBookmarkIDs.contains(bookmark.id) && content.relativePath(for: content.root.appendingPathComponent(path)) != nil + } + func checkpoint() { + webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil) + continuity?.checkpoint() + } + + fileprivate func receivedPosition(_ value: Any) { + guard let object = value as? [String: Any], let href = object["href"] as? String, + let url = URL(string: href), let path = content?.relativePath(for: url), + path == webView.url.flatMap({ content?.relativePath(for: $0) }), + url.pathExtension.lowercased() == "html" else { return } + let parts = path.split(separator: "/") + let bookID: String? = parts.count > 1 ? (parts[0] == "toolchain-reference" ? "toolchain-reference:" + String(parts[1]) : String(parts[0])) : nil + let anchor = (object["anchor"] as? String).flatMap { $0.isEmpty ? nil : $0 } + let position = LibraryReadingPosition(documentID: bookID ?? "manual-home", relativePath: path, + anchor: anchor, offset: min(1, max(0, (object["offset"] as? Double) ?? 0)), readingOrder: object["order"] as? Int) + currentBookID = bookID + currentBookTitle = object["bookTitle"] as? String ?? "Manual Library" + currentSectionTitle = object["sectionTitle"] as? String ?? currentBookTitle + currentPosition = position + continuity?.setReading(position, for: "manual-last") + continuity?.setReading(position, for: "manual-page:" + path) + if let bookID { continuity?.setReading(position, for: "manual-book:" + bookID) } + } + + private static let positionScript = #""" + (() => { + let timer; + const sections = () => Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]')); + window.vccLibraryCheckpoint = () => { + const y = window.scrollY, candidates = sections(); + let target = null; + for (const item of candidates) { if (item.getBoundingClientRect().top + y <= y + 12) target = item; } + const start = target ? target.getBoundingClientRect().top + y : 0; + const index = candidates.indexOf(target); + const next = target ? candidates[index + 1] : null; + const end = next ? next.getBoundingClientRect().top + y : document.documentElement.scrollHeight; + const title = target?.querySelector('h2,h3,h4')?.textContent || target?.textContent || document.querySelector('h1')?.textContent || document.title; + const crumb = document.querySelector('.crumb a:nth-child(2)')?.textContent; + const bookTitle = location.pathname.includes('/toolchain-reference/') ? (document.querySelector('h1')?.textContent || document.title) : (crumb || document.title); + const chapters = Array.from(document.querySelectorAll('.toc ol > li > a')); + const chapter = chapters.findIndex(link => new URL(link.href).pathname === location.pathname); + const position = {href: location.href, anchor: target?.id || '', offset: Math.min(1, Math.max(0, (y-start)/Math.max(1,end-start))), bookTitle, sectionTitle:title.slice(0,1024),order:Math.max(0,chapter)*10000+Math.max(0,index)}; + window.webkit.messageHandlers.libraryPosition.postMessage(position); + return position; + }; + window.addEventListener('scroll', () => { if (!timer) timer=setTimeout(() => { timer=null; window.vccLibraryCheckpoint(); },1000); }, {passive:true}); + window.addEventListener('pagehide', window.vccLibraryCheckpoint); + })(); + """# + func showLibrarySearch() { pageFind.close() if let url = webView.url, content?.relativePath(for: url) == "index.html", !webView.isLoading { @@ -151,11 +275,16 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { } @discardableResult - private func loadPage(_ url: URL?) -> WKNavigation? { + private func loadPage(_ url: URL?, restore: LibraryReadingPosition? = nil) -> WKNavigation? { guard let content, let url, content.relativePath(for: url) != nil else { error = "This page is missing from the bundled Manual Library." return nil } + checkpoint() + navigationRevision += 1 + restorePosition = restore + restoringBookmarkID = nil + currentPosition = nil error = nil return webView.loadFileURL(url, allowingReadAccessTo: content.root) } @@ -192,6 +321,21 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { } return } + if action.navigationType == .linkActivated { + navigationRevision += 1 + restorePosition = nil + if url.fragment == nil || url.fragment?.isEmpty == true { + if url.lastPathComponent == "template.html", let book = path.split(separator: "/").first, + let saved = continuity?.reading(for: "manual-book:" + String(book)), + let savedPath = saved.relativePath, savedPath != path, + let content, content.relativePath(for: content.root.appendingPathComponent(savedPath)) != nil { + decisionHandler(.cancel) + loadPage(content.root.appendingPathComponent(savedPath), restore: saved) + return + } + restorePosition = continuity?.reading(for: "manual-page:" + path) + } + } decisionHandler(.allow) return } @@ -211,6 +355,42 @@ final class ManualReader: NSObject, ObservableObject, WKNavigationDelegate { func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) { error = nil + let saved = restorePosition + let restoredBookmark = restoringBookmarkID + restorePosition = nil + restoringBookmarkID = nil + let revision = navigationRevision + if let saved, saved.relativePath == webView.url.flatMap({ content?.relativePath(for: $0) }) { + let argument = ["anchor": saved.anchor ?? "", "offset": saved.offset, "href": webView.url?.absoluteString ?? ""] as [String: Any] + if let data = try? JSONSerialization.data(withJSONObject: argument), let json = String(data: data, encoding: .utf8) { + webView.evaluateJavaScript(""" + (() => { + const p = \(json); + if (location.href !== p.href) return null; + const target = p.anchor ? document.getElementById(p.anchor) : null; + if (p.anchor && !target) return false; + const y = target ? target.getBoundingClientRect().top + window.scrollY : 0; + const candidates = Array.from(document.querySelectorAll('article section[id],article h2[id],article h3[id]')); + const next = target ? candidates[candidates.indexOf(target)+1] : null; + const end = next ? next.getBoundingClientRect().top + window.scrollY : document.documentElement.scrollHeight; + window.scrollTo(0,y + Math.max(0,end-y)*p.offset); + window.vccLibraryCheckpoint?.(); return true; + })(); + """) { [weak self] result, _ in + guard let self, self.navigationRevision == revision else { return } + if (result as? Bool) == false { + if let restoredBookmark { + self.changedBookmarkIDs.insert(restoredBookmark) + self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: true) + } + self.error = "Location changed. This saved section is no longer available; the page and bookmark have been preserved." + } else if let restoredBookmark { + self.changedBookmarkIDs.remove(restoredBookmark) + self.continuity?.markBookmarkLocationChanged(restoredBookmark, changed: false) + } + } + } + } else { webView.evaluateJavaScript("window.vccLibraryCheckpoint?.()", completionHandler: nil) } if let searchNavigation, navigation === searchNavigation { self.searchNavigation = nil focusLibrarySearch() @@ -248,6 +428,7 @@ private struct ManualWebPage: NSViewRepresentable { struct ManualLibraryView: View { @Environment(\.openWindow) private var openWindow @ObservedObject var reader: ManualReader + @State private var showsBookmarks = false var body: some View { VStack(spacing: 0) { @@ -264,6 +445,23 @@ struct ManualLibraryView: View { .focusedSceneValue(\.manualPageFind, reader.pageFind) .toolbar { ToolbarItemGroup(placement: .primaryAction) { + Button { + let exists = reader.hasCurrentBookmark + reader.bookmarkCurrentLocation() + if exists { showsBookmarks = true } + } label: { Image(systemName: reader.hasCurrentBookmark ? "bookmark.fill" : "bookmark") } + .disabled(reader.currentBookID == nil || reader.currentPosition == nil || reader.continuity == nil) + .help("Bookmark this location").accessibilityLabel("Bookmark this location") + .accessibilityIdentifier("manual.bookmark-location") + + Button { showsBookmarks.toggle() } label: { Image(systemName: "list.bullet") } + .help("Bookmarks").accessibilityLabel("Bookmarks") + .accessibilityIdentifier("manual.bookmarks") + .popover(isPresented: $showsBookmarks) { + if let continuity = reader.continuity { + ManualBookmarksPopover(reader: reader, continuity: continuity) { showsBookmarks = false } + } else { Text("Bookmarks are unavailable in this reader.").padding() } + } Button("Find on This Page", systemImage: "magnifyingglass") { reader.pageFind.show() } .help("Find on this page (⌘F)").accessibilityIdentifier("manual.find") @@ -288,7 +486,94 @@ struct ManualLibraryView: View { } .frame(minWidth: 420, minHeight: 340) .onAppear { - if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.showHome() } + if reader.error == nil && reader.webView.url == nil && !reader.webView.isLoading { reader.resume() } + } + .onDisappear { reader.checkpoint() } + .onReceive(NotificationCenter.default.publisher(for: NSApplication.willTerminateNotification)) { _ in reader.checkpoint() } + } +} + +private struct ManualBookmarksPopover: View { + @ObservedObject var reader: ManualReader + @ObservedObject var continuity: LibraryContinuityStore + let close: () -> Void + @State private var filter = "all" + @State private var renameID: UUID? + @State private var renameText = "" + + private var entries: [ManualBookmark] { + continuity.bookmarks.filter { filter != "book" || $0.bookID == reader.currentBookID } + .sorted { + if $0.bookID != $1.bookID { return order($0.bookID) < order($1.bookID) } + if let first = $0.position.readingOrder, let second = $1.position.readingOrder, first != second { return first < second } + let first = ($0.position.relativePath ?? "") + "#" + ($0.position.anchor ?? "") + let second = ($1.position.relativePath ?? "") + "#" + ($1.position.anchor ?? "") + return first.localizedStandardCompare(second) == .orderedAscending + } + } + private func order(_ id: String) -> String { + let books = ["meet-your-color-computer", "back-at-the-coco", "software-storage-and-peripherals", "users-handbook", "programming-in-coco-basic", "your-first-6809-programs", "assembly-language-programming", "programming-in-c", "inside-the-coco-3", "working-with-os9", "nitros9-on-vcc-plus", "vibe-coding-with-chatgpt"] + if let index = books.firstIndex(of: id) { return String(format: "%02d", index) } + return "99-" + id + } + var body: some View { + VStack(alignment: .leading, spacing: 10) { + Text("Bookmarks").font(.headline) + Picker("Bookmark scope", selection: $filter) { + Text("All Books").tag("all") + Text("This Book").tag("book").disabled(reader.currentBookID == nil) + }.pickerStyle(.segmented).accessibilityIdentifier("manual.bookmark-scope") + if let error = continuity.saveError { Text(error).font(.caption).foregroundStyle(.red) } + if entries.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Label("No bookmarks", systemImage: "bookmark").font(.headline) + Text("Use Bookmark This Location while reading a manual.") + .foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + } + .frame(maxWidth: .infinity, alignment: .leading) + .padding(.top, 12) + Spacer(minLength: 0) + } else { + List { + ForEach(Array(Set(entries.map(\.bookID))).sorted(by: { order($0) < order($1) }), id: \.self) { book in + Section(entries.first { $0.bookID == book }?.bookTitle ?? book) { + ForEach(entries.filter { $0.bookID == book }) { item in + HStack { + Button { + reader.openBookmark(item); close() + } label: { + VStack(alignment: .leading) { + Text(item.displayName).lineLimit(2) + Text(reader.bookmarkAvailable(item) ? item.sectionTitle : "Location changed — page unavailable") + .font(.caption).foregroundStyle(.secondary).lineLimit(2) + }.frame(maxWidth: .infinity, alignment: .leading) + }.buttonStyle(.plain) + .accessibilityIdentifier("manual.bookmark-open-" + item.id.uuidString) + Menu { + Button("Open") { reader.openBookmark(item); close() } + Button("Open Book") { reader.openBookmark(item, fromBookStart: true); close() } + Button("Rename…") { renameText = item.label ?? item.sectionTitle; renameID = item.id } + Button("Remove Bookmark", role: .destructive) { continuity.removeBookmark(item.id) } + } label: { Image(systemName: "ellipsis.circle") } + .menuStyle(.borderlessButton).fixedSize().accessibilityLabel("Bookmark actions for " + item.displayName) + .accessibilityIdentifier("manual.bookmark-actions-" + item.id.uuidString) + } + } + } + } + }.listStyle(.inset) + } + }.padding(12).frame(width: 400, height: 420, alignment: .topLeading) + .onAppear { + filter = continuity.browse(for: "manual-bookmark-ui")?.filters["scope"] ?? (reader.currentBookID == nil ? "all" : "book") + if reader.currentBookID == nil { filter = "all" } + } + .onChange(of: filter) { _, value in var state = LibraryBrowseState(); state.filters["scope"] = value; continuity.setBrowse(state, for: "manual-bookmark-ui") } + .onChange(of: reader.currentBookID) { _, value in if value == nil { filter = "all" } } + .alert("Rename Bookmark", isPresented: Binding(get: { renameID != nil }, set: { if !$0 { renameID = nil } })) { + TextField("Bookmark name", text: $renameText) + Button("Cancel", role: .cancel) { renameID = nil } + Button("Save") { if let renameID { continuity.renameBookmark(renameID, label: renameText) }; renameID = nil } } } } diff --git a/platforms/macos/App/SoftwareLibraryArtwork.swift b/platforms/macos/App/SoftwareLibraryArtwork.swift index 4f5d969..0bf6882 100644 --- a/platforms/macos/App/SoftwareLibraryArtwork.swift +++ b/platforms/macos/App/SoftwareLibraryArtwork.swift @@ -122,10 +122,10 @@ actor SoftwareLibraryArtworkCache { } static func canDisplay(_ asset: SoftwareLibraryAsset) -> Bool { - guard let url = asset.thumbnailURL, accepts(url), + guard let url = asset.thumbnailURL, accepts(url) || (asset.matchStatus == "personal" && url.isFileURL), let checksum = asset.thumbnailSHA256, checksum.count == 64, checksum.allSatisfy({ $0.isHexDigit }), - let size = asset.thumbnailByteSize, size > 0, size <= maximumThumbnailBytes else { return false } + let size = asset.thumbnailByteSize, size > 0, size <= (asset.matchStatus == "personal" ? Int64(maximumSourceBytes) : Int64(maximumThumbnailBytes)) else { return false } return true } @@ -165,6 +165,11 @@ actor SoftwareLibraryArtworkCache { } func thumbnail(for asset: SoftwareLibraryAsset, directory: URL) async throws -> Data { + if asset.matchStatus == "personal", let url = asset.thumbnailURL, url.isFileURL { + try SoftwareLibraryLocalAsset.validate(asset, url: url, maximumBytes: Int(Self.maximumSourceBytes)) + return try Self.downsample(Data(contentsOf: url), expectedSHA256: asset.thumbnailSHA256) + } + try Task.checkCancellation() guard Self.canDisplay(asset), let url = asset.thumbnailURL, let fingerprint = asset.thumbnailSHA256 else { throw Failure.unsupported } @@ -241,3 +246,35 @@ private final class LibraryArtworkRedirects: NSObject, URLSessionTaskDelegate { completionHandler(request.url.map(SoftwareLibraryArtworkCache.accepts) == true ? request : nil) } } + +/// Local assets are accepted only from a namespaced private entry's Assets tree. +/// The public catalog/cache URL allowlists remain unchanged. +enum SoftwareLibraryLocalAsset { + static func validate(_ asset: SoftwareLibraryAsset, url: URL, maximumBytes: Int) throws { + guard asset.matchStatus == "personal", url.isFileURL, url.host == nil || url.host == "localhost", + url.query == nil, url.fragment == nil, let expected = asset.sha256, + expected.count == 64, expected.allSatisfy(\.isHexDigit), let size = asset.byteSize, + size > 0, size <= maximumBytes else { throw SoftwareLibraryManualCache.Failure.unavailable } + let parts = url.standardizedFileURL.pathComponents + guard let index = parts.lastIndex(of: "PersonalLibrary"), parts.count > index + 3, + UUID(uuidString: parts[index + 1]) != nil, parts[index + 2] == "Assets", + asset.id.hasPrefix("personal:" + parts[index + 1].lowercased() + ":asset:") else { throw SoftwareLibraryManualCache.Failure.unavailable } + // System parent aliases such as /var are legitimate. The private + // library root and every component beneath it must be nonsymlink. + var checked = URL(fileURLWithPath: NSString.path(withComponents: Array(parts.prefix(index))), isDirectory: true) + for part in parts.dropFirst(index) { + checked.appendPathComponent(part) + guard try checked.resourceValues(forKeys: [.isSymbolicLinkKey]).isSymbolicLink != true else { throw SoftwareLibraryManualCache.Failure.unavailable } + } + let values = try url.resourceValues(forKeys: [.isRegularFileKey, .fileSizeKey]) + guard values.isRegularFile == true, values.fileSize == Int(size) else { throw SoftwareLibraryManualCache.Failure.changed } + let handle = try FileHandle(forReadingFrom: url); defer { try? handle.close() } + var hash = SHA256(), count = 0 + while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty { + try Task.checkCancellation(); count += block.count + guard count <= maximumBytes else { throw SoftwareLibraryManualCache.Failure.changed } + hash.update(data: block) + } + guard count == Int(size), hash.finalize().map({ String(format: "%02x", $0) }).joined() == expected.lowercased() else { throw SoftwareLibraryManualCache.Failure.changed } + } +} diff --git a/platforms/macos/App/SoftwareLibraryCatalog.swift b/platforms/macos/App/SoftwareLibraryCatalog.swift index b9be242..32c1cc4 100644 --- a/platforms/macos/App/SoftwareLibraryCatalog.swift +++ b/platforms/macos/App/SoftwareLibraryCatalog.swift @@ -234,6 +234,16 @@ struct SoftwareLibraryRelease: Identifiable, Codable, Sendable { } } try SoftwareLibraryOwnedGame.validateBrowseMetadata(metadata, optional: true) + if metadata["related_archive"] != .null { + guard metadata["related_archive_contract"].integer == 1, case .array(let references) = metadata["related_archive"], references.count <= 100 else { + throw SoftwareLibraryCatalog.Failure.invalid("unsupported related Archive document contract") + } + let parsed = try references.map(SoftwareLibraryRelatedReference.parse) + guard Set(parsed.map(\.id)).count == parsed.count, + Set(parsed.map { $0.documentID + ":" + String($0.page ?? 0) }).count == parsed.count else { + throw SoftwareLibraryCatalog.Failure.invalid("duplicate related Archive document relationship") + } + } } var publisher: String? { metadata["publisher"].string } var year: Int? { metadata["year"].integer } @@ -624,3 +634,46 @@ private extension Dictionary where Key == String, Value == String { return value } } + +/// Reviewed cross-library relationships are public metadata, never transport URLs. +struct SoftwareLibraryRelatedReference: Identifiable, Sendable { + let id: String + let title: String + let documentID: String + let sha256: String + let role: String + let page: Int? + let spoiler: Bool + let order: Int + static let roles = ["Guide", "Tutorial", "Reference", "Hints", "Walkthrough", "Solution", "Map"] + static func parse(_ json: LibraryJSON) throws -> Self { + guard let id = json["id"].string, !id.isEmpty, id.utf8.count <= 240, + let title = json["title"].string, !title.isEmpty, title.utf8.count <= 1000, + let document = json["document_id"].string, document.count == 64, document.allSatisfy(\.isHexDigit), + let sha = json["sha256"].string, sha == document, + let role = json["role"].string, roles.contains(role), + json["page"] == .null || (json["page"].integer ?? 0) > 0 else { + throw SoftwareLibraryCatalog.Failure.invalid("invalid related Archive document metadata") + } + return .init(id: id, title: title, documentID: document, sha256: sha, role: role, + page: json["page"].integer, spoiler: json["spoiler"] == .bool(true), order: json["order"].integer ?? 999) + } +} +extension SoftwareLibraryRelease { + var isDirectSubmission: Bool { metadata["origin"].string == "direct_submission" } + var isArchive: Bool { ownedGame == nil && !isPersonal && !isDirectSubmission } + var relatedArchiveReferences: [SoftwareLibraryRelatedReference] { + guard metadata["related_archive_contract"].integer == 1 else { return [] } + return metadata["related_archive"].array.compactMap { try? SoftwareLibraryRelatedReference.parse($0) }.sorted { + if $0.order != $1.order { return $0.order < $1.order } + let a = SoftwareLibraryRelatedReference.roles.firstIndex(of: $0.role) ?? 99 + let b = SoftwareLibraryRelatedReference.roles.firstIndex(of: $1.role) ?? 99 + if a != b { return a < b } + return $0.title.localizedStandardCompare($1.title) == .orderedAscending + } + } +} + +extension SoftwareLibraryRelease { + var isPersonal: Bool { metadata["personal"] == .bool(true) && titleID.hasPrefix("personal:") } +} diff --git a/platforms/macos/App/SoftwareLibraryLaunchPlan.swift b/platforms/macos/App/SoftwareLibraryLaunchPlan.swift index fcb469c..6746a51 100644 --- a/platforms/macos/App/SoftwareLibraryLaunchPlan.swift +++ b/platforms/macos/App/SoftwareLibraryLaunchPlan.swift @@ -5,7 +5,7 @@ import CryptoKit /// A bounded interpretation of catalog data, not executable host instructions. /// Preparation reads only the installed Working tree and never changes the machine. struct SoftwareLibraryLaunchPlan: Sendable { - enum Profile: String, Sendable { case diskBasic = "disk-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" } + enum Profile: String, Sendable { case diskBasic = "disk-basic", hardDriveBasic = "hard-drive-basic", romCartridge = "rom-cartridge", cocoSDC = "coco-sdc" } enum CartridgeDevice: String, Sendable { case rom, orchestra90 } struct Candidate: Identifiable, Equatable, Sendable { let path: String @@ -37,6 +37,7 @@ struct SoftwareLibraryLaunchPlan: Sendable { let controllerSlot: Int let cartridgeDevice: CartridgeDevice let floppyURLs: [Int: URL] + let hardDiskURLs: [Int: URL] let cassetteURL: URL? let cartridgeURL: URL? let sdcFolderURL: URL? @@ -46,13 +47,14 @@ struct SoftwareLibraryLaunchPlan: Sendable { let manualInstructions: String let compatibilityNotes: [String] let automaticallyStarts: Bool + let offersPlay: Bool let controls: LibraryJSON private let curatedStartup: SoftwareLibraryOwnedGame? var usesCuratedStartup: Bool { curatedStartup != nil } private static func supportsDisk(_ ext: String, profile: Profile) -> Bool { switch profile { - case .diskBasic: return DiskFiles.extensions.contains(ext) + case .diskBasic, .hardDriveBasic: return DiskFiles.extensions.contains(ext) case .cocoSDC: return ["dsk", "jvc", "os9"].contains(ext) case .romCartridge: return false } @@ -61,27 +63,43 @@ struct SoftwareLibraryLaunchPlan: Sendable { /// Presentation only: downloaded files still undergo full preparation before /// a restart is offered. Missing or ambiguous startup media remains Set Up. static func hasAutomaticStartup(for release: SoftwareLibraryRelease) -> Bool { + guard let profile = assignedMediaProfile(for: release) else { return false } + return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true + } + + /// Play opens a reviewed personal setup even when loading remains manual. + /// This does not claim that a guest program will start automatically. + static func hasPlayAction(for release: SoftwareLibraryRelease) -> Bool { + guard assignedMediaProfile(for: release) != nil else { return false } + return hasAutomaticStartup(for: release) || (release.isPersonal && + release.setup.configuration["personal_reviewed_setup"] == .bool(true)) + } + + private static func assignedMediaProfile(for release: SoftwareLibraryRelease) -> Profile? { guard let name = release.setup.configuration["profile"].string, let profile = Profile(rawValue: name), case .array(let members) = release.setup.selectedMembers, - !members.isEmpty, members.count <= 4 else { return false } - guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return false } + !members.isEmpty, members.count <= 4 else { return nil } + guard (try? recommendedCartridgeDevice(release.setup.configuration, profile: profile)) != nil else { return nil } var targets = Set() for member in members { guard let path = member["path"].string, validRelative(path), - let target = member["target"].string, targets.insert(target).inserted else { return false } + let target = member["target"].string, targets.insert(target).inserted else { return nil } let ext = (path as NSString).pathExtension.lowercased() switch profile { case .romCartridge: - guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return false } + guard members.count == 1, target == "cartridge", ["ccc", "rom"].contains(ext) else { return nil } + case .hardDriveBasic: + guard (["hard0", "hard1"].contains(target) && ["vhd", "os9", "img"].contains(ext)) || + (["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return nil } case .diskBasic: guard (target == "media" && ["cas", "wav"].contains(ext)) || - (["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return false } + (["disk0", "disk1", "disk2", "disk3"].contains(target) && Self.supportsDisk(ext, profile: profile)) else { return nil } case .cocoSDC: - guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return false } + guard ["disk0", "disk1"].contains(target), Self.supportsDisk(ext, profile: profile) else { return nil } } } - return profile == .romCartridge || decodeCommands(release.setup.command)?.contains(where: startsSoftware) == true + return profile } static func prepare(release: SoftwareLibraryRelease, receipt: SoftwareLibraryInstallationReceipt, @@ -136,9 +154,10 @@ struct SoftwareLibraryLaunchPlan: Sendable { let ext = (path as NSString).pathExtension.lowercased() let type: String? switch release.mediaType { - case "cartridge": type = ext == "ccc" ? "cartridge" : nil + case "cartridge": type = ["ccc", "rom"].contains(ext) ? "cartridge" : nil case "cassette": type = ["cas", "wav"].contains(ext) ? "cassette" : nil case "disk", "sdc": type = Self.supportsDisk(ext, profile: profile) ? "disk" : nil + case "hard-disk": type = profile == .hardDriveBasic && ["vhd", "os9", "img"].contains(ext) ? "hard-disk" : nil default: type = nil } return type.map { Candidate(path: path, mediaType: $0) } @@ -150,10 +169,10 @@ struct SoftwareLibraryLaunchPlan: Sendable { } else if candidates.count == 1 { choice = candidates[0] } else if !candidates.isEmpty { throw Failure.needsSelection(candidates) } else { throw Failure.unsupported("No supported startup media has been identified for this edition. Open its installed files and use the loading notes to configure it manually.") } - selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : "disk0", choice.path)] + selected = [(choice.mediaType == "cartridge" ? "cartridge" : choice.mediaType == "cassette" ? "media" : choice.mediaType == "hard-disk" ? "hard0" : "disk0", choice.path)] } else if selectedMember != nil { throw Failure.invalidRecipe("This edition already identifies its startup media.") } - guard selected.count <= 4, Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") } - var floppies: [Int: URL] = [:] + guard selected.count <= (release.isPersonal ? 8 : 4), Set(selected.map(\.target)).count == selected.count else { throw Failure.invalidRecipe("Conflicting startup media assignments.") } + var floppies: [Int: URL] = [:], hardDisks: [Int: URL] = [:] var cassette: URL?, cartridge: URL? var selectedSDC: [Int: URL] = [:] for member in selected { @@ -166,6 +185,12 @@ struct SoftwareLibraryLaunchPlan: Sendable { case "media": guard profile == .diskBasic, ["cas", "wav"].contains(ext) else { throw Failure.invalidRecipe("The selected file is not a supported cassette.") } cassette = url + case "hard0", "hard1": + guard profile == .hardDriveBasic, ["vhd", "os9", "img"].contains(ext), let drive = Int(member.target.suffix(1)) else { + throw Failure.invalidRecipe("Choose a supported raw hard-disk image for HD0 or HD1.") + } + _ = try HardDiskFiles.readImage(url) + hardDisks[drive] = url case "disk0", "disk1", "disk2", "disk3": guard Self.supportsDisk(ext, profile: profile), let drive = Int(member.target.suffix(1)) else { throw Failure.invalidRecipe("Unsupported disk assignment.") } @@ -197,7 +222,8 @@ struct SoftwareLibraryLaunchPlan: Sendable { } let decoded = members.isEmpty ? nil : decodeCommands(release.setup.command) let canStart = cartridge != nil || (decoded?.contains(where: startsSoftware) == true) - var commands = canStart ? (decoded ?? []) : [] + let offersPlay = canStart || Self.hasPlayAction(for: release) + var commands = offersPlay ? (decoded ?? []) : [] // Mounting an image is separate from executing its program. Manual SDC // editions still get their chosen image mounted before guidance appears. if sdcFolder != nil { @@ -205,16 +231,16 @@ struct SoftwareLibraryLaunchPlan: Sendable { } var instructions = release.setup.instructions.trimmingCharacters(in: .whitespacesAndNewlines) if instructions.isEmpty { instructions = "The selected media is mounted. Follow its manual or directory listing to choose a program; no startup command has been established." } - if !canStart, let command = release.setup.command, !command.isEmpty { + if !canStart && (!offersPlay || decoded == nil), let command = release.setup.command, !command.isEmpty { instructions += "\n\nThe catalog’s loading sequence needs manual entry. Review it before typing: " + command.replacingOccurrences(of: "\\r", with: " → ") } return Self(workingDirectory: root, canonicalWorkingDirectory: root.resolvingSymlinksInPath(), releaseID: release.id, title: release.metadata["title"].string ?? release.name, profile: profile, use6309: cpu == "6309", ramKiB: ram, ramIndex: ramIndex, - videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, cassetteURL: cassette, + videoOutput: video, controllerSlot: slot, cartridgeDevice: cartridgeDevice, floppyURLs: floppies, hardDiskURLs: hardDisks, cassetteURL: cassette, cartridgeURL: cartridge, sdcFolderURL: sdcFolder, sdcInitialImages: sdcNames, commands: commands, manualInstructions: instructions, compatibilityNotes: release.setup.compatibilityNotes + release.setup.configurationRequirements, - automaticallyStarts: canStart, controls: release.setup.controls, + automaticallyStarts: canStart, offersPlay: offersPlay, controls: release.setup.controls, curatedStartup: release.ownedGame.flatMap { $0.firstPlayColdDOS ? $0 : nil }) } @@ -241,7 +267,7 @@ struct SoftwareLibraryLaunchPlan: Sendable { throw Failure.invalidRecipe("The original game disk no longer matches its verified startup recipe. Your working files are kept.") } } - for url in Array(floppyURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) { + for url in Array(floppyURLs.values) + Array(hardDiskURLs.values) + [cassetteURL, cartridgeURL].compactMap({ $0 }) { guard url.path.hasPrefix(workingDirectory.path + "/") else { throw Failure.unsafeMedia(url.lastPathComponent) } _ = try Self.file(String(url.path.dropFirst(workingDirectory.path.count + 1)), root: workingDirectory) } @@ -323,8 +349,14 @@ struct SoftwareLibraryLaunchPlan: Sendable { guard let parts = statements(line) else { return false } let number = "(?:[0-9]+|&H[0-9A-F]+)" let filename = "\\\"[^\\\"\\\\]{1,64}\\\"" + // Disk BASIC's ordinary LOAD replaces the BASIC program and discards + // the rest of that command line. RUN must be delivered on a new line. + let programLoad = "LOAD *" + filename + guard !parts.dropLast().contains(where: { + $0.range(of: "^(?:" + programLoad + ")$", options: [.regularExpression, .caseInsensitive]) != nil + }) else { return false } let patterns = ["(?:CLOADM?|RUN)(?: *" + filename + ")?", "LOADM *" + filename, - "LOAD *" + filename + " *, *R", "LOAD +CHR\\$\\(42\\) *, *R", + programLoad + "(?: *, *R)?", "LOAD +CHR\\$\\(42\\) *, *R", "EXEC(?: *" + number + ")?", "DOS(?: +[0-9]+)?", "DIR(?: +[0-3])?", "PCLEAR *[0-9]+", "CLEAR *" + number + "(?: *, *" + number + ")?", "POKE *" + number + " *, *" + number, "NEW"] diff --git a/platforms/macos/App/SoftwareLibraryLaunchView.swift b/platforms/macos/App/SoftwareLibraryLaunchView.swift index 532f375..abd7525 100644 --- a/platforms/macos/App/SoftwareLibraryLaunchView.swift +++ b/platforms/macos/App/SoftwareLibraryLaunchView.swift @@ -10,13 +10,14 @@ struct SoftwareLibraryLaunchPreviewView: View { private var setupName: String { switch plan.profile { case .diskBasic: return "Disk BASIC" + case .hardDriveBasic: return "Hard-drive BASIC" case .romCartridge: return plan.cartridgeDevice == .orchestra90 ? "Orchestra-90" : "ROM Cartridge" case .cocoSDC: return "CoCo SDC" } } var body: some View { VStack(alignment: .leading, spacing: 18) { - Label(plan.automaticallyStarts ? "Start Software" : "Set Up Software", systemImage: "play.rectangle") + Label(plan.automaticallyStarts ? "Start Software" : plan.offersPlay ? "Play Software" : "Set Up Software", systemImage: "play.rectangle") .font(.title2.weight(.semibold)) Text(plan.title).font(.title3.weight(.medium)) ScrollView { @@ -42,14 +43,24 @@ struct SoftwareLibraryLaunchPreviewView: View { ForEach(plan.floppyURLs.keys.sorted(), id: \.self) { drive in LabeledContent("FD\(drive)", value: plan.floppyURLs[drive]!.lastPathComponent) } + ForEach(plan.hardDiskURLs.keys.sorted(), id: \.self) { drive in + LabeledContent("HD\(drive)", value: plan.hardDiskURLs[drive]!.lastPathComponent) + } if let folder = plan.sdcFolderURL { Label("SD card folder: " + folder.lastPathComponent, systemImage: "sdcard") } if !plan.compatibilityNotes.isEmpty { Text(plan.compatibilityNotes.joined(separator: "\n\n")).font(.callout).foregroundStyle(.secondary) } if !plan.automaticallyStarts { Label("Manual loading", systemImage: "keyboard").font(.headline) + if plan.offersPlay { + Text(plan.commands.isEmpty + ? "The CoCo will run with the selected media mounted. Load the program yourself; no loading commands will be typed automatically." + : "The CoCo will run with the selected media mounted and enter the commands below. Start the program yourself if those commands do not run it.") + .font(.callout) + } Text(plan.manualInstructions).font(.callout).textSelection(.enabled) - } else if !plan.commands.isEmpty { + } + if !plan.commands.isEmpty { DisclosureGroup("Loading commands") { Text(plan.commands.joined(separator: "\n")).font(.system(.callout, design: .monospaced)).textSelection(.enabled) } @@ -64,7 +75,7 @@ struct SoftwareLibraryLaunchPreviewView: View { HStack { Button("Cancel", role: .cancel, action: cancel).keyboardShortcut(.cancelAction).accessibilityIdentifier("library-cancel-play") Spacer() - Button(plan.automaticallyStarts ? "Start" : "Set Up", action: confirm) + Button(plan.automaticallyStarts ? "Start" : plan.offersPlay ? "Play" : "Set Up", action: confirm) .buttonStyle(.borderedProminent).keyboardShortcut(.defaultAction).accessibilityIdentifier("library-confirm-play") } }.padding(24).frame(width: 490) @@ -98,3 +109,33 @@ struct SoftwareLibraryMediaChoiceView: View { }.padding(24).frame(width: 520) } } + +#if !VCC_COMPANION_CLIENT +struct SoftwareLibraryPersonalPresentation: ViewModifier { + @ObservedObject var model: SoftwareLibraryModel + func body(content: Content) -> some View { + content + .sheet(item: $model.personalEditor, onDismiss: { model.cancelPersonalEdit() }) { entry in + PersonalSoftwareEditor(entry: entry, unsupported: model.personalUnsupported, isImport: model.isPersonalImport, + saving: model.personalSaving, error: model.personalError, duplicateID: model.personalDuplicateID, + save: { model.savePersonal($0, coverPNG: $1, allowDuplicate: $2) }, openExisting: model.openExistingPersonal, + previewCover: model.personalCoverPreview, + cancel: model.cancelPersonalEdit) + } + .safeAreaInset(edge: .bottom) { + if model.personalInspecting { + HStack { ProgressView().controlSize(.small); Text("Preparing a private import preview…"); Spacer(); Button("Cancel", role: .cancel) { model.cancelPersonalInspection() } }.padding(10) + } else if model.personalEditor == nil, let error = model.personalError { + Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) + .textSelection(.enabled).frame(maxWidth: .infinity, alignment: .leading).padding(10) + } + } + } +} +#else +import SwiftUI +struct SoftwareLibraryPersonalPresentation: ViewModifier { + let model: SoftwareLibraryModel + func body(content: Content) -> some View { content } +} +#endif diff --git a/platforms/macos/App/SoftwareLibraryManual.swift b/platforms/macos/App/SoftwareLibraryManual.swift index 824f8b0..eca43fd 100644 --- a/platforms/macos/App/SoftwareLibraryManual.swift +++ b/platforms/macos/App/SoftwareLibraryManual.swift @@ -105,8 +105,15 @@ final class SoftwareLibraryManualModel: ObservableObject { private var task: Task? private var directory: URL? private var companion: (any CompanionLibraryAccess)? + #if !VCC_COMPANION_CLIENT + var continuity: LibraryContinuityStore? + #endif + private var positionTracking: [NSObjectProtocol] = [] + private var lastPositionSave = Date.distantPast + private var restoringPosition = false func open(_ asset: SoftwareLibraryAsset, directory: URL, companion: (any CompanionLibraryAccess)? = nil) { if self.asset?.id == asset.id && (document != nil || text != nil) { return } + saveReadingPosition(force: true) task?.cancel(); self.asset = asset; self.directory = directory; self.companion = companion document = nil; pdfView.document = nil; text = nil; textView.string = ""; page = 1; searchText = ""; searchMessage = ""; error = nil; loading = true task = Task { @@ -124,11 +131,16 @@ final class SoftwareLibraryManualModel: ObservableObject { let size = values.fileSize, size > 0, size <= 64 * 1024 * 1024 else { throw SoftwareLibraryManualCache.Failure.response } }.value local = shared + } else if asset.matchStatus == "personal", let url = asset.manualURL, url.isFileURL { + local = try await Task.detached(priority: .userInitiated) { + try SoftwareLibraryLocalAsset.validate(asset, url: url, maximumBytes: url.pathExtension.lowercased() == "txt" ? 1024 * 1024 : 512 * 1024 * 1024) + return url + }.value } else { local = try await SoftwareLibraryManualCache.shared.localCopy(for: asset, directory: directory) } try Task.checkCancellation() - if local.pathExtension == "txt" { + if local.pathExtension.lowercased() == "txt" { let bytes = try await Task.detached(priority: .userInitiated) { try Data(contentsOf: local) }.value try Task.checkCancellation() let decoded = try Self.decodeText(bytes) @@ -142,7 +154,7 @@ final class SoftwareLibraryManualModel: ObservableObject { catch { self.error = error.localizedDescription; loading = false } } } - func cancel() { task?.cancel(); loading = false } + func cancel() { saveReadingPosition(force: true); task?.cancel(); loading = false; stopPositionTracking() } func retry() { if let asset, let directory { open(asset, directory: directory, companion: companion) } } func goToPage() { guard let document else { return } @@ -156,6 +168,70 @@ final class SoftwareLibraryManualModel: ObservableObject { if let selection { pdfView.setCurrentSelection(selection, animate: false); pdfView.go(to: selection); searchMessage = "" } else { searchMessage = "No matching text. Scanned pages may not contain searchable text." } } + func stopPositionTracking() { + for token in positionTracking { NotificationCenter.default.removeObserver(token) } + positionTracking = [] + } + func restoreReadingPosition() { + #if !VCC_COMPANION_CLIENT + guard companion == nil, let asset, let continuity else { return } + let identity = asset.id + let saved = continuity.reading(for: "software-manual:" + identity) + restoringPosition = true + DispatchQueue.main.async { [weak self] in + guard let self, self.asset?.id == identity else { return } + defer { self.restoringPosition = false; self.trackReadingPosition() } + if let saved, let document = self.document { + let index = min(max(0,saved.page-1),document.pageCount-1) + self.page = index+1 + if let page = document.page(at: index) { + self.pdfView.autoScales = saved.autoScales ?? true + if saved.autoScales == false, let zoom = saved.zoom { self.pdfView.scaleFactor = min(10,max(0.1,zoom)) } + let bounds = page.bounds(for: self.pdfView.displayBox) + self.pdfView.go(to: PDFDestination(page: page, at: CGPoint(x: bounds.minX + bounds.width * saved.horizontalOffset, + y: bounds.minY + bounds.height * saved.offset))) + } + } else if let saved, let clip = self.textView.enclosingScrollView?.contentView { + let height = max(0,self.textView.bounds.height - clip.bounds.height) + clip.scroll(to: NSPoint(x: 0,y: height * saved.offset)) + self.textView.enclosingScrollView?.reflectScrolledClipView(clip) + } + } + #endif + } + private func trackReadingPosition() { + stopPositionTracking() + for name in [Notification.Name.PDFViewPageChanged, .PDFViewScaleChanged] { + positionTracking.append(NotificationCenter.default.addObserver(forName: name, object: pdfView, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in self?.saveReadingPosition(force: true) } + }) + } + let clip = document == nil ? textView.enclosingScrollView?.contentView : pdfView.documentView?.enclosingScrollView?.contentView + if let clip { + clip.postsBoundsChangedNotifications = true + positionTracking.append(NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, object: clip, queue: .main) { [weak self] _ in + Task { @MainActor [weak self] in self?.saveReadingPosition() } + }) + } + } + func saveReadingPosition(force: Bool = false) { + #if !VCC_COMPANION_CLIENT + guard !restoringPosition, companion == nil, let asset, let continuity, document != nil || text != nil, + force || Date().timeIntervalSince(lastPositionSave) >= 1 else { return } + lastPositionSave = Date() + var position = LibraryReadingPosition(documentID: asset.id,page: page) + if let document, let destination = pdfView.currentDestination, let current = destination.page { + position.page = document.index(for: current)+1 + let bounds = current.bounds(for: pdfView.displayBox) + position.offset = bounds.height > 0 ? min(1,max(0,(destination.point.y-bounds.minY)/bounds.height)) : 0 + position.horizontalOffset = bounds.width > 0 ? min(1,max(0,(destination.point.x-bounds.minX)/bounds.width)) : 0 + position.zoom = pdfView.scaleFactor; position.autoScales = pdfView.autoScales + } else if let clip = textView.enclosingScrollView?.contentView { + position.offset = min(1,max(0,clip.bounds.minY / max(1,textView.bounds.height - clip.bounds.height))) + } + continuity.setReading(position, for: "software-manual:" + asset.id) + #endif + } } struct SoftwareLibraryManualView: View { @@ -192,10 +268,10 @@ struct SoftwareLibraryManualView: View { if model.document != nil { HStack(spacing: 0) { if showPages { ManualPages(view: model.pdfView).frame(width: 115) } - ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf") + ManualPDF(view: model.pdfView).accessibilityIdentifier("manual-pdf").onAppear { model.restoreReadingPosition() } } } else if model.text != nil { - ManualText(view: model.textView).accessibilityIdentifier("manual-text") + ManualText(view: model.textView).accessibilityIdentifier("manual-text").onAppear { model.restoreReadingPosition() } } else if model.loading { VStack(spacing: 12) { ProgressView("Downloading manual…"); Button("Cancel") { model.cancel() } }.frame(maxWidth: .infinity, maxHeight: .infinity) } else { @@ -211,12 +287,14 @@ struct SoftwareLibraryManualView: View { HStack { Text(model.asset?.credit ?? "Manual preserved by Color Computer Archive").foregroundStyle(.secondary) Spacer() - if let asset = model.asset { Link(asset.matchStatus == "project-owned" ? "Project source" : "Archive source", destination: asset.sourceURL) } + if let asset = model.asset, asset.matchStatus != "personal" { Link(asset.sourceURL.host?.lowercased() == "colorcomputerarchive.com" ? "Archive source" : "Project source", destination: asset.sourceURL) } + else if model.asset?.matchStatus == "personal" { Text("Private — On This Mac").foregroundStyle(.secondary) } } }.font(.caption).padding(10) }.frame(minWidth: 620, minHeight: 480) .onReceive(NotificationCenter.default.publisher(for: .PDFViewPageChanged, object: model.pdfView)) { _ in if let page = model.pdfView.currentPage, let document = model.document { model.page = document.index(for: page) + 1 } + model.saveReadingPosition(force: true) } .onDisappear { model.cancel() } } diff --git a/platforms/macos/App/SoftwareLibraryModel.swift b/platforms/macos/App/SoftwareLibraryModel.swift index 9048c4f..eee9ebb 100644 --- a/platforms/macos/App/SoftwareLibraryModel.swift +++ b/platforms/macos/App/SoftwareLibraryModel.swift @@ -2,6 +2,7 @@ import Foundation import Combine import AppKit +import UniformTypeIdentifiers #if !VCC_COMPANION_CLIENT /// Native review stays attached to its window and cannot strand shutdown on a @@ -49,9 +50,9 @@ struct LibraryCategory: Identifiable, Sendable { } } -struct LibraryBrowseQuery: Equatable, Sendable { - enum Scope: String, CaseIterable { case showcase, started, all, favorites, installed } - enum Sort: String, CaseIterable { case title = "Title", modified = "Last Modified", size = "Download Size" } +struct LibraryBrowseQuery: Equatable, Sendable, Codable { + enum Scope: String, CaseIterable, Codable { case showcase, started, all, favorites, installed, personal, search } + enum Sort: String, CaseIterable, Codable { case title = "Title", modified = "Last Modified", size = "Download Size" } var scope: Scope = .started var text = "" var category = "" @@ -129,6 +130,11 @@ struct LibraryBrowseQuery: Equatable, Sendable { } func apply(to titles: [SoftwareLibraryTitle], favorites: Set, installed: Set) -> [LibraryBrowseRow] { var rows = titles.compactMap { title -> LibraryBrowseRow? in + let personal = title.id.hasPrefix("personal:") + if scope == .personal && !personal { return nil } + // Getting Started and Cover Collection remain curated catalog + // views. General browsing/search can combine local and public data. + if personal && (scope == .started || scope == .showcase || scope == .installed) { return nil } if scope == .favorites && !favorites.contains(title.id) { return nil } let matches = title.releases.filter { (scope != .started || Self.isGettingStarted($0)) && @@ -139,11 +145,12 @@ struct LibraryBrowseQuery: Equatable, Sendable { return LibraryBrowseRow(title: title, matchingReleases: matches) } rows.sort { a, b in + if a.isPersonal != b.isPersonal { return a.isPersonal } let featuredGrouping = !category.isEmpty || !softwareType.isEmpty let aFeatured = featuredGrouping && a.categoryFeatured let bFeatured = featuredGrouping && b.categoryFeatured if aFeatured != bFeatured { return aFeatured } - switch aFeatured ? .title : sort { + switch a.isPersonal || aFeatured ? .title : sort { case .modified: let av = a.matchingReleases.compactMap(\.modifiedAt).max() ?? "" let bv = b.matchingReleases.compactMap(\.modifiedAt).max() ?? "" @@ -164,6 +171,7 @@ struct LibraryBrowseRow: Identifiable, Sendable { let title: SoftwareLibraryTitle let matchingReleases: [SoftwareLibraryRelease] var id: String { title.id } + var isPersonal: Bool { title.id.hasPrefix("personal:") && matchingReleases.contains(where: \.isPersonal) } var name: String { title.name } var categoryFeatured: Bool { matchingReleases.contains(where: \.categoryFeatured) } var formats: String { Set(matchingReleases.map(\.mediaLabel)).sorted().joined(separator: ", ") } @@ -197,14 +205,28 @@ final class SoftwareLibraryModel: ObservableObject { @Published private(set) var loading = false @Published private(set) var filtering = false @Published private(set) var error: String? - @Published var query = LibraryBrowseQuery() { didSet { if query != oldValue { filter() } } } - @Published var selection: String? - @Published var layout = "Shelf" + @Published var query = LibraryBrowseQuery() { didSet { if query != oldValue { saveBrowseContext(); filter() } } } + @Published var selection: String? { didSet { if selection != oldValue { saveBrowseContext() } } } + @Published var layout = "Shelf" { didSet { if layout != oldValue { saveBrowseContext() } } } + private(set) var browseTopID: String? + private(set) var browseOffset: Double = 0 + private var restoredBrowse = false + private var restoringBrowse = false let companionAccess: (any CompanionLibraryAccess)? private let insertCompanionDisk: ((URL) async throws -> Void)? #if !VCC_COMPANION_CLIENT let installer: SoftwareLibraryInstaller let machine: MachineModel? + private let browseContinuity: LibraryContinuityStore + lazy var personalStore = PersonalSoftwareLibraryStore(root: state.directory.appendingPathComponent("PersonalLibrary", isDirectory: true)) + @Published private(set) var personalEntries: [PersonalSoftwareEntry] = [] + @Published var personalEditor: PersonalSoftwareEntry? + @Published private(set) var personalInspecting = false + @Published private(set) var personalSaving = false + @Published private(set) var personalError: String? + @Published private(set) var personalDuplicateID: UUID? + private var personalDraft: PersonalSoftwareDraft? + private var personalTask: Task? private let sourceImporter: SoftwareLibrarySourceImporter private let sourceWorkspaceIdentity: (() -> UUID)? private let openSourceProject: ((URL, UUID, String?) async throws -> Bool)? @@ -239,11 +261,13 @@ final class SoftwareLibraryModel: ObservableObject { private var generation = 0 private var subscriptions: Set = [] #if !VCC_COMPANION_CLIENT - init(state: SoftwareLibraryState, artworkDirectory: URL? = nil, machine: MachineModel? = nil, + init(state: SoftwareLibraryState, continuity: LibraryContinuityStore? = nil, artworkDirectory: URL? = nil, machine: MachineModel? = nil, sourceWorkspaceIdentity: (() -> UUID)? = nil, openSourceProject: ((URL, UUID, String?) async throws -> Bool)? = nil) { companionAccess = nil; insertCompanionDisk = nil self.state = state + browseContinuity = continuity ?? LibraryContinuityStore(directory: state.directory) + manual.continuity = browseContinuity self.machine = machine self.sourceWorkspaceIdentity = sourceWorkspaceIdentity; self.openSourceProject = openSourceProject #if VCC_UI_TESTING @@ -277,6 +301,7 @@ final class SoftwareLibraryModel: ObservableObject { state = SoftwareLibraryState(companion: companion) artworkDirectory = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCompanionPresentation") #if !VCC_COMPANION_CLIENT + browseContinuity = LibraryContinuityStore(directory: state.directory) machine = nil; installer = SoftwareLibraryInstaller(root: state.directory) sourceWorkspaceIdentity = nil; openSourceProject = nil sourceImporter = SoftwareLibrarySourceImporter(cacheDirectory: state.directory.appendingPathComponent("SourcePackages")) @@ -373,7 +398,7 @@ final class SoftwareLibraryModel: ObservableObject { if isDiskCompanion { return installed ? "Insert Disk…" : "Download & Insert…" } #if !VCC_COMPANION_CLIENT if release.ownedGame?.firstPlayColdDOS == true { return installed ? "Play" : "Download & Play" } - return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) + return SoftwareLibraryLaunchPlan.hasPlayAction(for: release) ? (installed ? "Play…" : "Download & Play…") : (installed ? "Set Up…" : "Download & Set Up…") #else return "Insert Disk…" @@ -382,7 +407,7 @@ final class SoftwareLibraryModel: ObservableObject { func launchSymbol(_ release: SoftwareLibraryRelease) -> String { if isDiskCompanion { return "externaldrive" } #if !VCC_COMPANION_CLIENT - return SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release) ? "play.fill" : "desktopcomputer" + return SoftwareLibraryLaunchPlan.hasPlayAction(for: release) ? "play.fill" : "desktopcomputer" #else return "externaldrive" #endif @@ -392,11 +417,17 @@ final class SoftwareLibraryModel: ObservableObject { machine?.focusDisplay() #endif } - func load(from url: URL? = SoftwareLibraryCatalog.bundledURL()) async { + func load(from url: URL? = SoftwareLibraryCatalog.bundledURL(), + catalogLoader: @Sendable (URL) async throws -> SoftwareLibraryCatalog = { try await SoftwareLibraryCatalog.load(from: $0) }) async { guard catalog == nil, !loading else { return } + // Restoration may schedule a filter before recovered installations, + // private entries or the catalog arrive. Reconcile selection only once + // that complete initial result is available, preserving newer user input. loading = true; error = nil + restoreBrowseContext() + defer { loading = false; filter() } if let companionAccess { - defer { loading = false; recoveringInstallations = false } + defer { recoveringInstallations = false } do { let response = try await companionAccess.libraryRequest(.init(operation: .snapshot)) try acceptCompanion(response) @@ -406,21 +437,21 @@ final class SoftwareLibraryModel: ObservableObject { } #if !VCC_COMPANION_CLIENT await refreshInstallations() + await refreshPersonalEntries() #if VCC_UI_TESTING if SoftwareLibraryInstallFixture.enabled { catalog = SoftwareLibraryInstallFixture.catalog categories = LibraryCategory.tree(catalog!.categories) updateSoftwareTypes(catalog!) query.scope = .all - filter(); loading = false; return + filter(); return } #endif do { guard let url else { throw SoftwareLibraryCatalog.Failure.missing } - let snapshot = try await SoftwareLibraryCatalog.load(from: url) + let snapshot = try await catalogLoader(url) catalog = snapshot; categories = LibraryCategory.tree(snapshot.categories); updateSoftwareTypes(snapshot); filter() } catch { self.error = error.localizedDescription } - loading = false #endif } private func acceptCompanion(_ response: CompanionLibraryResponse) throws { @@ -464,8 +495,25 @@ final class SoftwareLibraryModel: ObservableObject { next.scope = scope; next.category = category; next.softwareType = "" query = next } - private func updateSoftwareTypes(_ catalog: SoftwareLibraryCatalog) { - softwareTypes = Array(Set(catalog.titles.flatMap { title in title.releases.flatMap { LibraryBrowseQuery.types(of: $0, related: title.releases) } })).sorted() + /// The header is a global search entry point, not an implicit filter of + /// whichever narrow collection happened to be selected before typing. + func setSearchText(_ text: String) { + guard text != query.text else { return } + if !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty && query.scope != .search { + query = LibraryBrowseQuery(scope: .search, text: text, sort: query.sort) + } else { + var next = query + next.text = text + if text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, next.scope == .search { next.scope = .all } + query = next + } + } + private func updateSoftwareTypes(_ catalog: SoftwareLibraryCatalog?) { + var types = Set(catalog?.titles.flatMap { title in title.releases.flatMap { LibraryBrowseQuery.types(of: $0, related: title.releases) } } ?? []) + #if !VCC_COMPANION_CLIENT + if !isDiskCompanion { types.formUnion(personalEntries.map { PersonalSoftwareEntry.standardCategory($0.category) }) } + #endif + softwareTypes = types.sorted() } func browseType(_ type: String) { var next = query @@ -479,6 +527,13 @@ final class SoftwareLibraryModel: ObservableObject { query = next } func install(_ release: SoftwareLibraryRelease, playAfter: Bool = false) { + #if !VCC_COMPANION_CLIENT + if release.isPersonal && !isDiskCompanion { + guard playAfter, let entry = personalEntries.first(where: { $0.releaseID == release.id }), !launchBusy, !hasPendingLaunch else { return } + personalTask = Task { await prepareLaunch(release, receipt: entry.receipt(in: await personalStore.directory(for: entry.id))) } + return + } + #endif guard installingReleaseID == nil, !recoveringInstallations, !launchBusy, !hasPendingLaunch else { return } if companionAccess != nil { installCompanion(release, insertAfter: playAfter); return } #if !VCC_COMPANION_CLIENT @@ -510,6 +565,10 @@ final class SoftwareLibraryModel: ObservableObject { } } func shutdown() async { + #if !VCC_COMPANION_CLIENT + personalTask?.cancel(); await personalTask?.value + if let draft = personalDraft { await personalStore.cancel(draft.id) } + #endif sourceImportTask?.cancel() await sourceImportTask?.value launchTask?.cancel() @@ -517,8 +576,14 @@ final class SoftwareLibraryModel: ObservableObject { cancelInstallation() await installationTask?.value await state.flush() + #if !VCC_COMPANION_CLIENT + await browseContinuity.flush() + #endif } func removeInstallation(_ id: String) async { + #if !VCC_COMPANION_CLIENT + if let entry = personalEntries.first(where: { $0.releaseID == id }) { removePersonal(entry); return } + #endif guard installingReleaseID == nil, !launchBusy, !hasPendingLaunch else { return } if let companionAccess { do { try acceptCompanion(try await companionAccess.libraryRequest(.init(operation: .removeInstallation, releaseID: id))) } @@ -687,19 +752,212 @@ final class SoftwareLibraryModel: ObservableObject { launchMessage = "The disk is inserted. Follow the loading instructions on your CoCo." } catch { if !Task.isCancelled { launchError = error.localizedDescription } } } + /// A presentation/permissioned-local-connection snapshot. The prepared + /// public catalog remains unchanged; private entries keep separate IDs. + var combinedCatalog: SoftwareLibraryCatalog { + var titles = catalog?.titles ?? [] + #if !VCC_COMPANION_CLIENT + if !isDiskCompanion { + titles += personalEntries.map { entry in + let directory = personalDirectory(entry) + return SoftwareLibraryTitle(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [entry.release(in: directory)]) + } + } + #endif + return SoftwareLibraryCatalog(titles: titles, metadata: catalog?.metadata ?? [:]) + } private func filter() { - guard let catalog else { return } + let titles = combinedCatalog.titles task?.cancel(); generation += 1; let version = generation let query = query, favorites = state.favoriteTitleIDs, installed = Set(state.installedReleases.keys) + let sourceTitles = titles filtering = true task = Task { // Debounce typing without blocking the machine's UI or audio queues. do { try await Task.sleep(nanoseconds: 90_000_000) } catch { return } - let worker = Task.detached(priority: .userInitiated) { query.apply(to: catalog.titles, favorites: favorites, installed: installed) } + let worker = Task.detached(priority: .userInitiated) { query.apply(to: sourceTitles, favorites: favorites, installed: installed) } let result = await worker.value guard !Task.isCancelled, version == generation else { return } rows = result; filtering = false - if !rows.contains(where: { $0.id == selection }) { selection = rows.first?.id } + // A failed public-catalog read is not evidence that a saved public + // title disappeared. Keep it pending for Retry; private-only browsing + // can still reconcile against the successfully recovered local set. + let selectionDomainAvailable = catalog != nil || query.scope == .personal || + selection?.hasPrefix("personal:") == true || (selection == nil && !rows.isEmpty) + if !loading, selectionDomainAvailable, !rows.contains(where: { $0.id == selection }) { selection = rows.first?.id } } } } + +#if !VCC_COMPANION_CLIENT +extension SoftwareLibraryModel { + var personalUnsupported: [String] { personalDraft?.unsupported ?? [] } + var isPersonalImport: Bool { personalDraft != nil } + var canEditPersonal: Bool { !isDiskCompanion && !personalInspecting && !personalSaving } + var selectedPersonalEntry: PersonalSoftwareEntry? { personalEntries.first { $0.titleID == selection } } + func choosePersonalSoftware() { + guard canEditPersonal, personalEditor == nil else { return } + let panel = NSOpenPanel() + panel.title = "Add Personal Software"; panel.prompt = "Review Files" + // The native panel sizes its message horizontally. Keep each line short + // so guidance does not force an excessively wide file chooser. + panel.message = "Choose a folder, ZIP, or CoCo media files.\nOriginals stay untouched. Nothing is uploaded or run." + panel.canChooseFiles = true; panel.canChooseDirectories = true; panel.allowsMultipleSelection = true + panel.begin { [weak self] response in + guard response == .OK, !panel.urls.isEmpty, let self else { return } + self.personalInspecting = true; self.personalError = nil + self.personalTask = Task { + defer { self.personalInspecting = false; self.personalTask = nil } + do { + let draft = try await self.personalStore.inspect(panel.urls) + if Task.isCancelled { await self.personalStore.cancel(draft.id); throw CancellationError() } + self.personalDraft = draft; self.personalEditor = draft.entry; self.personalDuplicateID = nil + } catch is CancellationError { } + catch { self.personalError = error.localizedDescription } + } + } + } + func cancelPersonalInspection() { if personalInspecting { personalTask?.cancel() } } + func editPersonal(_ entry: PersonalSoftwareEntry) { + guard canEditPersonal, personalEditor == nil else { return } + personalDraft = nil; personalError = nil; personalDuplicateID = nil; personalEditor = entry + } + func savePersonal(_ entry: PersonalSoftwareEntry, coverPNG: Data? = nil, allowDuplicate: Bool) { + guard !personalSaving else { return } + personalSaving = true; personalError = nil; personalDuplicateID = nil + personalTask = Task { + defer { personalSaving = false; personalTask = nil } + do { + if var draft = personalDraft { + draft.entry = entry + _ = try await personalStore.save(draft, allowDuplicate: allowDuplicate, coverPNG: coverPNG) + } else { try await personalStore.update(entry, coverPNG: coverPNG) } + personalDraft = nil; personalEditor = nil + await refreshPersonalEntries() + query = LibraryBrowseQuery(scope: .personal); selection = entry.titleID + installationNotice = "Your personal software is saved privately on this Mac. The CoCo has not been changed." + } catch PersonalSoftwareLibraryStore.Failure.duplicate(let id) { + personalDuplicateID = id + personalError = PersonalSoftwareLibraryStore.Failure.duplicate(id).localizedDescription + } catch { personalError = error.localizedDescription } + } + } + func cancelPersonalEdit() { + guard !personalSaving else { return } + let draft = personalDraft; personalEditor = nil; personalDraft = nil; personalDuplicateID = nil; personalError = nil + if let draft { Task { await personalStore.cancel(draft.id) } } + } + func openExistingPersonal(_ id: UUID) { + cancelPersonalEdit(); query = LibraryBrowseQuery(scope: .personal); selection = "personal:" + id.uuidString.lowercased() + } + func removePersonal(_ entry: PersonalSoftwareEntry) { + guard !personalSaving else { return } + personalTask = Task { + do { + var hidden = entry; hidden.hidden = true + try await personalStore.update(hidden); await refreshPersonalEntries() + installationNotice = "Removed from Personal Library. Original and working files are retained on this Mac; no space was reclaimed." + } catch { personalError = error.localizedDescription } + } + } + func personalDirectory(_ entry: PersonalSoftwareEntry) -> URL { + state.directory.appendingPathComponent("PersonalLibrary").appendingPathComponent(entry.id.uuidString.lowercased()) + } + func personalCoverPreview(_ entry: PersonalSoftwareEntry) async throws -> Data? { + let draftID = personalDraft?.entry.id == entry.id ? personalDraft?.id : nil + return try await personalStore.previewCover(entry, draftID: draftID) + } + func choosePersonalCover(for entry: PersonalSoftwareEntry) { + guard canEditPersonal, personalEditor == nil else { return } + let panel = NSOpenPanel() + panel.title = "Choose Cover Image"; panel.prompt = "Use Image" + panel.message = "Choose an image for this personal entry. Nothing is uploaded." + panel.allowedContentTypes = [.image] + panel.canChooseDirectories = false; panel.allowsMultipleSelection = false + panel.begin { [weak self] response in + guard response == .OK, let url = panel.url else { return } + self?.replacePersonalCover(from: url, for: entry) + } + } + func acceptPersonalCoverDrop(_ urls: [URL], for entry: PersonalSoftwareEntry) -> Bool { + guard urls.count == 1, let url = urls.first, url.isFileURL, + canEditPersonal, personalEditor == nil else { return false } + replacePersonalCover(from: url, for: entry) + return true + } + func selectPersonalCover(_ choice: PersonalSoftwareEntry.CoverChoice, for entry: PersonalSoftwareEntry) { + changePersonalCover(entry, choice: choice, source: nil) + } + private func replacePersonalCover(from url: URL, for entry: PersonalSoftwareEntry) { + changePersonalCover(entry, choice: nil, source: url) + } + private func changePersonalCover(_ entry: PersonalSoftwareEntry, + choice: PersonalSoftwareEntry.CoverChoice?, source: URL?) { + guard canEditPersonal, personalEditor == nil, selectedPersonalEntry?.id == entry.id else { return } + personalSaving = true; personalError = nil + personalTask = Task { + defer { personalSaving = false; personalTask = nil } + do { + let png: Data? + if let source { + let worker = Task.detached(priority: .userInitiated) { try PersonalCoverImage.prepare(source) } + png = try await withTaskCancellationHandler { try await worker.value } onCancel: { worker.cancel() } + } else { png = nil } + try Task.checkCancellation() + guard selectedPersonalEntry?.id == entry.id, + personalEntries.first(where: { $0.id == entry.id })?.updatedAt == entry.updatedAt else { + throw PersonalSoftwareLibraryStore.Failure.invalid("The selected personal entry changed. Choose its cover again.") + } + var edited = entry + if let choice { edited.cover = choice } + try await personalStore.update(edited, coverPNG: png) + await refreshPersonalEntries() + installationNotice = "Cover image updated privately on this Mac. Your software and saved games are unchanged." + } catch is CancellationError { } + catch { personalError = error.localizedDescription } + } + } + private func refreshPersonalEntries() async { + do { + personalEntries = try await personalStore.entries() + updateSoftwareTypes(catalog) + let warnings = await personalStore.warnings + personalError = warnings.isEmpty ? nil : warnings.joined(separator: "\n") + filter() + } + catch { personalError = error.localizedDescription } + } +} +#endif + + +extension SoftwareLibraryModel { + func restoreBrowseContext() { + guard !restoredBrowse else { return } + restoredBrowse = true + #if !VCC_COMPANION_CLIENT + guard !isDiskCompanion, let saved = browseContinuity.browse(for: "software-main"), + let encoded = saved.filters["browse-query"], let data = encoded.data(using: .utf8), + let restored = try? JSONDecoder().decode(LibraryBrowseQuery.self, from: data) else { return } + restoringBrowse = true + query = restored; selection = saved.selectedID + layout = saved.filters["layout"] == "Table" ? "Table" : "Shelf" + browseTopID = saved.topVisibleID; browseOffset = saved.offset + restoringBrowse = false + #endif + } + func saveBrowseContext() { + guard restoredBrowse, !restoringBrowse else { return } + #if !VCC_COMPANION_CLIENT + guard !isDiskCompanion, let encoded = try? JSONEncoder().encode(query), let json = String(data: encoded, encoding: .utf8) else { return } + browseContinuity.setBrowse(.init(scope: query.scope.rawValue, query: query.text, + filters: ["browse-query": json, "layout": layout], selectedID: selection, + selectedEditionID: selectedRelease?.id, topVisibleID: browseTopID, offset: browseOffset), for: "software-main") + #endif + } + func rememberBrowsePosition(id: String?, offset: Double) { + guard browseTopID != id || abs(browseOffset - offset) > 0.01 else { return } + browseTopID = id; browseOffset = max(0, min(offset.isFinite ? offset : 0, 1)) + saveBrowseContext() + } +} diff --git a/platforms/macos/App/SoftwareLibraryPersonal.swift b/platforms/macos/App/SoftwareLibraryPersonal.swift new file mode 100644 index 0000000..0ce200e --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryPersonal.swift @@ -0,0 +1,564 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CryptoKit +import Darwin +import ImageIO +import UniformTypeIdentifiers + +/// Private user data, separate from the prepared public catalog. Matching local +/// companion clients may request verified disk entries and supporting assets. +struct PersonalSoftwareEntry: Codable, Identifiable, Sendable { + struct CoverFile: Codable, Equatable, Sendable { + let path: String + let sha256: String + let byteSize: Int64 + } + enum CoverChoice: Codable, Equatable, Sendable { + case imported(String) + case custom(CoverFile) + case categoryIcon + } + static let standardCategories = SoftwareLibraryOwnedGame.categoryNames.sorted() + static func standardCategory(_ value: String) -> String { + standardCategories.contains(value) ? value : "Other" + } + struct File: Codable, Identifiable, Sendable { + let path: String + var kind: String + let byteSize: Int64 + let sha256: String + var id: String { path } + var isMedia: Bool { ["disk", "hard-disk", "cassette", "cartridge", "binary"].contains(kind) } + var role: String = "" + } + var schemaVersion = 1 + let id: UUID + var title: String + var author = "" + var softwareVersion = "" + var category = "Other" + var notes = "" + var profile = "disk-basic" + var processor = "6809" + var ramKiB = 512 + var video = "composite" + var command = "" + var configured = false + var hidden = false + var createdAt = Date() + var updatedAt = Date() + var files: [File] + var sourcePackageSHA256: String? = nil + var sourcePackageBytes: Int64? = nil + // Older entries retain their first imported cover until explicitly changed. + var cover: CoverChoice? = nil + var selectedCoverFile: CoverFile? { + switch cover { + case .custom(let file): return file + case .categoryIcon: return nil + case .imported(let path): + return files.first { $0.kind == "cover" && $0.path == path }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } + case nil: + return files.first { $0.kind == "cover" }.map { .init(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } + } + } + var titleID: String { "personal:" + id.uuidString.lowercased() } + var releaseID: String { titleID + ":edition" } + var packageSHA256: String { + let inventory = files.sorted { $0.path < $1.path }.map { "\($0.path)\n\($0.byteSize)\n\($0.sha256)" }.joined(separator: "\n") + return SHA256.hash(data: Data(inventory.utf8)).map { String(format: "%02x", $0) }.joined() + } + func release(in directory: URL) -> SoftwareLibraryRelease { + var configuration: [String: LibraryJSON] = ["profile": .string(profile), "processor": .string(processor), + "ram_kib": .number(Double(ramKiB)), "video": .string(video), "personal_reviewed_setup": .bool(configured)] + if !configured { configuration["personal_manual_setup"] = .bool(true) } + let members = configured ? files.filter { $0.isMedia && !$0.role.isEmpty }.map { + LibraryJSON.object(["path": .string($0.path), "target": .string($0.role)]) + } : [] + let selected = selectedCoverFile + let customCover: Bool + if case .custom = cover { customCover = true } else { customCover = false } + let supporting = files.filter { $0.kind == "manual" }.map { CoverFile(path: $0.path, sha256: $0.sha256, byteSize: $0.byteSize) } + let assets = (supporting + [selected].compactMap { $0 }).map { file -> SoftwareLibraryAsset in + let isCover = selected?.path == file.path + let url = directory.appendingPathComponent("Assets").appendingPathComponent(file.path) + var asset = SoftwareLibraryAsset(id: titleID + ":asset:" + file.path, + name: isCover && customCover ? "Personal Cover Image" : URL(fileURLWithPath: file.path).lastPathComponent, + kind: isCover ? "cover" : "manual", sourceURL: url, sha256: file.sha256, byteSize: file.byteSize, + credit: author.isEmpty ? "Personal collection — private on this Mac" : author, + matchStatus: "personal", matchReason: "Imported by this Mac's user; no public distribution permission inferred.") + if !isCover { asset.manualURL = url } + else { asset.thumbnailURL = url; asset.thumbnailSHA256 = file.sha256; asset.thumbnailByteSize = file.byteSize } + return asset + } + return SoftwareLibraryRelease(id: releaseID, titleID: titleID, name: softwareVersion.isEmpty ? title : softwareVersion, + category: Self.standardCategory(category), mediaType: files.first(where: \.isMedia)?.kind ?? "unknown", contentRole: "software", + sourceURL: directory, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, + packageSHA256: packageSHA256, byteSize: files.reduce(0) { $0 + $1.byteSize }, languageStatus: "unknown", + metadata: .object(["personal": .bool(true), "title": .string(title), "publisher": .string(author), + "personal_version": .string(softwareVersion), "personal_notes": .string(notes), "system": .string("coco3"), + "primary_browse_category": .string(Self.standardCategory(category)), + "browse_categories": .array([.string(Self.standardCategory(category))])]), + setup: .init(status: "manual-setup", command: configured && !command.isEmpty ? command : nil, + instructions: notes.isEmpty ? "Private software on this Mac. Review its files and launch setup before running it." : notes, + configuration: .object(configuration), selectedMembers: .array(members), reasons: [], validation: .object([:])), + assets: assets, downloadURLs: []) + } + func receipt(in directory: URL) -> SoftwareLibraryInstallationReceipt { + .init(releaseID: releaseID, packageSHA256: packageSHA256, installedAt: createdAt, + workingDirectory: directory.appendingPathComponent("Working"), relativeFiles: files.map(\.path)) + } +} + +/// Bounded local image decoding shared by import previews and persisted cover edits. +enum PersonalCoverImage { + enum Failure: LocalizedError { + case invalid + var errorDescription: String? { "Choose a readable image no larger than 8 MiB, with dimensions at most 16,384 pixels and 64 million pixels in total. Existing library files were preserved." } + } + static func prepare(_ url: URL) throws -> Data { + let access = url.startAccessingSecurityScopedResource() + defer { if access { url.stopAccessingSecurityScopedResource() } } + return try prepare(sourceData(url)) + } + fileprivate static func sourceData(_ url: URL) throws -> Data { + guard url.isFileURL, url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { throw Failure.invalid } + let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + guard fd >= 0 else { throw Failure.invalid } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close() } + var before = stat(), after = stat() + guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, + before.st_size > 0, before.st_size <= Int64(SoftwareLibraryArtworkCache.maximumSourceBytes) else { throw Failure.invalid } + let data = try handle.read(upToCount: SoftwareLibraryArtworkCache.maximumSourceBytes + 1) ?? Data() + guard data.count == Int(before.st_size), fstat(fd, &after) == 0, before.st_size == after.st_size, + before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, + before.st_ctimespec.tv_sec == after.st_ctimespec.tv_sec, before.st_ctimespec.tv_nsec == after.st_ctimespec.tv_nsec else { throw Failure.invalid } + return data + } + static func prepare(_ data: Data) throws -> Data { + guard !data.isEmpty, data.count <= SoftwareLibraryArtworkCache.maximumSourceBytes, + let source = CGImageSourceCreateWithData(data as CFData, [kCGImageSourceShouldCache: false] as CFDictionary), + CGImageSourceGetStatus(source) == .statusComplete, + let type = CGImageSourceGetType(source), UTType(type as String)?.conforms(to: .image) == true, + let properties = CGImageSourceCopyPropertiesAtIndex(source, 0, nil) as? [CFString: Any], + let width = properties[kCGImagePropertyPixelWidth] as? Int, + let height = properties[kCGImagePropertyPixelHeight] as? Int, + width > 0, height > 0, width <= 16_384, height <= 16_384, + Int64(width) * Int64(height) <= 64_000_000 else { throw Failure.invalid } + let normalized = try SoftwareLibraryArtworkCache.downsample(data, expectedSHA256: nil) + guard normalized.count <= SoftwareLibraryArtworkCache.maximumThumbnailBytes, + SoftwareLibraryArtworkCache.image(from: normalized) != nil else { throw Failure.invalid } + return normalized + } +} + +struct PersonalSoftwareDraft: Identifiable, Sendable { + let id: UUID + var entry: PersonalSoftwareEntry + let unsupported: [String] + var totalBytes: Int64 { entry.files.reduce(0) { $0 + $1.byteSize } } +} + +#if !VCC_COMPANION_CLIENT +actor PersonalSoftwareLibraryStore { + static let maximumBytes: Int64 = 1024 * 1024 * 1024 + static let maximumFiles = 20_000 + let root: URL + private let manager = FileManager.default + private var staged: Set = [] + private(set) var warnings: [String] = [] + enum Failure: LocalizedError { + case invalid(String), duplicate(UUID) + var errorDescription: String? { + switch self { + case .invalid(let message): return message + case .duplicate: return "This exact set of files is already in your Personal Library. Choose Open Existing, or explicitly add a separate copy." + } + } + } + init(root: URL) { self.root = root.standardizedFileURL } + func directory(for id: UUID) -> URL { root.appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) } + private func stage(_ id: UUID) -> URL { root.appendingPathComponent(".Staging", isDirectory: true).appendingPathComponent(id.uuidString.lowercased(), isDirectory: true) } + private func prepareRoot() throws { + for directory in [root, root.appendingPathComponent(".Staging")] { + if manager.fileExists(atPath: directory.path) { + let values = try directory.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard values.isDirectory == true, values.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory. Existing files were preserved.") } + } else { try manager.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) } + } + } + static func validRelative(_ path: String) -> Bool { + !path.isEmpty && path.utf8.count <= 4096 && !path.hasPrefix("/") && !path.contains("\\") && !path.contains(":") && + !path.unicodeScalars.contains(where: CharacterSet.controlCharacters.contains) && + path.split(separator: "/", omittingEmptySubsequences: false).allSatisfy { !$0.isEmpty && $0 != "." && $0 != ".." } + } + private static func fingerprint(_ url: URL, expectedSize: Int64? = nil) throws -> (Int64, String) { + let fd = open(url.path, O_RDONLY | O_NOFOLLOW | O_CLOEXEC) + guard fd >= 0 else { throw Failure.invalid("A selected file cannot be read safely: " + url.lastPathComponent) } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + defer { try? handle.close() } + var before = stat(), after = stat() + guard fstat(fd, &before) == 0, before.st_mode & S_IFMT == S_IFREG, before.st_size >= 0, + before.st_size <= maximumBytes else { throw Failure.invalid("Choose regular files no larger than 1 GiB.") } + var hash = SHA256(), size: Int64 = 0 + while let block = try handle.read(upToCount: 1024 * 1024), !block.isEmpty { + try Task.checkCancellation(); size += Int64(block.count) + guard size <= maximumBytes else { throw Failure.invalid("The selected file exceeds 1 GiB.") } + hash.update(data: block) + } + guard fstat(fd, &after) == 0, before.st_ino == after.st_ino, before.st_size == after.st_size, + before.st_mtimespec.tv_sec == after.st_mtimespec.tv_sec, before.st_mtimespec.tv_nsec == after.st_mtimespec.tv_nsec, + size == before.st_size, expectedSize == nil || size == expectedSize else { throw Failure.invalid("A source file changed while being copied. Please try again.") } + return (size, hash.finalize().map { String(format: "%02x", $0) }.joined()) + } + private static func kind(_ url: URL) throws -> String? { + switch url.pathExtension.lowercased() { + case "dsk", "jvc", "dmk", "vdk": _ = try DiskFiles.readImage(url); return "disk" + case "os9": + let size = try url.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0 + if size <= DiskFiles.limit { _ = try DiskFiles.readImage(url); return "disk" } + _ = try HardDiskFiles.readImage(url); return "hard-disk" + case "vhd", "img": _ = try HardDiskFiles.readImage(url); return "hard-disk" + case "ccc", "rom": _ = try DiskFiles.readCartridgeROM(url); return "cartridge" + case "cas", "wav": _ = try TapeImage.read(url); return "cassette" + case "bin": _ = try BinaryFile.read(url); return "binary" + case "pdf", "txt": return "manual" + case "png", "jpg", "jpeg": return "cover" + default: return nil + } + } + func inspect(_ sources: [URL]) throws -> PersonalSoftwareDraft { + try prepareRoot(); guard !sources.isEmpty else { throw CancellationError() } + let id = UUID(), destination = stage(id) + try manager.createDirectory(at: destination, withIntermediateDirectories: false) + staged.insert(id) + do { + let inputs = destination.appendingPathComponent("Inputs") + try manager.createDirectory(at: inputs, withIntermediateDirectories: false) + var inventory: [String] = [], unsupported: [String] = [], bytes: Int64 = 0 + for source in sources { + let access = source.startAccessingSecurityScopedResource() + defer { if access { source.stopAccessingSecurityScopedResource() } } + let values = try source.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]) + guard values.isSymbolicLink != true else { throw Failure.invalid("Choose original files or folders, rather than symbolic links.") } + if source.pathExtension.lowercased() == "zip", values.isRegularFile == true { + guard sources.count == 1 else { throw Failure.invalid("Import one ZIP at a time, or select its extracted files as one set.") } + let archive = destination.appendingPathComponent("Package.zip") + let reviewed = try Self.fingerprint(source) + try Self.copyReviewedPackage(from: source, to: archive, byteSize: reviewed.0, sha256: reviewed.1) + let extracted = destination.appendingPathComponent("Extracted") + inventory = try VCCLibraryArchive.extractZIP(at: archive, toNewDirectory: extracted, + maximumExpandedBytes: UInt64(Self.maximumBytes), maximumEntries: UInt(Self.maximumFiles), shouldCancel: { Task.isCancelled }) + for path in inventory { try copy(extracted.appendingPathComponent(path), to: inputs.appendingPathComponent(path), count: &bytes) } + } else if values.isDirectory == true { + let selectedPath = source.resolvingSymlinksInPath().standardizedFileURL.path + let stagingPath = destination.resolvingSymlinksInPath().standardizedFileURL.path + guard selectedPath != stagingPath, !stagingPath.hasPrefix(selectedPath + "/") else { + throw Failure.invalid("Select a software folder that does not contain the private library's import area.") + } + guard sources.count == 1 else { throw Failure.invalid("Select one coherent software folder, or choose individual files.") } + // URL enumeration can canonicalize /var to /private/var + // independently of the selected URL. Use the enumerator's + // actual relative names, never trim by absolute string length. + guard let enumerator = manager.enumerator(atPath: source.path) else { throw Failure.invalid("The selected folder cannot be read.") } + for case let path as String in enumerator { + try Task.checkCancellation() + guard Self.validRelative(path) else { throw Failure.invalid("The software folder contains an unsafe relative name.") } + let file = source.appendingPathComponent(path) + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .isDirectoryKey]) + guard info.isSymbolicLink != true else { throw Failure.invalid("The software folder contains a symbolic link: " + file.lastPathComponent) } + if info.isDirectory == true { + if file.lastPathComponent.hasPrefix(".") { enumerator.skipDescendants() } + continue + } + if file.lastPathComponent.hasPrefix(".") { continue } + guard info.isRegularFile == true else { throw Failure.invalid("The software folder contains an unsupported filesystem item.") } + guard inventory.count < Self.maximumFiles else { throw Failure.invalid("The software folder contains too many files.") } + try copy(file, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path) + } + } else { + let path = source.lastPathComponent + guard !inventory.contains(path) else { throw Failure.invalid("Two selected files have the same name. Put them in a folder with distinct relative paths first.") } + try copy(source, to: inputs.appendingPathComponent(path), count: &bytes); inventory.append(path) + } + } + var files: [PersonalSoftwareEntry.File] = [] + for path in inventory.sorted() { + guard Self.validRelative(path) else { throw Failure.invalid("The software contains an unsafe path.") } + let file = inputs.appendingPathComponent(path), info = try Self.fingerprint(file) + let kind = try Self.kind(file) ?? "supporting" + if ["disk", "hard-disk", "cartridge", "cassette", "binary"].contains(kind), info.0 == 0 { throw Failure.invalid("A selected media file is empty: " + path) } + if kind == "supporting" { unsupported.append(path) } + files.append(.init(path: path, kind: kind, byteSize: info.0, sha256: info.1)) + } + guard files.contains(where: \.isMedia) else { throw Failure.invalid("No supported CoCo media was found. Select a disk, cassette, raw cartridge, binary or software package.") } + let name = sources[0].deletingPathExtension().lastPathComponent + var entry = PersonalSoftwareEntry(id: id, title: name, files: files) + let package = destination.appendingPathComponent("Package.zip") + if manager.fileExists(atPath: package.path) { + let identity = try Self.fingerprint(package) + entry.sourcePackageBytes = identity.0; entry.sourcePackageSHA256 = identity.1 + } + if let media = files.first(where: \.isMedia) { + if media.kind == "cartridge" { entry.profile = "rom-cartridge" } + if media.kind == "hard-disk" { entry.profile = "hard-drive-basic" } + } + let mediaIndices = entry.files.indices.filter { entry.files[$0].isMedia } + if mediaIndices.count == 1, let index = mediaIndices.first, entry.files[index].kind == "disk" { + entry.files[index].role = "disk0" + } + return .init(id: id, entry: entry, unsupported: unsupported) + } catch { try? manager.removeItem(at: destination); staged.remove(id); throw error } + } + /// Retain exactly the bytes observed during package review. A source ZIP can + /// change between review and copying; a coherent newer ZIP is still a change, + /// not permission to silently import a different package. + static func copyReviewedPackage(from source: URL, to target: URL, byteSize: Int64, sha256: String) throws { + let manager = FileManager.default + guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("The retained package destination already exists.") } + try manager.copyItem(at: source, to: target) + do { + let retained = try fingerprint(target) + guard retained.0 == byteSize, retained.1 == sha256 else { + throw Failure.invalid("The source ZIP changed during copying. Select it again; existing library files were preserved.") + } + } catch { + try? manager.removeItem(at: target) + throw error + } + } + private func copy(_ source: URL, to target: URL, count: inout Int64) throws { + let relative = target.lastPathComponent + guard Self.validRelative(relative) else { throw Failure.invalid("The selected file has an unsafe name.") } + let before = try Self.fingerprint(source) + count += before.0; guard count <= Self.maximumBytes else { throw Failure.invalid("One personal software set may contain at most 1 GiB.") } + try Task.checkCancellation() + try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + guard !manager.fileExists(atPath: target.path) else { throw Failure.invalid("Duplicate file path in this software set.") } + try manager.copyItem(at: source, to: target) + let after = try Self.fingerprint(target) + guard before == after else { throw Failure.invalid("A source file changed during copying. Your source files were not modified.") } + } + func cancel(_ draftID: UUID) { + guard staged.remove(draftID) != nil else { return } + try? manager.removeItem(at: stage(draftID)) + } + func entries(includeHidden: Bool = false) throws -> [PersonalSoftwareEntry] { + try prepareRoot() + var result: [PersonalSoftwareEntry] = []; warnings = [] + for folder in try manager.contentsOfDirectory(at: root, includingPropertiesForKeys: [.isDirectoryKey, .isSymbolicLinkKey], options: [.skipsHiddenFiles]) { + guard UUID(uuidString: folder.lastPathComponent) != nil else { continue } + let info = try folder.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard info.isDirectory == true, info.isSymbolicLink != true else { throw Failure.invalid("A private library entry was replaced by an unsafe filesystem item.") } + do { + let entry = try read(folder.appendingPathComponent("Entry.json")) + guard entry.id.uuidString.lowercased() == folder.lastPathComponent.lowercased() else { throw Failure.invalid("A private library entry has a conflicting identity.") } + if includeHidden || !entry.hidden { result.append(entry) } + } catch { + if warnings.count < 10 { warnings.append("An unavailable private entry was preserved at " + folder.path + ". " + error.localizedDescription) } + } + } + return result.sorted { $0.title.localizedStandardCompare($1.title) == .orderedAscending } + } + private func read(_ file: URL) throws -> PersonalSoftwareEntry { + let info = try file.resourceValues(forKeys: [.isRegularFileKey, .isSymbolicLinkKey, .fileSizeKey]) + guard info.isRegularFile == true, info.isSymbolicLink != true, (info.fileSize ?? Int.max) <= 4 * 1024 * 1024 else { throw Failure.invalid("A private entry cannot be read safely; its files have been preserved.") } + var entry = try JSONDecoder().decode(PersonalSoftwareEntry.self, from: Data(contentsOf: file)) + entry.category = PersonalSoftwareEntry.standardCategory(entry.category) + try Self.validate(entry); return entry + } + private static func validate(_ entry: PersonalSoftwareEntry) throws { + guard entry.schemaVersion == 1, !entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + entry.title.utf8.count <= 240, entry.author.utf8.count <= 500, entry.notes.utf8.count <= 65536, + [128, 512, 2048, 8192].contains(entry.ramKiB), ["6809", "6309"].contains(entry.processor), + ["rgb", "composite"].contains(entry.video), ["disk-basic", "rom-cartridge", "hard-drive-basic"].contains(entry.profile), + !entry.files.isEmpty, entry.files.count <= maximumFiles, Set(entry.files.map(\.path)).count == entry.files.count, + entry.files.contains(where: \.isMedia), entry.command.utf8.count <= 4096, + entry.command.unicodeScalars.allSatisfy({ $0.value == 13 || $0.value == 10 || (32...126).contains($0.value) }), + entry.files.allSatisfy({ ["disk", "hard-disk", "cartridge", "cassette", "binary", "manual", "cover", "supporting"].contains($0.kind) && validRelative($0.path) && $0.byteSize >= 0 && $0.byteSize <= maximumBytes && $0.sha256.count == 64 && $0.sha256.allSatisfy(\.isHexDigit) }) else { + throw Failure.invalid("The personal entry is damaged, unsupported or contains invalid setup data. Its files have been preserved.") + } + if entry.sourcePackageSHA256 != nil || entry.sourcePackageBytes != nil { + guard let sha = entry.sourcePackageSHA256, sha.count == 64, sha.allSatisfy(\.isHexDigit), + let bytes = entry.sourcePackageBytes, bytes > 0, bytes <= maximumBytes else { throw Failure.invalid("The retained package identity is invalid; files were preserved.") } + } + switch entry.cover { + case .imported(let path): + guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { throw Failure.invalid("Choose a cover image from this entry's imported files.") } + case .custom(let file): + let parts = file.path.split(separator: "/", omittingEmptySubsequences: false) + guard validRelative(file.path), parts.count == 2, parts.first == "PersonalCovers", + (file.path as NSString).pathExtension == "png", UUID(uuidString: URL(fileURLWithPath: file.path).deletingPathExtension().lastPathComponent) != nil, + file.sha256.count == 64, file.sha256.allSatisfy(\.isHexDigit), file.byteSize > 0, + file.byteSize <= Int64(SoftwareLibraryArtworkCache.maximumThumbnailBytes) else { throw Failure.invalid("The private cover descriptor is invalid. Existing files were preserved.") } + case .categoryIcon, nil: break + } + let targets = entry.files.filter { !$0.role.isEmpty }.map(\.role) + guard Set(targets).count == targets.count, + targets.allSatisfy({ ["disk0", "disk1", "disk2", "disk3", "hard0", "hard1", "media", "cartridge"].contains($0) }) else { throw Failure.invalid("Assign each drive or media target at most once.") } + if entry.configured { + for file in entry.files where !file.role.isEmpty { + let valid = (file.kind == "disk" && file.role.hasPrefix("disk") && entry.profile != "rom-cartridge") || + (file.kind == "hard-disk" && file.role.hasPrefix("hard") && entry.profile == "hard-drive-basic") || + (file.kind == "cassette" && file.role == "media" && entry.profile == "disk-basic") || + (file.kind == "cartridge" && file.role == "cartridge" && entry.profile == "rom-cartridge") + guard valid else { throw Failure.invalid("A media assignment does not match this machine setup. Review the file's role and machine setup before saving.") } + } + } + } + func save(_ draft: PersonalSoftwareDraft, allowDuplicate: Bool = false, coverPNG: Data? = nil) throws -> PersonalSoftwareEntry { + var draft = draft + let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) } + draft.entry.category = PersonalSoftwareEntry.standardCategory(draft.entry.category) + try Self.validate(draft.entry) + guard staged.contains(draft.id), draft.entry.id == draft.id else { throw Failure.invalid("This import preview has expired. Select the files again.") } + if !allowDuplicate, let existing = try entries().first(where: { $0.packageSHA256 == draft.entry.packageSHA256 }) { throw Failure.duplicate(existing.id) } + let source = stage(draft.id), inputs = source.appendingPathComponent("Inputs") + try requireSafePath(inputs, directory: true) + let final = directory(for: draft.id) + guard !manager.fileExists(atPath: final.path) else { throw Failure.invalid("A personal entry already uses this identity.") } + let required = draft.entry.files.reduce(Int64(0)) { $0 + $1.byteSize } * 3 + 64 * 1024 * 1024 + if let free = try root.resourceValues(forKeys: [.volumeAvailableCapacityForImportantUsageKey]).volumeAvailableCapacityForImportantUsage, free < required { throw SoftwareLibraryInstaller.Failure.insufficientSpace } + let ready = source.appendingPathComponent("Ready") + if manager.fileExists(atPath: ready.path) { try manager.removeItem(at: ready) } + try manager.createDirectory(at: ready, withIntermediateDirectories: false) + do { + for name in ["Original/Files", "Working", "Assets"] { try manager.createDirectory(at: ready.appendingPathComponent(name), withIntermediateDirectories: true) } + for file in draft.entry.files { + try Task.checkCancellation() + if file.kind == "hard-disk" { _ = try HardDiskFiles.readImage(inputs.appendingPathComponent(file.path)) } + let original = ready.appendingPathComponent("Original/Files").appendingPathComponent(file.path) + var count: Int64 = 0 + try copy(inputs.appendingPathComponent(file.path), to: original, count: &count) + let actual = try Self.fingerprint(original) + guard actual.0 == file.byteSize, actual.1 == file.sha256 else { throw Failure.invalid("The staged import no longer matches its preview.") } + // A .txt or image can also be runtime program data. Preserve + // the coherent complete set in Working, even when an asset is + // additionally offered in the native manual/artwork reader. + let target = ready.appendingPathComponent("Working").appendingPathComponent(file.path) + try manager.createDirectory(at: target.deletingLastPathComponent(), withIntermediateDirectories: true) + try manager.copyItem(at: original, to: target) + try manager.setAttributes([.posixPermissions: 0o600], ofItemAtPath: target.path) + if ["manual", "cover"].contains(file.kind) { + let asset = ready.appendingPathComponent("Assets").appendingPathComponent(file.path) + try manager.createDirectory(at: asset.deletingLastPathComponent(), withIntermediateDirectories: true) + try manager.copyItem(at: original, to: asset) + } + try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: original.path) + } + let package = source.appendingPathComponent("Package.zip") + if manager.fileExists(atPath: package.path) { + let identity = try Self.fingerprint(package) + guard identity.0 == draft.entry.sourcePackageBytes, identity.1 == draft.entry.sourcePackageSHA256 else { throw Failure.invalid("The source ZIP no longer matches the reviewed import.") } + let retained = ready.appendingPathComponent("Original/Package.zip") + try manager.copyItem(at: package, to: retained) + guard try Self.fingerprint(retained) == identity else { throw Failure.invalid("The retained source ZIP did not copy correctly.") } + try manager.setAttributes([.posixPermissions: 0o444], ofItemAtPath: retained.path) + } + if let normalizedCover { + draft.entry.cover = .custom(try storeCover(normalizedCover, in: ready)) + } else if draft.entry.cover != nil { + _ = try previewCover(draft.entry, draftID: draft.id) + } + try write(draft.entry, to: ready.appendingPathComponent("Entry.json")) + try Task.checkCancellation(); try manager.moveItem(at: ready, to: final) + cancel(draft.id) + return draft.entry + } catch { try? manager.removeItem(at: ready); throw error } + } + private func write(_ entry: PersonalSoftwareEntry, to url: URL) throws { + let encoder = JSONEncoder(); encoder.outputFormatting = [.prettyPrinted, .sortedKeys] + try encoder.encode(entry).write(to: url, options: .atomic) + } + func update(_ entry: PersonalSoftwareEntry, coverPNG: Data? = nil) throws { + var entry = entry + let normalizedCover = try coverPNG.map { try PersonalCoverImage.prepare($0) } + entry.category = PersonalSoftwareEntry.standardCategory(entry.category) + try Self.validate(entry) + let directory = directory(for: entry.id) + try requireSafePath(directory, directory: true) + let file = directory.appendingPathComponent("Entry.json") + let previous = try read(file) + guard (coverPNG == nil && entry.cover == previous.cover) || previous.updatedAt == entry.updatedAt else { + throw Failure.invalid("This private entry changed while its cover was being edited. Reopen it before saving; existing files were preserved.") + } + func identities(_ files: [PersonalSoftwareEntry.File]) -> [String: String] { + Dictionary(uniqueKeysWithValues: files.map { ($0.path, $0.kind + ":" + String($0.byteSize) + ":" + $0.sha256) }) + } + guard identities(previous.files) == identities(entry.files), previous.createdAt == entry.createdAt, + previous.sourcePackageSHA256 == entry.sourcePackageSHA256, previous.sourcePackageBytes == entry.sourcePackageBytes else { throw Failure.invalid("Use a new import to replace media; existing working files are preserved.") } + var added: URL? + do { + if let normalizedCover { + let cover = try storeCover(normalizedCover, in: directory) + added = directory.appendingPathComponent("Assets").appendingPathComponent(cover.path) + entry.cover = .custom(cover) + } else if entry.cover != nil { + _ = try previewCover(entry, draftID: nil) + } + entry.updatedAt = Date(); try write(entry, to: file) + } catch { + if let added { try? manager.removeItem(at: added) } + throw error + } + } + + /// Preview reads retained assets or this draft's staged input; it never + /// persists a chosen replacement image or changes the media inventory. + func previewCover(_ entry: PersonalSoftwareEntry, draftID: UUID? = nil) throws -> Data? { + try Self.validate(entry) + guard let cover = entry.selectedCoverFile else { return nil } + let base: URL + if let draftID { + guard staged.contains(draftID), draftID == entry.id else { throw Failure.invalid("This import preview has expired. Select the files again.") } + base = stage(draftID).appendingPathComponent("Inputs") + } else { base = directory(for: entry.id).appendingPathComponent("Assets") } + let source = base.appendingPathComponent(cover.path) + try requireSafePath(source, directory: false) + let data = try PersonalCoverImage.sourceData(source) + guard Int64(data.count) == cover.byteSize, + SHA256.hash(data: data).map({ String(format: "%02x", $0) }).joined() == cover.sha256.lowercased() else { + throw Failure.invalid("The private cover no longer matches its saved identity. Existing files were preserved.") + } + return try PersonalCoverImage.prepare(data) + } + + private func requireSafePath(_ path: URL, directory: Bool) throws { + let path = path.standardizedFileURL + guard path.path == root.path || path.path.hasPrefix(root.path + "/") else { throw Failure.invalid("The private asset path leaves its library.") } + var checked = root + let relative = path.path.dropFirst(root.path.count).split(separator: "/") + let rootValues = try root.resourceValues(forKeys: [.isDirectoryKey, .isSymbolicLinkKey]) + guard rootValues.isDirectory == true, rootValues.isSymbolicLink != true else { throw Failure.invalid("The private library location is not a safe directory.") } + for (index, component) in relative.enumerated() { + checked.appendPathComponent(String(component)) + let values = try checked.resourceValues(forKeys: [.isDirectoryKey, .isRegularFileKey, .isSymbolicLinkKey]) + let needsDirectory = index < relative.count - 1 || directory + guard values.isSymbolicLink != true, needsDirectory ? values.isDirectory == true : values.isRegularFile == true else { + throw Failure.invalid("The private asset path contains an unsafe filesystem item. Existing files were preserved.") + } + } + } + + private func storeCover(_ data: Data, in directory: URL) throws -> PersonalSoftwareEntry.CoverFile { + try requireSafePath(directory, directory: true) + for relative in ["Assets", "Assets/PersonalCovers"] { + let folder = directory.appendingPathComponent(relative) + if !manager.fileExists(atPath: folder.path) { try manager.createDirectory(at: folder, withIntermediateDirectories: false, attributes: [.posixPermissions: 0o700]) } + try requireSafePath(folder, directory: true) + } + let path = "PersonalCovers/" + UUID().uuidString.lowercased() + ".png" + let destination = directory.appendingPathComponent("Assets").appendingPathComponent(path) + let fd = open(destination.path, O_WRONLY | O_CREAT | O_EXCL | O_NOFOLLOW | O_CLOEXEC, 0o600) + guard fd >= 0 else { throw Failure.invalid("The replacement cover could not be saved safely.") } + let handle = FileHandle(fileDescriptor: fd, closeOnDealloc: true) + do { + try handle.write(contentsOf: data); try handle.close() + return .init(path: path, sha256: SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), byteSize: Int64(data.count)) + } catch { + try? handle.close(); try? manager.removeItem(at: destination); throw error + } + } +} +#endif diff --git a/platforms/macos/App/SoftwareLibraryPersonalView.swift b/platforms/macos/App/SoftwareLibraryPersonalView.swift new file mode 100644 index 0000000..d4fdccc --- /dev/null +++ b/platforms/macos/App/SoftwareLibraryPersonalView.swift @@ -0,0 +1,556 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +#if !VCC_COMPANION_CLIENT +import SwiftUI +import AppKit +import UniformTypeIdentifiers + +/// Finder file drags use the native file-URL pasteboard representation. Image +/// decoding remains in the receiving model/editor's bounded background work. +struct PersonalCoverFileDropTarget: NSViewRepresentable { + let enabled: Bool + @Binding var isTargeted: Bool + let perform: ([URL]) -> Bool + + func makeNSView(context: Context) -> DropView { + let view = DropView() + view.registerForDraggedTypes([.fileURL]) + view.setAccessibilityElement(false) + view.setAccessibilityHidden(true) + return view + } + func updateNSView(_ view: DropView, context: Context) { + view.enabled = enabled + view.targeted = $isTargeted + view.perform = perform + if !enabled, isTargeted { + DispatchQueue.main.async { [weak view] in + guard let view, !view.enabled else { return } + view.setTargeted(false) + } + } + } + static func dismantleNSView(_ view: DropView, coordinator: ()) { + view.unregisterDraggedTypes() + view.perform = nil + let targeted = view.targeted + view.targeted = nil + if targeted?.wrappedValue == true { + DispatchQueue.main.async { targeted?.wrappedValue = false } + } + } + final class DropView: NSView { + var enabled = false + var targeted: Binding? + var perform: (([URL]) -> Bool)? + override func layout() { + super.layout() + #if VCC_UI_TESTING + trace("layout frame=\(frame) window=\(String(describing: window?.frame))") + #endif + } + private func trace(_ message: String) { + #if VCC_UI_TESTING + guard let path = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_TRACE"] else { return } + let url = URL(fileURLWithPath: path) + var data = (try? Data(contentsOf: url)) ?? Data() + guard data.count < 8192 else { return } + data.append(Data((message + "\n").utf8)); try? data.write(to: url) + #endif + } + + func setTargeted(_ value: Bool) { + if targeted?.wrappedValue != value { targeted?.wrappedValue = value } + } + private func urls(from sender: NSDraggingInfo) -> [URL]? { + guard enabled, + let urls = sender.draggingPasteboard.readObjects(forClasses: [NSURL.self], + options: [.urlReadingFileURLsOnly: true]) as? [URL], + urls.count == 1, let url = urls.first, url.isFileURL, + url.host == nil || url.host == "localhost", url.query == nil, url.fragment == nil else { return nil } + return urls + } + private func operation(for sender: NSDraggingInfo) -> NSDragOperation { + let accepts = sender.draggingSourceOperationMask.contains(.copy) && urls(from: sender) != nil + setTargeted(accepts) + return accepts ? .copy : [] + } + override func draggingEntered(_ sender: NSDraggingInfo) -> NSDragOperation { + trace("entered enabled=\(enabled) frame=\(frame)") + return operation(for: sender) + } + override func draggingUpdated(_ sender: NSDraggingInfo) -> NSDragOperation { operation(for: sender) } + override func draggingExited(_ sender: NSDraggingInfo?) { setTargeted(false) } + override func prepareForDragOperation(_ sender: NSDraggingInfo) -> Bool { + operation(for: sender) == .copy + } + override func performDragOperation(_ sender: NSDraggingInfo) -> Bool { + defer { setTargeted(false) } + guard sender.draggingSourceOperationMask.contains(.copy), let urls = urls(from: sender) else { return false } + trace("perform file-count=\(urls.count)") + return perform?(urls) ?? false + } + override func concludeDragOperation(_ sender: NSDraggingInfo?) { setTargeted(false) } + } +} + +#if VCC_UI_TESTING +/// Authored UI-test source for a real AppKit file drag. It uses the same +/// pasteboard representation as Finder and never calls a drop handler itself. +struct PersonalCoverFileDragFixture: NSViewRepresentable { + func makeNSView(context: Context) -> SourceView { + let view = SourceView() + view.setAccessibilityElement(true) + view.isEnabled = true + view.setAccessibilityLabel("Drag test image") + view.setAccessibilityIdentifier("personal-cover-drag-source") + return view + } + func updateNSView(_ view: SourceView, context: Context) { + view.sourceURL = ProcessInfo.processInfo.environment["VCC_COVER_DRAG_SOURCE"].map { URL(fileURLWithPath: $0) } + view.needsDisplay = true + } + final class SourceView: NSImageView, NSDraggingSource { + var sourceURL: URL? + override var intrinsicContentSize: NSSize { NSSize(width: 100, height: 45) } + override func acceptsFirstMouse(for event: NSEvent?) -> Bool { true } + + override func draw(_ dirtyRect: NSRect) { + super.draw(dirtyRect) + let frame = bounds.insetBy(dx: 1, dy: 1) + let border = NSBezierPath(roundedRect: frame, xRadius: 5, yRadius: 5) + NSColor.controlBackgroundColor.setFill(); border.fill() + NSColor.separatorColor.setStroke(); border.stroke() + NSImage(systemSymbolName: "doc", accessibilityDescription: nil)? + .draw(in: NSRect(x: bounds.midX - 8, y: 23, width: 16, height: 17)) + let paragraph = NSMutableParagraphStyle(); paragraph.alignment = .center + ("Drag test image" as NSString).draw(in: NSRect(x: 3, y: 5, width: bounds.width - 6, height: 14), + withAttributes: [.font: NSFont.systemFont(ofSize: 10), .foregroundColor: NSColor.labelColor, + .paragraphStyle: paragraph]) + } + override func mouseDown(with event: NSEvent) { + guard let sourceURL else { return } + let item = NSDraggingItem(pasteboardWriter: sourceURL as NSURL) + let icon = NSImage(systemSymbolName: "doc", accessibilityDescription: nil) + item.setDraggingFrame(NSRect(x: bounds.midX - 16, y: bounds.midY - 16, width: 32, height: 32), contents: icon) + let session = beginDraggingSession(with: [item], event: event, source: self) + session.animatesToStartingPositionsOnCancelOrFail = true + } + func draggingSession(_ session: NSDraggingSession, sourceOperationMaskFor context: NSDraggingContext) -> NSDragOperation { + .copy + } + } +} +#endif + +/// Guest command text must retain ASCII quotes and literal keystrokes. A native +/// plain-text editor also keeps Return inside the draft instead of saving it. +private struct PersonalLaunchCommandEditor: NSViewRepresentable { + @Binding var text: String + let isEnabled: Bool + + func makeCoordinator() -> Coordinator { Coordinator(text: $text) } + func makeNSView(context: Context) -> NSScrollView { + let scroll = NSTextView.scrollableTextView() + let editor = scroll.documentView as! NSTextView + scroll.drawsBackground = false + editor.drawsBackground = false + editor.isRichText = false + editor.allowsUndo = true + editor.font = .monospacedSystemFont(ofSize: NSFont.systemFontSize, weight: .regular) + editor.textColor = .labelColor + editor.isAutomaticQuoteSubstitutionEnabled = false + editor.isAutomaticDashSubstitutionEnabled = false + editor.isAutomaticTextReplacementEnabled = false + editor.isAutomaticSpellingCorrectionEnabled = false + editor.isContinuousSpellCheckingEnabled = false + editor.isAutomaticLinkDetectionEnabled = false + editor.isAutomaticDataDetectionEnabled = false + editor.isAutomaticTextCompletionEnabled = false + editor.smartInsertDeleteEnabled = false + editor.textContainerInset = NSSize(width: 4, height: 6) + editor.setAccessibilityLabel("Keyboard loading commands (optional)") + editor.setAccessibilityIdentifier("personal-launch-commands") + editor.delegate = context.coordinator + return scroll + } + func updateNSView(_ scroll: NSScrollView, context: Context) { + let editor = scroll.documentView as! NSTextView + context.coordinator.text = $text + editor.isEditable = isEnabled + if editor.string != text { editor.string = text } + } + final class Coordinator: NSObject, NSTextViewDelegate { + var text: Binding + init(text: Binding) { self.text = text } + func textDidChange(_ notification: Notification) { + guard let editor = notification.object as? NSTextView else { return } + text.wrappedValue = editor.string + } + } +} + +struct PersonalSoftwareEditor: View { + @State var entry: PersonalSoftwareEntry + let unsupported: [String] + let isImport: Bool + let saving: Bool + let error: String? + let duplicateID: UUID? + let save: (PersonalSoftwareEntry, Data?, Bool) -> Void + let openExisting: (UUID) -> Void + let previewCover: (PersonalSoftwareEntry) async throws -> Data? + let cancel: () -> Void + private let initialEntry: PersonalSoftwareEntry + @State private var included: Set + @State private var pendingCoverData: Data? + @State private var coverImage: NSImage? + @State private var coverBusy = false + @State private var coverError: String? + @State private var coverGeneration = UUID() + @State private var coverTask: Task? + @State private var coverImageTask: Task? + @State private var previewingImportedPath: String? + @State private var coverPanel: NSOpenPanel? + @State private var coverEditorActive = true + @State private var coverDropTargeted = false + init(entry: PersonalSoftwareEntry, unsupported: [String] = [], isImport: Bool, saving: Bool, + error: String?, duplicateID: UUID?, save: @escaping (PersonalSoftwareEntry, Data?, Bool) -> Void, + openExisting: @escaping (UUID) -> Void, + previewCover: @escaping (PersonalSoftwareEntry) async throws -> Data?, cancel: @escaping () -> Void) { + var normalized = entry + normalized.category = PersonalSoftwareEntry.standardCategory(entry.category) + _entry = State(initialValue: normalized); _included = State(initialValue: Set(entry.files.map(\.path))) + self.unsupported = unsupported; self.isImport = isImport; self.saving = saving; self.error = error + self.duplicateID = duplicateID; self.save = save; self.openExisting = openExisting + self.previewCover = previewCover; self.cancel = cancel; self.initialEntry = entry + } + var body: some View { + VStack(spacing: 0) { + HStack { + Label(isImport ? "Add Personal Software" : "Edit Personal Software", systemImage: "lock.rectangle.stack") + .font(.title2.weight(.semibold)) + Spacer() + Text("Private — On This Mac").font(.callout).foregroundStyle(.secondary) + }.padding(20) + Divider() + Form { + Section("Files & Details") { + TextField("Title", text: $entry.title).accessibilityIdentifier("personal-title") + TextField("Author / Publisher (optional)", text: $entry.author) + TextField("Software version (optional)", text: $entry.softwareVersion) + Picker("Category", selection: $entry.category) { + ForEach(PersonalSoftwareEntry.standardCategories, id: \.self) { category in + Text(SoftwareLibraryOwnedGame.categoryLabel(category)).tag(category) + } + }.pickerStyle(.menu).accessibilityIdentifier("personal-category") + Text("Find this personal software alongside matching catalog titles when browsing categories. Your files stay private on this Mac.") + .font(.caption).foregroundStyle(.secondary) + TextField("Notes / loading instructions", text: $entry.notes, axis: .vertical).lineLimit(3...8) + Text("Your source files stay untouched. Imported originals and writable working files are kept separately in the app's private library. Nothing is uploaded.") + .font(.caption).foregroundStyle(.secondary) + LabeledContent("Selected files", value: "\(included.count) · " + ByteCountFormatter.string(fromByteCount: entry.files.filter { included.contains($0.path) }.reduce(0) { $0 + $1.byteSize }, countStyle: .file)) + ForEach(Array(entry.files.indices), id: \.self) { index in + HStack { + if isImport { + Toggle(isOn: Binding(get: { included.contains(entry.files[index].path) }, set: { value in + setIncluded(entry.files[index].path, value) + })) { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) } + } else { Text(entry.files[index].path).lineLimit(2).textSelection(.enabled) } + Spacer() + if isImport, (entry.files[index].path as NSString).pathExtension.lowercased() == "os9" { + Picker("Interpret OS-9 media", selection: Binding(get: { entry.files[index].kind }, set: { + entry.files[index].kind = $0; entry.files[index].role = "" + })) { + Text("Floppy disk").tag("disk") + Text("Hard disk").tag("hard-disk") + }.labelsHidden().frame(width: 125).help("OS-9 files can represent floppy or hard disks. Choose how this file will be mounted.") + } else { Text(entry.files[index].kind.capitalized).font(.caption).foregroundStyle(.secondary) } + } + } + if !unsupported.isEmpty { + Label("Supporting files are retained but not run. Nested archives and unrecognized formats are not expanded or treated as media.", systemImage: "info.circle") + .font(.caption).foregroundStyle(.secondary) + } + } + Section("Cover Image") { coverEditor } + Section("Launch Setup") { + Toggle("Use reviewed launch settings", isOn: $entry.configured).accessibilityIdentifier("personal-configured") + Text("Save reviewed machine settings and media assignments to enable Play. Keyboard loading commands are optional: without them, Play opens the CoCo with its media ready for manual loading. Off keeps manual setup. Saving this entry never starts or changes the CoCo.") + .font(.caption).foregroundStyle(.secondary) + Picker("Machine setup", selection: $entry.profile) { + Text("Disk BASIC / Cassette").tag("disk-basic") + Text("ROM Cartridge").tag("rom-cartridge") + Text("Hard-drive BASIC").tag("hard-drive-basic") + } + Picker("Processor", selection: $entry.processor) { Text("MC6809").tag("6809"); Text("HD6309").tag("6309") } + Picker("RAM", selection: $entry.ramKiB) { + ForEach([128,512,2048,8192], id: \.self) { value in Text(value < 1024 ? "\(value) KB" : "\(value / 1024) MB").tag(value) } + } + Picker("Video", selection: $entry.video) { Text("Composite").tag("composite"); Text("RGB").tag("rgb") } + ForEach(Array(entry.files.indices).filter { entry.files[$0].isMedia && included.contains(entry.files[$0].path) }, id: \.self) { index in + Picker(entry.files[index].path, selection: $entry.files[index].role) { + Text("Not assigned").tag("") + ForEach(roles(entry.files[index].kind), id: \.self) { role in Text(roleLabel(role)).tag(role) } + }.disabled(!entry.configured) + } + VStack(alignment: .leading, spacing: 6) { + Text("Keyboard loading commands (optional)") + PersonalLaunchCommandEditor(text: $entry.command, isEnabled: entry.configured) + .frame(height: 90).padding(6) + .background(.background, in: RoundedRectangle(cornerRadius: 6)) + .overlay(RoundedRectangle(cornerRadius: 6).stroke(.secondary.opacity(0.3))) + } + Text("Press Return for a new command line. For a BASIC program, enter LOAD \"PROGRAM\" on one line and RUN on the next. Commands are ordinary CoCo keyboard input; leave this blank if the loading sequence is unknown.") + .font(.caption).foregroundStyle(.secondary) + if entry.configured, !entry.command.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty, + SoftwareLibraryLaunchPlan.decodeCommands(entry.command) == nil { + Label("These commands need manual entry and will not be typed automatically. Check the syntax and put LOAD and RUN on separate lines.", systemImage: "info.circle") + .font(.caption).foregroundStyle(.orange) + .accessibilityIdentifier("personal-launch-commands-manual") + } + } + }.formStyle(.grouped) + if let error { + Label(error, systemImage: "exclamationmark.triangle").foregroundStyle(.orange).textSelection(.enabled) + .frame(maxWidth: .infinity, alignment: .leading).padding(.horizontal,20).padding(.vertical,8) + } + Divider() + HStack { + if saving { ProgressView().controlSize(.small); Text("Saving private copy…").font(.callout) } + Spacer() + Button("Cancel", role: .cancel, action: cancelEditing).keyboardShortcut(.cancelAction).disabled(saving) + if let duplicateID { + Button("Open Existing") { openExisting(duplicateID) }.disabled(saving) + Button("Add Separate Copy") { submit(true) }.disabled(saving || coverBusy) + } else { + Button(isImport ? "Add to Personal Library" : "Save Details") { submit(false) } + .keyboardShortcut(.defaultAction).disabled(saving || coverBusy || entry.title.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty || !entry.files.contains(where: { $0.isMedia && included.contains($0.path) })) + .accessibilityIdentifier("personal-save") + } + }.padding(16) + }.frame(minWidth: 650, idealWidth: 720, minHeight: 600) + .onAppear { + coverEditorActive = true + loadCoverPreview(entry, commitChoice: false) + } + .onDisappear { discardPendingCover() } + } + private var coverEditor: some View { + VStack(alignment: .leading, spacing: 12) { + HStack(alignment: .top, spacing: 16) { + coverPreview + VStack(alignment: .leading, spacing: 10) { + Picker("Cover", selection: Binding(get: { coverSelection }, set: selectCover)) { + Text("Category Icon").tag("category") + ForEach(entry.files.filter { $0.kind == "cover" }) { file in + Text(file.path).tag("imported:" + file.path) + } + if hasExistingCustomCover { Text("Saved Custom Image").tag("custom") } + if pendingCoverData != nil { Text("Chosen Image").tag("replacement") } + }.pickerStyle(.menu).accessibilityIdentifier("personal-cover-selection") + Button("Choose Image…", systemImage: "photo.badge.plus", action: chooseCoverImage) + .disabled(saving || coverPanel != nil).accessibilityIdentifier("personal-cover-choose") + Button("Remove Cover", systemImage: "photo.badge.minus", action: useCategoryIcon) + .disabled(saving || (coverSelection == "category" && !coverBusy)) + .accessibilityIdentifier("personal-cover-remove") + Text("Choose an image or drop one image file onto the preview. The image stays private on this Mac and is saved only when you save this entry.") + .font(.caption).foregroundStyle(.secondary).fixedSize(horizontal: false, vertical: true) + }.frame(maxWidth: .infinity, alignment: .leading) + } + if let coverError { + Label(coverError, systemImage: "exclamationmark.triangle") + .font(.caption).foregroundStyle(.orange).textSelection(.enabled) + } + } + } + private var coverPreview: some View { + ZStack { + RoundedRectangle(cornerRadius: 9).fill(.quaternary.opacity(0.35)) + if let coverImage { + Image(nsImage: coverImage).resizable().scaledToFit().padding(5) + } else { + VStack(spacing: 12) { + Image(systemName: SoftwareLibraryCategoryStyle.symbol(for: entry.category)) + .font(.system(size: 42, weight: .light)) + .foregroundStyle(SoftwareLibraryCategoryStyle.tint(for: entry.category).opacity(0.7)) + Text(SoftwareLibraryOwnedGame.categoryLabel(entry.category)) + .font(.caption.weight(.medium)).foregroundStyle(.secondary) + }.padding(12) + } + if coverBusy { + ProgressView().controlSize(.small).frame(maxHeight: .infinity, alignment: .bottom).padding(8) + } + }.frame(width: 150, height: 180) + .overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(coverDropTargeted ? Color.accentColor : .clear, lineWidth: 3)) + .overlay { + PersonalCoverFileDropTarget(enabled: !saving && coverEditorActive, isTargeted: $coverDropTargeted) { urls in + guard let url = urls.first else { return false } + prepareCoverImage(url) + return true + }.frame(maxWidth: .infinity, maxHeight: .infinity).accessibilityHidden(true) + } + .accessibilityElement(children: .ignore).accessibilityLabel("Cover image preview") + .accessibilityValue(coverBusy ? "Loading image" : coverImage == nil ? "Category icon" : "Selected image") + .accessibilityIdentifier("personal-cover-preview") + .help("Drop one image file here to choose a private cover image") + } + private var hasExistingCustomCover: Bool { + if case .custom? = initialEntry.cover { return true } + return false + } + private var coverSelection: String { + if pendingCoverData != nil { return "replacement" } + switch entry.cover { + case .categoryIcon?: return "category" + case .imported(let path)?: return "imported:" + path + case .custom?: return "custom" + case nil: + return entry.files.first(where: { $0.kind == "cover" && included.contains($0.path) }) + .map { "imported:" + $0.path } ?? "category" + } + } + private func selectCover(_ selection: String) { + guard !saving, coverEditorActive, selection != coverSelection else { return } + if selection == "category" { useCategoryIcon(); return } + var candidate = entry + if selection == "custom", hasExistingCustomCover { candidate.cover = initialEntry.cover } + else if selection.hasPrefix("imported:") { + let path = String(selection.dropFirst("imported:".count)) + guard entry.files.contains(where: { $0.kind == "cover" && $0.path == path }) else { return } + candidate.cover = .imported(path) + } else { return } + loadCoverPreview(candidate, commitChoice: true) + } + private func loadCoverPreview(_ candidate: PersonalSoftwareEntry, commitChoice: Bool) { + let generation = beginCoverWork() + var snapshot = candidate + // A selected imported image is retained with the draft even if it had + // been unchecked in Files & Details before choosing it here. + let selectedPath: String? + if case .imported(let path)? = candidate.cover { selectedPath = path } else { selectedPath = nil } + previewingImportedPath = selectedPath + snapshot.files = snapshot.files.filter { included.contains($0.path) || $0.path == selectedPath } + coverTask = Task { @MainActor in + do { + let data = try await previewCover(snapshot) + guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return } + let image = data.flatMap(NSImage.init(data:)) + guard data == nil || image != nil else { throw CocoaError(.fileReadCorruptFile) } + if commitChoice { + entry.cover = candidate.cover + if let selectedPath { included.insert(selectedPath) } + pendingCoverData = nil + } + coverImage = image + finishCoverWork() + } catch { + guard coverEditorActive, entry.id == candidate.id, coverGeneration == generation, !Task.isCancelled else { return } + coverError = "Could not read this cover image. " + error.localizedDescription + finishCoverWork() + } + } + } + private func chooseCoverImage() { + guard !saving, coverEditorActive else { return } + let panel = NSOpenPanel() + panel.allowedContentTypes = [.image] + panel.canChooseDirectories = false; panel.canChooseFiles = true; panel.allowsMultipleSelection = false + panel.message = "Choose a private cover image for this software." + panel.prompt = "Choose Image" + coverPanel = panel + panel.begin { response in + Task { @MainActor in + guard coverEditorActive, coverPanel === panel else { return } + coverPanel = nil + if response == .OK, let url = panel.url { prepareCoverImage(url) } + } + } + } + private func prepareCoverImage(_ url: URL) { + let generation = beginCoverWork() + let entryID = entry.id + let worker = Task.detached(priority: .userInitiated) { + try Task.checkCancellation() + let data = try PersonalCoverImage.prepare(url) + try Task.checkCancellation() + return data + } + coverImageTask = worker + coverTask = Task { @MainActor in + do { + let data = try await worker.value + guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return } + guard let image = NSImage(data: data) else { throw CocoaError(.fileReadCorruptFile) } + pendingCoverData = data + coverImage = image + finishCoverWork() + } catch { + guard coverEditorActive, entry.id == entryID, coverGeneration == generation, !Task.isCancelled else { return } + coverError = "Could not use this image. " + error.localizedDescription + finishCoverWork() + } + } + } + private func beginCoverWork() -> UUID { + stopCoverWork() + coverBusy = true; coverError = nil + return coverGeneration + } + private func finishCoverWork() { + coverBusy = false; coverTask = nil; coverImageTask = nil; previewingImportedPath = nil + } + private func stopCoverWork() { + coverGeneration = UUID() + coverTask?.cancel(); coverTask = nil + coverImageTask?.cancel(); coverImageTask = nil + previewingImportedPath = nil + coverBusy = false + } + private func useCategoryIcon() { + stopCoverWork() + entry.cover = .categoryIcon; pendingCoverData = nil; coverImage = nil; coverError = nil + } + private func setIncluded(_ path: String, _ value: Bool) { + let removingSelectedCover = !value && coverSelection == "imported:" + path + if !value, previewingImportedPath == path { stopCoverWork() } + if value { included.insert(path) } else { included.remove(path) } + if !value, pendingCoverData != nil, case .imported(let previousPath)? = entry.cover, previousPath == path { + // The validated replacement is independent of this imported file. + entry.cover = .categoryIcon + } else if removingSelectedCover { useCategoryIcon() } + } + private func discardPendingCover() { + coverEditorActive = false + stopCoverWork() + coverPanel?.cancel(nil); coverPanel = nil + pendingCoverData = nil; coverDropTargeted = false + } + private func cancelEditing() { + discardPendingCover() + cancel() + } + private func submit(_ allowDuplicate: Bool) { + guard !saving, !coverBusy else { return } + var edited = entry + edited.files = edited.files.filter { included.contains($0.path) } + // The store validates the file inventory before installing the PNG. + // A replaced imported cover may have been excluded from that inventory. + if pendingCoverData != nil { edited.cover = .categoryIcon } + edited.command = edited.command.replacingOccurrences(of: "\r\n", with: "\r").replacingOccurrences(of: "\n", with: "\r") + save(edited, pendingCoverData, allowDuplicate) + } + private func roles(_ kind: String) -> [String] { + switch kind { + case "disk": return ["disk0","disk1","disk2","disk3"] + case "hard-disk": return ["hard0","hard1"] + case "cassette": return ["media"] + case "cartridge": return ["cartridge"] + default: return [] + } + } + private func roleLabel(_ role: String) -> String { + switch role { case "media": return "Cassette"; case "cartridge": return "ROM Cartridge" + default: return role.hasPrefix("hard") ? "HD" + role.suffix(1) : "FD" + role.suffix(1) } + } +} +#endif diff --git a/platforms/macos/App/SoftwareLibraryState.swift b/platforms/macos/App/SoftwareLibraryState.swift index 6beef5e..86477db 100644 --- a/platforms/macos/App/SoftwareLibraryState.swift +++ b/platforms/macos/App/SoftwareLibraryState.swift @@ -63,9 +63,11 @@ final class SoftwareLibraryState: ObservableObject { fileURL = directory.appendingPathComponent("Unused.json") } func applyRemoteSnapshot(_ snapshot: CompanionLibrarySnapshot) { - favoriteTitleIDs = snapshot.favorites - preferredReleaseIDs = snapshot.preferredReleaseIDs - installedReleases = Dictionary(snapshot.installations.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last }) + let visible = snapshot.catalog.companionDisksOnly + let titles = Set(visible.titles.map(\.id)), releases = Set(visible.releases.map(\.id)) + favoriteTitleIDs = snapshot.favorites.intersection(titles) + preferredReleaseIDs = snapshot.preferredReleaseIDs.filter { titles.contains($0.key) && releases.contains($0.value) } + installedReleases = Dictionary(snapshot.installations.filter { releases.contains($0.releaseID) }.map { ($0.releaseID, $0) }, uniquingKeysWith: { _, last in last }) saveError = nil } private func sendRemote(_ request: CompanionLibraryRequest) { diff --git a/platforms/macos/App/SoftwareLibraryView.swift b/platforms/macos/App/SoftwareLibraryView.swift index 264c9f8..296479a 100644 --- a/platforms/macos/App/SoftwareLibraryView.swift +++ b/platforms/macos/App/SoftwareLibraryView.swift @@ -10,6 +10,7 @@ struct SoftwareLibraryView: View { @State private var showAdvancedFilters = false @State private var confirmingReturn = false @State private var removingRelease: SoftwareLibraryRelease? + @State private var personalCoverDropTargeted = false var body: some View { VStack(spacing: 0) { header @@ -48,10 +49,10 @@ struct SoftwareLibraryView: View { } Divider() HStack { - Text("Color Computer Archive software and VCC Plus-exclusive titles").font(.caption).foregroundStyle(.secondary) + Text("Color Computer Archive, creator submissions and your private software").font(.caption).foregroundStyle(.secondary) Spacer() if model.filtering { ProgressView().controlSize(.mini) } - Text(model.catalog.map { "\($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "") + Text(model.catalog.map { "Catalog: \($0.titles.count.formatted()) titles · \($0.releaseCount.formatted()) editions" } ?? "") .font(.caption).foregroundStyle(.secondary) }.padding(.horizontal, 16).padding(.vertical, 9) } @@ -65,6 +66,7 @@ struct SoftwareLibraryView: View { if !model.isDiskCompanion { openWindow(id: "c-development") } } .modifier(SoftwareLibraryLaunchPresentation(model: model)) + .modifier(SoftwareLibraryPersonalPresentation(model: model)) .environment(\.companionLibraryAccess, model.companionAccess) .sheet(isPresented: $showManual) { VStack(spacing: 0) { @@ -82,7 +84,7 @@ struct SoftwareLibraryView: View { } message: { Text("This restarts the CoCo with the previous hardware and media assignments. It does not restore its previous program or memory. Unsaved media must be saved first.") } - .onDisappear { Task { await model.state.flush() } } + .onDisappear { model.saveBrowseContext(); Task { await model.state.flush() } } .alert("Remove from Library?", isPresented: Binding(get: { removingRelease != nil }, set: { if !$0 { removingRelease = nil } }), presenting: removingRelease) { release in Button("Cancel", role: .cancel) { removingRelease = nil } Button("Remove from Library") { Task { await model.removeInstallation(release.id) }; removingRelease = nil } @@ -100,12 +102,13 @@ struct SoftwareLibraryView: View { .accessibilityIdentifier("library-return-setup") .disabled(model.launchBusy || model.installingReleaseID != nil) } + libraryActions HStack(spacing: 7) { Image(systemName: "magnifyingglass").foregroundStyle(.secondary) - TextField("Search titles, authors, or keywords", text: $model.query.text) + TextField("Search titles, authors, or keywords", text: Binding(get: { model.query.text }, set: model.setSearchText)) .textFieldStyle(.plain).accessibilityLabel("Search software").accessibilityIdentifier("library-search") if !model.query.text.isEmpty { - Button { model.query.text = "" } label: { Image(systemName: "xmark.circle.fill") } + Button { model.setSearchText("") } label: { Image(systemName: "xmark.circle.fill") } .buttonStyle(.plain).help("Clear search").accessibilityLabel("Clear search") } }.padding(8).background(.quaternary.opacity(0.5), in: RoundedRectangle(cornerRadius: 8)) @@ -122,6 +125,7 @@ struct SoftwareLibraryView: View { Text("My Library").font(.caption.weight(.semibold)).foregroundStyle(.secondary).padding(.top, 8) scope("Favorites", icon: "heart", scope: .favorites, id: "favorites") scope("Installed", icon: "internaldrive", scope: .installed, id: "installed") + scope("Personal Library", icon: "lock.rectangle.stack", scope: .personal, id: "personal") }.padding(14) Divider() List { @@ -156,6 +160,7 @@ struct SoftwareLibraryView: View { }.buttonStyle(.plain).accessibilityIdentifier("library-scope-" + id) } private var heading: String { + if model.query.scope == .search { return "Search Results" } if !model.query.softwareType.isEmpty { return SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType) } if !model.query.category.isEmpty { return model.query.category.components(separatedBy: "/").last ?? "All Software" } switch model.query.scope { @@ -164,6 +169,8 @@ struct SoftwareLibraryView: View { case .all: return "All Software" case .favorites: return "Favorites" case .installed: return "Installed" + case .personal: return "Personal Library" + case .search: return "Search Results" } } private var browser: some View { @@ -186,6 +193,14 @@ struct SoftwareLibraryView: View { .help("Filter and sort").accessibilityLabel("Filter and sort").accessibilityIdentifier("library-filters") .popover(isPresented: $showFilters, arrowEdge: .bottom) { ScrollView { filters.padding(18) }.frame(width: 370, height: showAdvancedFilters ? 460 : 340) } }.padding(.horizontal, 16).padding(.top, 14) + if model.query.scope == .personal { + addPersonalSoftwareButton(id: "library-personal-add") + .padding(.horizontal, 16) + if model.isDiskCompanion { + Text("Add or edit personal software in VCC Plus. Your disk entries are available through the local connection.") + .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) + } + } if model.query.scope == .showcase { Text("Software with cover art, labels and screenshots.") .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16) @@ -193,10 +208,8 @@ struct SoftwareLibraryView: View { Text("A first selection to explore your CoCo. More guided picks will join the collection.") .font(.callout).foregroundStyle(.secondary).padding(.horizontal, 16) } - if !model.query.category.isEmpty || !model.query.softwareType.isEmpty { - Text(model.query.sort == .title - ? "Curated titles appear first, alphabetically, followed by the alphabetical collection." - : "Curated titles appear first, alphabetically; the remaining titles use your selected sort.") + if let orderingCaption { + Text(orderingCaption) .font(.caption).foregroundStyle(.secondary).padding(.horizontal, 16) } if !activeFilters.isEmpty { @@ -206,9 +219,19 @@ struct SoftwareLibraryView: View { Button("Clear filters") { model.clearFilters() }.controlSize(.small) }.padding(.horizontal, 16) } - if model.loading { + if let error = model.error, hasPersonalResults { + HStack(alignment: .top, spacing: 8) { + VStack(alignment: .leading, spacing: 3) { + Label("Catalog unavailable", systemImage: "exclamationmark.triangle") + Text(error).font(.caption).textSelection(.enabled) + Text("Your personal software is still available.").font(.caption) + }.foregroundStyle(.secondary).frame(maxWidth: .infinity, alignment: .leading) + Button("Retry") { Task { await model.load() } }.disabled(model.loading) + }.padding(.horizontal, 16).accessibilityIdentifier("library-catalog-unavailable-notice") + } + if model.loading && !hasPersonalResults { Spacer(); ProgressView("Opening the library…").frame(maxWidth: .infinity); Spacer() - } else if let error = model.error { + } else if let error = model.error, !hasPersonalResults { ContentUnavailableView { Label("Library unavailable", systemImage: "books.vertical") } description: { Text(error) } actions: { Button("Try Again") { Task { await model.load() } } } @@ -224,19 +247,76 @@ struct SoftwareLibraryView: View { model.selection = value } })) { - TableColumn("Title", value: \.name).width(min: 140, ideal: 240) + TableColumn("Title") { row in + HStack(spacing: 6) { + Text(row.name).lineLimit(2) + .accessibilityLabel(row.name + (row.isPersonal ? ", Personal Library" : "")) + .accessibilityIdentifier("library-table-title-" + row.id) + if row.isPersonal { personalBadge } + } + .accessibilityElement(children: .contain) + }.width(min: 140, ideal: 240) TableColumn("Format", value: \.formats).width(min: 65, ideal: 95) TableColumn("Size", value: \.size).width(55) }.accessibilityLabel("Software titles") + .background(SoftwareLibraryScrollTracker(ids: model.rows.map(\.id), table: true, + restoreID: model.browseTopID, restoreOffset: model.browseOffset, changed: model.rememberBrowsePosition)) } else { ScrollView { - LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) { - ForEach(model.rows) { row in shelfCard(row) } + LazyVStack(alignment: .leading, spacing: 18) { + if hasPersonalAndCatalog { + shelfHeading("Personal Library", icon: "lock.fill") + shelfGrid(model.rows.filter(\.isPersonal)) + shelfHeading("Catalog", icon: "books.vertical") + shelfGrid(model.rows.filter { !$0.isPersonal }) + } else { + shelfGrid(model.rows) + } }.padding(16) }.background(Color.primary.opacity(0.018)) + .background(SoftwareLibraryScrollTracker(ids: model.rows.map(\.id), table: false, + restoreID: model.browseTopID, restoreOffset: model.browseOffset, changed: model.rememberBrowsePosition)) } } } + private var hasPersonalResults: Bool { model.rows.contains(where: \.isPersonal) } + private var hasPersonalAndCatalog: Bool { + hasPersonalResults && model.rows.contains { !$0.isPersonal } + } + private var orderingCaption: String? { + let curatedFirst = !model.query.category.isEmpty || !model.query.softwareType.isEmpty + if hasPersonalAndCatalog { + if !curatedFirst { + return model.query.sort == .title + ? "Personal titles appear first, alphabetically. Catalog titles follow alphabetically." + : "Personal titles appear first, alphabetically. Catalog titles follow using your selected sort." + } + return model.query.sort == .title + ? "Personal titles appear first, alphabetically. Catalog titles follow, with curated titles first, then the alphabetical collection." + : "Personal titles appear first, alphabetically. Catalog titles follow, with curated titles first; the remaining titles use your selected sort." + } + guard model.rows.contains(where: { !$0.isPersonal }), curatedFirst else { return nil } + return model.query.sort == .title + ? "Curated titles appear first, alphabetically, followed by the alphabetical collection." + : "Curated titles appear first, alphabetically; the remaining titles use your selected sort." + } + private func shelfHeading(_ title: String, icon: String) -> some View { + Label(title, systemImage: icon).font(.headline).foregroundStyle(.secondary) + .accessibilityAddTraits(.isHeader) + } + private func shelfGrid(_ rows: [LibraryBrowseRow]) -> some View { + LazyVGrid(columns: [GridItem(.adaptive(minimum: 155, maximum: 215), spacing: 18)], alignment: .leading, spacing: 22) { + ForEach(rows) { row in shelfCard(row) } + } + } + private var personalBadge: some View { + Label("Personal", systemImage: "lock.fill").font(.caption2).foregroundStyle(.secondary) + .labelStyle(.titleAndIcon) + .fixedSize() + .accessibilityElement(children: .ignore) + .accessibilityLabel("Personal") + .accessibilityIdentifier("library-personal-badge") + } private var activeFilters: [String] { var labels: [String] = [] if !model.query.softwareType.isEmpty { labels.append(SoftwareLibraryOwnedGame.categoryLabel(model.query.softwareType)) } @@ -251,20 +331,33 @@ struct SoftwareLibraryView: View { } private var searchIsActive: Bool { !model.query.text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty } private var narrowed: Bool { searchIsActive || !activeFilters.isEmpty || !model.query.category.isEmpty } + private var personalLibraryIsEmpty: Bool { + #if !VCC_COMPANION_CLIENT + return !model.isDiskCompanion && model.query.scope == .personal && model.personalEntries.isEmpty + #else + return false + #endif + } private var emptyState: some View { ContentUnavailableView { - Label(!narrowed && model.query.scope == .installed ? "Your software will live here" : !narrowed && model.query.scope == .favorites ? "Keep your favorites close" : "No matching titles", systemImage: model.query.scope == .favorites ? "heart" : "books.vertical") + Label(personalLibraryIsEmpty ? "Add your first software" : !narrowed && model.query.scope == .installed ? "Your software will live here" : !narrowed && model.query.scope == .favorites ? "Keep your favorites close" : "No matching titles", systemImage: personalLibraryIsEmpty ? "lock.rectangle.stack" : model.query.scope == .favorites ? "heart" : "books.vertical") } description: { - if model.catalog?.releaseCount == 0 { Text("This development build has an empty catalog. Build with a prepared Software Library catalog to browse software.").accessibilityIdentifier("library-catalog-empty") } + if personalLibraryIsEmpty { Text("Add a folder, ZIP, or CoCo media files to your private library on this Mac. Your originals stay untouched; nothing is uploaded or run.") } + else if model.query.scope != .personal && model.catalog?.releaseCount == 0 { Text("This development build has an empty catalog. Build with a prepared Software Library catalog to browse software.").accessibilityIdentifier("library-catalog-empty") } else if narrowed { Text(searchIsActive ? "No titles match “\(model.query.text)” in this selection. Clear the search or adjust your filters." : "No titles match these filters. Try clearing them or choosing another category.") } else if model.query.scope == .installed { Text("Choose a title and Install Only to keep a copy on your Mac. Your running CoCo session will stay as it is.") } else if model.query.scope == .favorites { Text("Choose the heart beside a title to add it to your collection.") } else { Text("Try a different search, category, or filter.") } } actions: { - if searchIsActive { - Button("Clear Search") { model.query.text = "" }.accessibilityIdentifier("library-empty-clear-search") + if personalLibraryIsEmpty { + addPersonalSoftwareButton(id: "library-personal-add-first") + .buttonStyle(.borderedProminent) + } else { + if searchIsActive { + Button("Clear Search") { model.setSearchText("") }.accessibilityIdentifier("library-empty-clear-search") + } + Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) } } - Button("Browse All Titles") { model.query = LibraryBrowseQuery(scope: .all) } } } private var filters: some View { @@ -337,10 +430,13 @@ struct SoftwareLibraryView: View { Text(row.name).font(.callout.weight(.medium)).lineLimit(2).frame(maxWidth: .infinity, alignment: .leading) if model.state.isFavorite(row.id) { Image(systemName: "heart.fill").font(.caption).foregroundStyle(.pink) } } - Text(row.formats).font(.caption).foregroundStyle(.secondary).lineLimit(1) + HStack { + Text(row.formats).font(.caption).foregroundStyle(.secondary).lineLimit(1) + if row.isPersonal { personalBadge } + } }.padding(4).contentShape(Rectangle()) }.buttonStyle(.plain).accessibilityIdentifier("library-title-" + row.id) - .accessibilityLabel(row.name + ", " + row.formats).help(row.name) + .accessibilityLabel(row.name + (row.isPersonal ? ", Personal Library" : "") + ", " + row.formats).help(row.name) } @ViewBuilder private var detail: some View { if let row = model.selectedRow, let release = model.selectedRelease { @@ -358,11 +454,15 @@ struct SoftwareLibraryView: View { .accessibilityIdentifier("library-favorite") } if let error = model.state.saveError { Label(error, systemImage: "exclamationmark.triangle").font(.callout).foregroundStyle(.orange) } - SoftwareLibraryArtworkView( - asset: release.assets.first(where: { SoftwareLibraryArtworkCache.canDisplay($0) }), - cacheDirectory: model.artworkDirectory, - softwareType: LibraryBrowseQuery.type(of: release, related: row.title.releases)) - .frame(maxWidth: .infinity).frame(height: 200) + detailArtwork(release, title: row.title) + if release.isPersonal { + Label("Personal Library — Private on This Mac", systemImage: "lock.fill").font(.headline) + .accessibilityIdentifier("library-personal") + } + if release.isDirectSubmission { + Label("Creator-submitted software", systemImage: "person.crop.square").font(.headline) + if let author = release.metadata["author"].string { Text("By " + author).font(.callout) } + } if let owned = release.ownedGame { Label("VCC Plus-exclusive", systemImage: "sparkles").font(.headline) .accessibilityIdentifier("library-exclusive") @@ -408,11 +508,13 @@ struct SoftwareLibraryView: View { } } assetLinks(release) + relatedReferences(release) DisclosureGroup("Edition & source details") { metadata(release, title: row.title).padding(.top, 10) } .font(.callout) - if release.ownedGame == nil { + if release.isArchive { Link(destination: release.sourceURL.deletingLastPathComponent().appendingPathComponent("", isDirectory: true)) { Label("View on Color Computer Archive", systemImage: "arrow.up.right.square") } } + if release.isDirectSubmission { Link("Visit Project", destination: URL(string: release.metadata["project_url"].string ?? "") ?? release.sourceURL) } Text(model.isDiskCompanion ? "Insert Disk creates a separate writable copy for DriveWire. Choose its drive slot, then follow the loading instructions on your real CoCo." : "Play previews the recommended setup before restarting. You can also use the Media menu to mount installed files yourself.") @@ -423,6 +525,59 @@ struct SoftwareLibraryView: View { ContentUnavailableView("Choose a title", systemImage: "book.closed", description: Text("Explore its editions, loading instructions, and manuals.")) } } + private func artwork(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View { + SoftwareLibraryArtworkView(asset: release.assets.first(where: { SoftwareLibraryArtworkCache.canDisplay($0) }), + cacheDirectory: model.artworkDirectory, softwareType: LibraryBrowseQuery.type(of: release, related: title.releases)) + .frame(maxWidth: .infinity).frame(height: 200) + } + @ViewBuilder private func detailArtwork(_ release: SoftwareLibraryRelease, title: SoftwareLibraryTitle) -> some View { + #if !VCC_COMPANION_CLIENT + if !model.isDiskCompanion, let entry = model.selectedPersonalEntry { + VStack(alignment: .leading, spacing: 8) { + artwork(release, title: title) + .overlay(RoundedRectangle(cornerRadius: 9).strokeBorder(personalCoverDropTargeted ? Color.accentColor : .clear, lineWidth: 3)) + .contentShape(Rectangle()) + .overlay { + PersonalCoverFileDropTarget(enabled: model.canEditPersonal && model.personalEditor == nil, + isTargeted: $personalCoverDropTargeted) { urls in + model.acceptPersonalCoverDrop(urls, for: entry) + }.frame(maxWidth: .infinity, maxHeight: .infinity).accessibilityHidden(true) + } + .accessibilityIdentifier("library-personal-cover") + HStack { + Menu { + Button("Choose Cover Image…", systemImage: "photo") { model.choosePersonalCover(for: entry) } + let imported = entry.files.filter { $0.kind == "cover" } + if !imported.isEmpty { + Menu("Use Imported Image") { + ForEach(imported) { file in + Button(URL(fileURLWithPath: file.path).lastPathComponent) { + model.selectPersonalCover(.imported(file.path), for: entry) + } + } + } + } + Button("Remove Cover", systemImage: "photo.badge.minus") { + model.selectPersonalCover(.categoryIcon, for: entry) + }.disabled(!release.assets.contains(where: { SoftwareLibraryArtworkCache.canDisplay($0) })) + } label: { Label("Cover Image", systemImage: "photo") } + .disabled(!model.canEditPersonal || model.personalEditor != nil) + .accessibilityIdentifier("library-personal-cover-menu") + if model.personalSaving { ProgressView().controlSize(.small) } + } + Text("Drop an image onto the cover, or choose one. It stays private on this Mac.") + .font(.caption).foregroundStyle(.secondary) + #if VCC_UI_TESTING + if ProcessInfo.processInfo.environment["VCC_COVER_DRAG_SOURCE"] != nil { + PersonalCoverFileDragFixture().frame(width: 120, height: 45) + } + #endif + } + } else { artwork(release, title: title) } + #else + artwork(release, title: title) + #endif + } private func sourceCard(_ release: SoftwareLibraryRelease, owned: SoftwareLibraryOwnedGame) -> some View { SecondaryCard { Label("Learn from the source", systemImage: "curlybraces").font(.headline) @@ -460,6 +615,8 @@ struct SoftwareLibraryView: View { .font(.caption).foregroundStyle(.secondary) } Button("Cancel", role: .cancel) { model.cancelInstallation() }.accessibilityIdentifier("library-cancel-install") + } else if release.isPersonal && !model.isDiskCompanion { + personalActions(release) } else if let installed = model.state.installedReleases[release.id] { Label("Installed", systemImage: "checkmark.circle.fill").font(.headline).foregroundStyle(.green) .accessibilityIdentifier("library-install-status") @@ -467,8 +624,12 @@ struct SoftwareLibraryView: View { Text("Your writable media is ready. The original files are kept separately.").font(.callout) Button { NSWorkspace.shared.open(installed.workingDirectory) } label: { Label("Show Files in Finder", systemImage: "folder") } .accessibilityIdentifier("library-reveal-install") - Button("Remove from Library…") { removingRelease = release } - .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil).accessibilityIdentifier("library-remove-install") + if release.isPersonal && model.isDiskCompanion { + Text("Manage this personal entry in VCC Plus.").font(.caption).foregroundStyle(.secondary) + } else { + Button("Remove from Library…") { removingRelease = release } + .disabled(model.launchBusy || model.hasPendingLaunch || model.installingReleaseID != nil).accessibilityIdentifier("library-remove-install") + } } else { if model.canLaunch { playButton(release, installed: false) } Button { model.install(release) } label: { Label(model.installationErrors[release.id] == nil ? "Install Only" : "Try Again", systemImage: "arrow.down.circle") } @@ -534,7 +695,7 @@ struct SoftwareLibraryView: View { VStack(alignment: .leading, spacing: 6) { Label("Controls", systemImage: "gamecontroller").font(.subheadline.weight(.medium)) ForEach(controls.keys.sorted(), id: \.self) { key in - Text(release.setup.controlDescription(key, source: release.ownedGame == nil ? "the Archive" : "the project")).font(.callout).textSelection(.enabled) + Text(release.setup.controlDescription(key, source: release.isPersonal ? "your setup" : release.isArchive ? "the Archive" : "the author")).font(.callout).textSelection(.enabled) .accessibilityIdentifier("library-controls-" + key) } } @@ -557,7 +718,7 @@ struct SoftwareLibraryView: View { .accessibilityIdentifier("library-manual-" + manual.id) } else { Link(destination: manual.sourceURL) { Label(manual.name, systemImage: "arrow.up.right.square") } - .font(.callout).help(release.ownedGame == nil ? "Open this document on Color Computer Archive" : "Open this project document") + .font(.callout).help(release.isArchive ? "Open this document on Color Computer Archive" : "Open this project document") } } } @@ -578,18 +739,23 @@ struct SoftwareLibraryView: View { } if let publisher = release.publisher { LabeledContent("Publisher", value: publisher) } if let year = release.year { LabeledContent("Year", value: String(year)) } - LabeledContent("Download", value: ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file)) + LabeledContent(release.isPersonal ? "Retained files" : "Download", value: ByteCountFormatter.string(fromByteCount: release.byteSize, countStyle: .file)) + if release.isDirectSubmission { + if let author = release.metadata["author"].string { LabeledContent("Author", value: author) } + if let license = release.metadata["license"].string { LabeledContent("License", value: license) } + if let version = release.metadata["software_version"].string { LabeledContent("Software version", value: version) } + } if let owned = release.ownedGame { LabeledContent("Author", value: owned.author) LabeledContent("License", value: owned.license) } - LabeledContent(release.ownedGame == nil ? "Archive modified" : "Project modified", value: release.modifiedAt ?? "Unknown") - if release.ownedGame == nil, release.modifiedAt != nil, release.modifiedTimezone == nil || release.modifiedTimezone == "unspecified" { + LabeledContent(release.isArchive ? "Archive modified" : "Modified", value: release.modifiedAt ?? "Unknown") + if release.isArchive, release.modifiedAt != nil, release.modifiedTimezone == nil || release.modifiedTimezone == "unspecified" { Text("Archive date; time zone not specified.").font(.caption).foregroundStyle(.secondary) } - LabeledContent("Loading evidence", value: release.ownedGame == nil ? release.setup.statusLabel : "Project-provided loading instructions") + LabeledContent("Loading evidence", value: release.isPersonal ? "User-provided private setup" : release.ownedGame == nil ? release.setup.statusLabel : "Project-provided loading instructions") Text(release.setup.validationScope.map { "VCC Plus check: " + $0.replacingOccurrences(of: "-", with: " ") } ?? "Not individually tested in VCC Plus.") - if release.ownedGame == nil && title.releases.count > 1 && title.identityStatus == "suggested" { Text("Related editions are grouped from Archive names; their contents may differ.") } + if release.isArchive && title.releases.count > 1 && title.identityStatus == "suggested" { Text("Related editions are grouped from Archive names; their contents may differ.") } if !release.videoModes.isEmpty { Text("Video: " + release.videoModes.joined(separator: ", ")) } if let note = release.setup.curationNote { Text(note) } if !release.assets.isEmpty { @@ -597,7 +763,8 @@ struct SoftwareLibraryView: View { Text("Artwork & manual sources").fontWeight(.medium) ForEach(release.assets) { asset in VStack(alignment: .leading, spacing: 3) { - Link(asset.name, destination: asset.sourceURL) + if asset.matchStatus == "personal" { Text(asset.name) } + else { Link(asset.name, destination: asset.sourceURL) } Text(asset.credit).foregroundStyle(.secondary) if asset.matchStatus == "candidate" { Text("Suggested match from Archive names; corrections are welcome.").font(.caption).foregroundStyle(.secondary) } } @@ -621,6 +788,65 @@ struct SoftwareLibraryView: View { private func systemName(_ value: String) -> String { switch value { case "coco3": return "Color Computer 3"; case "coco1-2", "coco1/2": return "Color Computer 1/2"; case "unknown": return "Not specified"; default: return value } } + @ViewBuilder private func addPersonalSoftwareButton(id: String) -> some View { + #if !VCC_COMPANION_CLIENT + if !model.isDiskCompanion { + Button("Add Software…", systemImage: "folder.badge.plus") { model.choosePersonalSoftware() } + .disabled(!model.canEditPersonal || model.personalEditor != nil) + .help("Add software to your private Personal Library") + .accessibilityIdentifier(id) + } + #endif + } + @ViewBuilder private var libraryActions: some View { + #if !VCC_COMPANION_CLIENT + if !model.isDiskCompanion { + Menu { + Button("Add Personal Software…", systemImage: "folder.badge.plus") { model.choosePersonalSoftware() } + .disabled(!model.canEditPersonal) + Button("Submit Software…", systemImage: "paperplane") { + NSWorkspace.shared.open(URL(string: "https://vccplus.brianholman.com/software/submit/")!) + } + } label: { Image(systemName: "ellipsis.circle") } + .help("Library Actions").accessibilityLabel("Library Actions").accessibilityIdentifier("library-actions") + } + #endif + } + @ViewBuilder private func personalActions(_ release: SoftwareLibraryRelease) -> some View { + #if !VCC_COMPANION_CLIENT + if let entry = model.selectedPersonalEntry { + Label("Private copy", systemImage: "lock.fill").font(.headline) + if model.canLaunch, release.mediaType != "binary" { playButton(release, installed: true) } + Text(release.mediaType == "binary" ? "Open the working folder, then use File → Load Binary to load this program deliberately." : "Your writable media and retained originals are kept separately. Nothing is uploaded.").font(.caption).foregroundStyle(.secondary) + Button("Edit Details…", systemImage: "pencil") { model.editPersonal(entry) }.disabled(!model.canEditPersonal) + Button("Show Files in Finder", systemImage: "folder") { NSWorkspace.shared.open(model.personalDirectory(entry).appendingPathComponent("Working")) } + Button("Remove from Library…") { removingRelease = release } + .disabled(model.launchBusy || model.hasPendingLaunch) + } + #endif + } + @ViewBuilder private func relatedReferences(_ release: SoftwareLibraryRelease) -> some View { + #if !VCC_COMPANION_CLIENT + if !model.isDiskCompanion, !release.relatedArchiveReferences.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("Guides & References").font(.headline) + ForEach(release.relatedArchiveReferences) { reference in + Button { + ArchiveLibraryNavigation.shared.open(documentID: reference.documentID, location: reference.page, + expectedSHA256: reference.sha256) + openWindow(id: "archive-library") + } label: { + VStack(alignment: .leading, spacing: 2) { + Label(reference.title, systemImage: "doc.text.magnifyingglass") + Text(reference.role + (reference.spoiler ? " · Contains spoilers" : "") + (reference.page.map { " · Page \($0)" } ?? "")) + .font(.caption).foregroundStyle(.secondary) + } + }.buttonStyle(.link).help("Open in Archive Library").accessibilityIdentifier("library-reference-" + reference.id) + } + } + } + #endif + } private func profileName(_ value: String) -> String { switch value { case "rom-cartridge": return "ROM Cartridge"; case "disk-basic": return "Disk BASIC"; case "hard-drive-basic", "hard-basic": return "Hard Drive BASIC"; case "coco-sdc": return "CoCo SDC"; case "nitros9": return "NitrOS-9"; default: return value.replacingOccurrences(of: "-", with: " ").capitalized } } @@ -642,3 +868,101 @@ private struct SoftwareLibraryLaunchPresentation: ViewModifier { #endif } } + +/// Observes the actual native clip view without taking over its delegate or +/// sending pointer events. Restoration runs once, after content is installed. +private struct SoftwareLibraryScrollTracker: NSViewRepresentable { + let ids: [String] + let table: Bool + let restoreID: String? + let restoreOffset: Double + let changed: (String?, Double) -> Void + func makeCoordinator() -> Coordinator { Coordinator() } + func makeNSView(context: Context) -> NSView { NSView() } + func updateNSView(_ view: NSView, context: Context) { + context.coordinator.ids = ids; context.coordinator.table = table; context.coordinator.changed = changed + context.coordinator.restoreID = restoreID; context.coordinator.restoreOffset = restoreOffset + context.coordinator.attach(view) + context.coordinator.refreshRestoration() + } + static func dismantleNSView(_ view: NSView, coordinator: Coordinator) { coordinator.clear() } + final class Coordinator { + var ids: [String] = [], table = false + var restoreID: String?, restoreOffset: Double = 0 + var changed: ((String?, Double) -> Void)? + private var token: NSObjectProtocol? + private weak var scroll: NSScrollView? + private var restored = false, attaching = false + private var attachAttempts = 0, restoreAttempts = 0 + func clear() { if let token { NotificationCenter.default.removeObserver(token) }; token = nil; scroll = nil; restored = false } + func attach(_ marker: NSView) { + guard scroll == nil, !attaching else { return } + attaching = true + DispatchQueue.main.async { [weak self, weak marker] in + guard let self else { return }; self.attaching = false + guard let marker, marker.window != nil else { return } + var ancestor: NSView? = marker.superview + let target = marker.convert(marker.bounds, to: nil) + for _ in 0..<6 { + guard let root = ancestor else { break } + func descendants(_ view: NSView) -> [NSScrollView] { + (view as? NSScrollView).map { [$0] } ?? view.subviews.flatMap(descendants) + } + if let match = descendants(root).first(where: { candidate in + let frame = candidate.convert(candidate.bounds, to: nil) + return target.width > 0 && target.height > 0 && frame.intersection(target).width > target.width * 0.8 && + frame.intersection(target).height > target.height * 0.8 && (!self.table || candidate.documentView is NSTableView) + }) { + self.scroll = match; match.contentView.postsBoundsChangedNotifications = true + self.token = NotificationCenter.default.addObserver(forName: NSView.boundsDidChangeNotification, + object: match.contentView, queue: .main) { [weak self] _ in self?.record() } + DispatchQueue.main.async { [weak self] in self?.restore() } + return + } + ancestor = root.superview + } + if self.attachAttempts < 20 { + self.attachAttempts += 1 + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self, weak marker] in + if let marker { self?.attach(marker) } + } + } + } + } + func refreshRestoration() { + guard !restored else { return } + DispatchQueue.main.async { [weak self] in self?.restore() } + } + private func restore() { + guard !restored, !ids.isEmpty, let scroll, let document = scroll.documentView else { return } + if document.bounds.height <= 0 || scroll.contentView.bounds.height <= 0 || ((document as? NSTableView).map { $0.numberOfRows < ids.count } ?? false) { + if restoreAttempts < 20 { + restoreAttempts += 1 + DispatchQueue.main.asyncAfter(deadline: .now() + 0.05) { [weak self] in self?.restore() } + } + return + } + restored = true + let range = max(0, document.bounds.height - scroll.contentView.bounds.height) + var y = CGFloat(max(0, min(restoreOffset, 1))) * range + if let table = document as? NSTableView, let id = restoreID, let index = ids.firstIndex(of: id), index < table.numberOfRows { + let row = table.rect(ofRow: index); y = row.minY + CGFloat(restoreOffset) * row.height + } + scroll.contentView.scroll(to: NSPoint(x: 0, y: min(max(0,y), range))); scroll.reflectScrolledClipView(scroll.contentView) + } + private func record() { + guard restored, let scroll, let document = scroll.documentView else { return } + let y = scroll.contentView.bounds.minY + if let table = document as? NSTableView { + let index = table.row(at: NSPoint(x: 1, y: y)) + if ids.indices.contains(index) { + let row = table.rect(ofRow: index) + changed?(ids[index], Double((y - row.minY) / max(1,row.height))); return + } + } + let range = max(1, document.bounds.height - scroll.contentView.bounds.height) + changed?(nil, Double(y/range)) + } + deinit { if let token { NotificationCenter.default.removeObserver(token) } } + } +} diff --git a/platforms/macos/App/VCCMacApp.swift b/platforms/macos/App/VCCMacApp.swift index 9d147a2..dcfdbb0 100644 --- a/platforms/macos/App/VCCMacApp.swift +++ b/platforms/macos/App/VCCMacApp.swift @@ -54,7 +54,7 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje basicExamples[id] = workspace return workspace } - lazy var softwareLibrary = SoftwareLibraryModel(state: SoftwareLibraryState(directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary")), artworkDirectory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary/ArtworkCache"), machine: machine, + lazy var softwareLibrary = SoftwareLibraryModel(state: SoftwareLibraryState(directory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary")), continuity: LibraryContinuityStore.shared, artworkDirectory: profileStore.directory.deletingLastPathComponent().appendingPathComponent("SoftwareLibrary/ArtworkCache"), machine: machine, sourceWorkspaceIdentity: { [weak self] in self?.development.assistantProjectID ?? UUID() }, openSourceProject: { [weak self] directory, identity, configuration in guard let self else { return false } @@ -121,6 +121,7 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje #endif } super.init() + LibraryContinuityStore.configureShared(directory: profileStore.directory.deletingLastPathComponent()) } func applicationDidFinishLaunching(_ notification: Notification) { #if VCC_UI_TESTING @@ -239,6 +240,33 @@ final class ApplicationDelegate: NSObject, NSApplicationDelegate, ObservableObje } private var terminationPending = false func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + if machine.captures.saving { + let alert = NSAlert(); alert.messageText = "Wait for the CoCo image to finish saving." + alert.informativeText = "Your captured picture is still being written. Try quitting again after saving completes." + alert.runModal() + return .terminateCancel + } + if machine.captures.hasPendingImage { + let alert = NSAlert(); alert.messageText = "A captured CoCo image has not been saved." + alert.addButton(withTitle: "Cancel Quit"); alert.addButton(withTitle: "Save Image As…"); alert.addButton(withTitle: "Discard Image and Continue") + let choice = alert.runModal() + if choice == .alertSecondButtonReturn { machine.captures.saveImageAs(); return .terminateCancel } + guard choice == .alertThirdButtonReturn else { return .terminateCancel } + machine.captures.discardImage() + } + if machine.captures.active { + guard machine.captures.recording, !terminationPending else { return .terminateCancel } + let alert = NSAlert(); alert.messageText = "Stop and save the CoCo movie before quitting?" + alert.addButton(withTitle: "Cancel Quit"); alert.addButton(withTitle: "Stop and Save") + guard alert.runModal() == .alertSecondButtonReturn else { return .terminateCancel } + terminationPending = true + Task { @MainActor in + await machine.captures.stopRecording() + terminationPending = false + if machine.captures.error == nil { sender.terminate(nil) } + } + return .terminateCancel + } if companionLaunchDeferred { guard !terminationPending else { return .terminateCancel } terminationPending = true @@ -392,6 +420,7 @@ struct MachineCommands: Commands { @FocusedValue(\.emulatorWindow) private var emulatorWindow let machine: MachineModel @ObservedObject private var menu: MachineMenuState + @ObservedObject private var captureMenu: CoCoCaptureMenuState @ObservedObject var presentation: PresentationSettings let connectAssistant: () -> Void init(machine: MachineModel, presentation: PresentationSettings, connectAssistant: @escaping () -> Void) { @@ -399,6 +428,7 @@ struct MachineCommands: Commands { self.presentation = presentation self.machine = machine self.menu = machine.menuState + self.captureMenu = machine.captures.menuState } @Environment(\.openWindow) private var openWindow @CommandsBuilder @@ -414,6 +444,9 @@ struct MachineCommands: Commands { Button("Assembly Quick Reference…") { openWindow(id: "assembly-reference") } Button("Keyboard & Shortcuts…") { openWindow(id: "keyboard-help") } Button("Release History…") { openWindow(id: "release-history") } + Button("Feedback…") { + NSWorkspace.shared.open(URL(string: "https://vccplus.brianholman.com/feedback/?product=vcc-plus")!) + } Button("Licenses & Notices…") { openWindow(id: "credits") } Button("About VCC Plus OSS") { openWindow(id: "about") } } @@ -479,6 +512,16 @@ struct MachineCommands: Commands { Button("Save CoCo Screen…", action: machine.saveScreenshot) .keyboardShortcut("s", modifiers: [.command, .shift]) .disabled(menu.values.busy || !(menu.values.state == .running || menu.values.state == .paused)) + Menu("Quick CoCo Capture") { + Button("Capture CoCo Screen", action: machine.captures.capture) + CoCoCaptureOptions(preferences: machine.captures.preferences) + Button("Cancel Timed Capture", action: machine.captures.cancelCountdown).disabled(!captureMenu.countdown) + }.disabled(!(menu.values.state == .running || menu.values.state == .paused)) + Button(captureMenu.state == .recording ? "Stop CoCo Video Recording" : "Record CoCo Video") { + if machine.captures.recording { Task { await machine.captures.stopRecording() } } + else { machine.captures.startRecording() } + }.disabled(captureMenu.state == .starting || captureMenu.state == .finishing || (captureMenu.state != .recording && !(menu.values.state == .running || menu.values.state == .paused))) + Button("Capture Settings…") { openWindow(id: "machine"); machine.captures.settingsShown = true } } CommandGroup(after: .pasteboard) { Divider() diff --git a/platforms/macos/Bridge/VCCMachineController.h b/platforms/macos/Bridge/VCCMachineController.h index 3bf4721..dd8db75 100644 --- a/platforms/macos/Bridge/VCCMachineController.h +++ b/platforms/macos/Bridge/VCCMachineController.h @@ -60,7 +60,7 @@ typedef NS_ENUM(NSInteger, VCCDiskInsertionReset) { @interface VCCMachineSnapshot : NSObject @property(nonatomic, readonly) VCCMachineState state; @property(nonatomic, readonly) uint64_t generation; -@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision; +@property(nonatomic, readonly) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, debuggerResidencyFingerprint, assistantMediaRevision; @property(nonatomic, readonly) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping; @property(nonatomic, readonly) BOOL debuggerBankedDevelopment; @property(nonatomic, readonly) BOOL basicDebugAttached, assistantCompiledReturned; @@ -221,7 +221,21 @@ typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot); @property(nonatomic, readonly) NSArray *records; @end +// Guest-only immutable recording input. Each audio frame is Float32 stereo at +// 44.1 kHz. The offset is a monotonic recording timeline, not a CPU cycle count. +@interface VCCVideoPacket : NSObject +@property(nonatomic, readonly) NSData *pixels, *samples; +@property(nonatomic, readonly) CGRect activeArea; +@property(nonatomic, readonly) uint64_t sampleOffset; +@end + @interface VCCMachineController : NSObject +- (void)beginVideoCaptureWithCompletion:(VCCMachineCompletion)completion NS_SWIFT_NAME(beginVideoCapture(completion:)); +- (void)takeVideoCapturePackets:(BOOL)finish completion:(void (^)(NSArray *, NSString * _Nullable))completion NS_SWIFT_NAME(takeVideoCapture(finish:completion:)); +// Recording data must continue draining while a native modal loop owns the UI. +// Ordinary callers retain the main-queue completion methods above. +- (void)beginVideoCaptureOnQueue:(dispatch_queue_t)replyQueue completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(beginVideoCapture(replyQueue:completion:)); +- (void)takeVideoCapturePackets:(BOOL)finish replyQueue:(dispatch_queue_t)replyQueue completion:(void (^)(NSArray *, NSString * _Nullable))completion NS_SWIFT_NAME(takeVideoCapture(finish:replyQueue:completion:)); // Capture starts disabled. Toggling or clearing never pauses/resets the machine. // Closing a UI window has no effect; reset/profile replacement retain output. - (void)setPrinterEnabled:(BOOL)enabled completion:(VCCMachineCompletion)completion; @@ -236,7 +250,7 @@ typedef void (^VCCMachineCompletion)(VCCMachineSnapshot *snapshot); // mode: 0 into, 1 over, 2 out. Completion acknowledges start; poll machine state // for the eventual pause. pauseWithCompletion cancels a pending source step. - (void)debuggerStepSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepSource(mode:addresses:locations:bytes:generation:programRevision:mappingFingerprint:programCounter:completion:)); -- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:programCounter:completion:)); +- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint residencyFingerprint:(uint64_t)residencyFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion NS_SWIFT_NAME(debuggerStepBankedSource(mode:addresses:locations:bytes:moduleIdentifiers:generation:programRevision:mappingFingerprint:residencyFingerprint:programCounter:completion:)); - (void)debuggerMemoryAtAddress:(uint32_t)address count:(uint32_t)count physical:(BOOL)physical logicalAddress:(uint16_t)logicalAddress os9:(BOOL)os9 decode:(BOOL)decode completion:(void (^)(VCCDebugMemoryCapture *))completion NS_SWIFT_NAME(debuggerMemory(address:count:physical:logicalAddress:os9:decode:completion:)); - (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion; - (void)debuggerSetBreakpoints:(NSArray *)addresses completion:(VCCMachineCompletion)completion; diff --git a/platforms/macos/Bridge/VCCMachineController.mm b/platforms/macos/Bridge/VCCMachineController.mm index 902fe1e..452c285 100644 --- a/platforms/macos/Bridge/VCCMachineController.mm +++ b/platforms/macos/Bridge/VCCMachineController.mm @@ -17,12 +17,21 @@ #include #include #include +#include #include #include #include #include #include +@interface VCCVideoPacket () +@property(nonatomic, readwrite, copy) NSData *pixels, *samples; +@property(nonatomic, readwrite) CGRect activeArea; +@property(nonatomic, readwrite) uint64_t sampleOffset; +@end +@implementation VCCVideoPacket +@end + @interface VCCTraceRecord () @property(nonatomic, readwrite) NSUInteger index; @property(nonatomic, readwrite) uint64_t clock, frame; @@ -291,7 +300,7 @@ static std::vector DebugAddresses(NSArray* values, unsigned @property(nonatomic, readwrite) uint64_t generation, frames, cycles; @property(nonatomic, readwrite, copy) NSArray *joystickInputs; @property(nonatomic, readwrite) BOOL keyboardInputHeld; -@property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, assistantMediaRevision; +@property(nonatomic, readwrite) uint64_t debuggerProgramRevision, debuggerMappingFingerprint, debuggerResidencyFingerprint, assistantMediaRevision; @property(nonatomic, readwrite) BOOL debuggerDevelopmentAttached, debuggerAssemblyAttached, debuggerSourceStepping; @property(nonatomic, readwrite) BOOL debuggerBankedDevelopment; @property(nonatomic, readwrite) BOOL basicDebugAttached, assistantCompiledReturned; @@ -384,6 +393,11 @@ struct Worker { VCC::Mac::MachineSession machine; VCC::Mac::MacAudioOutput audio; bool audioEnabled = false, fastForward = false; + bool recording = false; + NSMutableArray *recordingPackets = nil; + std::chrono::steady_clock::time_point recordingOrigin{}, recordingLast{}; + uint64_t recordingSample = 0; + std::string recordingError; VCC::Mac::FramePacer pacer; VCC::Mac::AudioProgress audioProgress; std::chrono::steady_clock::time_point previousAudioTick{}; @@ -500,6 +514,19 @@ std::vector BankedModules(NSArray 128 || + [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128) + throw std::invalid_argument("Overlay modules require bounded group and owner identities"); + const char *groupText = [overlayGroup UTF8String], *ownerText = [overlayOwner UTF8String]; + if (!groupText || !ownerText || std::strlen(groupText) != [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] || + std::strlen(ownerText) != [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) + throw std::invalid_argument("Overlay identities must not contain embedded NUL bytes"); + parsed.overlayGroup = groupText; parsed.overlayOwner = ownerText; + } if (id qualified = module[@"breakpoints"]) { if (![qualified isKindOfClass:NSArray.class]) throw std::invalid_argument("Module breakpoints must be an array"); for (id point in qualified) @@ -528,6 +555,7 @@ VCC::Mac::Snapshot AssemblyIdentity(VCCMachineSnapshot *snapshot) { expected.generation = snapshot.generation; expected.debuggerProgramRevision = snapshot.debuggerProgramRevision; expected.debuggerMappingFingerprint = snapshot.debuggerMappingFingerprint; + expected.debuggerResidencyFingerprint = snapshot.debuggerResidencyFingerprint; expected.cpu.PC = snapshot.programCounter; expected.cycles = snapshot.cycles; return expected; @@ -664,6 +692,7 @@ VCCMachineSnapshot *Capture(Worker& worker) { if (worker.closed) result.state = VCCMachineStateClosed; result.generation = value.generation; result.frames = value.frames; result.debuggerProgramRevision = value.debuggerProgramRevision; result.debuggerMappingFingerprint = value.debuggerMappingFingerprint; + result.debuggerResidencyFingerprint = value.debuggerResidencyFingerprint; result.debuggerDevelopmentAttached = value.debuggerDevelopmentAttached; result.debuggerBankedDevelopment = value.debuggerBankedDevelopment; result.debuggerAssemblyAttached = value.debuggerAssemblyAttached; @@ -714,6 +743,32 @@ void CheckCompiledRun(Worker& worker, VCCCompiledRunLease *lease, VCCMachineSnap if (!worker.machine.sharedCompiledCallActive()) throw std::logic_error(worker.machine.sharedCompiledCallReturned() ? "run_finished" : "unverified_program_entry"); } +void RecordVideoPacket(Worker& worker, const std::vector& samples) { + if (!worker.recording) return; + const auto value = worker.machine.snapshot(); + if (!value.frame || value.frame->pixels.size() != 640 * 480) return; + if (worker.recordingPackets.count >= 8) { + worker.recording = false; + worker.recordingError = "Recording input stopped keeping up. The working movie has been retained; the CoCo keeps running."; + return; + } + const auto now = std::chrono::steady_clock::now(); + const auto elapsed = std::chrono::duration(now - worker.recordingOrigin).count(); + const uint64_t position = std::max(worker.recordingSample, uint64_t(elapsed * 44100)); + const auto& frame = *value.frame; + auto packet = [VCCVideoPacket new]; + packet.pixels = [NSData dataWithBytes:frame.pixels.data() length:frame.pixels.size() * sizeof(uint32_t)]; + packet.activeArea = CGRectMake(frame.activeArea.x, frame.activeArea.y, frame.activeArea.width, frame.activeArea.height); + packet.samples = [NSData dataWithBytes:samples.data() length:samples.size() * sizeof(VCC::Mac::StereoSample)]; + packet.sampleOffset = position; + worker.recordingSample = position + samples.size(); worker.recordingLast = now; + [worker.recordingPackets addObject:packet]; +} +std::vector DrainWorkerAudio(Worker& worker) { + auto samples = worker.machine.takeAudio(); + RecordVideoPacket(worker, samples); + return samples; +} void AdvanceWorker(Worker& worker) { if (worker.compiledKeyLease) { if (worker.machine.pasteRemaining()) { @@ -749,6 +804,40 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin dispatch_source_t _timer; std::shared_ptr _worker; } +- (void)beginVideoCaptureWithCompletion:(VCCMachineCompletion)completion { + [self beginVideoCaptureOnQueue:dispatch_get_main_queue() completion:completion]; +} +- (void)beginVideoCaptureOnQueue:(dispatch_queue_t)replyQueue completion:(VCCMachineCompletion)completion { + auto worker = _worker; + dispatch_async(_queue, ^{ + try { + worker->error.clear(); + worker->requireNoDiskEditor(); + if (worker->closed || !worker->machine.snapshot().frame) throw std::logic_error("No CoCo picture is available to record."); + if (worker->fastForward) throw std::logic_error("Turn off fast-forward before recording video."); + if (worker->recording) throw std::logic_error("A CoCo movie is already recording."); + worker->recordingPackets = [NSMutableArray new]; worker->recordingError.clear(); + worker->recordingSample = 0; + worker->recordingOrigin = worker->recordingLast = std::chrono::steady_clock::now(); + worker->recording = true; + } catch (const std::exception& error) { worker->error = error.what(); } + VCCMachineSnapshot *snapshot = Capture(*worker); + dispatch_async(replyQueue, ^{ completion(snapshot); }); + }); +} +- (void)takeVideoCapturePackets:(BOOL)finish completion:(void (^)(NSArray *, NSString *))completion { + [self takeVideoCapturePackets:finish replyQueue:dispatch_get_main_queue() completion:completion]; +} +- (void)takeVideoCapturePackets:(BOOL)finish replyQueue:(dispatch_queue_t)replyQueue completion:(void (^)(NSArray *, NSString *))completion { + auto worker = _worker; + dispatch_async(_queue, ^{ + if (finish) worker->recording = false; + NSArray *packets = [worker->recordingPackets copy] ?: @[]; + [worker->recordingPackets removeAllObjects]; + NSString *error = worker->recordingError.empty() ? nil : [NSString stringWithUTF8String:worker->recordingError.c_str()]; + dispatch_async(replyQueue, ^{ completion(packets, error); }); + }); +} - (instancetype)init { if ((self = [super init])) { _worker = std::make_shared(); @@ -765,6 +854,8 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin try { if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) { if (worker->audio.running()) worker->audio.stop(); + if (worker->recording && std::chrono::steady_clock::now() - worker->recordingLast >= std::chrono::microseconds(16667)) + RecordVideoPacket(*worker, std::vector(735)); worker->pacer.reset(); worker->audioProgress.reset(); return; } if (worker->fastForward) { @@ -772,7 +863,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin // input, pause, and automatic media saves keep getting turns. const auto deadline = std::chrono::steady_clock::now() + std::chrono::milliseconds(8); for (unsigned i = 0; i < 4; ++i) { - AdvanceWorker(*worker); worker->machine.takeAudio(); + AdvanceWorker(*worker); DrainWorkerAudio(*worker); if (std::chrono::steady_clock::now() >= deadline) break; } } else if (worker->audioEnabled) { @@ -784,7 +875,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin // Roughly 100 ms ahead, at most four frames per queue turn. // The physical audio clock paces production; guest clocks stay fixed. for(unsigned i=0;i<4 && worker->audio.buffer().size()machine.takeAudio(); + AdvanceWorker(*worker); auto samples=DrainWorkerAudio(*worker); worker->audio.buffer().write(samples.data(), samples.size()); if (worker->machine.snapshot().state != VCC::Mac::RunState::Running) break; } @@ -805,7 +896,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin throw std::runtime_error("Audio output stopped consuming samples. Emulation continues without sound; turn Sound on to retry."); } else { if (worker->pacer.ready(std::chrono::steady_clock::now())) { - AdvanceWorker(*worker); worker->machine.takeAudio(); + AdvanceWorker(*worker); DrainWorkerAudio(*worker); } } } catch (const std::exception& error) { @@ -842,6 +933,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin VCCMachineProfile* p = [profile copy]; __block BOOL applied = NO; [self perform:^(Worker& worker) { + if (worker.recording) throw std::logic_error("Stop the CoCo movie before replacing the machine profile."); if (worker.closed) throw std::logic_error("The machine controller has shut down"); if (p.ram < 0 || p.ram > 3 || p.overclock < 1 || p.overclock > 16 || p.frameInterval < 1 || p.frameInterval > 6 || p.videoOutput < 0 || p.videoOutput > 2 || p.physicalSlot < 1 || p.physicalSlot > 4 || @@ -943,6 +1035,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin value.ram = unsigned(ram); value.overclock = unsigned(overclock); value.frameInterval = unsigned(interval); const auto previous = worker.machine.snapshot().configuration; const bool restart = previous.processor != value.processor || previous.ram != value.ram; + if (worker.recording && (restart || fastForward)) throw std::logic_error("Stop the CoCo movie before changing CPU/RAM or enabling fast-forward."); if (restart) { if (auto* disk = worker.floppy(); disk && disk->snapshot().busy) throw std::logic_error("Wait for the disk operation to finish before changing CPU or memory."); @@ -976,6 +1069,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin - (void)loadROM:(NSData *)rom use6309:(BOOL)use6309 completion:(VCCMachineCompletion)completion { NSData *owned = [rom copy]; [self command:^(Worker& worker) { + if (worker.recording) throw std::logic_error("Stop the CoCo movie before replacing the system ROM."); if (owned.length != 0x8000) throw std::invalid_argument("A 32 KiB CoCo 3 ROM image is required"); const auto *begin = static_cast(owned.bytes); worker.machine.load({begin, begin + owned.length}, use6309 ? VCC::Mac::Processor::HD6309 : VCC::Mac::Processor::MC6809); @@ -1414,7 +1508,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin generation, programRevision, mappingFingerprint, programCounter); } completion:completion]; } -- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { +- (void)debuggerStepBankedSource:(NSInteger)mode addresses:(NSArray *)addresses locations:(NSArray *)locations bytes:(NSArray *)bytes moduleIdentifiers:(NSArray *)moduleIdentifiers generation:(uint64_t)generation programRevision:(uint64_t)programRevision mappingFingerprint:(uint64_t)mappingFingerprint residencyFingerprint:(uint64_t)residencyFingerprint programCounter:(uint16_t)programCounter completion:(VCCMachineCompletion)completion { NSArray *ownedAddresses = [addresses copy], *ownedLocations = [locations copy]; NSArray *ownedBytes = [[NSArray alloc] initWithArray:bytes copyItems:YES]; NSArray *identifiers = [[NSArray alloc] initWithArray:moduleIdentifiers copyItems:YES]; @@ -1433,7 +1527,7 @@ void CheckAssistantMachine(Worker& worker, VCCMachineSnapshot *expected, NSStrin instructions.push_back({parsed[i], uint32_t(location), OwnedBytes(ownedBytes[i], 8), identifiers[i].UTF8String}); } worker.machine.debuggerStepSource(static_cast(mode), instructions, - generation, programRevision, mappingFingerprint, programCounter); + generation, programRevision, mappingFingerprint, programCounter, 1000000, 600, residencyFingerprint); } completion:completion]; } - (void)debuggerSetPC:(uint16_t)address completion:(VCCMachineCompletion)completion { diff --git a/platforms/macos/Companion/CompanionTransport.swift b/platforms/macos/Companion/CompanionTransport.swift index 20f784a..120f909 100644 --- a/platforms/macos/Companion/CompanionTransport.swift +++ b/platforms/macos/Companion/CompanionTransport.swift @@ -48,7 +48,7 @@ enum CompanionTransport { } enum Failure: LocalizedError { - case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut + case unavailable, busy, untrustedPeer, unsafeEndpoint, unsupportedVersion, malformedFrame, tooLarge, timedOut, startupTimedOut case remote(String) var errorDescription: String? { switch self { @@ -60,11 +60,36 @@ enum CompanionTransport { case .malformedFrame: "The companion service returned an invalid response." case .tooLarge: "The companion request or response exceeds the supported size." case .timedOut: "The companion operation timed out." + case .startupTimedOut: "VCC Plus did not finish starting. Check for a macOS permission prompt, then try opening the Software Library again." case .remote(let message): message } } } + /// Launch Services can return before a cold app finishes macOS startup + /// checks. Retry only a missing listener, with a monotonic deadline and + /// cancellation; identity/protocol/permission failures remain immediate. + static func waitForService(timeout: TimeInterval = 45, retryInterval: TimeInterval = 0.1, + now: () -> TimeInterval = { ProcessInfo.processInfo.systemUptime }, + sleep: (TimeInterval) async throws -> Void = { try await Task.sleep(for: .seconds($0)) }, + probe: (TimeInterval) async throws -> Void) async throws { + let deadline = now() + timeout + while true { + try Task.checkCancellation() + let remaining = deadline - now() + guard remaining > 0 else { throw Failure.startupTimedOut } + do { + try await probe(remaining) + try Task.checkCancellation() + return + } catch Failure.unavailable { + let remaining = deadline - now() + guard remaining > 0 else { throw Failure.startupTimedOut } + try await sleep(min(retryInterval, remaining)) + } + } + } + private struct Request: Codable { let version: Int let id: UUID diff --git a/platforms/macos/Resources/About/ThirdPartyNotices.txt b/platforms/macos/Resources/About/ThirdPartyNotices.txt index d4339e3..fa6e242 100644 --- a/platforms/macos/Resources/About/ThirdPartyNotices.txt +++ b/platforms/macos/Resources/About/ThirdPartyNotices.txt @@ -1,3 +1,16 @@ +Capture feedback audio + +The screenshot cue derives from “iPhone Camera Capture.wav” by pooky1: +https://freesound.org/people/pooky1/sounds/431588/ +The recording-start cue is a trimmed excerpt of “Tape start .wav” by sophiehall3535: +https://freesound.org/people/sophiehall3535/sounds/245927/ +Both original Freesound pages identify Creative Commons Zero (CC0 1.0): +https://creativecommons.org/publicdomain/zero/1.0/ +VCC Plus downmixes and adjusts playback levels, fades cue edges, and removes the +tape recording's lead-in and later sounds. These public-domain dedications are +separate from the GPL code and the original VCC Plus artwork notice. Source, +preparation instructions and file hashes are retained in docs/media/capture-sounds. + Original VCC Original VCC source and Windows About artwork retain their upstream copyright and licensing notices. The complete original Windows credits are included in About and in the Original Windows VCC notice. The GNU GPL version 3 is included in full; the project permits version 3 or later. diff --git a/platforms/macos/Resources/CaptureSounds/recording-start.wav b/platforms/macos/Resources/CaptureSounds/recording-start.wav new file mode 100644 index 0000000000000000000000000000000000000000..a345bf63feb4de8c502a8ac91891e66b3dbc28c3 GIT binary patch literal 45908 zcmX_}1DqUL`?kx~aWcUK6Wg|J8yjq_iEZ1qZQHiF;l|b^Q?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{dr+AW;1OmueuJgKzRg%^dmP W|6FUy`G0e3u50er%;^8u|NjGjA-9wO literal 0 HcmV?d00001 diff --git a/platforms/macos/Resources/CaptureSounds/screenshot.wav b/platforms/macos/Resources/CaptureSounds/screenshot.wav new file mode 100644 index 0000000000000000000000000000000000000000..e95316f7b64f931ce2a701611eac2cb7a54460bb GIT binary patch literal 48886 zcmeFZ1(;RGwlzAdYVF;MySqbhf(3Vn;Dq21B)DsE3m)9v-QC?GkOa5jPSf3cud14F zY`FPyV&~@k_nhy)-+Pb#lHPl*TD3~&9COT3U8`cbaxeE0)hk)IZ0oPPr;bfT0zYNe z5RIxYNK$NS*{plBQz-NQ|NGxK0^)yTqyAQ#nEzI>|8b#z_MU(L=>4;|eeBBr?47@V z`k%e;*L%Ny`X3MH|3@nLJ0ljbl!1T0pOfDY(LcNY&)@UUp8Wk={?+gQ{LTMrZU2e# zjDP=$djGu6-;VWfzkPh-kFEK$Qh!zU&)@p@uKx9Vi2hGU>5skn$F}_QyB|ybvsV3M zU4Q3u;C=sEeg9hNzte_)wakClg1<9{AK&@+N(SEd_e%bEJ^5oTf4uVF)$xDx{-2Nh zpZDR<%l@ZZ|L1M_^{xN@R{dFxe|GKHHvI9^KbHT;&w-M^|Nh6Pf4LIq`#<*o*U!Ix z`lalj{SK58zp3GuQh)FHUrPV=?_c`z$NGM`^ViS*^_`FH{_Fd{9hKjg`(s;vU*fO7 z|Gj5_+qb{>%wNCrf76|hefb5C{VOf|PmaQ$*Zpx8emfWcN{jz}W&gZ=|GxVF)tY|W zp1;C1zb*B5-|>I4HvU-mU%&g0cm8Be}CluyORIi z{eRzRGyk2Q{rlec$D00?zW&nIUw;3wwm)78)c>!P|FwqSx9s=de=Yfc=hJW7^XGm1 z{T~0vmj3w@|5)PR|M}0}8MyY#_22gC*Xw`QlD~T9&&vLK?e}l^_0E6p)1SZdm-hd= z-uv6R{_}VKW5oVfCH`IQ`TOTKWp_r@A+Tf{r%g2`TmbP_?K&c{r+D|{Q9O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-*oQ8o|)#g4)D)L1*ZC z==qQoh-;#@Uw_Ll_v^m}&;R;*=$p7JY7y;(O6F6R|6J(%m3Q;+{A&fZ z-N>g<4f!-(Szp1^p|uNTNkVYL3wy_Vmb{J(`!dM&P9>)!QbL$rDA=L@6e@4t2}Ui`7v^J^@uw^v@f z^79{S>GwUAPuK5z>UyO^y(qdb;?CdG^7SYy?EcksUj4nWX9}nOKhv+m+b*E;diM)T z{B_@ixJkEUzi z5Ao;sOXKyay?%*nQTFGazE;io_llB?>$hB3iK1%DZ|%x=yMk*s@~Nnr3$7P@x{>-q zWeT3T`cuL88>#Kur3>TK)wNz-!;L&6>bUy3tLwei_kw3{w6(%&6VLvc=kx0nbrevP zfAzof_qTNX_R4Q5E8s%Gr{9(;>Pk`1+(^qs)%jOkFRJ~buKyKn{#AAS)inM!_5C%q z{FX;WNziXg{!h757{!HM`%lyR_t5Znjr$+t&b6qy*1a2TEmX%}QPYjK_@6CTxQtxu zYT@_(9M#vZ^V)X{Yx&A2uKav;+5hIa{<*e)Etl8ojbG6xUV@s!>%a0&;U%s|%at`0R`z=L3w!48zxMZ2 zb$xDLzr?Tk5GwzBpZawj`QJqU|E`~+DJ<;H^(nc2iNbqQSZjrsywR(Fl#*Z9e|0U_ fr!&9A)ldGq-W&h+=j-|NHQYG0|5x&_=fM91>!CDL literal 0 HcmV?d00001 diff --git a/platforms/macos/Resources/SourceProjectSetupPrompt.txt b/platforms/macos/Resources/SourceProjectSetupPrompt.txt index d2845cb..39a4824 100644 --- a/platforms/macos/Resources/SourceProjectSetupPrompt.txt +++ b/platforms/macos/Resources/SourceProjectSetupPrompt.txt @@ -1,2 +1,4 @@ Work with the selected VCC Plus project and its installed development tools. Read the project's source and build configuration before changing it. Preserve the user's documents and media. Use the connection's read-only inspection and BASIC/Assembly lookup tools to understand current state. Run a build or disposable playtest only within the connection's granted capabilities. Verify actual tool discovery and successful requests separately. Report what was checked and any unavailable evidence honestly. The source content profile includes reference lookup rather than the full manual collection. Do not bypass a missing capability through private files or guest-state injection. + +For packed or banked projects, discover get_capabilities before choosing a debugging approach. Check banked_debug_manifest_versions and verified_code_overlays, and use available installed help for the verified physical code overlay contract. Prove the currently loaded owner from complete mapped executable bytes and fresh residency evidence; never guess ownership from an address or reuse a stale owner after replacement. Test loaders through ordinary guest execution, without debugger writes to guest memory or registers. diff --git a/platforms/macos/Tests/ArchiveReaderTests.swift b/platforms/macos/Tests/ArchiveReaderTests.swift index ff5341d..8672dcd 100644 --- a/platforms/macos/Tests/ArchiveReaderTests.swift +++ b/platforms/macos/Tests/ArchiveReaderTests.swift @@ -3,6 +3,7 @@ import CryptoKit import Foundation import PDFKit import SQLite3 +import SwiftUI import XCTest @MainActor @@ -40,6 +41,33 @@ final class ArchiveReaderTests: XCTestCase { private struct ReaderTimeout: Error {} + func testSavedPDFPageAndZoomResumeButExplicitLocationWins() async throws { + let pdf = PDFDocument() + for color in [NSColor.white, .gray] { + let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true } + pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount) + } + let bytes = try XCTUnwrap(pdf.dataRepresentation()) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + let item = ArchiveDocument(id: digest, title: "Resume", collection: "Books", + sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Resume.pdf")!, memberPath: nil, + pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Resume.pdf")!, deliveryBytes: Int64(bytes.count)) + try bytes.write(to: directory.appendingPathComponent(digest + ".pdf")) + let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + store.setReading(LibraryReadingPosition(documentID: digest, page: 2, offset: 0.7, zoom: 1.75, autoScales: false), for: "archive:" + digest) + let resumed = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store) + defer { resumed.reset() } + resumed.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300) + resumed.open(item, page: resumed.savedPage(for: digest), resumePosition: true) + try await waitFor { resumed.progress == nil } + XCTAssertNil(resumed.error) + XCTAssertEqual(resumed.page, 2) + XCTAssertEqual(resumed.view.scaleFactor, 1.75, accuracy: 0.01) + resumed.open(item, page: 1) + XCTAssertEqual(resumed.page, 1) + XCTAssertTrue(resumed.view.currentPage === resumed.document?.page(at: 0)) + } + func testSelectingPDFPagesReusesTheVerifiedDocumentAndOpensTheCitedPage() async throws { let pdf = PDFDocument() for color in [NSColor.white, .gray] { @@ -75,6 +103,36 @@ final class ArchiveReaderTests: XCTestCase { XCTAssertTrue(model.view.currentPage === rendered.page(at: 0)) } + func testExplicitSamePageDuringPDFResumeDiscardsSavedZoomAndOffset() async throws { + let pdf = PDFDocument() + let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in NSColor.white.setFill(); rect.fill(); return true } + pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: 0) + let bytes = try XCTUnwrap(pdf.dataRepresentation()) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + let item = ArchiveDocument(id: digest, title: "Same page", collection: "Books", + sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Same.pdf")!, memberPath: nil, + pageCount: 1, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Same.pdf")!, deliveryBytes: Int64(bytes.count)) + try bytes.write(to: directory.appendingPathComponent(digest + ".pdf")) + let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + store.setReading(LibraryReadingPosition(documentID: digest, page: 1, offset: 0.7, horizontalOffset: 0.6, zoom: 9, autoScales: false), for: "archive:" + digest) + let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store) + defer { model.reset() } + model.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300) + model.open(item, page: 1, resumePosition: true) + XCTAssertNotNil(model.progress) + // Both calls occur before the load task gets its first execution turn: + // same bytes and same page, but the second action is an explicit link. + model.open(item, page: 1, resumePosition: false) + try await waitFor { model.progress == nil } + XCTAssertNil(model.error) + XCTAssertEqual(model.page, 1) + XCTAssertTrue(model.view.autoScales, "An explicit target must not inherit the pending resume's manual zoom") + XCTAssertNotEqual(model.view.scaleFactor, 9) + let position = try XCTUnwrap(store.reading(for: "archive:" + digest)) + XCTAssertNotEqual(position.offset, 0.7, "An explicit target must not restore the old within-page offset") + XCTAssertNotEqual(position.horizontalOffset, 0.6) + } + func testSelectingTextThenCachedImageReplacesThePreview() async throws { let model = ArchiveReaderModel(remembersPage: false, cache: cache) defer { model.reset() } @@ -108,6 +166,49 @@ final class ArchiveReaderTests: XCTestCase { XCTAssertNil(model.referenceID) } + func testExplicitTextNavigationOverridesInFlightAndVisibleResume() async throws { + _ = NSApplication.shared + let bytes = Data((0..<250).map { "Line \($0): Archive reading position fixture." }.joined(separator: "\n").utf8) + let item = record("Resume.txt", format: "text", bytes: bytes) + try bytes.write(to: directory.appendingPathComponent(item.id + ".txt")) + let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + store.setReading(LibraryReadingPosition(documentID: item.id, offset: 0.65), for: "archive:" + item.id) + let model = ArchiveReaderModel(remembersPage: true, cache: cache, continuity: store) + defer { model.reset() } + model.open(item, page: 1, resumePosition: true) + model.open(item, page: 1, resumePosition: false) + try await waitFor { model.progress == nil } + XCTAssertNil(model.error) + XCTAssertEqual(model.inlinePosition?.offset, 0, "Explicit intent must replace the in-flight resume's saved inline position") + + model.updateInlinePosition(offset: 0.65) + let host = NSHostingView(rootView: ArchiveReaderPane(record: item, hit: nil, reader: model, + requestedPage: 1, catalog: ArchiveLibraryCatalog(url: nil), resumesPosition: true)) + host.frame = NSRect(x: 0, y: 0, width: 700, height: 500) + func textView(_ root: NSView) -> NSTextView? { + if let text = root as? NSTextView, text.accessibilityIdentifier() == "archive-inline-text" { return text } + return root.subviews.lazy.compactMap { textView($0) }.first + } + host.layoutSubtreeIfNeeded() + try await waitFor { + host.layoutSubtreeIfNeeded() + return textView(host)?.enclosingScrollView?.contentView.bounds.minY ?? 0 > 100 + } + let resumedText = try XCTUnwrap(textView(host)) + let revision = model.inlineNavigationRevision + model.open(item, page: 1, resumePosition: true) + XCTAssertEqual(model.inlineNavigationRevision, revision) + XCTAssertGreaterThan(resumedText.enclosingScrollView?.contentView.bounds.minY ?? 0, 100) + model.open(item, page: 1, resumePosition: false) + try await waitFor { + host.layoutSubtreeIfNeeded() + guard let current = textView(host), current !== resumedText else { return false } + return (current.enclosingScrollView?.contentView.bounds.minY ?? 1) == 0 + } + XCTAssertEqual(model.inlinePosition?.offset, 0) + withExtendedLifetime(host) {} + } + func testTextReaderPreservesLegacyEncodingsAndRemovesFloppyPadding() throws { let url = directory.appendingPathComponent("Letter.txt") let accented = "Café\n£5" diff --git a/platforms/macos/Tests/BASICReferenceTests.swift b/platforms/macos/Tests/BASICReferenceTests.swift index 7d56179..6e18de9 100644 --- a/platforms/macos/Tests/BASICReferenceTests.swift +++ b/platforms/macos/Tests/BASICReferenceTests.swift @@ -164,6 +164,22 @@ final class BASICReferenceTests: XCTestCase { XCTAssertFalse(content.allowsExternalReference(URL(fileURLWithPath: "/tmp/private.txt"))) } + func testOverlayContractIsDiscoverableAndReadableThroughTheBundledMCPIndex() async throws { + try requireFullManualEdition() + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let app = try XCTUnwrap(Bundle(url: products.appendingPathComponent("VCC Plus OSS.app"))) + let root = try XCTUnwrap(app.url(forResource: "ManualLibrary", withExtension: nil)) + let index = MCPHelpIndex(root: root) + let hits = try await index.search("overlayGroups") + let hit = try XCTUnwrap(hits.first { $0.id.hasSuffix("#verified-physical-code-overlays") }) + let read = try await index.read(hit.id) + let topic = try XCTUnwrap(read) + for field in ["banked_debug_manifest_versions", "verified_code_overlays", "overlayGroups", "residency_fingerprint"] { + XCTAssertTrue(topic.text.contains(field), field) + } + XCTAssertLessThanOrEqual(topic.text.utf8.count, 12 * 1024, "The complete contract must fit a read_topic response") + } + func testOriginalToolReferencesAreReadableThroughTheNativeMCPIndex() async throws { try requireFullManualEdition() let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() diff --git a/platforms/macos/Tests/CMOCSourceMapTests.swift b/platforms/macos/Tests/CMOCSourceMapTests.swift index e954b0c..ff75e0f 100644 --- a/platforms/macos/Tests/CMOCSourceMapTests.swift +++ b/platforms/macos/Tests/CMOCSourceMapTests.swift @@ -2,51 +2,306 @@ import XCTest final class CMOCSourceMapTests: XCTestCase { - /// Explicit opt-in diagnostic for any retained custom project's immutable - /// build result. No project Makefile is executed and no emulator is loaded. - func testExplicitlySuppliedBankedBuildEvidence() throws { + private enum RetainedEvidenceFailure: Error { case missingCompilationRoot, ambiguousCompilationRoot } + + /// Test harness recovery only. Ordinary CMOC markers survive optimized builds + /// even when optional VCCDBG1 type records are absent. Never infer from a Mac + /// username, output directory name or current project location. + private func retainedCompilationDirectory(files: [String: Data], entrySource: String) throws -> URL { + let pattern = try NSRegularExpression(pattern: #"\* (?:Line (.+):([0-9]+)(?::.*)?|FUNCTION .+: defined at (.+):([0-9]+))$"#) + var roots = Set() + func consider(_ path: String) { + guard path.hasPrefix("/"), path.hasSuffix("/" + entrySource) else { return } + roots.insert(URL(fileURLWithPath: String(path.dropLast(entrySource.count))).standardizedFileURL.path) + } + for (name, data) in files where ["s", "lst"].contains((name as NSString).pathExtension.lowercased()) { + guard let text = String(data: data, encoding: .utf8) else { continue } + for row in text.components(separatedBy: .newlines) { + if let marker = row.range(of: "* VCCDBG1 "), + let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any], + let location = record["location"] as? String, let colon = location.lastIndex(of: ":") { + consider(String(location[.. CMOCBuildArtifact { guard let path = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT"] else { throw XCTSkip("Supply a retained banked artifact directory for project qualification.") } let directory = URL(fileURLWithPath: path).resolvingSymlinksInPath() + if let expected = ProcessInfo.processInfo.environment["VCC_TEST_BANKED_ARTIFACT_ID"] { + XCTAssertEqual(directory.lastPathComponent, expected, "Qualification must read the explicitly selected artifact") + } let project = try CMOCProject.open(at: directory) let files = try CMOCProject.files(in: directory) let sources = files.filter { CMOCProject.isSource($0.key) && String(data: $0.value, encoding: .utf8) != nil && !$0.value.contains(0) } let settings = project.configuration let entry = try XCTUnwrap(sources[settings.entrySource]) - let binaryPath = try XCTUnwrap(settings.binary) - let binary = try XCTUnwrap(files[binaryPath]) - // Compiler source markers retain the original isolated working folder. - // Recover it from a full, retained metadata record rather than assuming - // it is the current output folder or a historical machine path. - var compilationDirectory: URL? - for (name, data) in sources where name.hasSuffix(".s") { - guard let text = String(data: data, encoding: .utf8) else { continue } - for row in text.components(separatedBy: .newlines) { - guard let marker = row.range(of: "* VCCDBG1 "), - let record = try? JSONSerialization.jsonObject(with: Data(row[marker.upperBound...].utf8)) as? [String: Any], - let location = record["location"] as? String, let colon = location.lastIndex(of: ":") else { continue } - let sourcePath = String(location[.. Void = { _ in }) throws -> Data { + var value: [String: Any] = ["version": 2, "entryPoint": 0x0e00, + "binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)], + "linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)], + "sources": ["main.c": CMOCSourceMap.sha256(source)], + "artifacts": files.filter { $0.key != "game.bin" && $0.key != "game.map" }.mapValues(CMOCSourceMap.sha256), + "overlayGroups": [["id": "stages", "owners": ["A", "B"]]], "modules": modules] + edit(&value); return try JSONSerialization.data(withJSONObject: value) + } + func layout(_ edit: (inout [String: Any]) -> Void = { _ in }) throws -> CMOCBankedDebugLayout { + for (name, bytes) in files { try bytes.write(to: directory.appendingPathComponent(name)) } + return try CMOCBankedDebugLayout.parse(data: manifest(edit), directory: directory, sources: ["main.c": source], binary: packed, + binaryPath: "game.bin", allowedOutputs: Array(files.keys)) + } + let verified = try layout() + XCTAssertTrue(verified.permitsPhysicalOverlap(between: "a1", and: "b1")) + XCTAssertFalse(verified.permitsPhysicalOverlap(between: "a1", and: "a2")) + let mapping = try CMOCProjectSourceMap.parse(sources: ["main.c": source], compilationDirectory: directory, + units: [.init(sourcePath: "main.c", sourceName: "main.c", objectName: "main.o", listing: listing, object: objectBytes)], + linkMap: map, binary: packed, bankedLayout: verified) + XCTAssertEqual(mapping.instructions.count, 4, "Distinct exclusive owners may occupy the same physical instruction identity") + XCTAssertEqual(mapping.projected(physicalPages: [2: 30, 3: 31]).activeModuleIDs, ["resident"], "Pages alone never identify an overlay owner") + var memory = Data(repeating: 0, count: 65536), available = Data(repeating: 1, count: 65536) + memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; memory[0x7000] = 0x39 + func selected() -> CMOCProjectSourceMap { mapping.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) } + XCTAssertEqual(selected().activeModuleIDs, ["a1", "a2", "dataA", "bssA", "resident"]) + XCTAssertEqual(selected().instructions.map(\.moduleID), ["a1", "a2"]) + let typed = CMOCVariableDebug(functions: [ + .init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "a1"), + .init(name: "stage", sourcePath: "main.c", entry: 0x4000, body: 0x4000, end: 0x4001, frame: false, moduleID: "b1")], variables: [ + .init(name: "stateA", sourcePath: "main.c", line: 1, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssA"), + .init(name: "stateB", sourcePath: "main.c", line: 2, type: .integer, address: 0x6100, offset: nil, scope: nil, isStatic: false, moduleID: "bssB"), + .init(name: "wrongScope", sourcePath: "main.c", line: 1, type: .integer, address: 0x6000, offset: nil, scope: 0x4000..<0x4001, isStatic: true, moduleID: "dataA", scopeModuleID: "b1")], sourceMap: mapping) + func typedSelection() -> CMOCVariableDebug { typed.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available) } + XCTAssertTrue(typed.projected(physicalPages: [2: 30, 3: 31]).variables.isEmpty) + XCTAssertEqual(typedSelection().variables.map(\.name), ["stateA"], "BSS inherits only its uniquely proven owner; lexical owner must also match") + XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "a1") + memory[0x5000] = opcodes[3] + XCTAssertEqual(selected().activeModuleIDs, ["resident"], "A half-loaded owner must not establish residency") + XCTAssertTrue(typedSelection().functions.isEmpty); XCTAssertTrue(typedSelection().variables.isEmpty) + memory[0x4000] = opcodes[2] + XCTAssertEqual(selected().activeModuleIDs, ["b1", "b2", "dataB", "bssB", "resident"]) + XCTAssertEqual(typedSelection().variables.map(\.name), ["stateB"]) + XCTAssertEqual(typedSelection().entryFunction(named: "stage")?.moduleID, "b1") + available[0x5000] = 0 + XCTAssertEqual(selected().activeModuleIDs, ["resident"], "Unavailable executable bytes never establish residency") + XCTAssertThrowsError(try layout { $0["version"] = 1 }) + XCTAssertThrowsError(try layout { $0.removeValue(forKey: "overlayGroups") }) + XCTAssertThrowsError(try layout { value in + var changed = modules; changed[2]["overlay"] = ["group": "stages", "owner": "A"]; value["modules"] = changed + }, "Same-owner physical overlap remains invalid") + XCTAssertThrowsError(try layout { value in + var changed = modules; changed[2].removeValue(forKey: "overlay"); value["modules"] = changed + }, "Ordinary resident code cannot share overlay storage") + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "unused"]]] + }) + XCTAssertThrowsError(try layout { value in + var changed = modules; changed[5]["overlay"] = ["group": "stages", "owner": "C"] + value["modules"] = changed; value["overlayGroups"] = [["id": "stages", "owners": ["A", "B", "C"]]] + }, "A data/BSS-only owner has no immutable executable residency proof") + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = [["id": "stages", "owners": ["A", "A"]]] + }) + XCTAssertThrowsError(try layout { value in + var changed = modules; changed[2]["overlay"] = ["group": "other", "owner": "C"] + value["modules"] = changed + value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "other", "owners": ["C", "D"]]] + }, "Different overlay groups may coexist and cannot share physical storage") { + XCTAssertTrue($0.localizedDescription.contains("module images overlap physical RAM")) + } + XCTAssertThrowsError(try layout { value in + var changed = modules; changed[0]["overlay"] = ["group": "stages", "owner": "unknown"]; value["modules"] = changed + }) + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = [["id": "stages", "owners": ["A", "B"]], ["id": "stages", "owners": ["C", "D"]]] + }) + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = [["id": String(repeating: "x", count: 129), "owners": ["A", "B"]]] + }) + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = (0..<65).map { ["id": "g\($0)", "owners": ["A", "B"]] } + }) + XCTAssertThrowsError(try layout { value in + value["overlayGroups"] = [["id": "stages", "owners": (0..<257).map { "o\($0)" }]] + }) + XCTAssertThrowsError(try layout { value in + // Even null metadata cannot silently downgrade to version 1. + value["version"] = 1; value["overlayGroups"] = NSNull() + }) + let catalog = CMOCPublicDebugEvidence.fields(map: mapping, metadata: nil, variableError: nil, sharedPaths: ["main.c"]) + XCTAssertEqual(catalog["supported_manifest_versions"] as? [Int], [1, 2]) + XCTAssertEqual(catalog["module_catalog_scope"] as? String, "verified_static_declarations_not_residency") + XCTAssertEqual((catalog["overlay_groups"] as? [[String: Any]])?.first?["owners"] as? [String], ["A", "B"]) + XCTAssertNil(catalog["active_overlay_owners"], "Build declarations never assert runtime residency") + files["b1.raw"] = files["a1.raw"]; files["b2.raw"] = files["a2.raw"] + let ambiguousLayout = try layout() + let ambiguous = CMOCProjectSourceMap(entryPoint: mapping.entryPoint, binarySHA256: mapping.binarySHA256, sourceHashes: mapping.sourceHashes, + instructions: mapping.instructions, objectHashes: mapping.objectHashes, listingHashes: mapping.listingHashes, + linkMapSHA256: mapping.linkMapSHA256, bankedLayout: ambiguousLayout) + memory[0x4000] = opcodes[0]; memory[0x5000] = opcodes[1]; available[0x5000] = 1 + XCTAssertEqual(ambiguous.projected(physicalPages: [2: 30, 3: 31], memory: memory, available: available).activeModuleIDs, ["resident"], + "Identical code signatures must not guess an owner or expose its BSS") + } + + func testGeneratedAssemblyEvidenceUsesTypedBudgetsAndExactIdentity() throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("CMOCEvidence-" + UUID().uuidString).resolvingSymlinksInPath() + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: directory) } + let source = Data("void main(void) {}\n".utf8) + let packed = binary([(0x0e00, [0x12])], entry: 0x0e00) + let map = Data("Section: code (main.o) load at 4000, length 0001\n".utf8) + let raw = Data([0x39]) + for (name, data) in ["game.bin": packed, "game.map": map, "code.raw": raw] { + try data.write(to: directory.appendingPathComponent(name)) + } + var artifacts = ["code.raw": CMOCSourceMap.sha256(raw)] + func parse(outputs: [String]? = nil) throws -> CMOCBankedDebugLayout { + let value: [String: Any] = ["version": 1, "entryPoint": 0x0e00, + "binary": ["path": "game.bin", "sha256": CMOCSourceMap.sha256(packed)], + "linkMap": ["path": "game.map", "sha256": CMOCSourceMap.sha256(map)], + "sources": ["main.c": CMOCSourceMap.sha256(source)], "artifacts": artifacts, + "modules": [["id": "code", "sections": ["code"], "codeSections": ["code"], + "image": ["path": "code.raw", "logicalAddress": 0x4000], + "pages": [["logicalPage": 2, "physicalPage": 30]]]]] + return try CMOCBankedDebugLayout.parse(data: JSONSerialization.data(withJSONObject: value), + directory: directory, sources: ["main.c": source], binary: packed, binaryPath: "game.bin", + allowedOutputs: outputs ?? (["game.bin", "game.map"] + Array(artifacts.keys))) + } + // A compiler can emit large type records/data while retaining small code. + let assembly = Data(repeating: 0x3b, count: 9 * 1024 * 1024 + 17) + let path = "generated.s", file = directory.appendingPathComponent(path) + try assembly.write(to: file); artifacts[path] = CMOCSourceMap.sha256(assembly) + let verified = try parse() + XCTAssertEqual(verified.artifactHashes[path], CMOCSourceMap.sha256(assembly)) + XCTAssertEqual(verified.modules.first?.physicalAddress(0x4000), 30 * 8192) + XCTAssertNoThrow(try CMOCSourceMap.validateEvidenceSize(assembly.count, path: path)) + XCTAssertThrowsError(try parse(outputs: ["game.bin", "game.map", "code.raw"])) + try Data(repeating: 0x21, count: assembly.count).write(to: file) + XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s SHA-256")) } + try FileManager.default.removeItem(at: file) + try FileManager.default.createSymbolicLink(at: file, withDestinationURL: directory.appendingPathComponent("code.raw")) + XCTAssertThrowsError(try parse()) { XCTAssertTrue($0.localizedDescription.contains("generated.s must not traverse symbolic links")) } + try FileManager.default.removeItem(at: file) + artifacts.removeValue(forKey: path) + for (name, size, limit) in [("oversized.s", 32 * 1024 * 1024 + 1, 32 * 1024 * 1024), + ("oversized.lst", 8 * 1024 * 1024 + 1, 8 * 1024 * 1024)] { + let bytes = Data(repeating: 0x3b, count: size) + try bytes.write(to: directory.appendingPathComponent(name)); artifacts[name] = CMOCSourceMap.sha256(bytes) + XCTAssertThrowsError(try parse()) { + let message = $0.localizedDescription + XCTAssertTrue(message.contains(name)); XCTAssertTrue(message.contains("\(size) bytes")) + XCTAssertTrue(message.contains("\(limit) bytes")) + } + XCTAssertThrowsError(try CMOCSourceMap.validateEvidenceSize(size, path: name)) + artifacts.removeValue(forKey: name) + try FileManager.default.removeItem(at: directory.appendingPathComponent(name)) + } + let chunk = Data(repeating: 0x3b, count: 27 * 1024 * 1024) + let hash = CMOCSourceMap.sha256(chunk) + for index in 0..<5 { + let name = "part\(index).s" + try chunk.write(to: directory.appendingPathComponent(name)); artifacts[name] = hash + } + XCTAssertThrowsError(try parse()) { + XCTAssertTrue($0.localizedDescription.contains("aggregate limit is 134217728 bytes")) + } + } + // Small LWOBJ16 records are constructed here to exercise relocation failures // independently of a compiler installation or personal ROM files. private struct Section { diff --git a/platforms/macos/Tests/CartridgePersistenceTests.swift b/platforms/macos/Tests/CartridgePersistenceTests.swift index 5a9bc97..dffc271 100644 --- a/platforms/macos/Tests/CartridgePersistenceTests.swift +++ b/platforms/macos/Tests/CartridgePersistenceTests.swift @@ -354,6 +354,60 @@ final class CartridgePersistenceTests: XCTestCase { XCTAssertFalse(model.disks[0].dirty); XCTAssertTrue(model.diskConnected) } } + @MainActor func testMediaCommandsRecheckActiveTransferWithoutChangingDisksOnBothCPUs() async throws { + // The native controls remain available during guest I/O. Their safety + // must come from the worker's current state, not a stale UI snapshot. + for use6309 in [false, true] { + let controller = VCCMachineController() + func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in action { c.resume(returning: $0) } } + } + let original = Data(repeating: 0, count: 161280) + _ = await step { controller.loadDiskROM(Data(repeating: 0, count: 8192), name: "Original ROM", completion: $0) } + _ = await step { controller.mountDisk(original, drive: 0, name: "Original.dsk", readOnly: false, completion: $0) } + var system = Data(repeating: 0, count: 32768) + // Begin a write, then leave its sector data transfer incomplete. + let code: [UInt8] = [0x86,0x29,0xb7,0xff,0x40,0x86,1,0xb7,0xff,0x4a,0x86,0xa0,0xb7,0xff,0x48,0x20,0xfe] + system.replaceSubrange(0.. Void) -> Void] = [ + controller.pauseForDiskChange, + { controller.mountDisk(Data(repeating: 0xe5, count: 161280), drive: 0, name: "Replacement.dsk", readOnly: false, completion: $0) }, + { controller.createDisk(inDrive: 0, format: .standard, completion: $0) }, + { controller.ejectDisk(inDrive: 0, discard: false, completion: $0) }, + { controller.setDiskWriteProtected(true, drive: 0, completion: $0) }, + { controller.loadDiskROM(Data(repeating: 0x12, count: 8192), name: "Replacement ROM", completion: $0) }, + controller.disableDisks, + ] + for operation in operations { + snapshot = await step(operation) + XCTAssertNotNil(snapshot.errorMessage) + XCTAssertTrue(snapshot.diskBusy) + XCTAssertTrue(snapshot.disks[0].mounted) + XCTAssertEqual(snapshot.disks[0].name, "Original.dsk") + XCTAssertFalse(snapshot.disks[0].writeProtected) + XCTAssertEqual(snapshot.diskROMName, "Original ROM") + } + _ = await step(controller.reset) + let (bytes, _, exported): (Data?, UInt64, VCCMachineSnapshot) = await withCheckedContinuation { done in + controller.exportDisk(inDrive: 0) { done.resume(returning: ($0, $1, $2)) } + } + XCTAssertNil(exported.errorMessage) + XCTAssertEqual(bytes, original, "Rejected actions must retain the original bytes") + snapshot = await step { controller.ejectDisk(inDrive: 0, discard: false, completion: $0) } + XCTAssertNil(snapshot.errorMessage) + XCTAssertFalse(snapshot.disks[0].mounted, "Ejection works once the controller is idle") + _ = await step(controller.shutdown) + } + } @MainActor func testBridgeRejectsInvalidAndBusyLayoutsWithoutReplacingSlots() async throws { let controller = VCCMachineController() func step(_ action: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { diff --git a/platforms/macos/Tests/CoCoCaptureTests.swift b/platforms/macos/Tests/CoCoCaptureTests.swift new file mode 100644 index 0000000..536c9f2 --- /dev/null +++ b/platforms/macos/Tests/CoCoCaptureTests.swift @@ -0,0 +1,779 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import AVFoundation +import AppKit + +final class CoCoCaptureTests: XCTestCase { + private final class HeldPullController: VCCMachineController, @unchecked Sendable { + private let lock = NSLock() + private var reply: (() -> Void)? + private var holdNextPull = true + private var finals = 0 + var heldReply: (() -> Void)? { lock.withLock { reply } } + var finalPulls: Int { lock.withLock { finals } } + override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) { + if finish { lock.withLock { finals += 1 } } + super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in + let held = lock.withLock { + if !finish && holdNextPull { + holdNextPull = false; reply = { completion(packets, error) }; return true + } + return false + } + if !held { completion(packets, error) } + } + } + func releasePull() { let value = lock.withLock { let value = reply; reply = nil; return value }; value?() } + } + private final class InvalidCapturePacket: VCCVideoPacket { + private let original: VCCVideoPacket + init(_ original: VCCVideoPacket) { self.original = original; super.init() } + override var pixels: Data { Data() } + override var samples: Data { original.samples } + override var activeArea: CGRect { original.activeArea } + override var sampleOffset: UInt64 { original.sampleOffset } + } + private final class FailingPullController: VCCMachineController, @unchecked Sendable { + private let lock = NSLock() + private var failPull = false + private var invalidPull = false + private var finals = 0 + var finalPulls: Int { lock.withLock { finals } } + var failNextPull: Bool { get { lock.withLock { failPull } } set { lock.withLock { failPull = newValue } } } + var invalidateNextPull: Bool { get { lock.withLock { invalidPull } } set { lock.withLock { invalidPull = newValue } } } + override func takeVideoCapture(finish: Bool, replyQueue: DispatchQueue, completion: @escaping ([VCCVideoPacket], String?) -> Void) { + if finish { lock.withLock { finals += 1 } } + super.takeVideoCapture(finish: finish, replyQueue: replyQueue) { [self] packets, error in + let fail = lock.withLock { let fail = !finish && failPull; if fail { failPull = false }; return fail } + if fail { + completion(packets, "Authored capture-consumer interruption") + } else { + let invalid = lock.withLock { let invalid = !finish && invalidPull && !packets.isEmpty; if invalid { invalidPull = false }; return invalid } + if invalid { completion([InvalidCapturePacket(packets[0])] + Array(packets.dropFirst()), error) } + else { completion(packets, error) } + } + } + } + } + /// Deliberately occupies the UI executor longer than the bridge's eight + /// packets can buffer. This is test-only starvation, never a product wait. + private func holdMainActor() { Thread.sleep(forTimeInterval: 0.8) } + private final class BookmarkGate: @unchecked Sendable { + private let lock = NSLock() + private let release = DispatchSemaphore(value: 0) + private var began = false + let blocked: URL + let fails: Bool + init(blocked: URL, fails: Bool = false) { self.blocked = blocked; self.fails = fails } + var started: Bool { lock.withLock { began } } + func unblock() { release.signal() } + func prepare(_ url: URL) throws -> Data { + XCTAssertFalse(Thread.isMainThread, "Bookmark creation must not occupy the UI thread") + if url == blocked { + lock.withLock { began = true } + guard release.wait(timeout: .now() + 5) == .success else { throw CoCoRecordingError.message("The authored bookmark gate timed out") } + if fails { throw CocoaError(.fileReadNoSuchFile) } + } + return try url.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) + } + } + /// Each lifecycle case owns its controller, defaults and media directory. + /// Feedback is injected by the caller; these tests never play host cues. + @MainActor private func guest(controller: VCCMachineController = VCCMachineController(), use6309: Bool = false) async throws -> (URL, UserDefaults, MachineModel) { + let root = try folder(), suite = "CoCoCaptureLifecycle-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + addTeardownBlock { defaults.removePersistentDomain(forName: suite) } + // Never ask the native test runner to bookmark the person's Desktop. + // Seed the owned location before preferences initialize, on both hosts. + defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.shared") + let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller, + displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false) + addTeardownBlock { await withCheckedContinuation { c in controller.shutdown { _ in c.resume() } } } + await withCheckedContinuation { c in controller.loadDiagnostic(use6309: use6309) { _ in c.resume() } } + await withCheckedContinuation { c in controller.resume { _ in c.resume() } } + for _ in 0..<200 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) } + _ = try XCTUnwrap(model.pixels, "The owned authored diagnostic must publish a frame") + return (root, defaults, model) + } + private func folder() throws -> URL { + let url = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoCapture-" + UUID().uuidString) + try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: url) } + return url + } + private func picture() -> Data { + var data = Data(count: 640 * 480 * 4) + data.withUnsafeMutableBytes { raw in + let p = raw.bindMemory(to: UInt8.self) + for y in 0..<480 { for x in 0..<640 { + let n = (y * 640 + x) * 4 + // Green outside the crop, red above blue inside: catches both + // unwanted border content and an upside-down encoded picture. + if x < 64 || x >= 576 || y < 48 || y >= 432 { p[n+1] = 255 } + else if y < 240 { p[n+2] = 255 } else { p[n] = 255 } + } } + } + return data + } + func testQuickSaveCollisionIsAtomicAndRetainsOriginal() throws { + let dir = try folder() + let first = dir.appendingPathComponent("Example.png") + try Data([1,2,3]).write(to: first) + let temporary = dir.appendingPathComponent("temporary") + try Data([4,5,6]).write(to: temporary) + let second = try CoCoCaptureFiles.promote(temporary, folder: dir, name: "Example", extension: "png") + XCTAssertEqual(second.lastPathComponent, "Example-1.png") + XCTAssertEqual(try Data(contentsOf: first), Data([1,2,3])) + XCTAssertEqual(try Data(contentsOf: second), Data([4,5,6])) + let capture = try ScreenCapture(pixels: picture(), area: CGRect(x: 64, y: 48, width: 512, height: 384)) + let png = try CoCoCaptureFiles.save(capture, folder: dir) + let image = try XCTUnwrap(NSImage(contentsOf: png)) + XCTAssertEqual(image.size, NSSize(width: 512, height: 384)) + } + + func testNativeMovieCompletesMP4WithGuestOnlyCropAndStereo() async throws { + let dir = try folder(), movie = dir.appendingPathComponent("Working.mov"), final = dir.appendingPathComponent("Final.mp4") + let encoder = try CoCoVideoEncoder(workingURL: movie) + let bytes = picture() + for n in 0..<60 { + var samples = Data(count: 735 * 8) + samples.withUnsafeMutableBytes { raw in + let values = raw.bindMemory(to: Float.self) + for i in 0..<735 { values[2*i] = Float(sin(Double(n*735+i)*2 * .pi * 440 / 44100)) * 0.2; values[2*i+1] = -values[2*i] } + } + encoder.append([CoCoVideoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: samples, sampleOffset: Int64(n*735))]) + try await Task.sleep(for: .milliseconds(17)) + } + let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } } + try await CoCoVideoEncoder.exportMP4(from: working, to: final) + let asset = AVURLAsset(url: final) + let duration = try await asset.load(.duration).seconds + XCTAssertEqual(duration, 1, accuracy: 0.03) + let video = try await asset.loadTracks(withMediaType: .video), audio = try await asset.loadTracks(withMediaType: .audio) + XCTAssertEqual(video.count, 1); XCTAssertEqual(audio.count, 1) + let dimensions = try await video[0].load(.naturalSize) + XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960)) + let generator = AVAssetImageGenerator(asset: asset) + let frame = try await generator.image(at: .zero).image + var rgba = Data(count: 1280 * 960 * 4) + rgba.withUnsafeMutableBytes { p in + let context = CGContext(data: p.baseAddress, width: 1280, height: 960, bitsPerComponent: 8, + bytesPerRow: 1280 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.noneSkipLast.rawValue)! + context.draw(frame, in: CGRect(x: 0, y: 0, width: 1280, height: 960)) + } + let top = (240 * 1280 + 640) * 4, bottom = (720 * 1280 + 640) * 4 + XCTAssertGreaterThan(rgba[top], 200); XCTAssertLessThan(rgba[top+1], 40); XCTAssertLessThan(rgba[top+2], 40) + XCTAssertGreaterThan(rgba[bottom+2], 200); XCTAssertLessThan(rgba[bottom+1], 40); XCTAssertLessThan(rgba[bottom], 40) + // Passthrough refuses overwrite, leaving an already delivered movie intact. + let hash = try Data(contentsOf: final) + do { try await CoCoVideoEncoder.exportMP4(from: working, to: final); XCTFail("Must not overwrite") } catch { } + XCTAssertEqual(try Data(contentsOf: final), hash) + } + + @MainActor func testBridgeCaptureBothProcessorsDoesNotAdvancePausedGuest() async throws { + for hd in [false, true] { + let controller = VCCMachineController() + func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async -> VCCMachineSnapshot { + await withCheckedContinuation { c in op { c.resume(returning: $0) } } + } + func packets(_ finish: Bool) async -> ([VCCVideoPacket], String?) { + await withCheckedContinuation { c in controller.takeVideoCapture(finish: finish) { c.resume(returning: ($0,$1)) } } + } + _ = await command { controller.loadDiagnostic(use6309: hd, completion: $0) } + _ = await command(controller.resume) + var available = await command(controller.snapshot) + for _ in 0..<50 where available.presentedFrame == 0 { + try await Task.sleep(for: .milliseconds(10)) + available = await command(controller.snapshot) + } + XCTAssertGreaterThan(available.presentedFrame, 0) + let before = await command(controller.pause) + let started = await command(controller.beginVideoCapture) + XCTAssertNil(started.errorMessage) + try await Task.sleep(for: .milliseconds(65)) + let capture = await packets(true) + XCTAssertNil(capture.1); XCTAssertFalse(capture.0.isEmpty) + for p in capture.0 { + XCTAssertEqual(p.pixels.count, 640 * 480 * 4) + XCTAssertTrue(p.samples.allSatisfy { $0 == 0 }) + XCTAssertGreaterThan(p.activeArea.width, 0) + } + let after = await command(controller.snapshot) + XCTAssertEqual(after.generation, before.generation) + XCTAssertEqual(after.cycles, before.cycles) + XCTAssertEqual(after.presentedFrame, before.presentedFrame) + XCTAssertEqual(after.audioStarts, before.audioStarts) + XCTAssertEqual(after.use6309, hd) + _ = await command(controller.shutdown) + } + } + + @MainActor func testStopWaitsForAnInFlightDrainedPacketBeforeFinalizing() async throws { + let root = try folder(), controller = HeldPullController() + let suite = "CoCoCaptureStop-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + defaults.set(try root.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.recordings") + let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller, + displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false) + func command(_ op: (@escaping @Sendable (VCCMachineSnapshot) -> Void) -> Void) async { + _ = await withCheckedContinuation { c in op { c.resume(returning: $0) } } + } + await command { controller.loadDiagnostic(use6309: false, completion: $0) } + await command(controller.resume) + // This fixture owns its guest setup. An asynchronous remembered-media + // restore must not race that load or supply the frame incidentally. + for _ in 0..<100 where model.pixels == nil { + model.poll(); try await Task.sleep(for: .milliseconds(10)) + } + guard model.pixels != nil else { + await withCheckedContinuation { c in model.shutdown { c.resume() } } + XCTFail("The authored diagnostic guest did not produce its first frame") + return + } + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + capture.startRecording() + capture.startRecording() // Repeated Start while starting cannot add another cue. + for _ in 0..<100 where controller.heldReply == nil { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertNotNil(controller.heldReply) + XCTAssertEqual(cues, [.recordingStarted]) + let stopping = Task { await capture.stopRecording() } + try await Task.sleep(for: .milliseconds(30)) + XCTAssertEqual(capture.state, .finishing) + XCTAssertEqual(controller.finalPulls, 0, "Stop must not overtake the pull that already owns drained samples") + await capture.stopRecording() + XCTAssertEqual(capture.state, .finishing, "Duplicate Stop must leave the first finalization in control") + XCTAssertEqual(controller.finalPulls, 0) + controller.releasePull() + await stopping.value + XCTAssertEqual(controller.finalPulls, 1) + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error) + let saved = capture.saved + XCTAssertTrue(capture.recoveries.isEmpty) + XCTAssertEqual(cues, [.recordingStarted], "Stop/finalization must not replay the start cue") + await withCheckedContinuation { c in model.shutdown { c.resume() } } + let movie = try XCTUnwrap(saved) + XCTAssertTrue(FileManager.default.fileExists(atPath: movie.path)) + } + + @MainActor func testFailedQuickSaveRetainsImageAndRejectsReplacementUntilExplicitDiscard() async throws { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller) + let blocked = root.appendingPathComponent("Not a folder") + let original = Data("existing user file".utf8) + try original.write(to: blocked) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + // A regular file is a deterministic inaccessible-directory fixture, + // independent of the account's administrator/write permissions. + try await capture.preferences.setFolder(blocked) + capture.captureNow() + for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertFalse(capture.saving); XCTAssertNotNil(capture.error) + XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.saved) + XCTAssertEqual(cues, [.screenshot]) + try await capture.preferences.setFolder(root) + capture.captureNow(); capture.delay(5) + XCTAssertTrue(capture.hasPendingImage); XCTAssertNil(capture.countdown) + XCTAssertEqual(cues, [.screenshot], "A failed image cannot be silently replaced or cue again") + XCTAssertEqual(try Data(contentsOf: blocked), original) + capture.discardImage() + XCTAssertFalse(capture.hasPendingImage); XCTAssertNil(capture.error) + capture.captureNow() + for _ in 0..<200 where capture.saving { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage) + XCTAssertEqual(cues, [.screenshot, .screenshot]) + XCTAssertEqual(try Data(contentsOf: blocked), original) + } + + @MainActor func testFastForwardStartRefusesWithoutChangingMachineOrCreatingRecovery() async throws { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller) + await withCheckedContinuation { c in + controller.configureMachine(use6309: false, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { _ in c.resume() } + } + for _ in 0..<200 where !model.settings.fastForward { model.poll(); try await Task.sleep(for: .milliseconds(5)) } + XCTAssertTrue(model.settings.fastForward) + let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + try await capture.preferences.setFolder(root) + capture.startRecording(); capture.startRecording() + XCTAssertEqual(capture.state, .idle) + XCTAssertTrue(capture.error?.contains("fast-forward") == true) + XCTAssertTrue(capture.recoveries.isEmpty); XCTAssertTrue(cues.isEmpty) + let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + XCTAssertTrue(after.fastForward); XCTAssertEqual(after.generation, before.generation) + XCTAssertFalse(FileManager.default.fileExists(atPath: root.appendingPathComponent("CaptureRecovery.json").path)) + } + + @MainActor func testTenSecondCaptureExpiresWhilePausedWithoutAdvancingGuest() async throws { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller) + let before = await withCheckedContinuation { c in controller.pause { c.resume(returning: $0) } } + model.poll() + try await Task.sleep(for: .milliseconds(20)) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + try await capture.preferences.setFolder(root) + capture.preferences.setTimerSeconds(10) + capture.capture() + XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty) + for _ in 0..<1_200 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving) + XCTAssertEqual(cues, [.screenshot]); XCTAssertNil(capture.error) + let image = try XCTUnwrap(NSImage(contentsOf: try XCTUnwrap(capture.saved))) + XCTAssertEqual(image.size, NSSize(width: model.activeVideoRect.width, height: model.activeVideoRect.height)) + let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + XCTAssertEqual(after.generation, before.generation) + XCTAssertEqual(after.cycles, before.cycles) + XCTAssertEqual(after.presentedFrame, before.presentedFrame) + XCTAssertEqual(after.audioStarts, before.audioStarts) + } + + @MainActor func testResetsCancelScreenshotTimersButContinueTheSameRecording() async throws { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + model.captures = capture + try await capture.preferences.setFolder(root) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording) + let record = try XCTUnwrap(capture.recoveries.first) + for cold in [false, true] { + capture.delay(10) + XCTAssertEqual(capture.countdown, 10) + if cold { model.reset() } else { model.softReset() } + XCTAssertNil(capture.countdown) + for _ in 0..<200 where model.busy { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertFalse(model.busy) + XCTAssertEqual(capture.state, .recording) + XCTAssertEqual(capture.recoveries.map(\.id), [record.id]) + try await Task.sleep(for: .milliseconds(80)) + } + XCTAssertEqual(cues, [.recordingStarted], "A reset neither restarts recording nor takes a delayed screenshot") + await capture.stopRecording() + XCTAssertNil(capture.error); XCTAssertEqual(capture.state, .idle) + let asset = AVURLAsset(url: try XCTUnwrap(capture.saved)) + let duration = try await asset.load(.duration).seconds + XCTAssertGreaterThan(duration, 0.12) + XCTAssertTrue(capture.recoveries.isEmpty) + } + + @MainActor func testCaptureInterruptionRetainsOwnedMovieAndRecoveryAcrossRelaunch() async throws { + let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + try await capture.preferences.setFolder(root) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording) + let record = try XCTUnwrap(capture.recoveries.first) + let unrelated = record.directory.appendingPathComponent("User note.txt"), original = Data("preserve".utf8) + try original.write(to: unrelated) + try await Task.sleep(for: .milliseconds(250)) + controller.failNextPull = true + for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved) + XCTAssertEqual(capture.error, "Authored capture-consumer interruption") + XCTAssertEqual(capture.recoveries.map(\.id), [record.id]) + XCTAssertTrue(FileManager.default.fileExists(atPath: record.working.path)) + XCTAssertGreaterThan(try Data(contentsOf: record.working).count, 0) + XCTAssertEqual(cues, [.recordingStarted]) + let reopened = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + XCTAssertEqual(reopened.recoveries.map(\.id), [record.id]) + let recoveredFolder = root.appendingPathComponent("Recovered", isDirectory: true) + try FileManager.default.createDirectory(at: recoveredFolder, withIntermediateDirectories: true) + try await reopened.preferences.setFolder(recoveredFolder) + reopened.recover(record) + for _ in 0..<400 where reopened.state != .idle { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertNil(reopened.error); XCTAssertTrue(reopened.recoveries.isEmpty) + let final = try XCTUnwrap(reopened.saved) + XCTAssertEqual(final.deletingLastPathComponent().standardizedFileURL, recoveredFolder.standardizedFileURL) + let duration = try await AVURLAsset(url: final).load(.duration).seconds + XCTAssertGreaterThan(duration, 0.2, "Recovery must deliver preceding recorded content") + XCTAssertEqual(try Data(contentsOf: unrelated), original, "Completion cleans only its working movie, never unexpected files") + XCTAssertFalse(FileManager.default.fileExists(atPath: record.working.path)) + XCTAssertEqual(cues, [.recordingStarted], "Recovery must not emit a new recording-start cue") + } + + @MainActor func testRecordingTransportSurvivesAnOccupiedMainActorOnBothProcessors() async throws { + for hd in [false, true] { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording) + let before = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + holdMainActor() + let after = await withCheckedContinuation { c in controller.snapshot { c.resume(returning: $0) } } + // Allow any delayed failure notification to run before assertions; + // merely observing the old published Recording state proves little. + try await Task.sleep(for: .milliseconds(100)) + XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error) + XCTAssertEqual(after.generation, before.generation) + XCTAssertEqual(after.audioStarts, before.audioStarts) + XCTAssertGreaterThan(after.cycles, before.cycles) + XCTAssertGreaterThan(after.presentedFrame, before.presentedFrame) + XCTAssertEqual(after.use6309, hd) + await capture.stopRecording() + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error) + XCTAssertTrue(capture.recoveries.isEmpty) + let asset = AVURLAsset(url: try XCTUnwrap(capture.saved)) + let duration = try await asset.load(.duration).seconds + XCTAssertGreaterThan(duration, 0.75, "The movie must span the occupied UI interval") + XCTAssertEqual(cues, [.recordingStarted]) + await withCheckedContinuation { c in model.shutdown { c.resume() } } + } + } + + @MainActor func testCaptureFailureQuiescesAndFinalizesWhileMainActorIsOccupied() async throws { + let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller) + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in }) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording) + let record = try XCTUnwrap(capture.recoveries.first) + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.failNextPull = true } + holdMainActor() + XCTAssertEqual(controller.finalPulls, 1, "Failure must stop the source without waiting for the UI notification") + for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved) + XCTAssertEqual(capture.error, "Authored capture-consumer interruption") + XCTAssertEqual(capture.recoveries.map(\.id), [record.id]) + let duration = try await AVURLAsset(url: record.working).load(.duration).seconds + XCTAssertGreaterThan(duration, 0.1) + XCTAssertEqual(controller.finalPulls, 1, "The later UI stop shares the same backend finalization") + } + + @MainActor func testEncoderFailureQuiescesSourceBeforeItsMainActorNotification() async throws { + let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller) + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { _ in }) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording) + let record = try XCTUnwrap(capture.recoveries.first) + // A malformed authored transport frame exercises the real encoder's + // validation/failure callback; no guest memory or registers are changed. + DispatchQueue.global(qos: .userInitiated).asyncAfter(deadline: .now() + .milliseconds(200)) { controller.invalidateNextPull = true } + holdMainActor() + XCTAssertEqual(controller.finalPulls, 1) + // User Stop can arrive before the queued UI failure notification. Both + // paths must share the already-started backend finalization. + await capture.stopRecording() + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.saved) + XCTAssertTrue(capture.error?.contains("ordering") == true) + XCTAssertEqual(capture.recoveries.map(\.id), [record.id]) + XCTAssertEqual(controller.finalPulls, 1) + let duration = try await AVURLAsset(url: record.working).load(.duration).seconds + XCTAssertGreaterThan(duration, 0.1) + } + + @MainActor func testImmediateFailureDoesNotLatchRecordingOrStopItsSuccessor() async throws { + let controller = FailingPullController(), (root, defaults, model) = try await guest(controller: controller) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + for _ in 0..<4 { + controller.failNextPull = true + capture.startRecording() + for _ in 0..<300 where capture.state != .idle { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertEqual(capture.state, .idle, "An immediate background failure must not leave a stale Recording state") + XCTAssertEqual(capture.error, "Authored capture-consumer interruption") + } + let retained = capture.recoveries.map(\.id), oldCues = cues.count + XCTAssertEqual(retained.count, 4) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + try await Task.sleep(for: .milliseconds(150)) + XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error) + XCTAssertEqual(cues.count, oldCues + 1) + await capture.stopRecording() + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error) + XCTAssertNotNil(capture.saved) + XCTAssertEqual(capture.recoveries.map(\.id), retained) + } + + @MainActor func testCaptureStartOwnsFreshErrorStateAndBridgeRefusalNeverCuesOnBothProcessors() async throws { + for hd in [false, true] { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller, use6309: hd) + let rejected = await withCheckedContinuation { c in + controller.configureMachine(use6309: hd, ram: 99, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) } + } + XCTAssertNotNil(rejected.errorMessage) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + capture.startRecording() + for _ in 0..<200 where capture.state == .starting { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .recording); XCTAssertNil(capture.error) + try await Task.sleep(for: .milliseconds(100)) + await capture.stopRecording() + XCTAssertEqual(capture.state, .idle); XCTAssertNil(capture.error) + XCTAssertNotNil(capture.saved); XCTAssertTrue(capture.recoveries.isEmpty) + XCTAssertEqual(cues, [.recordingStarted]) + // The model deliberately retains its last normal-speed snapshot; + // the owner queue independently refuses the actual fast-forward run. + _ = await withCheckedContinuation { c in + controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: true) { c.resume(returning: $0) } + } + XCTAssertFalse(model.settings.fastForward) + capture.startRecording() + for _ in 0..<200 where capture.state != .idle { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertEqual(capture.state, .idle) + XCTAssertTrue(capture.error?.contains("fast-forward") == true) + XCTAssertEqual(cues, [.recordingStarted], "A refused bridge start must not emit a success cue") + _ = await withCheckedContinuation { c in + controller.configureMachine(use6309: hd, ram: model.settings.ram, overclock: 1, frameInterval: 1, fastForward: false) { c.resume(returning: $0) } + } + let probe = await withCheckedContinuation { c in controller.beginVideoCapture(replyQueue: .global(qos: .userInitiated)) { c.resume(returning: $0) } } + XCTAssertNil(probe.errorMessage, "The rejected start must not leave an unowned capture producer active") + let stopped: String? = await withCheckedContinuation { c in controller.takeVideoCapture(finish: true, replyQueue: .global(qos: .userInitiated)) { _, error in c.resume(returning: error) } } + XCTAssertNil(stopped) + await withCheckedContinuation { c in model.shutdown { c.resume() } } + } + } + + @MainActor func testNewerRecoveryManifestIsPreservedAndBlocksAnotherWriter() async throws { + let controller = VCCMachineController(), (root, defaults, model) = try await guest(controller: controller) + let manifest = root.appendingPathComponent("CaptureRecovery.json") + let original = Data(#"{"version":2,"recordings":[],"futureMetadata":"preserve exactly"}"#.utf8) + try original.write(to: manifest) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + try await capture.preferences.setFolder(root) + XCTAssertNotNil(capture.error) + capture.startRecording() + XCTAssertEqual(capture.state, .idle); XCTAssertTrue(capture.recoveries.isEmpty) + XCTAssertTrue(capture.error?.contains("preserved recording recovery") == true) + XCTAssertTrue(cues.isEmpty) + XCTAssertEqual(try Data(contentsOf: manifest), original) + let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) + XCTAssertFalse(contents.contains { $0.lastPathComponent.hasPrefix(".vcc-recording-") }) + } + @MainActor func testSharedDestinationDefaultsTimerAndAudioPersistWithoutMovingFiles() async throws { + let root = try folder(), suite = "CoCoCapturePreferences-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let first = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + XCTAssertEqual(first.destination, .desktop) + XCTAssertEqual(first.folder, root) + XCTAssertEqual(first.screenshots, first.recordings) + XCTAssertEqual(first.timerSeconds, 0); XCTAssertTrue(first.includeVideoAudio) + XCTAssertNil(defaults.data(forKey: "capture.folder.shared"), "A logical default must not create a security bookmark before the user chooses a folder") + let custom = root.appendingPathComponent("My Captures", isDirectory: true) + try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true) + let original = custom.appendingPathComponent("Existing.txt") + try Data("keep me".utf8).write(to: original) + try await first.setFolder(custom); first.setTimerSeconds(10); first.includeVideoAudio = false + let chosenBookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared")) + let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + XCTAssertEqual(reopened.folder.standardizedFileURL, custom.standardizedFileURL) + XCTAssertEqual(reopened.screenshots, reopened.recordings) + XCTAssertEqual(reopened.destination, .other) + XCTAssertEqual(reopened.timerSeconds, 10); XCTAssertFalse(reopened.includeVideoAudio) + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), chosenBookmark, "Reopening preferences preserves an explicit selected-folder grant") + reopened.setTimerSeconds(3) + XCTAssertEqual(reopened.timerSeconds, 10, "Only None, 5 and 10 are valid timer choices") + reopened.setDestination(.documents) + XCTAssertEqual(reopened.folder, root.appendingPathComponent("Documents", isDirectory: true)) + XCTAssertEqual(try Data(contentsOf: original), Data("keep me".utf8)) + reopened.setDestination(.desktop) + XCTAssertEqual(reopened.folder, root) + defaults.set(999, forKey: "capture.timer.seconds") + XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).timerSeconds, 0) + } + + @MainActor func testLegacyCaptureFoldersMigrateWithExplicitScreenshotChoiceFirst() throws { + let root = try folder(), screenshot = root.appendingPathComponent("Pictures"), video = root.appendingPathComponent("Movies") + for path in [screenshot, video] { try FileManager.default.createDirectory(at: path, withIntermediateDirectories: true) } + for screenshotChosen in [false, true] { + let suite = "CoCoCaptureMigration-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let videoBookmark = try video.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) + defaults.set(videoBookmark, forKey: "capture.folder.recordings") + if screenshotChosen { + defaults.set(try screenshot.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil), forKey: "capture.folder.screenshots") + } + let migrated = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + let expected = screenshotChosen ? screenshot : video + XCTAssertEqual(migrated.folder.standardizedFileURL, expected.standardizedFileURL) + XCTAssertEqual(migrated.screenshots, migrated.recordings) + XCTAssertEqual(defaults.data(forKey: "capture.folder.recordings"), videoBookmark) + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), + defaults.data(forKey: screenshotChosen ? "capture.folder.screenshots" : "capture.folder.recordings"), + "Migration reuses the existing security bookmark bytes instead of requesting a new grant") + let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + XCTAssertEqual(reopened.folder.standardizedFileURL, expected.standardizedFileURL) + } + } + + @MainActor func testBuiltInDestinationsPersistWithoutBookmarkOrDirectoryWorkAndOverrideOther() async throws { + let root = try folder(), custom = root.appendingPathComponent("Chosen Other", isDirectory: true) + try FileManager.default.createDirectory(at: custom, withIntermediateDirectories: true) + let suite = "CoCoLogicalDestination-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root) + try await preferences.setFolder(custom) + let bookmark = try XCTUnwrap(defaults.data(forKey: "capture.folder.shared")) + let documents = root.appendingPathComponent("Documents", isDirectory: true) + XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path)) + preferences.setDestination(.documents) + XCTAssertEqual(preferences.destination, .documents); XCTAssertEqual(preferences.folder, documents) + XCTAssertEqual(defaults.string(forKey: "capture.destination"), "documents") + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark, "Keep the previous explicit grant for in-flight writers") + XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path), "Selecting a logical folder must not create it on the UI thread") + let reopened = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { _ in + XCTFail("Logical destination restore must not make a bookmark"); return Data() + }) + XCTAssertEqual(reopened.destination, .documents); XCTAssertEqual(reopened.folder, documents) + reopened.setDestination(.desktop) + XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder, root) + XCTAssertEqual(defaults.string(forKey: "capture.destination"), "desktop") + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), bookmark) + XCTAssertFalse(FileManager.default.fileExists(atPath: documents.path)) + } + + @MainActor func testLateOtherGrantCannotReplaceNewerBuiltInOrOtherChoice() async throws { + for newerOther in [false, true] { + let root = try folder(), first = root.appendingPathComponent("First"), second = root.appendingPathComponent("Second") + for url in [first, second] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) } + let suite = "CoCoDestinationOrder-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let gate = BookmarkGate(blocked: first) + let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) }) + let stale = Task { try await preferences.setFolder(first) } + for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertTrue(gate.started); XCTAssertTrue(preferences.preparingDestination) + if newerOther { try await preferences.setFolder(second) } else { preferences.setDestination(.documents) } + gate.unblock() + do { try await stale.value; XCTFail("A superseded grant must not become the selected folder") } + catch is CancellationError { } + let expected = newerOther ? second : root.appendingPathComponent("Documents", isDirectory: true) + XCTAssertEqual(preferences.folder, expected); XCTAssertFalse(preferences.preparingDestination) + XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, expected.standardizedFileURL) + } + } + + @MainActor func testLateOtherFailureIsCancellationAndLegacyFallbackStillMigrates() async throws { + let root = try folder(), first = root.appendingPathComponent("First"), legacy = root.appendingPathComponent("Legacy") + for url in [first, legacy] { try FileManager.default.createDirectory(at: url, withIntermediateDirectories: true) } + let suite = "CoCoDestinationFailure-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let legacyBookmark = try legacy.bookmarkData(options: .withSecurityScope, includingResourceValuesForKeys: nil, relativeTo: nil) + defaults.set(Data("invalid shared bookmark".utf8), forKey: "capture.folder.shared") + defaults.set(legacyBookmark, forKey: "capture.folder.recordings") + let gate = BookmarkGate(blocked: first, fails: true) + let preferences = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try gate.prepare($0) }) + XCTAssertEqual(preferences.folder.standardizedFileURL, legacy.standardizedFileURL) + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark) + let stale = Task { try await preferences.setFolder(first) } + for _ in 0..<200 where !gate.started { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertTrue(gate.started) + preferences.setDestination(.desktop); gate.unblock() + do { try await stale.value; XCTFail("A superseded failed grant must be ignored") } + catch is CancellationError { } + XCTAssertEqual(preferences.folder, root); XCTAssertFalse(preferences.preparingDestination) + XCTAssertEqual(defaults.data(forKey: "capture.folder.shared"), legacyBookmark) + XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).destination, .desktop) + let later = root.appendingPathComponent("Later Other") + try FileManager.default.createDirectory(at: later, withIntermediateDirectories: true) + let nextGate = BookmarkGate(blocked: first, fails: true) + let next = CoCoCapturePreferences(defaults: defaults, fallbackRoot: root, makeBookmark: { try nextGate.prepare($0) }) + let superseded = Task { try await next.setFolder(first) } + for _ in 0..<200 where !nextGate.started { try await Task.sleep(for: .milliseconds(5)) } + XCTAssertTrue(nextGate.started) + try await next.setFolder(later); nextGate.unblock() + do { try await superseded.value; XCTFail("An old failure must not replace a newer accepted Other folder") } + catch is CancellationError { } + XCTAssertEqual(next.folder, later); XCTAssertFalse(next.preparingDestination) + XCTAssertEqual(CoCoCapturePreferences(defaults: defaults, fallbackRoot: root).folder.standardizedFileURL, later.standardizedFileURL) + } + + @MainActor func testTimerSelectionCancellationAndRealCaptureEmitOnlyActualCaptureCues() async throws { + let root = try folder(), suite = "CoCoCaptureCues-" + UUID().uuidString + let defaults = try XCTUnwrap(UserDefaults(suiteName: suite)) + defer { defaults.removePersistentDomain(forName: suite) } + let controller = VCCMachineController() + let model = MachineModel(diskStore: .init(url: root.appendingPathComponent("Disks.json")), controller: controller, + displayDefaults: defaults, inputStore: .init(url: root.appendingPathComponent("Input.json")), restoreMediaOnLaunch: false) + var cues: [CoCoCaptureFeedback.Cue] = [] + let capture = CoCoCaptureCoordinator(machine: model, controller: controller, defaults: defaults, directory: root, feedback: { cues.append($0) }) + try await capture.preferences.setFolder(root) + capture.captureNow(); capture.startRecording() + XCTAssertTrue(cues.isEmpty, "A missing framebuffer cannot emit a success cue") + XCTAssertEqual(capture.state, .idle) + await withCheckedContinuation { c in controller.loadDiagnostic(use6309: false) { _ in c.resume() } } + await withCheckedContinuation { c in controller.resume { _ in c.resume() } } + for _ in 0..<100 where model.pixels == nil { model.poll(); try await Task.sleep(for: .milliseconds(10)) } + guard model.pixels != nil else { + await withCheckedContinuation { c in model.shutdown { c.resume() } } + return XCTFail("The diagnostic guest did not provide a picture") + } + capture.preferences.setTimerSeconds(10); capture.preferences.includeVideoAudio = false + XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty) + capture.capture() + XCTAssertEqual(capture.countdown, 10); XCTAssertTrue(cues.isEmpty) + capture.cancelCountdown() + try await Task.sleep(for: .milliseconds(50)) + XCTAssertNil(capture.countdown); XCTAssertNil(capture.saved); XCTAssertTrue(cues.isEmpty) + capture.preferences.setTimerSeconds(0); capture.capture(); capture.capture() + XCTAssertEqual(cues, [.screenshot], "A duplicate click during saving must not capture or cue twice") + for _ in 0..<100 where capture.saving { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertNotNil(capture.saved); XCTAssertFalse(capture.hasPendingImage) + capture.preferences.setTimerSeconds(5); capture.capture() + XCTAssertEqual(capture.countdown, 5); XCTAssertEqual(cues.count, 1) + for _ in 0..<650 where capture.countdown != nil || capture.saving { try await Task.sleep(for: .milliseconds(10)) } + XCTAssertNil(capture.countdown); XCTAssertFalse(capture.saving) + XCTAssertEqual(cues, [.screenshot, .screenshot], "Only timer expiry emits the delayed capture cue") + let pngs = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil).filter { $0.pathExtension == "png" } + XCTAssertEqual(pngs.count, 2) + await withCheckedContinuation { c in model.shutdown { c.resume() } } + } + + func testSilentVideoDecodesToSilenceWithUnchangedPictureAndTimeline() async throws { + let root = try folder(), movie = root.appendingPathComponent("Silent.mov"), final = root.appendingPathComponent("Silent.mp4") + let encoder = try CoCoVideoEncoder(workingURL: movie), bytes = picture() + var source = Data(count: 735 * 8) + source.withUnsafeMutableBytes { raw in + let floats = raw.bindMemory(to: Float.self) + for i in 0..<735 { floats[2*i] = 0.25; floats[2*i+1] = -0.25 } + } + let live = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: CGRect(x: 64, y: 48, width: 512, height: 384), audio: source, sampleOffset: 735, includeAudio: true) + XCTAssertEqual(live.audio, source) + for n in 0..<60 { + let silent = CoCoCaptureCoordinator.videoFrame(pixels: bytes, area: live.area, audio: source, sampleOffset: Int64(n*735), includeAudio: false) + XCTAssertEqual(silent.pixels, bytes); XCTAssertEqual(silent.area, live.area) + XCTAssertEqual(silent.sampleOffset, Int64(n*735)); XCTAssertEqual(silent.audio.count, source.count) + XCTAssertTrue(silent.audio.allSatisfy { $0 == 0 }) + encoder.append([silent]); try await Task.sleep(for: .milliseconds(17)) + } + let working: URL = try await withCheckedThrowingContinuation { c in encoder.finish { c.resume(with: $0) } } + try await CoCoVideoEncoder.exportMP4(from: working, to: final) + let asset = AVURLAsset(url: final) + let duration = try await asset.load(.duration).seconds + XCTAssertEqual(duration, 1, accuracy: 0.03) + let audio = try await asset.loadTracks(withMediaType: .audio), video = try await asset.loadTracks(withMediaType: .video) + XCTAssertEqual(video.count, 1) + let track = try XCTUnwrap(audio.first) + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false]) + reader.add(output); XCTAssertTrue(reader.startReading()) + var peak: Float = 0, count = 0 + while let sample = output.copyNextSampleBuffer() { + let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample)) + var data = Data(count: CMBlockBufferGetDataLength(buffer)) + let result = data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) } + XCTAssertEqual(result, noErr) + data.withUnsafeBytes { raw in + for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); count += 1 } + } + } + XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0) + XCTAssertLessThan(peak, 0.00001, "The delivered MP4 must decode to silence, despite nonzero source PCM") + } + +} diff --git a/platforms/macos/Tests/CoCoVideoBudgetTests.swift b/platforms/macos/Tests/CoCoVideoBudgetTests.swift new file mode 100644 index 0000000..c97e884 --- /dev/null +++ b/platforms/macos/Tests/CoCoVideoBudgetTests.swift @@ -0,0 +1,110 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AVFoundation +import Foundation +import XCTest + +final class CoCoVideoBudgetTests: XCTestCase { + private func directory() throws -> URL { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CoCoVideoBudget-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: false) + addTeardownBlock { try? FileManager.default.removeItem(at: root) } + return root + } + private func frames(count: Int, audioFrames: Int = 735) -> [CoCoVideoFrame] { + let pixels = Data(repeating: 0x40, count: 640 * 480 * 4) + return (0.. = await withCheckedContinuation { c in encoder.finish { c.resume(returning: $0) } } + if case .success = stopped { XCTFail("Writer failure must not be advertised as a completed movie") } + XCTAssertTrue(encoder.writerIsTerminal) + let drained: Result = await withCheckedContinuation { c in encoder.whenDrained { c.resume(returning: $0) } } + if case .success = drained { XCTFail("Failed input cannot be acknowledged as a successful drain") } + // The failure notification can precede AVFoundation's closure, but the + // finish callback cannot. No polling/retry is permitted after finish. + let duration = try await AVURLAsset(url: working).load(.duration).seconds + XCTAssertGreaterThan(duration, 0.2, "A failed writer retains its preceding playable content") + XCTAssertGreaterThan(try Data(contentsOf: working).count, 0) + XCTAssertEqual(try Data(contentsOf: neighbor), original) + let contents = try FileManager.default.contentsOfDirectory(at: root, includingPropertiesForKeys: nil) + XCTAssertEqual(Set(contents.map(\.lastPathComponent)), ["Working.mov", "Existing.mp4"]) + } +} diff --git a/platforms/macos/Tests/CompanionLibraryTests.swift b/platforms/macos/Tests/CompanionLibraryTests.swift index abf784b..c019e27 100644 --- a/platforms/macos/Tests/CompanionLibraryTests.swift +++ b/platforms/macos/Tests/CompanionLibraryTests.swift @@ -1,13 +1,66 @@ // SPDX-License-Identifier: GPL-3.0-or-later import XCTest +import ImageIO +import UniformTypeIdentifiers final class CompanionLibraryTests: XCTestCase { - private static func release(_ id: String, media: String = "disk") -> SoftwareLibraryRelease { - .init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media, + func testColdServiceReadinessCanOutlastOldSixSecondLimitWithoutDelayingReadyService() async throws { + var uptime: TimeInterval = 100, attempts = 0, pauses = 0 + try await CompanionTransport.waitForService(now: { uptime }, sleep: { delay in + pauses += 1; uptime += delay + }, probe: { remaining in + attempts += 1 + XCTAssertGreaterThan(remaining, 0); XCTAssertLessThanOrEqual(remaining, 45) + if uptime < 123 { throw CompanionTransport.Failure.unavailable } + }) + XCTAssertGreaterThan(uptime - 100, 22.9) + XCTAssertGreaterThan(attempts, 60); XCTAssertEqual(pauses, attempts - 1) + pauses = 0; attempts = 0 + try await CompanionTransport.waitForService(now: { uptime }, sleep: { _ in pauses += 1 }, probe: { _ in attempts += 1 }) + XCTAssertEqual(attempts, 1); XCTAssertEqual(pauses, 0) + } + + func testColdServiceReadinessHasBoundedDeadlineAndKeepsRealErrors() async throws { + var uptime: TimeInterval = 0, pauses = 0 + do { + try await CompanionTransport.waitForService(timeout: 0.25, now: { uptime }, sleep: { delay in + pauses += 1; uptime += delay + }, probe: { _ in throw CompanionTransport.Failure.unavailable }) + XCTFail("A service that never starts must time out") + } catch CompanionTransport.Failure.startupTimedOut { } + XCTAssertEqual(uptime, 0.25, accuracy: 0.00001); XCTAssertEqual(pauses, 3) + for failure in [CompanionTransport.Failure.untrustedPeer, .unsafeEndpoint, .unsupportedVersion, .timedOut, .remote("Denied")] { + pauses = 0 + do { + try await CompanionTransport.waitForService(sleep: { _ in pauses += 1 }, probe: { _ in throw failure }) + XCTFail("A real companion error must not be retried") + } catch { XCTAssertEqual(error.localizedDescription, failure.localizedDescription) } + XCTAssertEqual(pauses, 0) + } + } + + func testColdServiceReadinessCancelsDuringStartupWait() async throws { + let waiting = expectation(description: "Startup is waiting for its missing listener") + let task = Task { + try await CompanionTransport.waitForService(sleep: { _ in + waiting.fulfill() + try await Task.sleep(for: .seconds(60)) + }, probe: { _ in throw CompanionTransport.Failure.unavailable }) + } + await fulfillment(of: [waiting], timeout: 2) + task.cancel() + do { try await task.value; XCTFail("Cancellation must end startup polling") } + catch is CancellationError { } + } + + private static func release(_ id: String, media: String = "disk", owned: Bool = false) -> SoftwareLibraryRelease { + var metadata: [String: LibraryJSON] = ["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)] + if owned { metadata["owned_game"] = .object([:]) } + return .init(id: id, titleID: "title", name: id, category: "Disks/Games", mediaType: media, contentRole: "software", sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Example.zip")!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: String(repeating: "a", count: 64), byteSize: 256, languageStatus: "unknown", - metadata: .object(["title": .string("Authored Example"), "optional": .null, "enabled": .bool(false), "count": .number(2)]), + metadata: .object(metadata), setup: .init(status: "manual-setup", command: nil, instructions: "Follow the authored instructions.", configuration: .object([:]), selectedMembers: .array([]), reasons: [], validation: .object([:])), assets: [], downloadURLs: []) @@ -44,6 +97,61 @@ final class CompanionLibraryTests: XCTestCase { XCTAssertNil(state.saveError) XCTAssertFalse(FileManager.default.fileExists(atPath: state.directory.appendingPathComponent("Unused.json").path)) } + + @MainActor + func testBothAppsSharePersistedFavoritesAndEditionChoicesWithoutASecondStateFile() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("CompanionChoices-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let catalog = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Authored Example", identityStatus: "reviewed", + releases: [Self.release("disk"), Self.release("second-disk")])], metadata: [:]) + let host = SoftwareLibraryModel(state: .init(directory: root)) + await host.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in catalog }) + host.state.toggleFavorite("title") + host.state.selectRelease("second-disk", for: "title") + await host.state.flush() + + let service = AuthorityLibrary(authority: .init(model: host)) + let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Changing choices must not insert media.") } + await client.load() + XCTAssertTrue(client.state.isFavorite("title"), "A companion opening after a VCC Plus change reads the same choices.") + XCTAssertEqual(client.state.preferredReleaseID(for: "title"), "second-disk") + client.state.toggleFavorite("title") + client.state.selectRelease("disk", for: "title") + await client.state.flush() + XCTAssertNil(client.state.saveError) + XCTAssertFalse(host.state.isFavorite("title")) + XCTAssertEqual(host.state.preferredReleaseID(for: "title"), "disk") + + // Reopening the authoritative state proves the response was persisted, + // rather than copied only between the two current in-memory models. + let persisted = SoftwareLibraryState(directory: root) + XCTAssertNil(persisted.saveError) + XCTAssertFalse(persisted.isFavorite("title")) + XCTAssertEqual(persisted.preferredReleaseID(for: "title"), "disk") + XCTAssertFalse(FileManager.default.fileExists(atPath: client.state.directory.appendingPathComponent("Unused.json").path)) + let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Reopening must not insert media.") } + await reopened.load() + XCTAssertFalse(reopened.state.isFavorite("title")) + XCTAssertEqual(reopened.state.preferredReleaseID(for: "title"), "disk") + await reopened.shutdown(); await client.shutdown(); await host.shutdown() + } + + @MainActor + func testUnavailableCompanionCanBeRetriedWithoutCreatingLocalLibraryState() async throws { + let service = RecoveringLibrary(catalog: Self.catalog) + let model = SoftwareLibraryModel(companion: service) { _ in XCTFail("A failed or retried browse must not insert media.") } + await model.load() + XCTAssertNotNil(model.error) + XCTAssertNil(model.catalog) + XCTAssertFalse(model.loading) + await service.reconnect() + await model.load() + XCTAssertNil(model.error) + XCTAssertEqual(model.catalog?.releases.map(\.id), ["disk"]) + XCTAssertFalse(model.loading) + XCTAssertFalse(FileManager.default.fileExists(atPath: model.state.directory.appendingPathComponent("Unused.json").path)) + await model.shutdown() + } @MainActor func testClearingFiltersAndChangingEditionCannotExposeTapeOrCartridge() async throws { let service = FakeLibrary(catalog: Self.catalog) @@ -68,6 +176,301 @@ final class CompanionLibraryTests: XCTestCase { } } + func testPersonalCapabilityIsExplicitAndOlderRequestsDecodeWithoutIt() throws { + let current = CompanionLibraryRequest(operation: .snapshot) + XCTAssertEqual(current.personalTitlesVersion, 1) + let old = try JSONDecoder().decode(CompanionLibraryRequest.self, from: Data("{\"operation\":\"snapshot\",\"requestID\":\"00000000-0000-0000-0000-000000000001\"}".utf8)) + XCTAssertNil(old.personalTitlesVersion) + XCTAssertNil(old.ownedTitlesVersion) + let entry = PersonalSoftwareEntry(id: UUID(), title: "Private disk", files: [ + .init(path: "game.dsk", kind: "disk", byteSize: 256, sha256: String(repeating: "a", count: 64))]) + let release = entry.release(in: URL(fileURLWithPath: "/unused/PersonalLibrary/" + entry.id.uuidString.lowercased())) + let catalog = SoftwareLibraryCatalog(titles: Self.catalog.titles + [ + .init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:]) + XCTAssertEqual(catalog.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk"]) + XCTAssertEqual(Set(catalog.companionDisksOnly.releases.map(\.id)), Set(["disk", entry.releaseID])) + let mixed = SoftwareLibraryCatalog(titles: [.init(id: "title", name: "Mixed editions", identityStatus: "reviewed", + releases: [Self.release("disk"), Self.release("owned", owned: true), Self.release("cart", media: "cartridge")])], metadata: [:]) + XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: false, includingPersonalTitles: true).releases.map(\.id), ["disk"]) + XCTAssertEqual(mixed.companionDisks(includingOwnedTitles: true).releases.map(\.id), ["disk", "owned"]) + } + + @MainActor + func testAuthoritySharesCurrentPersonalDiskChoicesAndIndependentWritableCopies() async throws { + let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionPersonal-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + let source = root.appendingPathComponent("GAME.dsk") + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let original = try Data(contentsOf: fixture) + try original.write(to: source) + let manual = root.appendingPathComponent("README.txt"), instructions = Data("Private local instructions".utf8) + try instructions.write(to: manual) + let draft = try await model.personalStore.inspect([source, manual]) + let entry = try await model.personalStore.save(draft) + await model.load(from: root.appendingPathComponent("authored.sqlite"), catalogLoader: { _ in Self.catalog }) + let authority = CompanionLibraryAuthority(model: model) + let initial = try await authority.handle(.init(operation: .snapshot)) + let snapshot = try XCTUnwrap(initial.snapshot) + XCTAssertEqual(Set(snapshot.catalog.releases.map(\.id)), Set(["disk", entry.releaseID])) + XCTAssertEqual(snapshot.installations.map(\.releaseID), [entry.releaseID]) + XCTAssertTrue(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })!.downloadURLs.isEmpty) + let favorite = try await authority.handle(.init(operation: .setFavorite, titleID: entry.titleID, enabled: true)) + XCTAssertTrue(favorite.snapshot!.favorites.contains(entry.titleID)) + let preferred = try await authority.handle(.init(operation: .setPreferredRelease, releaseID: entry.releaseID, titleID: entry.titleID)) + XCTAssertEqual(preferred.snapshot!.preferredReleaseIDs[entry.titleID], entry.releaseID) + for operation in [CompanionLibraryRequest.Operation.install, .installStatus] { + let status = try await authority.handle(.init(operation: operation, releaseID: entry.releaseID)) + XCTAssertFalse(status.isInstalling); XCTAssertEqual(status.receipt?.releaseID, entry.releaseID) + } + let directory = model.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk") + var saved = original; saved[0] ^= 1; try saved.write(to: working) + let members = try await authority.handle(.init(operation: .diskMembers, releaseID: entry.releaseID)) + XCTAssertEqual(members.disks?.map(\.path), ["GAME.dsk"]) + let export = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk")) + let copy = try XCTUnwrap(export.exportedDiskURL) + XCTAssertNotEqual(copy, working); XCTAssertEqual(try Data(contentsOf: copy), saved) + try Data([1, 2, 3]).write(to: copy) + let second = try await authority.handle(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk")) + XCTAssertNotEqual(second.exportedDiskURL, copy) + XCTAssertEqual(try Data(contentsOf: working), saved) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original) + XCTAssertEqual(try Data(contentsOf: source), original) + let asset = try XCTUnwrap(snapshot.catalog.releases.first(where: { $0.id == entry.releaseID })?.primaryManualAsset) + let response = try await authority.handle(.init(operation: .manual, assetID: asset.id)) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(response.assetFileURL)), instructions) + let localManual = try XCTUnwrap(response.assetFileURL) + try FileManager.default.removeItem(at: localManual) + try FileManager.default.createSymbolicLink(at: localManual, withDestinationURL: manual) + await assertFailure(authority, .init(operation: .manual, assetID: asset.id)) + await assertFailure(authority, .init(operation: .removeInstallation, releaseID: entry.releaseID)) + XCTAssertTrue(FileManager.default.fileExists(atPath: working.path)) + await model.shutdown() + } + + @MainActor + func testAuthorityRefusesHiddenUnknownNondiskAndUnnegotiatedPersonalIDs() async throws { + let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionHidden-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let draft = try await model.personalStore.inspect([fixture]) + let visible = try await model.personalStore.save(draft) + let duplicate = try await model.personalStore.inspect([fixture]) + var hidden = try await model.personalStore.save(duplicate, allowDuplicate: true) + hidden.hidden = true; try await model.personalStore.update(hidden) + let cart = root.appendingPathComponent("CART.ccc"); try Data([0x39]).write(to: cart) + let cartDraft = try await model.personalStore.inspect([cart]) + let nondisk = try await model.personalStore.save(cartDraft) + var unsupported: [PersonalSoftwareEntry] = [] + for ext in ["dmk", "jvc", "vdk"] { + let file = root.appendingPathComponent("Unsupported." + ext) + try FileManager.default.copyItem(at: fixture, to: file) + let draft = try await model.personalStore.inspect([file]) + unsupported.append(try await model.personalStore.save(draft)) + } + await model.load(from: fixture, catalogLoader: { _ in Self.catalog }) + let authority = CompanionLibraryAuthority(model: model) + let current = try await authority.handle(.init(operation: .snapshot)) + XCTAssertEqual(Set(current.snapshot!.catalog.releases.map(\.id)), Set(["disk", visible.releaseID])) + for version in [nil, 2] as [Int?] { + let response = try await authority.handle(.init(operation: .snapshot, personalTitlesVersion: version)) + XCTAssertEqual(response.snapshot?.catalog.releases.map(\.id), ["disk"]) + XCTAssertTrue(response.snapshot!.installations.isEmpty) + await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID, personalTitlesVersion: version)) + await assertFailure(authority, .init(operation: .setFavorite, titleID: visible.titleID, enabled: true, personalTitlesVersion: version)) + } + for entry in [hidden, nondisk] + unsupported { + await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID)) + await assertFailure(authority, .init(operation: .setFavorite, titleID: entry.titleID, enabled: true)) + } + await assertFailure(authority, .init(operation: .diskMembers, releaseID: "personal:unknown:edition")) + await assertFailure(authority, .init(operation: .setPreferredRelease, releaseID: visible.releaseID, titleID: hidden.titleID)) + await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "../DECB.dsk")) + await assertFailure(authority, .init(operation: .exportDisk, releaseID: visible.releaseID, memberPath: "missing.dsk")) + var removed = visible; removed.hidden = true; try await model.personalStore.update(removed) + await assertFailure(authority, .init(operation: .diskMembers, releaseID: visible.releaseID)) + await model.shutdown() + } + + @MainActor + func testAuthorityRefusesPersonalWorkingAndMemberSymlinks() async throws { + let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionLinks-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + let source = root.appendingPathComponent("Set/sub"), fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + try FileManager.default.copyItem(at: fixture, to: source.appendingPathComponent("GAME.dsk")) + let draft = try await model.personalStore.inspect([source.deletingLastPathComponent()]) + let entry = try await model.personalStore.save(draft) + await model.load(from: fixture, catalogLoader: { _ in Self.catalog }) + let authority = CompanionLibraryAuthority(model: model), directory = model.personalDirectory(entry) + let working = directory.appendingPathComponent("Working"), member = working.appendingPathComponent("sub/GAME.dsk") + let original = try Data(contentsOf: fixture) + try FileManager.default.removeItem(at: member) + try FileManager.default.createSymbolicLink(at: member, withDestinationURL: fixture) + await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk")) + try FileManager.default.removeItem(at: working.appendingPathComponent("sub")) + try FileManager.default.createSymbolicLink(at: working.appendingPathComponent("sub"), withDestinationURL: source) + await assertFailure(authority, .init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "sub/GAME.dsk")) + try FileManager.default.moveItem(at: working, to: directory.appendingPathComponent("RetainedWorking")) + try FileManager.default.createSymbolicLink(at: working, withDestinationURL: directory.appendingPathComponent("RetainedWorking")) + await assertFailure(authority, .init(operation: .diskMembers, releaseID: entry.releaseID)) + XCTAssertEqual(try Data(contentsOf: fixture), original) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/sub/GAME.dsk")), original) + await model.shutdown() + } + + @MainActor + func testCompanionModelPlaysPersonalDiskThroughActualAuthority() async throws { + let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionClient-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let source = root.appendingPathComponent("PRIVATE.dsk"), original = try Data(contentsOf: fixture) + try original.write(to: source) + let draft = try await host.personalStore.inspect([source]) + let entry = try await host.personalStore.save(draft) + await host.load(from: fixture, catalogLoader: { _ in Self.catalog }) + let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/PRIVATE.dsk") + var workingBytes = original; workingBytes[0] ^= 1 + try workingBytes.write(to: working) + let service = AuthorityLibrary(authority: .init(model: host)) + var inserted: [URL] = [] + var insertedBytes: [Data] = [] + let client = SoftwareLibraryModel(companion: service) { url in + inserted.append(url) + insertedBytes.append(try Data(contentsOf: url)) + // Real DriveWire writes must affect only its separate handoff image. + try Data([0x42, 0x43]).write(to: url) + } + await client.load() + XCTAssertNil(client.error) + let release = try XCTUnwrap(client.catalog?.releases.first(where: { $0.id == entry.releaseID })) + XCTAssertTrue(release.isPersonal) + XCTAssertNotNil(client.state.installedReleases[entry.releaseID]) + client.play(release) + for _ in 0..<100 where client.installingReleaseID != nil { try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertNil(client.installingReleaseID, "The local companion operation must complete without downloading or launching the emulator.") + XCTAssertNil(client.installationErrors[entry.releaseID]); XCTAssertNil(client.launchError) + XCTAssertEqual(inserted.count, 1) + XCTAssertEqual(insertedBytes, [workingBytes]) + let copy = try XCTUnwrap(inserted.first) + XCTAssertNotEqual(copy, working) + XCTAssertTrue(copy.path.hasPrefix(host.state.directory.appendingPathComponent("CompanionDisks").path + "/")) + XCTAssertEqual(try Data(contentsOf: copy), Data([0x42, 0x43])) + XCTAssertEqual(try Data(contentsOf: working), workingBytes) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/PRIVATE.dsk")), original) + XCTAssertEqual(try Data(contentsOf: source), original) + let requests = await service.requests + XCTAssertEqual(requests.map(\.operation), [.snapshot, .install, .diskMembers, .exportDisk]) + XCTAssertTrue(requests.allSatisfy { $0.personalTitlesVersion == 1 }) + await client.shutdown(); await host.shutdown() + } + + @MainActor + func testSelectedPersonalCoverAndRemovalReachCompanionWithoutChangingDiskBytes() async throws { + let root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("CompanionCover-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + defer { try? FileManager.default.removeItem(at: root) } + let host = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let source = root.appendingPathComponent("GAME.dsk"), original = try Data(contentsOf: fixture) + try original.write(to: source) + let context = try XCTUnwrap(CGContext(data: nil, width: 24, height: 36, bitsPerComponent: 8, + bytesPerRow: 24 * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + context.setFillColor(CGColor(gray: 0.3, alpha: 1)); context.fill(CGRect(x: 0, y: 0, width: 24, height: 36)) + let imageBytes = NSMutableData() + let encoder = try XCTUnwrap(CGImageDestinationCreateWithData(imageBytes, UTType.png.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(encoder, try XCTUnwrap(context.makeImage()), nil) + XCTAssertTrue(CGImageDestinationFinalize(encoder)) + let authored = imageBytes as Data, imported = root.appendingPathComponent("Imported.png") + try authored.write(to: imported) + var draft = try await host.personalStore.inspect([source, imported]); draft.entry.category = "Games" + let entry = try await host.personalStore.save(draft, coverPNG: authored) + let directory = host.personalDirectory(entry), working = directory.appendingPathComponent("Working/GAME.dsk") + var saved = original; saved[0] ^= 1; try saved.write(to: working) + await host.load(from: fixture, catalogLoader: { _ in Self.catalog }) + let authority = CompanionLibraryAuthority(model: host), service = AuthorityLibrary(authority: authority) + let client = SoftwareLibraryModel(companion: service) { _ in XCTFail("Artwork browsing must not insert media.") } + await client.load() + let release = try XCTUnwrap(client.catalog?.releases.first { $0.id == entry.releaseID }) + let asset = try XCTUnwrap(release.assets.first { $0.kind == "cover" }) + XCTAssertEqual(release.assets.filter { $0.kind == "cover" }.count, 1) + XCTAssertEqual(asset.name, "Personal Cover Image") + XCTAssertTrue(asset.id.contains(":asset:PersonalCovers/")) + XCTAssertTrue(SoftwareLibraryArtworkCache.canDisplay(asset)) + let local = try XCTUnwrap(asset.thumbnailURL), retainedCover = try Data(contentsOf: local) + let thumbnail = try await service.libraryRequest(.init(operation: .thumbnail, assetID: asset.id)) + let decoded = try XCTUnwrap(SoftwareLibraryArtworkCache.image(from: XCTUnwrap(thumbnail.assetData))) + XCTAssertEqual(decoded.width, 24); XCTAssertEqual(decoded.height, 36) + // Even an otherwise selected local asset must retain its recorded hash. + var changed = retainedCover; changed[changed.count - 1] ^= 1; try changed.write(to: local) + await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id)) + try retainedCover.write(to: local) + let oldClient = try await service.libraryRequest(.init(operation: .snapshot, personalTitlesVersion: nil)) + XCTAssertFalse(oldClient.snapshot!.catalog.titles.contains { $0.id == entry.titleID }) + let beforeRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk")) + let beforeCopy = try XCTUnwrap(beforeRemoval.exportedDiskURL) + XCTAssertEqual(try Data(contentsOf: beforeCopy), saved) + host.query.scope = .personal; host.selection = entry.titleID + host.selectPersonalCover(.categoryIcon, for: entry) + for _ in 0..<100 where host.personalSaving { try await Task.sleep(nanoseconds: 20_000_000) } + XCTAssertFalse(host.personalSaving); XCTAssertNil(host.personalError) + let reopened = SoftwareLibraryModel(companion: service) { _ in XCTFail("Removing artwork must not insert media.") } + await reopened.load() + let withoutCover = try XCTUnwrap(reopened.catalog?.releases.first { $0.id == entry.releaseID }) + XCTAssertTrue(withoutCover.assets.filter { $0.thumbnailURL != nil }.isEmpty, + "Removal must suppress the imported image as well, leaving the category illustration.") + XCTAssertEqual(SoftwareLibraryCategoryStyle.symbol(for: LibraryBrowseQuery.type(of: withoutCover)), "gamecontroller") + XCTAssertEqual(withoutCover.packageSHA256, release.packageSHA256) + await assertFailure(authority, .init(operation: .thumbnail, assetID: asset.id)) + let afterRemoval = try await service.libraryRequest(.init(operation: .exportDisk, releaseID: entry.releaseID, memberPath: "GAME.dsk")) + let afterCopy = try XCTUnwrap(afterRemoval.exportedDiskURL) + XCTAssertNotEqual(beforeCopy, afterCopy) + XCTAssertEqual(try Data(contentsOf: afterCopy), saved) + XCTAssertEqual(try Data(contentsOf: beforeCopy), saved) + XCTAssertEqual(try Data(contentsOf: working), saved) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.dsk")), original) + XCTAssertEqual(try Data(contentsOf: source), original) + XCTAssertEqual(try Data(contentsOf: local), retainedCover) + XCTAssertEqual(try Data(contentsOf: imported), authored) + await client.shutdown(); await reopened.shutdown(); await host.shutdown() + } + + @MainActor + private func assertFailure(_ authority: CompanionLibraryAuthority, _ request: CompanionLibraryRequest, + file: StaticString = #filePath, line: UInt = #line) async { + do { _ = try await authority.handle(request); XCTFail("Expected refusal for \(request.operation)", file: file, line: line) } + catch { } + } + + private actor AuthorityLibrary: CompanionLibraryAccess { + let authority: CompanionLibraryAuthority + private(set) var requests: [CompanionLibraryRequest] = [] + init(authority: CompanionLibraryAuthority) { self.authority = authority } + func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse { + requests.append(request) + return try await authority.handle(request) + } + } + + private actor RecoveringLibrary: CompanionLibraryAccess { + let catalog: SoftwareLibraryCatalog + private var connected = false + init(catalog: SoftwareLibraryCatalog) { self.catalog = catalog } + func reconnect() { connected = true } + func libraryRequest(_ request: CompanionLibraryRequest) async throws -> CompanionLibraryResponse { + guard connected else { throw CompanionTransport.Failure.unavailable } + guard request.operation == .snapshot else { throw CompanionLibraryFailure(message: "Unexpected mutation in reconnect fixture.") } + return .init(snapshot: .init(catalog: catalog, favorites: [], preferredReleaseIDs: [:], installations: [])) + } + } + private actor FakeLibrary: CompanionLibraryAccess { let catalog: SoftwareLibraryCatalog var favorites = Set() diff --git a/platforms/macos/Tests/DebuggerMMUBridgeTests.swift b/platforms/macos/Tests/DebuggerMMUBridgeTests.swift index f8cad39..87d25b7 100644 --- a/platforms/macos/Tests/DebuggerMMUBridgeTests.swift +++ b/platforms/macos/Tests/DebuggerMMUBridgeTests.swift @@ -2,6 +2,64 @@ import XCTest final class DebuggerMMUBridgeTests: XCTestCase { + @MainActor func testOverlayBridgeQualifiesOwnerAndRequiresFreshResidencyForSourceStep() async { + for enhanced in [false, true] { + let controller = VCCMachineController() + _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } + _ = await command { controller.configureMachine(use6309: enhanced, ram: 1, overclock: 1, frameInterval: 1, fastForward: false, completion: $0) } + _ = await command { controller.loadDiagnostic(use6309: enhanced, completion: $0) } + // Initial authored code setup. Guest-driven replacement itself is + // covered by the core and disposable-worker loader fixtures. + let a = Data([0x12, 0x86, 0x11, 0x39]), b = Data([0x12, 0x86, 0x22, 0x39]) + _ = await command { controller.debuggerWriteMemory(address: 0x4000, data: a, completion: $0) } + _ = await command { controller.debuggerSetPC(0x4000, completion: $0) } + _ = await command { controller.debuggerSetBreakpoints([0x4567], completion: $0) } + let initial = await capture(controller, includePhysical: false) + let physical = Int(initial.mmu.effective[2].sourceAddress / 8192) + let modules: [[String: Any]] = [("a", a), ("b", b)].map { name, bytes in + ["id": name, "pages": [["logicalPage": 2, "physicalPage": physical]], + "addresses": [0x4000], "bytes": [bytes], "breakpoints": [], + "overlay_group": "stage", "overlay_owner": name] + } + let armed = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: modules, completion: $0) } + XCTAssertNil(armed.errorMessage); XCTAssertTrue(armed.debuggerDevelopmentAttached) + XCTAssertNotEqual(armed.debuggerResidencyFingerprint, 0) + var malformed = modules + malformed[0].removeValue(forKey: "overlay_owner") + let invalid = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: malformed, completion: $0) } + XCTAssertNotNil(invalid.errorMessage) + XCTAssertEqual(invalid.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint) + for key in ["overlay_group", "overlay_owner"] { + var definitions = modules; definitions[0][key] = "a\0truncated" + let rejectedDefinitions = definitions + let rejected = await command { controller.debuggerArmBankedDevelopmentBreakpoints([], modules: rejectedDefinitions, completion: $0) } + XCTAssertNotNil(rejected.errorMessage) + XCTAssertEqual(rejected.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint) + } + func step(_ fingerprint: UInt64) async -> VCCMachineSnapshot { + await command { + controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001,0x4000,0x4001], locations: [1,2,3,4], + bytes: [Data([0x12]),Data([0x86,0x11]),Data([0x12]),Data([0x86,0x22])], + moduleIdentifiers: ["a","a","b","b"], generation: armed.generation, + programRevision: armed.debuggerProgramRevision, mappingFingerprint: armed.debuggerMappingFingerprint, + residencyFingerprint: fingerprint, programCounter: 0x4000, completion: $0) + } + } + let stale = await step(armed.debuggerResidencyFingerprint &+ 1) + XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.cycles, armed.cycles) + let started = await step(armed.debuggerResidencyFingerprint) + XCTAssertNil(started.errorMessage) + var stopped = started + for _ in 0..<100 where stopped.state == .running { + try? await Task.sleep(for: .milliseconds(5)); stopped = await command(controller.snapshot) + } + XCTAssertEqual(stopped.state, .paused); XCTAssertEqual(stopped.programCounter, 0x4001) + XCTAssertEqual(stopped.debuggerResidencyFingerprint, armed.debuggerResidencyFingerprint) + let final = await capture(controller, includePhysical: false) + XCTAssertEqual(final.breakpoints.map(\.uint16Value), [0x4567]) + _ = await command(controller.shutdown) + } + } @MainActor func testBankedGuardBridgeFreezesModulesAndPreservesManualPoints() async { let controller = VCCMachineController() _ = await command { controller.setAudioEnabled(false, volume: 0, completion: $0) } @@ -41,7 +99,8 @@ final class DebuggerMMUBridgeTests: XCTestCase { controller.debuggerStepBankedSource(mode: 0, addresses: [0x4000,0x4001], locations: [1,2], bytes: [Data([0x12]),Data([0x20,0xfe])], moduleIdentifiers: ["resident","resident"], generation: armed.generation, programRevision: armed.debuggerProgramRevision, - mappingFingerprint: armed.debuggerMappingFingerprint &+ 1, programCounter: 0x4000, completion: $0) + mappingFingerprint: armed.debuggerMappingFingerprint &+ 1, + residencyFingerprint: armed.debuggerResidencyFingerprint, programCounter: 0x4000, completion: $0) } XCTAssertNotNil(stale.errorMessage); XCTAssertEqual(stale.state, .paused) let cleared = await command(controller.debuggerClearDevelopmentBreakpoints) diff --git a/platforms/macos/Tests/InputTests.swift b/platforms/macos/Tests/InputTests.swift index c4d2c6e..c529cb6 100644 --- a/platforms/macos/Tests/InputTests.swift +++ b/platforms/macos/Tests/InputTests.swift @@ -1,7 +1,155 @@ // SPDX-License-Identifier: GPL-3.0-or-later import XCTest +import AppKit final class InputTests: XCTestCase { + private func inputStore() throws -> InputSettingsStore { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent("InputSelection-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true) + addTeardownBlock { try? FileManager.default.removeItem(at: directory) } + return InputSettingsStore(url: directory.appendingPathComponent("input.json")) + } + + func testSoleControllerPolicyPreservesOtherSourcesAndRememberedAssignments() { + for source in JoystickSource.allCases { + var settings = InputSettings(); settings.right.source = source + settings.right.interface = .tandy; settings.right.rightStick = true + settings.right.fire1 = 4; settings.right.fire2 = 8; settings.right.deadZone = 0.3 + settings.left.source = .controller; settings.left.device = "disconnected-remembered" + XCTAssertEqual(settings.assigningSoleController([]), settings) + XCTAssertEqual(settings.assigningSoleController(["first", "second"]), settings) + let selected = settings.assigningSoleController(["sole"]) + var expected = settings + if source == .controller { expected.right.device = "sole" } + XCTAssertEqual(selected, expected) + var remembered = settings; remembered.right.device = "previous-controller" + XCTAssertEqual(remembered.assigningSoleController(["sole"]), remembered) + } + } + + @MainActor func testSelectingControllerWithSoleCachedDevicePersistsOnceAndReopens() throws { + _ = NSApplication.shared + let store = try inputStore() + var settings = InputSettings(); settings.right.source = .keyboard + settings.right.interface = .tandy; settings.right.rightStick = true + settings.right.fire1 = 4; settings.right.fire2 = 1; settings.right.deadZone = 0.25 + try store.save(settings) + let device = ControllerReading(id: "gc:authored:0", name: "Authored controller", rx: 1, ry: -1, buttons: 8) + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false) + hub.poll() + XCTAssertEqual(hub.epoch, 0) + hub.settings.right.source = .controller + settings.right.source = .controller; settings.right.device = device.id + XCTAssertEqual(hub.settings, settings) + XCTAssertEqual(hub.epoch, 1, "One effective settings edit must release and persist once") + XCTAssertEqual(try store.load(), settings) + XCTAssertFalse(try store.loadState().automaticRightController) + hub.poll() + XCTAssertEqual(hub.preview[0], JoystickSample(x: 16383, y: 0, buttons: 1)) + let stamp = Date(timeIntervalSince1970: 1234) + try FileManager.default.setAttributes([.modificationDate: stamp], ofItemAtPath: store.url.path) + for _ in 0..<8 { hub.poll() } + XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp) + let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [device] }, automaticallyPoll: false) + reopened.poll() + XCTAssertEqual(reopened.settings, settings); XCTAssertEqual(reopened.epoch, 0) + XCTAssertEqual(try FileManager.default.attributesOfItem(atPath: store.url.path)[.modificationDate] as? Date, stamp) + } + + @MainActor func testUnassignedControllerAdoptsLateDeviceButNeverStealsDisconnectedAssignment() throws { + _ = NSApplication.shared + let store = try inputStore() + var settings = InputSettings(); settings.right.source = .controller + try store.save(settings) + var observed: [ControllerReading] = [] + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false) + hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0) + observed = [ControllerReading(id: "hid:authored:one", name: "First"), ControllerReading(id: "gc:authored:two", name: "Second")] + hub.poll(); XCTAssertEqual(hub.settings.right.device, ""); XCTAssertEqual(hub.epoch, 0) + observed.removeLast(); hub.poll() + XCTAssertEqual(hub.settings.right.device, "hid:authored:one"); XCTAssertEqual(hub.epoch, 1) + observed = [ControllerReading(id: "gc:authored:two", name: "Other", x: 1, buttons: 3)] + hub.poll() + XCTAssertEqual(hub.settings.right.device, "hid:authored:one") + XCTAssertEqual(hub.preview[0], JoystickSample()); XCTAssertEqual(hub.epoch, 1) + XCTAssertEqual(try store.load(), hub.settings) + } + + @MainActor func testFreshMouseFallbackSurvivesStoreRecreationThenAdoptsSoleController() throws { + _ = NSApplication.shared + let immediateStore = try inputStore() + let immediate = InputHub(controller: VCCMachineController(), store: immediateStore, + controllerReadings: { [ControllerReading(id: "connected-at-launch", name: "Sole")] }, automaticallyPoll: false) + immediate.poll() + XCTAssertEqual(immediate.settings.right.source, .controller) + XCTAssertEqual(immediate.settings.right.device, "connected-at-launch") + XCTAssertEqual(immediate.settings.left.source, .none) + XCTAssertEqual(try immediateStore.load(), immediate.settings) + let store = try inputStore() + var observed: [ControllerReading] = [] + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false) + XCTAssertEqual(hub.settings, .freshDefaults) + hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse); XCTAssertEqual(hub.settings.left.source, .none) + observed = [ControllerReading(id: "one", name: "First"), ControllerReading(id: "two", name: "Second")] + hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse) + hub.settings.keyboard = .compact + XCTAssertTrue(try store.loadState().automaticRightController) + let reopened = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false) + observed.removeLast(); reopened.poll() + XCTAssertEqual(reopened.settings.right.source, .controller); XCTAssertEqual(reopened.settings.right.device, "one") + XCTAssertEqual(reopened.settings.keyboard, .compact); XCTAssertEqual(reopened.settings.left.source, .none) + XCTAssertFalse(try store.loadState().automaticRightController) + } + + @MainActor func testLegacyExplicitSourcesAndPersonalProfileOverrideFreshAutomaticDefault() throws { + _ = NSApplication.shared + let sole = ControllerReading(id: "one", name: "Sole") + for source in [JoystickSource.none, .keyboard, .mouse] { + let store = try inputStore() + var settings = InputSettings(); settings.right.source = source + // Exact previous-format document has no automatic-default marker. + try JSONEncoder().encode(settings).write(to: store.url) + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [sole] }, automaticallyPoll: false) + hub.poll(); XCTAssertEqual(hub.settings, settings); XCTAssertEqual(hub.epoch, 0) + } + let store = try inputStore() + var observed: [ControllerReading] = [] + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { observed }, automaticallyPoll: false) + hub.applyProfileSettings(.freshDefaults) + XCTAssertFalse(try store.loadState().automaticRightController, "An explicit profile's Mouse source is authoritative even when it matches the fresh fallback") + observed = [sole]; hub.poll(); XCTAssertEqual(hub.settings.right.source, .mouse) + hub.restoreDefaultSettings(); hub.poll() + XCTAssertEqual(hub.settings.right.source, .controller); XCTAssertEqual(hub.settings.right.device, sole.id) + XCTAssertEqual(hub.settings.left.source, .none) + hub.settings.right = PortSettings(source: .mouse) + hub.poll() + XCTAssertEqual(hub.settings.right.source, .mouse) + XCTAssertFalse(try store.loadState().automaticRightController, "An explicit right-port edit must end fresh automatic discovery") + } + @MainActor func testLibraryHintsPreserveUnchangedFreshRightPolicyAcrossReload() throws { + _ = NSApplication.shared + let store = try inputStore() + let hub = InputHub(controller: VCCMachineController(), store: store, controllerReadings: { [] }, automaticallyPoll: false) + var librarySettings = hub.settings + librarySettings.left.source = .keyboard + hub.applyLibrarySettings(librarySettings) + XCTAssertEqual(try store.load(), librarySettings) + XCTAssertTrue(try store.loadState().automaticRightController) + let reopened = InputHub(controller: VCCMachineController(), store: store, + controllerReadings: { [ControllerReading(id: "late", name: "Sole")] }, automaticallyPoll: false) + reopened.poll() + XCTAssertEqual(reopened.settings.right.source, .controller) + XCTAssertEqual(reopened.settings.right.device, "late") + XCTAssertEqual(reopened.settings.left, librarySettings.left) + XCTAssertFalse(try store.loadState().automaticRightController) + // A library action must not re-enable discovery after an explicit + // personal profile selected Mouse, even if all its values match. + reopened.applyProfileSettings(.freshDefaults) + reopened.applyLibrarySettings(.freshDefaults) + reopened.poll() + XCTAssertEqual(reopened.settings.right.source, .mouse) + XCTAssertFalse(try store.loadState().automaticRightController) + } func testKeyboardModesAndReservedNavigation() { var keyboard = CocoKeyboard() keyboard.mode = .coco @@ -194,7 +342,7 @@ final class InputTests: XCTestCase { let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) defer { try? FileManager.default.removeItem(at: directory) } let store = InputSettingsStore(url: directory.appendingPathComponent("input.json")) - XCTAssertEqual(try store.load(), InputSettings()) + XCTAssertEqual(try store.load(), .freshDefaults) var settings = InputSettings(); settings.keyboard = .compact settings.right.source = .controller; settings.right.device = "authored controller" settings.right.interface = .tandy; settings.left.source = .keyboard; settings.left.keys = .wasd diff --git a/platforms/macos/Tests/LibraryContinuityTests.swift b/platforms/macos/Tests/LibraryContinuityTests.swift new file mode 100644 index 0000000..e99aa2b --- /dev/null +++ b/platforms/macos/Tests/LibraryContinuityTests.swift @@ -0,0 +1,324 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import AppKit +import CryptoKit +import Foundation +import PDFKit +import WebKit +import XCTest +import SQLite3 + +@MainActor +final class LibraryContinuityTests: XCTestCase { + private var directory: URL! + override func setUpWithError() throws { + directory = FileManager.default.temporaryDirectory.appendingPathComponent("LibraryContinuity-" + UUID().uuidString) + try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: false) + } + override func tearDownWithError() throws { try FileManager.default.removeItem(at: directory) } + + func testBrowseReadingAndIndependentBookmarksRoundTripAcrossRelaunch() async throws { + let store = LibraryContinuityStore(directory: directory) + var browse = LibraryBrowseState() + browse.scope = "Games"; browse.query = "adventure"; browse.selectedID = "personal:one" + browse.filters = ["format":"disk", "sort":"name"]; browse.topVisibleID = "personal:two" + store.setBrowse(browse, for: "software-main") + let first = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "alpha", offset: 0.25) + let second = LibraryReadingPosition(documentID: "book-two", relativePath: "book-two/chapter.html", anchor: "beta", offset: 0.5) + let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Alpha", position: first)) + store.setReading(second, for: "manual-last") + store.renameBookmark(mark.id, label: "My reference") + await store.flush() + let restored = LibraryContinuityStore(directory: directory) + XCTAssertEqual(restored.browse(for: "software-main"), browse) + XCTAssertEqual(restored.reading(for: "manual-last"), second) + XCTAssertEqual(restored.bookmarks.first?.position, first) + XCTAssertEqual(restored.bookmarks.first?.displayName, "My reference") + } + + func testDuplicateBookmarkPreservesOriginalLabelAndPosition() async throws { + let store = LibraryContinuityStore(directory: directory) + let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/a.html", anchor: "section", offset: 0.2) + let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "Section", position: position)) + store.renameBookmark(mark.id, label: "Keep this") + var moved = position; moved.offset = 0.8 + let again = store.addBookmark(bookID: "book-one", bookTitle: "One", sectionTitle: "New heading", position: moved) + XCTAssertEqual(again?.id, mark.id) + XCTAssertEqual(store.bookmarks.count, 1) + XCTAssertEqual(store.bookmarks.first?.position.offset, 0.2) + XCTAssertEqual(store.bookmarks.first?.label, "Keep this") + store.removeBookmark(mark.id) + await store.flush() + XCTAssertTrue(LibraryContinuityStore(directory: directory).bookmarks.isEmpty) + } + + func testNewerOrUnreadableStateIsNeverOverwritten() async throws { + let file = directory.appendingPathComponent("LibraryContinuity.json") + for bytes in [Data("{\"version\":999,\"browse\":{},\"reading\":{},\"bookmarks\":[]}".utf8), Data("invalid json".utf8)] { + try bytes.write(to: file, options: .atomic) + let store = LibraryContinuityStore(directory: directory) + XCTAssertNotNil(store.saveError) + store.setBrowse(LibraryBrowseState(), for: "archive-main") + await store.flush() + XCTAssertEqual(try Data(contentsOf: file), bytes) + } + } + + func testInvalidPositionsCannotEscapeContentRootOrPersistNonfiniteValues() async throws { + let store = LibraryContinuityStore(directory: directory) + store.setReading(LibraryReadingPosition(documentID: "one", relativePath: "../private.html"), for: "bad-path") + store.setReading(LibraryReadingPosition(documentID: "one", offset: .nan), for: "bad-offset") + var browse = LibraryBrowseState(); browse.pageOffset = -1 + store.setBrowse(browse, for: "bad-browse") + await store.flush() + XCTAssertNil(store.reading(for: "bad-path")); XCTAssertNil(store.reading(for: "bad-offset")) + XCTAssertNil(store.browse(for: "bad-browse")) + } + + func testManualScrollBookmarkAndResumeUseStableSectionInSeparateReader() async throws { + _ = NSApplication.shared + let contentRoot = directory.appendingPathComponent("Manuals") + let book = contentRoot.appendingPathComponent("book-one") + try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true) + let page = book.appendingPathComponent("chapter.html") + try """ + One +

+

Chapter

Alpha

+

Beta

+ + """.write(to: page, atomically: true, encoding: .utf8) + try "Home".write(to: contentRoot.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) + let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + let reader = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: store) + reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) + reader.webView.loadFileURL(page, allowingReadAccessTo: contentRoot) + try await waitFor { reader.currentPosition?.relativePath == "book-one/chapter.html" } + _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();") + try await waitFor { reader.currentPosition?.anchor == "beta" } + reader.bookmarkCurrentLocation() + try await waitFor { store.bookmarks.count == 1 } + XCTAssertEqual(store.bookmarks.first?.sectionTitle, "Beta") + await store.flush() + let restoredStore = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + let reopened = ManualReader(content: ManualLibraryContent(root: contentRoot), continuity: restoredStore) + reopened.webView.frame = reader.webView.frame + reopened.resume() + try await waitFor { reopened.currentPosition?.anchor == "beta" } + XCTAssertGreaterThan(reopened.currentPosition?.offset ?? 0, 0) + XCTAssertEqual(reopened.currentBookTitle, "Book One") + XCTAssertEqual(restoredStore.bookmarks.count, 1) + } + + func testImmediateBookmarkSamplesFreshScrollAndIgnoresSupersedingNavigation() async throws { + _ = NSApplication.shared + let root = directory.appendingPathComponent("Manuals") + let book = root.appendingPathComponent("book-one") + try FileManager.default.createDirectory(at: book, withIntermediateDirectories: true) + let page = book.appendingPathComponent("chapter.html") + try """ + One +

Chapter

Alpha

+

Beta

+ + """.write(to: page, atomically: true, encoding: .utf8) + try "Home".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) + let store = LibraryContinuityStore(directory: directory.appendingPathComponent("State")) + let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) + reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) + reader.webView.loadFileURL(page, allowingReadAccessTo: root) + try await waitFor { reader.currentPosition != nil } + XCTAssertNotEqual(reader.currentPosition?.anchor, "beta") + // Deliberately do not call the checkpoint or wait for its one-second + // scroll timer before performing the user's bookmark action. + _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100)") + reader.bookmarkCurrentLocation() + try await waitFor { store.bookmarks.count == 1 } + XCTAssertEqual(store.bookmarks[0].position.anchor, "beta") + XCTAssertEqual(store.bookmarks[0].sectionTitle, "Beta") + XCTAssertGreaterThan(store.bookmarks[0].position.offset, 0) + + store.removeBookmark(store.bookmarks[0].id) + reader.bookmarkCurrentLocation() + reader.showHome() + try await waitFor { reader.currentPosition?.relativePath == "index.html" } + XCTAssertTrue(store.bookmarks.isEmpty, "A checkpoint from a superseded page must not create a bookmark") + } + + func testArchiveDeepLinkFindsExactDocumentOutsideFirstBrowseBatch() async throws { + let database = directory.appendingPathComponent("Archive.sqlite") + var handle: OpaquePointer? + XCTAssertEqual(sqlite3_open(database.path, &handle), SQLITE_OK) + defer { sqlite3_close(handle) } + var sql = """ + PRAGMA application_id=0x56434341; PRAGMA user_version=2; + CREATE TABLE document(id INTEGER PRIMARY KEY,sha256 TEXT,title TEXT,collection TEXT,format TEXT,source_url TEXT,page_count INTEGER,issue_year TEXT); + """ + for n in 0..<72 { + let digest = String(format: "%064x", n+1) + sql += "INSERT INTO document VALUES(\(n+1),'\(digest)','Title \(String(format: "%03d", n))','Books','text','https://colorcomputerarchive.com/repo/Documents/Books/\(n).txt',1,NULL);" + } + XCTAssertEqual(sqlite3_exec(handle, sql, nil, nil, nil), SQLITE_OK) + let catalog = ArchiveLibraryCatalog(url: database) + let digest = String(format: "%064x", 61) + let exact = try await catalog.document(id: digest) + XCTAssertEqual(exact?.title, "Title 060") + let offset = try await catalog.browseOffset(documentID: digest, collection: "Books", batchSize: 35) + XCTAssertEqual(offset, 35) + let rows = try await catalog.browse(collection: "Books", limit: 35, offset: offset ?? 0) + XCTAssertTrue(rows.contains { $0.id == digest }) + let malformed = try await catalog.document(id: "not-a-content-identity") + XCTAssertNil(malformed) + } + + func testTwoBookReadingPositionsAndBookmarksSurviveReaderAndStoreRecreation() async throws { + _ = NSApplication.shared + let root = try makeTwoBookManuals() + let state = directory.appendingPathComponent("State") + let store = LibraryContinuityStore(directory: state) + let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) + reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) + for book in ["book-one", "book-two"] { + reader.webView.loadFileURL(root.appendingPathComponent(book + "/chapter.html"), allowingReadAccessTo: root) + try await waitFor { reader.currentBookID == book } + _ = try await reader.webView.evaluateJavaScript("window.scrollTo(0,document.getElementById('beta').offsetTop+100);window.vccLibraryCheckpoint();") + try await waitFor { reader.currentPosition?.anchor == "beta" } + reader.bookmarkCurrentLocation() + try await waitFor { store.bookmarks.contains { $0.bookID == book } } + } + let originalBookmarks = store.bookmarks + func assertSavedBookmarks(_ actual: [ManualBookmark], file: StaticString = #filePath, line: UInt = #line) { + // Successful navigation may update location validation metadata; + // the user's saved identity, label and position must stay fixed. + XCTAssertEqual(actual.map(\.id), originalBookmarks.map(\.id), file: file, line: line) + XCTAssertEqual(actual.map(\.position), originalBookmarks.map(\.position), file: file, line: line) + XCTAssertEqual(actual.map(\.displayName), originalBookmarks.map(\.displayName), file: file, line: line) + } + let firstPosition = try XCTUnwrap(store.reading(for: "manual-book:book-one")) + let secondPosition = try XCTUnwrap(store.reading(for: "manual-book:book-two")) + XCTAssertNotEqual(firstPosition.relativePath, secondPosition.relativePath) + await store.flush() + + let recreatedStore = LibraryContinuityStore(directory: state) + let reopened = ManualReader(content: ManualLibraryContent(root: root), continuity: recreatedStore) + reopened.webView.frame = reader.webView.frame + reopened.resume() + try await waitFor { reopened.currentBookID == "book-two" && reopened.currentPosition?.anchor == "beta" } + XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-one"), firstPosition) + assertSavedBookmarks(recreatedStore.bookmarks) + + // An explicit bookmark in another book wins over the last-active book. + reopened.openBookmark(try XCTUnwrap(originalBookmarks.first { $0.bookID == "book-one" })) + try await waitFor { reopened.currentBookID == "book-one" && reopened.currentPosition?.anchor == "beta" } + _ = try await reopened.webView.evaluateJavaScript("window.scrollTo(0,0);window.vccLibraryCheckpoint();") + try await waitFor { reopened.currentPosition?.anchor == nil } + assertSavedBookmarks(recreatedStore.bookmarks) + XCTAssertEqual(recreatedStore.reading(for: "manual-book:book-two"), secondPosition) + reopened.showHome() + try await waitFor { reopened.currentPosition?.relativePath == "index.html" } + reopened.resume() + XCTAssertEqual(reopened.currentPosition?.relativePath, "index.html", "Explicit Library Home must not be replaced by automatic resume") + await recreatedStore.flush() + assertSavedBookmarks(LibraryContinuityStore(directory: state).bookmarks) + } + + func testUpdatedManualMissingSectionAndPagePreserveBookmarksWithoutOpeningOtherContent() async throws { + _ = NSApplication.shared + let root = try makeTwoBookManuals() + let state = directory.appendingPathComponent("State") + let store = LibraryContinuityStore(directory: state) + let position = LibraryReadingPosition(documentID: "book-one", relativePath: "book-one/chapter.html", anchor: "removed-section", offset: 0.7) + let mark = try XCTUnwrap(store.addBookmark(bookID: "book-one", bookTitle: "Book One", sectionTitle: "Removed section", position: position)) + store.renameBookmark(mark.id, label: "Keep my reference") + let reader = ManualReader(content: ManualLibraryContent(root: root), continuity: store) + reader.webView.frame = CGRect(x: 0, y: 0, width: 800, height: 600) + reader.openBookmark(mark) + try await waitFor { reader.error?.contains("Location changed") == true } + XCTAssertEqual(reader.webView.url?.lastPathComponent, "chapter.html") + let fallbackScroll = try await reader.webView.evaluateJavaScript("window.scrollY") as? Double + XCTAssertEqual(fallbackScroll, 0) + XCTAssertFalse(reader.bookmarkAvailable(try XCTUnwrap(store.bookmarks.first))) + await store.flush() + let preserved = try XCTUnwrap(LibraryContinuityStore(directory: state).bookmarks.first) + XCTAssertEqual(preserved.id, mark.id) + XCTAssertEqual(preserved.position, position) + XCTAssertEqual(preserved.displayName, "Keep my reference") + XCTAssertEqual(preserved.locationChanged, true) + + reader.showHome() + try await waitFor { reader.currentPosition?.relativePath == "index.html" } + try FileManager.default.removeItem(at: root.appendingPathComponent("book-one/chapter.html")) + reader.openBookmark(preserved) + XCTAssertTrue(reader.error?.contains("page is no longer") == true) + XCTAssertEqual(reader.currentPosition?.relativePath, "index.html") + XCTAssertEqual(store.bookmarks.first?.position, position) + XCTAssertEqual(store.bookmarks.count, 1) + } + + func testLegacyArchivePageMigratesToPersistentStateIndependentOfAssetCache() async throws { + let pdf = PDFDocument() + for color in [NSColor.white, .gray] { + let image = NSImage(size: NSSize(width: 240, height: 900), flipped: false) { rect in color.setFill(); rect.fill(); return true } + pdf.insert(try XCTUnwrap(PDFPage(image: image)), at: pdf.pageCount) + } + let bytes = try XCTUnwrap(pdf.dataRepresentation()) + let digest = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() + let key = "archive-library.page." + digest + let original = UserDefaults.standard.object(forKey: key) + defer { + if let original { UserDefaults.standard.set(original, forKey: key) } + else { UserDefaults.standard.removeObject(forKey: key) } + } + UserDefaults.standard.set(2, forKey: key) + let cached = directory.appendingPathComponent(digest + ".pdf") + try bytes.write(to: cached) + let state = directory.appendingPathComponent("State") + let store = LibraryContinuityStore(directory: state) + let reader = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: store) + defer { reader.reset() } + reader.view.frame = NSRect(x: 0, y: 0, width: 300, height: 300) + let item = ArchiveDocument(id: digest, title: "Migration fixture", collection: "Books", + sourceURL: URL(string: "https://colorcomputerarchive.com/repo/Documents/Books/Migration.pdf")!, memberPath: nil, + pageCount: 2, deliveryURL: URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Books/Migration.pdf")!, deliveryBytes: Int64(bytes.count)) + reader.open(item, page: reader.savedPage(for: digest), resumePosition: true) + try await waitFor { reader.progress == nil } + XCTAssertNil(reader.error) + XCTAssertEqual(reader.page, 2) + reader.reset() + await store.flush() + + // Clearing an asset cache or moving away from old preferences must not + // clear the user's newly migrated reading position. + try FileManager.default.removeItem(at: cached) + UserDefaults.standard.removeObject(forKey: key) + let recreated = LibraryContinuityStore(directory: state) + let reopened = ArchiveReaderModel(remembersPage: true, cache: ArchiveAssetCache(directory: directory), continuity: recreated) + defer { reopened.reset() } + XCTAssertEqual(reopened.savedPage(for: digest), 2) + XCTAssertEqual(recreated.reading(for: "archive:" + digest)?.documentID, digest) + XCTAssertFalse(FileManager.default.fileExists(atPath: cached.path)) + } + + private func makeTwoBookManuals() throws -> URL { + let root = directory.appendingPathComponent("Manuals") + for book in ["book-one", "book-two"] { + let folder = root.appendingPathComponent(book) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try """ + \(book) + +

Chapter

Alpha

+

Beta

+ """.write(to: folder.appendingPathComponent("chapter.html"), atomically: true, encoding: .utf8) + } + try "Library Home".write(to: root.appendingPathComponent("index.html"), atomically: true, encoding: .utf8) + return root + } + + private func waitFor(_ condition: () -> Bool) async throws { + let deadline = ContinuousClock.now + .seconds(8) + while !condition() { + guard ContinuousClock.now < deadline else { XCTFail("Reader did not reach its expected state"); throw CocoaError(.fileReadUnknown) } + try await Task.sleep(for: .milliseconds(25)) + } + } +} diff --git a/platforms/macos/Tests/MCPCallContextAccessTests.swift b/platforms/macos/Tests/MCPCallContextAccessTests.swift index cddedf4..dc775ae 100644 --- a/platforms/macos/Tests/MCPCallContextAccessTests.swift +++ b/platforms/macos/Tests/MCPCallContextAccessTests.swift @@ -156,11 +156,14 @@ final class MCPCallContextAccessTests: XCTestCase { do { try await host.exportCallContextRegression(model, at: grantFile, helperURL: worker, roms: roms) let grant = try readGrant(grantFile) - XCTAssertEqual(grant["toolset"] as? Int, 11) + XCTAssertEqual(grant["toolset"] as? Int, 12) + XCTAssertEqual(grant["playtestVideo"] as? Bool, true) XCTAssertEqual(grant["playtestCallContext"] as? Bool, true) let capabilities = try await result("get_capabilities", grant: grant) XCTAssertTrue((capabilities["tools"] as? [String])?.contains("get_call_context") == true) XCTAssertEqual(capabilities["call_context"] as? Bool, true) + XCTAssertEqual(capabilities["banked_debug_manifest_versions"] as? [Int], [1, 2]) + XCTAssertEqual(capabilities["verified_code_overlays"] as? Bool, true) XCTAssertTrue((capabilities["build_actions"] as? [String])?.contains("disk") == true) XCTAssertTrue((capabilities["configurations"] as? [String])?.contains("Debug") == true) let scope: [String: Any] = ["project_id": try XCTUnwrap(capabilities["project_id"] as? String), @@ -176,6 +179,12 @@ final class MCPCallContextAccessTests: XCTestCase { XCTAssertEqual(running["run_id"] as? String, run) let snapshot = try await result("get_debug_snapshot", ["run_id": run], grant: grant) let snapshotID = try XCTUnwrap(snapshot["snapshot_id"] as? String) + XCTAssertEqual(snapshot["residency_fingerprint"] as? String, "0", "Ordinary flat runs retain their existing identity") + let range = try XCTUnwrap((snapshot["memory_ranges"] as? [[String: Int]])?.first) + let memoryArguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID, + "address": try XCTUnwrap(range["address"]), "count": min(8, try XCTUnwrap(range["count"]))] + let frozenRead = try await result("read_debug_memory", memoryArguments, grant: grant) + XCTAssertFalse((frozenRead["bytes"] as? [Int] ?? []).isEmpty) let arguments: [String: Any] = ["run_id": run, "snapshot_id": snapshotID] let context = try await result("get_call_context", arguments, grant: grant) XCTAssertEqual(context["run_id"] as? String, run) @@ -203,6 +212,8 @@ final class MCPCallContextAccessTests: XCTestCase { let repeated = try await result("get_call_context", arguments, grant: grant) XCTAssertEqual(repeated as NSDictionary, context as NSDictionary, "Repeated context reads preserve clock, registers, mapping and snapshot identity.") + let memoryRead = try await result("read_debug_memory", memoryArguments, grant: grant) + XCTAssertEqual(memoryRead as NSDictionary, frozenRead as NSDictionary) } for invalid in [arguments.merging(["run_id": "ordinary-shared-run"]) { _, new in new }, arguments.merging(["snapshot_id": "stale-snapshot"]) { _, new in new }, @@ -213,11 +224,78 @@ final class MCPCallContextAccessTests: XCTestCase { _ = try await result("playtest_debug", ["run_id": run, "request_id": UUID().uuidString, "action": "step"], grant: grant) let staleAfterStep = try await request("get_call_context", arguments, grant: grant) XCTAssertNotNil(staleAfterStep["error"]) + let staleMemory = try await request("read_debug_memory", memoryArguments, grant: grant) + XCTAssertNotNil(staleMemory["error"]) let newer = try await result("get_debug_snapshot", ["run_id": run], grant: grant) let newerArguments: [String: Any] = ["run_id": run, "snapshot_id": try XCTUnwrap(newer["snapshot_id"] as? String)] - _ = try await build(scope, grant: grant) + let latestArtifact = try await build(scope, grant: grant) let staleAfterBuild = try await request("get_call_context", newerArguments, grant: grant) XCTAssertNotNil(staleAfterBuild["error"]) + // Exercise the real stdio public schema and authenticated app host, + // not a fixture host returning a manufactured MP4 response. + let helper = Bundle(for: Self.self).bundleURL.deletingLastPathComponent().appendingPathComponent("vcc-mcp") + let clientSource = resources.deletingLastPathComponent().appendingPathComponent("Tools/MCP/test-helper.py") + var selection = scope; selection["artifact_id"] = try XCTUnwrap(latestArtifact["artifact_id"] as? String) + let selectionJSON = String(decoding: try JSONSerialization.data(withJSONObject: selection), as: UTF8.self) + let movie = root.appendingPathComponent("PublicVideo.mp4") + let script = """ + import base64,hashlib,importlib.util,json,pathlib,sys,time,uuid + spec=importlib.util.spec_from_file_location('mcp_fixture',sys.argv[1]) + fixture=importlib.util.module_from_spec(spec);spec.loader.exec_module(fixture) + selection=json.loads(sys.argv[4]) + with fixture.Client(sys.argv[2],sys.argv[3]) as client: + client.handshake('2025-06-18') + def call(name,**args): + result=client.call(name,**args)['result'] + assert not result.get('isError'), result + return result['structuredContent'] + run=call('start_playtest',**selection,request_id=str(uuid.uuid4()))['run_id'] + scope={k:selection[k] for k in ('project_id','revision')} + deadline=time.monotonic()+60 + while True: + ready=call('get_run',**scope) + if ready['status']!='starting': + assert ready['status']=='ready', ready + break + assert time.monotonic() Data { + let id = try XCTUnwrap(metadata["clip_id"] as? String) + let size = try XCTUnwrap(metadata["byte_count"] as? Int) + XCTAssertGreaterThan(size, 0); XCTAssertLessThanOrEqual(size, 64 * 1024 * 1024) + var data = Data(), offset = 0 + while offset < size { + let arguments: [String: Any] = ["run_id": test.runID, "clip_id": id, "offset": offset, "limit": 4096] + let chunk = try await test.reply("read_playtest_video", arguments: arguments) + XCTAssertEqual(chunk["clip_id"] as? String, id) + XCTAssertEqual(chunk["offset"] as? Int, offset) + XCTAssertEqual(chunk["byte_count"] as? Int, size) + XCTAssertEqual(chunk["mime_type"] as? String, "video/mp4") + XCTAssertEqual(chunk["sha256"] as? String, metadata["sha256"] as? String) + let bytes = try XCTUnwrap((chunk["video_chunk_base64"] as? String).flatMap { Data(base64Encoded: $0) }) + XCTAssertFalse(bytes.isEmpty); XCTAssertLessThanOrEqual(bytes.count, 4096) + guard !bytes.isEmpty else { throw ProfileFailure.message("Empty video chunk before EOF") } + data.append(bytes); offset += bytes.count + XCTAssertEqual(chunk["next_offset"] as? Int, offset) + XCTAssertEqual(chunk["eof"] as? Bool, offset == size) + let retry = try await test.reply("read_playtest_video", arguments: arguments) + XCTAssertEqual(retry["video_chunk_base64"] as? String, chunk["video_chunk_base64"] as? String) + } + XCTAssertEqual(data.count, size); XCTAssertEqual(CMOCProject.sha256(data), metadata["sha256"] as? String) + let eof = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id, "offset": size]) + XCTAssertEqual(eof["eof"] as? Bool, true); XCTAssertEqual(eof["video_chunk_base64"] as? String, "") + return data + } + + private func decodedVideoAudio(_ url: URL) async throws -> (Float, Float, Int) { + let asset = AVURLAsset(url: url) + let tracks = try await asset.loadTracks(withMediaType: .audio) + let track = try XCTUnwrap(tracks.first) + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false]) + reader.add(output); XCTAssertTrue(reader.startReading()) + var minimum: Float = 1, maximum: Float = -1, count = 0 + while let sample = output.copyNextSampleBuffer() { + let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample)) + var data = Data(count: CMBlockBufferGetDataLength(buffer)) + XCTAssertEqual(data.withUnsafeMutableBytes { + CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) + }, noErr) + data.withUnsafeBytes { raw in + for value in raw.bindMemory(to: Float.self) { minimum = min(minimum, value); maximum = max(maximum, value); count += 1 } + } + } + XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(count, 0) + return (minimum, maximum, count) + } + + func testOwnedVideoRecordsActualFieldsAudioChoiceAndRetryIdentityOnBothProcessors() async throws { + let (helper, system, diskROM) = try inputs() + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOwnedVideo-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: folder) } + for cpu in ["6809", "6309"] { + let root = folder.appendingPathComponent(cpu) + let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), + bootCommands: "10 CLS 3:PRINT \"VIDEO\"\n20 SOUND 80,255:GOTO20\nRUN\n", + projectID: "video-fixture", revision: 1, artifactID: UUID().uuidString, cpu: cpu, + helperURL: helper, retentionDirectory: root) + do { + let before = try await test.capture() + for value: Any in [0, 3601, true, 1.5] { + await expectDiskFailure { + _ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid", "max_fields": value]) + } + } + for value: Any in [1, "yes"] { + await expectDiskFailure { + _ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "invalid-audio", "include_audio": value]) + } + } + await expectDiskFailure { _ = try await test.reply("start_playtest_video", arguments: ["run_id": "foreign", "request_id": "foreign"]) } + let afterInvalid = try await test.capture() + XCTAssertEqual(afterInvalid["field_clock"] as? Int, before["field_clock"] as? Int) + + for includeAudio in [true, false] { + let key = includeAudio ? "audio" : "silent" + let starting = try await test.capture() + let startArgs: [String: Any] = ["run_id": test.runID, "request_id": "begin-" + key, + "include_audio": includeAudio, "max_fields": 120] + let started = try await test.reply("start_playtest_video", arguments: startArgs) + XCTAssertEqual(started["field_clock"] as? Int, starting["field_clock"] as? Int, "Starting video must not execute the guest") + let startRetry = try await test.reply("start_playtest_video", arguments: startArgs) + XCTAssertEqual(startRetry as NSDictionary, started as NSDictionary) + await expectDiskFailure { + _ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-" + key, "include_audio": !includeAudio, "max_fields": 120]) + } + await expectDiskFailure { + _ = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart-" + key]) + } + let inputArgs: [String: Any] = ["run_id": test.runID, "request_id": "fields-" + key, + "steps": [["keys": ["space"], "fields": 30], ["keys": [], "fields": 30]]] + let input = try await test.reply("playtest_input", arguments: inputArgs) + assertProcessor(input, cpu: cpu) + let trace = try XCTUnwrap(input["input_trace"] as? [[String: Any]]) + XCTAssertEqual(trace.count, 2); XCTAssertEqual(trace[0]["fields_advanced"] as? Int, 30) + XCTAssertEqual((trace[0]["input"] as? [String: Any])?["neutral"] as? Bool, false) + XCTAssertEqual((trace[1]["input"] as? [String: Any])?["neutral"] as? Bool, true) + let inputRetry = try await test.reply("playtest_input", arguments: inputArgs) + XCTAssertEqual(inputRetry["field_clock"] as? Int, input["field_clock"] as? Int) + let stopArgs: [String: Any] = ["run_id": test.runID, "request_id": "end-" + key] + let stopped = try await test.reply("stop_playtest_video", arguments: stopArgs) + let stopRetry = try await test.reply("stop_playtest_video", arguments: stopArgs) + XCTAssertEqual(stopRetry as NSDictionary, stopped as NSDictionary) + XCTAssertEqual(stopped["field_clock"] as? Int, input["field_clock"] as? Int, "Stopping video must not execute the guest") + let video = try XCTUnwrap(stopped["video"] as? [String: Any]) + XCTAssertEqual(video["include_audio"] as? Bool, includeAudio) + XCTAssertEqual(video["fields_recorded"] as? Int, 60) + XCTAssertEqual(video["truncated"] as? Bool, false) + XCTAssertEqual((video["field_end"] as? Int ?? -1) - (video["field_start"] as? Int ?? -1), 60) + let movie = root.appendingPathComponent(key + ".mp4") + try await videoBytes(test, metadata: video).write(to: movie) + let asset = AVURLAsset(url: movie) + let duration = try await asset.load(.duration).seconds + XCTAssertEqual(duration, 1, accuracy: 0.05) + let tracks = try await asset.loadTracks(withMediaType: .video) + XCTAssertEqual(tracks.count, 1) + let dimensions = try await XCTUnwrap(tracks.first).load(.naturalSize) + XCTAssertEqual(dimensions, CGSize(width: 1280, height: 960)) + let generator = AVAssetImageGenerator(asset: asset) + let frame = try await generator.image(at: .zero).image + XCTAssertEqual(frame.width, 1280); XCTAssertEqual(frame.height, 960) + let samples = try await decodedVideoAudio(movie) + if includeAudio { XCTAssertGreaterThan(samples.1 - samples.0, 0.01, "A real guest SOUND program must reach the delivered MP4") } + else { XCTAssertLessThan(max(abs(samples.0), abs(samples.1)), 0.00001, "Silent video must exclude guest audio and all UI cues") } + if !includeAudio { + let id = try XCTUnwrap(video["clip_id"] as? String) + let retained = root.appendingPathComponent("Videos/\(test.runID)/\(id)/Clip.mp4") + try FileManager.default.removeItem(at: retained) + XCTAssertEqual(mkfifo(retained.path, 0o600), 0) + let began = ContinuousClock.now + await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": id]) } + XCTAssertLessThan(began.duration(to: .now), .seconds(2), "A replaced FIFO must not block the ownership lease before validation") + } + let clipID = try XCTUnwrap(video["clip_id"] as? String) + await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": clipID, "offset": -1]) } + await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": test.runID, "clip_id": UUID().uuidString]) } + await expectDiskFailure { _ = try await test.reply("read_playtest_video", arguments: ["run_id": "foreign", "clip_id": clipID]) } + } + let retained = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain"]) + XCTAssertEqual(retained["disk_retained"] as? Bool, true) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk()) + } catch { await test.invalidate().value; throw error } + await test.invalidate().value + } + } + + func testVideoFieldBoundAndRunStopRetainCompletedClipsWithoutMoreExecution() async throws { + let (helper, system, diskROM) = try inputs() + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCVideoBounds-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: disk(), + bootCommands: "10 CLS:PRINT \"BOUNDED VIDEO\"\n20 GOTO20\nRUN\n", projectID: "video-bound", revision: 1, + artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: root) + do { + _ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-limit", "max_fields": 2]) + let input = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cross-limit", "steps": [["keys": [], "fields": 5]]]) + let limited = try await test.reply("stop_playtest_video", arguments: ["run_id": test.runID, "request_id": "end-limit"]) + let video = try XCTUnwrap(limited["video"] as? [String: Any]) + XCTAssertEqual(video["fields_recorded"] as? Int, 2); XCTAssertEqual(video["truncated"] as? Bool, true) + XCTAssertEqual(video["reason"] as? String, "field_limit"); XCTAssertEqual(video["completed"] as? Bool, true) + XCTAssertEqual(limited["field_clock"] as? Int, input["field_clock"] as? Int) + _ = try await videoBytes(test, metadata: video) + _ = try await test.reply("start_playtest_video", arguments: ["run_id": test.runID, "request_id": "begin-cleanup", "include_audio": false]) + let last = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "cleanup-fields", "steps": [["keys": [], "fields": 3]]]) + let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "retain-with-video"]) + XCTAssertEqual(stopped["disk_retained"] as? Bool, true) + XCTAssertEqual(stopped["field_clock"] as? Int, last["field_clock"] as? Int) + let finalVideo = try XCTUnwrap(stopped["video"] as? [String: Any]) + XCTAssertEqual(finalVideo["fields_recorded"] as? Int, 3) + XCTAssertEqual(finalVideo["reason"] as? String, "run_stopped"); XCTAssertEqual(finalVideo["truncated"] as? Bool, false) + _ = try await videoBytes(test, metadata: finalVideo) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(test.retainedDiskURL)), disk()) + } catch { await test.invalidate().value; throw error } + await test.invalidate().value + } + func testPhysicalKeysCoverGameplayWithoutHostLayoutOrArbitraryText() { XCTAssertEqual(MCPPlaytest.chord("left"), UInt64(1) << 29) XCTAssertEqual(MCPPlaytest.chord("right"), UInt64(1) << 30) @@ -551,7 +768,11 @@ final class MCPPlaytestTests: XCTestCase { projectID: "request-limit-fixture", revision: 1, artifactID: UUID().uuidString, helperURL: helper, retentionDirectory: folder) defer { test.invalidate() } - for index in 0.. (disk: Data, modules: [[String: Any]], a: Data, b: Data) { + let a = Data([0x12, 0x86, 0x11, 0xb7, 0x50, 0x00, 0x7e, 0x11, 0x00]) + let b = mode == .complete + ? Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x7e, 0x12, 0x00]) + : Data([0x12, 0x86, 0x22, 0xb7, 0x50, 0x00, 0x20, 0xf8]) + let witnessA = Data([0x12, 0x86, 0xa1, 0x39]), witnessB = Data([0x12, 0x86, 0xb2, 0x39]) + func raw(_ code: Data, _ witness: Data) -> Data { + code + Data(repeating: 0x12, count: 0x20 - code.count) + witness + } + let rawA = raw(a, witnessA), rawB = raw(b, witnessB) + func loader(_ source: UInt16, count: Int, corruptWitness: Bool = false) -> Data { + // LDX #$4000; LDY #source; LDB #count; + // copy: LDA ,Y+; STA ,X+; DECB; BNE copy. + var code = Data([0x8e, 0x40, 0, 0x10, 0x8e, UInt8(source >> 8), UInt8(source & 255), + 0xc6, UInt8(count), 0xa6, 0xa0, 0xa7, 0x80, 0x5a, 0x26, 0xf9]) + if corruptWitness { code.append(contentsOf: [0x86, 0xc3, 0xb7, 0x40, 0x22]) } // Guest LDA/STA. + code.append(contentsOf: [0x7e, 0x40, 0]) + return code + } + let loadA = loader(0x2000, count: rawA.count) + let loadB = loader(0x2100, count: mode == .partial ? b.count : rawB.count, corruptWitness: mode == .corrupted) + let blocks: [(UInt16, Data)] = [(0x1000, loadA), (0x1100, loadB), (0x1200, loadA), (0x2000, rawA), (0x2100, rawB)] + var binary = Data() + for (address, bytes) in blocks { + binary.append(contentsOf: [0, UInt8(bytes.count >> 8), UInt8(bytes.count & 255), UInt8(address >> 8), UInt8(address & 255)]) + binary.append(bytes) + } + binary.append(contentsOf: [255, 0, 0, 0x10, 0]) + guard binary.count < 256 else { throw ProfileFailure.message("The authored overlay fixture must fit one DECB sector.") } + var image = disk() + image.replaceSubrange(0.. [String: Any] { + ["address": address, "bytes_base64": bytes.base64EncodedString()] + } + func piece(_ id: String, owner: String, address: Int, bytes: Data) -> [String: Any] { + ["id": id, "overlay_group": "stage-code", "overlay_owner": owner, + "pages": [["logical_page": 2, "physical_page": 58]], "guards": [guardBytes(address, bytes)]] + } + let modules = [ + piece("a-entry", owner: "A", address: 0x4000, bytes: a), + piece("a-witness", owner: "A", address: 0x4020, bytes: witnessA), + piece("b-entry", owner: "B", address: 0x4000, bytes: b), + piece("b-witness", owner: "B", address: 0x4020, bytes: witnessB), + ["id": "loader", "pages": [["logical_page": 0, "physical_page": 56]], + "guards": [guardBytes(0x1000, loadA), guardBytes(0x1100, loadB), guardBytes(0x1200, loadA)]] + ] + return (image, modules, a, b) + } + + func testPhysicalCodeOverlayWorkerFollowsActualGuestCopiesAndRetainsDiskOnBothProcessors() async throws { + let (helper, system, diskROM) = try inputs() + let fixture = try physicalOverlayFixture(.complete) + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlay-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + for cpu in ["6809", "6309"] { + let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk, + // Buffer disk operations in one BASIC command before SAVE runs, + // so subsequent pasted characters cannot arrive during disk I/O. + bootCommands: "10 PRINT 7\nSAVE\"MARKER\":LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-worker", + revision: 1, artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000, + stopModule: "a-entry", cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu)) + defer { test.invalidate() } + if test.startReceipt["state"] as? String != "paused" { + let screen = try await test.capture() + _ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "failed-start-cleanup"]) + XCTFail("Overlay guest did not reach A: \(screen["screen_text"] ?? "no screen text"); PC \(screen["pc"] ?? "unknown")") + return + } + XCTAssertEqual(test.startReceipt["ram_kb"] as? Int, 512) + assertProcessor(test.startReceipt, cpu: cpu) + XCTAssertNotEqual(test.startReceipt["disk_sha256"] as? String, CMOCProject.sha256(fixture.disk), "SAVE must actually modify the disposable guest disk") + func captured(_ expected: Data, witness: UInt8) async throws -> [String: Any] { + let capture = try await test.debugCapture() + assertProcessor(capture, cpu: cpu) + XCTAssertEqual(capture["pc"] as? Int, 0x4000) + XCTAssertEqual(capture["attached"] as? Bool, true) + XCTAssertEqual((capture["physical_pages"] as? [String: Int])?["2"], 58) + let memory = try XCTUnwrap((capture["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) }) + XCTAssertEqual(Data(memory[0x4000..<(0x4000 + expected.count)]), expected) + XCTAssertEqual(memory[0x4022], witness) + XCTAssertNotEqual(capture["residency_fingerprint"] as? String, "0") + return capture + } + let first = try await captured(fixture.a, witness: 0xa1) + let firstResidency = try XCTUnwrap(first["residency_fingerprint"] as? String) + func stop(_ module: String, request: String) async throws { + _ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": request, + "action": "stop_at", "address": 0x4000, "module_id": module, "selection": "function_entry:" + module]) + let receipt = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": request + "-advance", + "steps": [["keys": [], "fields": 2]]]) + XCTAssertEqual(receipt["state"] as? String, "paused") + } + // The entry opcode, logical address and physical page are identical. + // Asking for B must run past A and let the guest loader install B. + try await stop("b-entry", request: "owner-b") + let second = try await captured(fixture.b, witness: 0xb2) + XCTAssertNotEqual(second["residency_fingerprint"] as? String, firstResidency) + XCTAssertEqual(second["mapping_fingerprint"] as? String, first["mapping_fingerprint"] as? String) + XCTAssertEqual(second["program_revision"] as? Int, first["program_revision"] as? Int) + let secondMemory = try XCTUnwrap((second["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) }) + XCTAssertEqual(secondMemory[0x5000], 0x11, "A executed its own guest STA before loading B") + try await stop("a-entry", request: "owner-a-again") + let third = try await captured(fixture.a, witness: 0xa1) + XCTAssertEqual(third["residency_fingerprint"] as? String, firstResidency) + let thirdMemory = try XCTUnwrap((third["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) }) + XCTAssertEqual(thirdMemory[0x5000], 0x22, "B executed its own guest STA before restoring A") + let restarted = try await test.reply("restart_playtest", arguments: ["run_id": test.runID, "request_id": "restart"]) + XCTAssertEqual(restarted["boot"] as? Int, 2) + XCTAssertEqual(restarted["disk_sha256"] as? String, test.startReceipt["disk_sha256"] as? String) + XCTAssertEqual(restarted["disk_original_sha256"] as? String, CMOCProject.sha256(fixture.disk)) + _ = try await captured(fixture.a, witness: 0xa1) + let stopped = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"]) + XCTAssertEqual(stopped["disk_retained"] as? Bool, true) + let saved = try XCTUnwrap(test.retainedDiskURL) + XCTAssertEqual(CMOCProject.sha256(try Data(contentsOf: saved)), restarted["disk_sha256"] as? String) + } + } + + func testPhysicalCodeOverlayWorkerRejectsPartialAndCorruptedOwnerWitnessesOnBothProcessors() async throws { + let (helper, system, diskROM) = try inputs() + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCPhysicalOverlayPartial-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + for cpu in ["6809", "6309"] { + for (name, mode, witness) in [("partial", PhysicalOverlayLoad.partial, UInt8(0xa1)), ("corrupted", .corrupted, UInt8(0xc3))] { + let fixture = try physicalOverlayFixture(mode) + let test = try await MCPPlaytest.start(systemROM: system, diskROM: diskROM, disk: fixture.disk, + bootCommands: "LOADM\"PROBE\":EXEC\n", projectID: "physical-overlay-invalid-worker", revision: 1, + artifactID: UUID().uuidString, modules: fixture.modules, stopAt: 0x4000, stopModule: "a-entry", + cpu: cpu, helperURL: helper, retentionDirectory: root.appendingPathComponent(cpu + "-" + name)) + defer { test.invalidate() } + let valid = try await test.debugCapture() + XCTAssertEqual(valid["attached"] as? Bool, true) + _ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "want-b", + "action": "stop_at", "address": 0x4000, "module_id": "b-entry", "selection": "function_entry:b-entry"]) + let advanced = try await test.reply("playtest_input", arguments: ["run_id": test.runID, "request_id": "load-invalid", + "steps": [["keys": [], "fields": 2]]]) + XCTAssertEqual(advanced["state"] as? String, "running", "An invalid owner must not qualify B's stop") + _ = try await test.reply("playtest_debug", arguments: ["run_id": test.runID, "request_id": "pause", "action": "pause"]) + let invalid = try await test.debugCapture() + assertProcessor(invalid, cpu: cpu) + XCTAssertEqual(invalid["attached"] as? Bool, false) + XCTAssertEqual(invalid["mapping_fingerprint"] as? String, valid["mapping_fingerprint"] as? String) + XCTAssertNotEqual(invalid["residency_fingerprint"] as? String, valid["residency_fingerprint"] as? String) + let pc = try XCTUnwrap(invalid["pc"] as? Int) + XCTAssertTrue((0x4000..<0x4008).contains(pc), "Pause observes the actual guest loop, not a manufactured PC") + let memory = try XCTUnwrap((invalid["logical_memory"] as? String).flatMap { Data(base64Encoded: $0) }) + XCTAssertEqual(Data(memory[0x4000..<(0x4000 + fixture.b.count)]), fixture.b, "B's entry alone is insufficient proof") + XCTAssertEqual(memory[0x4022], witness, "The guest partial copy/corruption must remain visible in the full capture") + XCTAssertEqual(memory[0x5000], 0x22) + _ = try await test.reply("stop_playtest", arguments: ["run_id": test.runID, "request_id": "stop"]) + } + } + } + + func testPhysicalOverlayWireRejectsEmbeddedNULIdentityBeforeGuestExecution() async throws { + let products = Bundle(for: Self.self).bundleURL.deletingLastPathComponent() + let helper = ProcessInfo.processInfo.environment["VCC_TEST_PLAYTEST_HELPER"].map { URL(fileURLWithPath: $0) } + ?? products.appendingPathComponent("vcc-playtest") + try XCTSkipUnless(FileManager.default.isExecutableFile(atPath: helper.path), "Requires the built, isolated vcc-playtest helper.") + let fixture = try physicalOverlayFixture(.complete) + let root = FileManager.default.temporaryDirectory.appendingPathComponent("VCCOverlayWire-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + for field in ["overlay_group", "overlay_owner"] { + var modules = fixture.modules + modules[0][field] = "a\0alias" + do { + // These deliberately unusable ROM bytes must never execute. + // This is a wire validation check, not a firmware/CPU pass. + let run = try await MCPPlaytest.start(systemROM: Data(repeating: 0, count: 32768), + diskROM: Data(repeating: 0, count: 8192), disk: fixture.disk, bootCommands: "\n", + projectID: "overlay-wire-invalid", revision: 1, artifactID: UUID().uuidString, + modules: modules, stopAt: 0x4000, stopModule: "a-entry", cpu: "6809", helperURL: helper, + retentionDirectory: root.appendingPathComponent(field)) + await run.invalidate().value + XCTFail("An embedded NUL in \(field) crossed the worker boundary") + } catch { + XCTAssertTrue(error.localizedDescription.contains("invalid_overlay_identity"), error.localizedDescription) + } + } + } + func testFlatOwnedStopUsesVerifiedBytesAndActualRuntimeMapping() async throws { let (helper, system, diskROM) = try inputs() // Guest instructions assign42 to a global, then loop at a verified stop. diff --git a/platforms/macos/Tests/SoftwareLibraryBrowseTests.swift b/platforms/macos/Tests/SoftwareLibraryBrowseTests.swift index 5675b05..2fb14e4 100644 --- a/platforms/macos/Tests/SoftwareLibraryBrowseTests.swift +++ b/platforms/macos/Tests/SoftwareLibraryBrowseTests.swift @@ -93,6 +93,68 @@ final class SoftwareLibraryBrowseTests: XCTestCase { XCTAssertEqual(LibraryBrowseQuery.type(of: cartridge, related: [disk, music]), "Other", "Conflicting editions do not establish a type") XCTAssertEqual(LibraryBrowseQuery.type(of: release("demo", category: "Disks/Games/Sierra Games/Demos")), "Games") } + + func testUnifiedPersonalGamesAreFirstAndAvailableToLocalDiskCompanion() { + var entry = PersonalSoftwareEntry(id: UUID(), title: "Private Game", files: [ + .init(path: "PRIVATE.DSK", kind: "disk", byteSize: 4, sha256: String(repeating: "a", count: 64)) + ]) + entry.category = "Games" + let privateRelease = entry.release(in: directory) + let privateTitle = SoftwareLibraryTitle(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [privateRelease]) + let publicGame = title("public-game", name: "Public Game", [release("public-edition", category: "Disks/Games")]) + let titles = [privateTitle, publicGame] + XCTAssertEqual(LibraryBrowseQuery(scope: .all, softwareType: "Games").apply(to: titles, favorites: [entry.titleID], installed: [entry.releaseID]).map(\.id), [entry.titleID, publicGame.id]) + XCTAssertEqual(LibraryBrowseQuery(scope: .all, category: "Games").apply(to: [privateTitle], favorites: [], installed: []).count, 1) + for scope in [LibraryBrowseQuery.Scope.started, .showcase, .installed] { + XCTAssertTrue(LibraryBrowseQuery(scope: scope).apply(to: [privateTitle], favorites: [entry.titleID], installed: [entry.releaseID]).isEmpty) + } + XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID]) + XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: titles, favorites: [entry.titleID], installed: []).map(\.id), [entry.titleID]) + XCTAssertEqual(LibraryBrowseQuery(scope: .search, text: "Private Game").apply(to: titles, favorites: [], installed: []).map(\.id), [entry.titleID]) + let companion = SoftwareLibraryCatalog(titles: titles, metadata: [:]).companionDisksOnly + XCTAssertEqual(companion.titles.map(\.id), [privateTitle.id, publicGame.id], "The user's local companion can browse their own disks") + } + func testPersonalGroupIsAlphabeticalBeforeCatalogWithoutMergingSameNames() { + func personal(_ name: String, bytes: Int64) -> SoftwareLibraryTitle { + var entry = PersonalSoftwareEntry(id: UUID(), title: name, files: [.init(path: "GAME.dsk", kind: "disk", byteSize: bytes, sha256: String(repeating: "a", count: 64))]) + entry.category = "Games" + return .init(id: entry.titleID, name: name, identityStatus: "personal", releases: [entry.release(in: directory)]) + } + let privateA = personal("A Game", bytes: 10000), privateZ = personal("Z Game", bytes: 1) + let publicA = title("public-a", name: "A Game", [release("a", bytes: 10)]) + let publicB = title("public-b", name: "B Game", [release("b", bytes: 50)]) + for sort in LibraryBrowseQuery.Sort.allCases { + let rows = LibraryBrowseQuery(scope: .all, softwareType: "Games", sort: sort).apply(to: [publicA, privateZ, publicB, privateA], favorites: [], installed: []) + XCTAssertEqual(Array(rows.prefix(2)).map(\.id), [privateA.id, privateZ.id]) + XCTAssertTrue(rows[0].isPersonal); XCTAssertFalse(rows[2].isPersonal) + XCTAssertEqual(rows.count, 4, "Personal and catalog editions with the same name stay distinct") + XCTAssertEqual(Array(rows.suffix(2)).map(\.id), sort == .size ? [publicB.id, publicA.id] : [publicA.id, publicB.id]) + } + XCTAssertTrue(LibraryBrowseQuery(scope: .all, softwareType: "Music").apply(to: [privateA], favorites: [], installed: []).isEmpty) + } + + @MainActor + func testHeaderSearchEscapesEveryPriorScopeAndFacetsAndResumes() async throws { + let support = directory.appendingPathComponent("GlobalSearch") + let continuity = LibraryContinuityStore(directory: support) + let model = SoftwareLibraryModel(state: .init(directory: support), continuity: continuity) + model.restoreBrowseContext() + for scope in LibraryBrowseQuery.Scope.allCases where scope != .search { + model.query = .init(scope: scope, category: "Disks", softwareType: "Music", media: "cassette", evidence: "checked", sort: .modified) + model.setSearchText("Popstar") + XCTAssertEqual(model.query, .init(scope: .search, text: "Popstar", sort: .modified)) + } + model.query.media = "disk"; model.setSearchText("Popstar Game") + XCTAssertEqual(model.query.media, "disk", "Explicit filters within Search Results survive further typing") + model.saveBrowseContext(); await continuity.flush() + let resumed = SoftwareLibraryModel(state: .init(directory: support), continuity: LibraryContinuityStore(directory: support)) + await resumed.load(from: try database()); try await settle(resumed) + XCTAssertEqual(resumed.query.scope, .search); XCTAssertEqual(resumed.query.text, "Popstar Game") + XCTAssertEqual(resumed.query.media, "disk") + model.setSearchText("") + XCTAssertEqual(model.query.scope, .all); XCTAssertEqual(model.query.text, "") + await model.shutdown(); await resumed.shutdown() + } func testAdvancedFacetsMatchTheSameEditionAndKeepUnknownEvidenceHonest() { let disk = release("disk", environment: "os9", processor: "6309", hardware: ["speech-sound": "optional"], videoModes: ["SG-12"]) let tape = release("tape", media: "cassette", environment: "basic", processor: "either", hardware: ["joystick": "unspecified"], videoModes: ["6847T1"]) @@ -221,6 +283,87 @@ final class SoftwareLibraryBrowseTests: XCTestCase { await state.flush() } @MainActor + func testColdResumeRetainsSelectionWhileCatalogRecoveryIsDelayed() async throws { + let support = directory.appendingPathComponent("DelayedResume") + let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support) + let query = LibraryBrowseQuery(scope: .all) + let encoded = String(decoding: try JSONEncoder().encode(query), as: UTF8.self) + continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded, "layout": "Table"], selectedID: "other"), for: "software-main") + await continuity.flush() + let restored = LibraryContinuityStore(directory: support) + let model = SoftwareLibraryModel(state: state, continuity: restored), url = try database() + let loading = Task { await model.load(from: url, catalogLoader: { url in + try await Task.sleep(nanoseconds: 350_000_000) + return try await SoftwareLibraryCatalog.load(from: url) + }) } + for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) } + try await Task.sleep(nanoseconds: 180_000_000) // exceeds the empty-result filter debounce + XCTAssertTrue(model.loading) + XCTAssertEqual(model.selection, "other") + XCTAssertEqual(restored.browse(for: "software-main")?.selectedID, "other", "An empty interim result must not overwrite resume state") + await loading.value; try await settle(model) + XCTAssertEqual(model.selection, "other"); XCTAssertEqual(model.layout, "Table") + XCTAssertEqual(model.selectedRow?.name, "Other Game") + await model.shutdown() + } + @MainActor + func testFailedCatalogReadKeepsPublicResumePendingForRetry() async throws { + let support = directory.appendingPathComponent("FailedResume") + let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support) + let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self) + continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main") + let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database() + await model.load(from: url, catalogLoader: { _ in throw CocoaError(.fileReadNoPermission) }) + try await settle(model) + XCTAssertNotNil(model.error); XCTAssertNil(model.catalog) + XCTAssertEqual(model.selection, "other") + XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, "other") + await model.load(from: url); try await settle(model) + XCTAssertNil(model.error); XCTAssertEqual(model.selection, "other") + XCTAssertEqual(model.selectedRow?.name, "Other Game") + await model.shutdown() + } + @MainActor + func testPrivateScopeRemainsUsableWhenPublicCatalogCannotLoad() async throws { + let support = directory.appendingPathComponent("PrivateWithoutCatalog") + let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support) + let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .personal)), as: UTF8.self) + continuity.setBrowse(.init(scope: "personal", filters: ["browse-query": encoded], selectedID: "personal:missing"), for: "software-main") + let model = SoftwareLibraryModel(state: state, continuity: continuity) + let source = directory.appendingPathComponent("LOCAL.ccc"); try Data([0x12,0x39]).write(to: source) + let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft) + await model.load(from: directory.appendingPathComponent("Unavailable.sqlite"), catalogLoader: { _ in throw CocoaError(.fileReadNoSuchFile) }) + try await settle(model) + XCTAssertNil(model.catalog); XCTAssertNotNil(model.error) + XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selectedRow?.id, entry.titleID) + await model.shutdown() + } + @MainActor + func testPersonalSaveDuringColdCatalogLoadWinsOverResumedPublicScope() async throws { + let support = directory.appendingPathComponent("PersonalDuringLoad") + let state = SoftwareLibraryState(directory: support), continuity = LibraryContinuityStore(directory: support) + let encoded = String(decoding: try JSONEncoder().encode(LibraryBrowseQuery(scope: .all)), as: UTF8.self) + continuity.setBrowse(.init(scope: "all", filters: ["browse-query": encoded], selectedID: "other"), for: "software-main") + let model = SoftwareLibraryModel(state: state, continuity: continuity), url = try database() + let source = directory.appendingPathComponent("AUTHORED.ccc") + try Data([0x12,0x39]).write(to: source) + let draft = try await model.personalStore.inspect([source]), entry = try await model.personalStore.save(draft) + let loading = Task { await model.load(from: url, catalogLoader: { url in + try await Task.sleep(nanoseconds: 500_000_000) + return try await SoftwareLibraryCatalog.load(from: url) + }) } + for _ in 0..<100 where !model.loading { try await Task.sleep(nanoseconds: 1_000_000) } + try await Task.sleep(nanoseconds: 150_000_000) + model.editPersonal(entry); model.savePersonal(entry, allowDuplicate: false) + for _ in 0..<100 where model.personalSaving { try await Task.sleep(nanoseconds: 5_000_000) } + XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID) + await loading.value; try await settle(model) + XCTAssertEqual(model.query.scope, .personal); XCTAssertEqual(model.selection, entry.titleID) + XCTAssertEqual(model.selectedRow?.id, entry.titleID) + await model.shutdown() + XCTAssertEqual(continuity.browse(for: "software-main")?.selectedID, entry.titleID) + } + @MainActor func testRapidQueriesAndFavoriteChangesPublishLatestResults() async throws { let state = SoftwareLibraryState(directory: directory.appendingPathComponent("Personal")) let model = SoftwareLibraryModel(state: state) diff --git a/platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift b/platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift index a695a0f..216c247 100644 --- a/platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift +++ b/platforms/macos/Tests/SoftwareLibraryLaunchPlanTests.swift @@ -40,6 +40,20 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase { XCTAssertFalse(automatic(release(media: "hard-disk", profile: "hard-drive-basic", paths: [("hardDisk0", "GAME.vhd")], command: "DOS\r"))) XCTAssertFalse(automatic(release(paths: [("disk0", "GAME.vhd")], command: "DOS\r"))) } + func testUnconfiguredPersonalROMImportOffersRealCartridgeSetup() async throws { + let selected = root.appendingPathComponent("AUTHORED.ROM"), bytes = Data([0x12,0x39]) + try bytes.write(to: selected) + let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary")) + let draft = try await store.inspect([selected]), entry = try await store.save(draft) + XCTAssertFalse(entry.configured) + let imported = await store.directory(for: entry.id) + let plan = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: imported), receipt: entry.receipt(in: imported)) + XCTAssertEqual(plan.profile, .romCartridge) + XCTAssertEqual(plan.cartridgeURL?.lastPathComponent, "AUTHORED.ROM") + XCTAssertTrue(plan.commands.isEmpty) + XCTAssertEqual(try Data(contentsOf: selected), bytes) + try plan.validateMedia() + } func testCartridgeAutostartsWithoutTypingAndHonorsItsStartupSlot() throws { try file("GAME.ccc") let plan = try SoftwareLibraryLaunchPlan.prepare(release: release(media: "cartridge", profile: "rom-cartridge", paths: [("cartridge", "GAME.ccc")], extra: ["cartridge_slot": .number(2)]), receipt: receipt(["GAME.ccc"])) @@ -186,4 +200,53 @@ final class SoftwareLibraryLaunchPlanTests: XCTestCase { XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands(command), command) } } + + func testBasicProgramLoadThenRunUsesSeparateKeyboardLines() throws { + for sequence in ["LOAD \"POPSTAR\"\nRUN", "load \"POPSTAR\"\r\nrun", "LOAD\"POPSTAR\"\\rRUN\\r"] { + let commands = try XCTUnwrap(SoftwareLibraryLaunchPlan.decodeCommands(sequence)) + XCTAssertEqual(commands.count, 2) + XCTAssertEqual(commands[0].uppercased().replacingOccurrences(of: " ", with: ""), "LOAD\"POPSTAR\"") + XCTAssertEqual(commands[1].uppercased(), "RUN") + } + try file("POPSTAR.DSK") + let item = release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\"\nRUN", status: "manual-setup") + XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item)) + let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: receipt(["POPSTAR.DSK"])) + XCTAssertTrue(plan.automaticallyStarts) + XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"]) + XCTAssertEqual(plan.floppyURLs[0]?.lastPathComponent, "POPSTAR.DSK") + XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\":RUN"), "BASIC discards the rest of the LOAD command line") + XCTAssertEqual(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\""), ["LOAD \"POPSTAR\""]) + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release(paths: [("disk0", "POPSTAR.DSK")], command: "LOAD \"POPSTAR\""))) + XCTAssertNil(SoftwareLibraryLaunchPlan.decodeCommands("LOAD \"POPSTAR\"\nRUN\nDIR"), "No later commands may be typed into a started guest program") + } + @MainActor + func testReviewedPersonalDiskOffersPlayWithoutLoadingCommands() throws { + try file("GAME.DSK") + var entry = PersonalSoftwareEntry(id: UUID(), title: "Reviewed personal disk", files: [ + .init(path: "GAME.DSK", kind: "disk", byteSize: 3, sha256: sha, role: "disk0") + ]) + entry.configured = true + let item = entry.release(in: root) + XCTAssertTrue(SoftwareLibraryLaunchPlan.hasPlayAction(for: item)) + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: item)) + let plan = try SoftwareLibraryLaunchPlan.prepare(release: item, receipt: entry.receipt(in: root)) + XCTAssertTrue(plan.offersPlay); XCTAssertFalse(plan.automaticallyStarts) + XCTAssertTrue(plan.commands.isEmpty); XCTAssertNotNil(plan.floppyURLs[0]) + let model = SoftwareLibraryModel(state: .init(directory: root.appendingPathComponent("State"))) + XCTAssertEqual(model.launchLabel(item, installed: true), "Play…") + XCTAssertEqual(model.launchSymbol(item), "play.fill") + entry.command = "LOAD \"GAME\"" + let loadOnly = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root)) + XCTAssertTrue(loadOnly.offersPlay); XCTAssertFalse(loadOnly.automaticallyStarts) + XCTAssertEqual(loadOnly.commands, ["LOAD \"GAME\""]) + entry.command = "SYSTEM \"curl example.invalid\"" + let unsupported = try SoftwareLibraryLaunchPlan.prepare(release: entry.release(in: root), receipt: entry.receipt(in: root)) + XCTAssertTrue(unsupported.offersPlay); XCTAssertTrue(unsupported.commands.isEmpty) + entry.configured = false + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root))) + entry.configured = true; entry.files[0].role = "" + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: root))) + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: release(paths: [("disk0", "GAME.DSK")])), "Public catalog labels retain their existing behavior") + } } diff --git a/platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift b/platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift index 3e2965c..e607ee3 100644 --- a/platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift +++ b/platforms/macos/Tests/SoftwareLibraryMachineLaunchTests.swift @@ -36,21 +36,21 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase { profile.input.right.source = .controller; profile.input.right.device = "remembered-controller" return profile } - func plan(cartridge: Bool = true, command: String? = nil, keyboardControls: Bool = false, cartridgeDevice: String = "rom") throws -> SoftwareLibraryLaunchPlan { + func plan(cartridge: Bool = true, command: String? = nil, keyboardControls: Bool = false, cartridgeDevice: String = "rom", hardDrive: Bool = false) throws -> SoftwareLibraryLaunchPlan { let working = folder.appendingPathComponent(UUID().uuidString).appendingPathComponent("Working") try FileManager.default.createDirectory(at: working, withIntermediateDirectories: true) - let filename = cartridge ? "Fixture.ccc" : "Fixture.dsk" + let filename = hardDrive ? "Fixture.vhd" : cartridge ? "Fixture.ccc" : "Fixture.dsk" var bytes = Data(repeating: cartridge ? 0x12 : 0, count: cartridge ? 8192 : 161280) if cartridge { bytes[0] = 0x20; bytes[1] = 0xfe } try bytes.write(to: working.appendingPathComponent(filename)) let sha = SHA256.hash(data: bytes).map { String(format: "%02x", $0) }.joined() - var configuration: [String: LibraryJSON] = ["profile": .string(cartridge ? "rom-cartridge" : "disk-basic"), "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), "controller_slot": .number(4), "controls": .object(["right": .object(["suggested_input": .string("keyboard-joystick")])])] + var configuration: [String: LibraryJSON] = ["profile": .string(hardDrive ? "hard-drive-basic" : cartridge ? "rom-cartridge" : "disk-basic"), "processor": .string("6809"), "ram_kib": .number(2048), "video": .string("composite"), "controller_slot": .number(4), "controls": .object(["right": .object(["suggested_input": .string("keyboard-joystick")])])] if keyboardControls { configuration["controls"] = .object(["keyboard": .string("Arrow keys, Z, X and C")]) } if cartridge { configuration["launch_method"] = .string("cartridge-autostart"); configuration["cartridge_device"] = .string(cartridgeDevice) } let setup = SoftwareLibrarySetup(status: command == nil && !cartridge ? "manual-setup" : "inferred-ready", command: command, instructions: "Authored launch fixture", configuration: .object(configuration), - selectedMembers: .array([.object(["path": .string(filename), "target": .string(cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:])) - let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: cartridge ? "cartridge" : "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/" + filename)!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: Int64(bytes.count), languageStatus: "english", metadata: .object(["title": .string("Authored Launch")]), setup: setup, assets: [], downloadURLs: []) + selectedMembers: .array([.object(["path": .string(filename), "target": .string(hardDrive ? "hard0" : cartridge ? "cartridge" : "disk0")])]), reasons: [], validation: .object([:])) + let release = SoftwareLibraryRelease(id: "fixture", titleID: "fixture", name: "Fixture", category: cartridge ? "Cartridges" : "Disks/Games", mediaType: hardDrive ? "hard-disk" : cartridge ? "cartridge" : "disk", contentRole: "software", sourceURL: URL(string: "https://example.invalid/" + filename)!, modifiedAt: nil, modifiedPrecision: nil, modifiedTimezone: nil, packageSHA256: sha, byteSize: Int64(bytes.count), languageStatus: "english", metadata: .object(["title": .string("Authored Launch")]), setup: setup, assets: [], downloadURLs: []) let receipt = SoftwareLibraryInstallationReceipt(releaseID: release.id, packageSHA256: sha, installedAt: Date(), workingDirectory: working, relativeFiles: [filename]) return try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: receipt) } @@ -114,6 +114,56 @@ final class SoftwareLibraryMachineLaunchTests: XCTestCase { XCTAssertEqual(model.profileName, initial.name); XCTAssertTrue(after.disks[0].mounted) } } + @MainActor func testHardDriveLibraryRejectsUnrecognizedDiskROMWithoutChangingMachine() async throws { + let fixture = try Fixture(); defer { fixture.cleanup() } + try await withMachine(fixture) { model, controller, initial in + let before = await step(controller.snapshot) + do { + _ = try await model.prepareLibraryLaunch(fixture.plan(cartridge: false, hardDrive: true)) + XCTFail("An arbitrary Disk BASIC ROM cannot stand in for RGB-DOS") + } catch { + XCTAssertTrue(error.localizedDescription.contains("rgbdos.rom")) + } + let after = await step(controller.snapshot) + XCTAssertEqual(after.generation, before.generation) + XCTAssertEqual(after.state, .running) + XCTAssertEqual(model.diskAssignments.rom, initial.media.rom) + XCTAssertEqual(model.profileName, initial.name) + } + } + @MainActor func testHardDriveLibraryUsesSuppliedRGBDOSAndRecognizedCachedFallback() async throws { + let startup = try StartupTests.Fixture(); defer { startup.remove() } + let fixture = try Fixture(); defer { fixture.cleanup() } + let rgbdos = Data(repeating: 0x39, count: 8192) + try rgbdos.write(to: startup.kit.directory.appendingPathComponent("rgbdos.rom")) + let model = MachineModel(diskStore: startup.disks, displayDefaults: fixture.defaults, + inputStore: .init(url: fixture.folder.appendingPathComponent("Input.json")), startupStore: startup.startup) + do { + try await settle(model) + let initial = try fixture.initialProfile() + await model.loadProfile(initial); XCTAssertNil(model.profileError) + let plan = try fixture.plan(cartridge: false, hardDrive: true) + let prepared = try await model.prepareLibraryLaunch(plan) + let rom = try XCTUnwrap(prepared.profile.media.rom) + XCTAssertNotEqual(rom, initial.media.rom) + XCTAssertEqual(try Data(contentsOf: rom), rgbdos) + XCTAssertEqual(prepared.profile.media.hardDisks?.drives[0]?.url, plan.hardDiskURLs[0]) + XCTAssertEqual(prepared.profile.media.cartridges?.slots[4].kind, .floppy) + XCTAssertEqual(prepared.profile.media.cartridges?.slots[1].kind, .hardDisk) + + // Known starter firmware remains a valid fallback after bundle moves. + let loaded = await model.loadSystemProfile(.hardDriveBasic) + XCTAssertTrue(loaded) + XCTAssertEqual(model.usageProfile, .hardDriveBasic) + try FileManager.default.removeItem(at: startup.kit.directory.appendingPathComponent("rgbdos.rom")) + let cached = try await model.prepareLibraryLaunch(plan) + XCTAssertEqual(cached.profile.media.rom, rom) + XCTAssertEqual(try Data(contentsOf: XCTUnwrap(cached.profile.media.rom)), rgbdos) + } catch { + await withCheckedContinuation { done in model.shutdown { done.resume() } }; throw error + } + await withCheckedContinuation { done in model.shutdown { done.resume() } } + } @MainActor func testPreviewDoesNotChangeSessionAndStaleConfigurationCannotLaunch() async throws { let fixture = try Fixture(); defer { fixture.cleanup() } try await withMachine(fixture) { model, controller, _ in diff --git a/platforms/macos/Tests/SoftwareLibraryManualTests.swift b/platforms/macos/Tests/SoftwareLibraryManualTests.swift index 5b1a429..186325c 100644 --- a/platforms/macos/Tests/SoftwareLibraryManualTests.swift +++ b/platforms/macos/Tests/SoftwareLibraryManualTests.swift @@ -18,6 +18,25 @@ final class SoftwareLibraryManualTests: XCTestCase { asset.manualURL = URL(string: "https://vccplus.brianholman.com/dl/software/CoCoLibrary/Documents/Manuals/Games/Manual.pdf") return (asset, bytes) } + func testImportedUppercaseTextManualUsesTextReaderWithoutNetwork() async throws { + let root = FileManager.default.temporaryDirectory.appendingPathComponent("PersonalManual-" + UUID().uuidString) + defer { try? FileManager.default.removeItem(at: root) } + let source = root.appendingPathComponent("Selected") + try FileManager.default.createDirectory(at: source, withIntermediateDirectories: true) + let text = Data("Authored local loading instructions\n".utf8) + try text.write(to: source.appendingPathComponent("README.TXT")) + try Data([0x12,0x39]).write(to: source.appendingPathComponent("GAME.ccc")) + let store = PersonalSoftwareLibraryStore(root: root.appendingPathComponent("PersonalLibrary")) + let draft = try await store.inspect([source]), entry = try await store.save(draft) + let imported = await store.directory(for: entry.id) + let manual = try XCTUnwrap(entry.release(in: imported).primaryManualAsset) + let model = SoftwareLibraryManualModel(); model.open(manual, directory: root.appendingPathComponent("UnusedCache")) + for _ in 0..<100 where model.loading { try await Task.sleep(nanoseconds: 10_000_000) } + XCTAssertEqual(model.text, String(decoding: text, as: UTF8.self)) + XCTAssertNil(model.document); XCTAssertNil(model.error) + XCTAssertEqual(try Data(contentsOf: source.appendingPathComponent("README.TXT")), text) + model.cancel() + } func testPlainTextDecodingPreservesInstructionsAndRejectsBinaryData() throws { XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data("Z = start\r\nX = kick\u{1A}".utf8)), "Z = start\nX = kick") XCTAssertEqual(try SoftwareLibraryManualModel.decodeText(Data([0x63, 0x61, 0x66, 0xe9])), "café") diff --git a/platforms/macos/Tests/SoftwareLibraryPersonalTests.swift b/platforms/macos/Tests/SoftwareLibraryPersonalTests.swift new file mode 100644 index 0000000..fea4c48 --- /dev/null +++ b/platforms/macos/Tests/SoftwareLibraryPersonalTests.swift @@ -0,0 +1,380 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import XCTest +import CryptoKit +import ImageIO +import UniformTypeIdentifiers + +final class SoftwareLibraryPersonalTests: XCTestCase { + private var root: URL! + override func setUpWithError() throws { + root = FileManager.default.temporaryDirectory.resolvingSymlinksInPath().appendingPathComponent("PersonalLibraryTests-" + UUID().uuidString) + try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true) + } + override func tearDownWithError() throws { if let root { try? FileManager.default.removeItem(at: root) } } + private func service() -> PersonalSoftwareLibraryStore { .init(root: root.appendingPathComponent("PersonalLibrary")) } + private func cartridge(_ name: String = "GAME.ccc") throws -> URL { + let source = root.appendingPathComponent(name) + try Data([0x39,0x12,0x12,0x12]).write(to: source) + return source + } + private func png(width: Int = 96, height: Int = 128, gray: CGFloat = 0.25) throws -> Data { + let context = try XCTUnwrap(CGContext(data: nil, width: width, height: height, bitsPerComponent: 8, + bytesPerRow: width * 4, space: CGColorSpaceCreateDeviceRGB(), bitmapInfo: CGImageAlphaInfo.premultipliedLast.rawValue)) + context.setFillColor(CGColor(gray: gray, alpha: 1)) + context.fill(CGRect(x: 0, y: 0, width: width, height: height)) + let data = NSMutableData() + let destination = try XCTUnwrap(CGImageDestinationCreateWithData(data, UTType.png.identifier as CFString, 1, nil)) + CGImageDestinationAddImage(destination, try XCTUnwrap(context.makeImage()), nil) + XCTAssertTrue(CGImageDestinationFinalize(destination)) + return data as Data + } + func testSingleFloppyDefaultsToFD0WithoutEnablingAutomation() async throws { + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let source = root.appendingPathComponent("GAME.dsk") + let bytes = try Data(contentsOf: fixture); try bytes.write(to: source) + let readme = root.appendingPathComponent("README.txt"); try Data("Instructions".utf8).write(to: readme) + let store = service(), draft = try await store.inspect([source, readme]) + XCTAssertEqual(draft.entry.files.first(where: { $0.kind == "disk" })?.role, "disk0") + XCTAssertFalse(draft.entry.configured); XCTAssertTrue(draft.entry.command.isEmpty) + let entry = try await store.save(draft), directory = await store.directory(for: entry.id) + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasPlayAction(for: entry.release(in: directory))) + let recovered = try await store.entries() + XCTAssertEqual(recovered.first?.files.first(where: { $0.kind == "disk" })?.role, "disk0") + XCTAssertEqual(try Data(contentsOf: source), bytes) + } + func testMultipleFloppiesKeepExplicitRolesAndSavedChoicesAreNotReset() async throws { + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let first = root.appendingPathComponent("FIRST.dsk"), second = root.appendingPathComponent("SECOND.dsk") + let bytes = try Data(contentsOf: fixture); try bytes.write(to: first); try bytes.write(to: second) + let store = service(), multiple = try await store.inspect([first, second]) + XCTAssertTrue(multiple.entry.files.allSatisfy { $0.role.isEmpty }, "Do not infer a boot disk from filename order") + await store.cancel(multiple.id) + let single = try await store.inspect([first]); var entry = try await store.save(single) + entry.files[0].role = "disk2"; try await store.update(entry) + let saved = try await store.entries() + XCTAssertEqual(saved.first?.files[0].role, "disk2", "Defaulting applies to new imports, not saved user choices") + XCTAssertEqual(try Data(contentsOf: second), bytes) + } + func testImportPreservesOriginalsAndWorkingSavesAndNeverPublishes() async throws { + let source = try cartridge(), bytes = try Data(contentsOf: source), store = service() + let draft = try await store.inspect([source]) + XCTAssertEqual(draft.entry.profile, "rom-cartridge") + XCTAssertFalse(draft.entry.configured) + let entry = try await store.save(draft) + let directory = await store.directory(for: entry.id) + let working = directory.appendingPathComponent("Working/GAME.ccc") + XCTAssertEqual(try Data(contentsOf: working), bytes) + let saved = Data([0x10,0x20,0x30]); try saved.write(to: working) + XCTAssertEqual(try Data(contentsOf: source), bytes) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), bytes) + let restored = try await service().entries() + XCTAssertEqual(restored.map(\.id), [entry.id]) + XCTAssertEqual(try Data(contentsOf: working), saved) + let release = entry.release(in: directory) + XCTAssertTrue(release.isPersonal); XCTAssertFalse(release.isArchive) + XCTAssertTrue(release.downloadURLs.isEmpty) + XCTAssertTrue(release.sourceURL.isFileURL) + let catalog = SoftwareLibraryCatalog(titles: [.init(id: entry.titleID, name: entry.title, identityStatus: "personal", releases: [release])], metadata: [:]) + XCTAssertTrue(catalog.companionDisksOnly.titles.isEmpty) + XCTAssertEqual(LibraryBrowseQuery(scope: .all).apply(to: catalog.titles, favorites: [], installed: []).map(\.id), [entry.titleID]) + XCTAssertEqual(LibraryBrowseQuery(scope: .personal).apply(to: catalog.titles, favorites: [], installed: []).count,1) + XCTAssertEqual(LibraryBrowseQuery(scope: .favorites).apply(to: catalog.titles, favorites: [entry.titleID], installed: []).count,1) + } + func testDuplicateRequiresExplicitSeparateCopyAndHiddenEntryStaysHidden() async throws { + let source = try cartridge(), store = service() + let initial = try await store.inspect([source]) + let first = try await store.save(initial) + let duplicate = try await store.inspect([source]) + do { _ = try await store.save(duplicate); XCTFail("Expected duplicate review") } + catch PersonalSoftwareLibraryStore.Failure.duplicate(let id) { XCTAssertEqual(id, first.id) } + let second = try await store.save(duplicate, allowDuplicate: true) + XCTAssertNotEqual(first.id, second.id) + var removed = first; removed.hidden = true + try await store.update(removed) + let visible = try await service().entries() + XCTAssertEqual(visible.map(\.id), [second.id]) + let retained = await store.directory(for: first.id) + XCTAssertTrue(FileManager.default.fileExists(atPath: retained.appendingPathComponent("Working/GAME.ccc").path)) + } + func testPersonalCategoryDefaultsAndNormalizesWithoutReplacingWorkingFiles() async throws { + let source = try cartridge(), store = service() + var draft = try await store.inspect([source]) + XCTAssertEqual(draft.entry.category, "Other") + draft.entry.category = "A custom category" + var entry = try await store.save(draft) + XCTAssertEqual(entry.category, "Other") + let directory = await store.directory(for: entry.id) + let working = directory.appendingPathComponent("Working/GAME.ccc") + let bytes = Data([0x39, 0x20, 0x30]); try bytes.write(to: working) + entry.category = "Games"; try await store.update(entry) + var recovered = try await store.entries() + XCTAssertEqual(recovered.first?.category, "Games") + for category in PersonalSoftwareEntry.standardCategories { + entry.category = category + let release = entry.release(in: directory) + XCTAssertEqual(LibraryBrowseQuery.type(of: release), category, "Each dropdown choice must use its actual category illustration") + } + // Simulate a free-form category saved by the previous development UI. + entry.category = "An old custom category" + try JSONEncoder().encode(entry).write(to: directory.appendingPathComponent("Entry.json"), options: .atomic) + recovered = try await store.entries() + XCTAssertEqual(recovered.first?.category, "Other") + XCTAssertEqual(try Data(contentsOf: working), bytes) + XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12])) + } + func testSavedReviewedBasicCommandsOfferAutomaticLaunchWithoutTouchingMedia() async throws { + let fixture = URL(fileURLWithPath: #filePath).deletingLastPathComponent().appendingPathComponent("Fixtures/DiskEditor/DECB.dsk") + let source = root.appendingPathComponent("POPSTAR.DSK") + let bytes = try Data(contentsOf: fixture) + try bytes.write(to: source) + let store = service(), draft = try await store.inspect([source]) + var entry = try await store.save(draft) + entry.configured = true; entry.video = "rgb"; entry.ramKiB = 512 + entry.files[0].role = "disk0" + entry.command = "LOAD \"POPSTAR\"\nRUN" + try await store.update(entry) + let recovered = try await store.entries() + let saved = try XCTUnwrap(recovered.first) + let directory = await store.directory(for: saved.id) + let release = saved.release(in: directory) + XCTAssertTrue(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: release)) + let plan = try SoftwareLibraryLaunchPlan.prepare(release: release, receipt: saved.receipt(in: directory)) + XCTAssertTrue(plan.automaticallyStarts) + XCTAssertEqual(plan.commands, ["LOAD \"POPSTAR\"", "RUN"]) + XCTAssertEqual(plan.floppyURLs[0], directory.appendingPathComponent("Working/POPSTAR.DSK")) + XCTAssertEqual(plan.ramKiB, 512) + XCTAssertEqual(try Data(contentsOf: source), bytes) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/POPSTAR.DSK")), bytes) + var manual = saved; manual.configured = false + XCTAssertFalse(SoftwareLibraryLaunchPlan.hasAutomaticStartup(for: manual.release(in: directory))) + } + func testCancelAndSymlinkFailurePreserveSelectedFiles() async throws { + let source = try cartridge(), store = service() + let draft = try await store.inspect([source]) + await store.cancel(draft.id) + let entries = try await store.entries(); XCTAssertTrue(entries.isEmpty) + XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12])) + let folder = root.appendingPathComponent("Set") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try FileManager.default.createSymbolicLink(at: folder.appendingPathComponent("GAME.ccc"), withDestinationURL: source) + do { _ = try await store.inspect([folder]); XCTFail("Symbolic links must not be followed") } catch { } + XCTAssertEqual(try Data(contentsOf: source), Data([0x39,0x12,0x12,0x12])) + do { _ = try await store.inspect([root]); XCTFail("A source folder must not recursively include its own import destination.") } catch { } + } + func testMultiFileSetMetadataEditsAndInvalidRecipePreserveMedia() async throws { + let folder = root.appendingPathComponent("Owned Software") + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true) + try Data([0x39]).write(to: folder.appendingPathComponent("GAME.ccc")) + try Data("Private instructions".utf8).write(to: folder.appendingPathComponent("README.txt")) + let store = service(); let draft = try await store.inspect([folder]) + XCTAssertEqual(draft.entry.files.map(\.path), ["GAME.ccc", "README.txt"], "Selected-folder aliases must not become member prefixes.") + var entry = try await store.save(draft) + let directory = await store.directory(for: entry.id) + let original = try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")) + entry.title = "My purchased game"; entry.author = "Original author" + try await store.update(entry) + let recovered = try await service().entries() + XCTAssertEqual(recovered.first?.title, entry.title) + XCTAssertEqual(recovered.first?.files.count,2) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/README.txt")), Data("Private instructions".utf8)) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Files/GAME.ccc")), original) + entry.command = "hello\u{1B}" + do { try await store.update(entry); XCTFail("Control injection must fail") } catch { } + XCTAssertEqual(try Data(contentsOf: folder.appendingPathComponent("README.txt")), Data("Private instructions".utf8)) + let release = recovered[0].release(in: directory) + let manual = try XCTUnwrap(release.primaryManualAsset) + try SoftwareLibraryLocalAsset.validate(manual, url: manual.manualURL!, maximumBytes: 1024*1024) + try Data("changed".utf8).write(to: manual.manualURL!) + XCTAssertThrowsError(try SoftwareLibraryLocalAsset.validate(manual,url:manual.manualURL!,maximumBytes:1024*1024)) + } + func testZIPKeepsOriginalPackageAndCompleteWorkingTree() async throws { + let archive = root.appendingPathComponent("Authored Software.zip") + let bytes = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")! + try bytes.write(to: archive) + let store = service() + let owned = try await store.inspect([archive]) + let entry = try await store.save(owned) + let directory = await store.directory(for: entry.id) + XCTAssertEqual(entry.files.map(\.path), ["Game/GAME.ccc", "Game/README.txt"]) + XCTAssertEqual(try Data(contentsOf: archive),bytes) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Original/Package.zip")),bytes) + XCTAssertEqual(try Data(contentsOf: directory.appendingPathComponent("Working/Game/README.txt")),Data("Authored local instructions\n".utf8)) + } + func testReviewedZIPRejectsChangedValidBytesAndPreservesExistingLibrary() async throws { + let source = root.appendingPathComponent("Authored.zip") + let original = Data(base64Encoded: "UEsDBBQAAAAAAAAAIVyFZweNAQAAAAEAAAANAAAAR2FtZS9HQU1FLmNjYzlQSwMEFAAAAAAAAAAhXFokposcAAAAHAAAAA8AAABHYW1lL1JFQURNRS50eHRBdXRob3JlZCBsb2NhbCBpbnN0cnVjdGlvbnMKUEsBAhQDFAAAAAAAAAAhXIVnB40BAAAAAQAAAA0AAAAAAAAAAAAAAKSBAAAAAEdhbWUvR0FNRS5jY2NQSwECFAMUAAAAAAAAACFcWiSmixwAAAAcAAAADwAAAAAAAAAAAAAApIEsAAAAR2FtZS9SRUFETUUudHh0UEsFBgAAAAACAAIAeAAAAHUAAAAAAA==")! + try original.write(to: source) + let store = service(), reviewedHash = SHA256.hash(data: original).map { String(format: "%02x", $0) }.joined() + let draft = try await store.inspect([source]), entry = try await store.save(draft) + let retained = await store.directory(for: entry.id) + // Rename ZIP member directories in both local/central headers. Sizes and + // file CRCs remain valid: rejection must bind bytes, not just ZIP validity. + var changed = original, offset = 0 + while let range = changed.range(of: Data("Game/".utf8), in: offset.. *MCPBuildDiagnosticTools() { @"annotations":@{@"readOnlyHint":@YES,@"openWorldHint":@NO}}]; } +static NSArray *MCPPlaytestVideoTools() { + NSDictionary *identifier = @{ @"type":@"string", @"minLength":@1, @"maxLength":@64 }; + NSDictionary *(^tool)(NSString *, NSString *, NSDictionary *, NSArray *, BOOL) = + ^NSDictionary *(NSString *name, NSString *description, NSDictionary *fields, NSArray *required, BOOL readOnly) { + return @{ @"name":name, @"description":description, + @"inputSchema":@{ @"type":@"object", @"properties":fields, @"required":required, @"additionalProperties":@NO }, + @"annotations":@{ @"readOnlyHint":@(readOnly), @"openWorldHint":@NO } }; + }; + return @[ + tool(@"start_playtest_video", @"Start a bounded MP4 recording of an owned disposable playtest's actual CoCo picture and optional generated CoCo audio. Does not advance execution: use ordinary playtest_input afterward. No microphone, Mac windows, personal emulator audio or capture UI cues are recorded. Maximum 3600 emulated fields (60 seconds), 64 MiB per clip, four clips and 256 MiB retained per run. Reuse an identical request_id on retry. Recordings end at their field/size limit with explicit truncation status; stop and retrieve the completed clip before restarting.", + @{ @"run_id":identifier, @"request_id":identifier, @"include_audio":@{ @"type":@"boolean", @"default":@YES }, + @"max_fields":@{ @"type":@"integer", @"minimum":@1, @"maximum":@3600, @"default":@1800 } }, + @[@"run_id", @"request_id"], NO), + tool(@"stop_playtest_video", @"Finish the current owned playtest recording without advancing the guest. Returns completed MP4 identity, byte count, SHA-256, actual field interval and truncation status. Retrying the identical request_id returns the same receipt. Remains available when ordinary mutation requests are exhausted; working files are retained if finalization fails.", + @{ @"run_id":identifier, @"request_id":identifier }, @[@"run_id", @"request_id"], NO), + tool(@"read_playtest_video", @"Read a completed MP4 belonging to this owned playtest in bounded base64 chunks. Assemble the chunks in offset order and verify the complete byte_count and SHA-256 from the receipt. Accepts only a clip_id returned by this run, never a host file path. Does not advance or change the guest.", + @{ @"run_id":identifier, @"clip_id":identifier, + @"offset":@{ @"type":@"integer", @"minimum":@0, @"maximum":@67108864, @"default":@0 }, + @"limit":@{ @"type":@"integer", @"minimum":@1, @"maximum":@65536, @"default":@65536 } }, + @[@"run_id", @"clip_id"], YES) + ]; +} + static NSArray *MCPPlaytestAudioTools() { return @[@{@"name":@"capture_playtest_audio", @"description":@"Advance an owned disposable guest for 1 to 120 emulated fields and return its direct audio as PCM16 stereo WAV. Leaves the guest paused; verified stops can shorten the interval. Uses no microphone or personal emulator audio. Reuse request_id on retry to return the same clip without execution. Maximum 16 clips and 4 MiB retained WAV per run across boots; a maximum-clip allowance must remain before capture. Receipts include actual field interval, boot/run/artifact identity, sample count and SHA-256.", @"inputSchema":@{@"type":@"object", @"properties":@{ diff --git a/platforms/macos/Tools/MCP/main.mm b/platforms/macos/Tools/MCP/main.mm index acf64e0..139bd6b 100644 --- a/platforms/macos/Tools/MCP/main.mm +++ b/platforms/macos/Tools/MCP/main.mm @@ -114,7 +114,7 @@ NSDictionary *hostCall(NSDictionary *grant, bool loopback, NSString *tool, NSDic Descriptor peer(socket(address->sa_family, SOCK_STREAM, 0)); const bool playtestCall = [@[@"start_playtest", @"playtest_input", @"playtest_debug", @"capture_playtest", @"restart_playtest", @"stop_playtest", @"get_debug_snapshot", @"capture_playtest_graphics", - @"exchange_playtest_media"] containsObject:tool]; + @"exchange_playtest_media", @"start_playtest_video", @"stop_playtest_video"] containsObject:tool]; const auto deadline = Clock::now() + std::chrono::seconds(playtestCall ? 55 : 5); if (peer.fd < 0 || fcntl(peer.fd, F_SETFL, O_NONBLOCK) < 0) return @{@"error":@"host_unavailable"}; if (connect(peer.fd, address, address->sa_len) != 0) { @@ -381,6 +381,23 @@ NSDictionary *handle(id message, NSDictionary *grant, bool loopback, NSArray *to } NSMutableDictionary *data = [reply[@"result"] mutableCopy]; NSMutableArray *content = [NSMutableArray array]; + if ([name isEqual:@"read_playtest_video"]) { + NSString *encoded = data[@"video_chunk_base64"], *hash = data[@"sha256"]; + if (!string(encoded) || encoded.length > 87384 || !string(hash) || hash.length != 64 || + [hash rangeOfCharacterFromSet:[[NSCharacterSet characterSetWithCharactersInString:@"0123456789abcdef"] invertedSet]].location != NSNotFound || + ![data[@"mime_type"] isEqual:@"video/mp4"] || ![data[@"clip_id"] isEqual:args[@"clip_id"]] || + !integer(data[@"offset"]) || !integer(data[@"next_offset"]) || !integer(data[@"byte_count"]) || + ![data[@"eof"] isKindOfClass:NSNumber.class] || CFGetTypeID((__bridge CFTypeRef)data[@"eof"]) != CFBooleanGetTypeID()) + return toolError(rid, @"invalid_playtest_video"); + NSData *chunk = [[NSData alloc] initWithBase64EncodedString:encoded options:0]; + const long long offset = [data[@"offset"] longLongValue], next = [data[@"next_offset"] longLongValue], total = [data[@"byte_count"] longLongValue]; + const long long requestedOffset = args[@"offset"] ? [args[@"offset"] longLongValue] : 0; + const NSUInteger limit = args[@"limit"] ? [args[@"limit"] unsignedIntegerValue] : 65536; + if (!chunk || chunk.length > limit || chunk.length > 65536 || offset != requestedOffset || offset < 0 || + total < 1 || total > 67108864 || offset > total || next != offset + (long long)chunk.length || next > total || + [data[@"eof"] boolValue] != (next == total) || (!chunk.length && next < total)) + return toolError(rid, @"invalid_playtest_video"); + } if ([name isEqual:@"capture_playtest_audio"]) { NSString *encoded = data[@"audio_wav_base64"]; if (!string(encoded) || !object(data[@"audio"])) return toolError(rid, @"invalid_playtest_audio"); @@ -492,6 +509,10 @@ int main(int argc, char **argv) { if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 7 && [grant[@"playtest"] isEqual:@YES] && [grant[@"playtestAudio"] isEqual:@YES]) tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestAudioTools()]; + if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 12 && + [grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() && + [grant[@"playtestVideo"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtestVideo"]) == CFBooleanGetTypeID()) + tools = [tools arrayByAddingObjectsFromArray:MCPPlaytestVideoTools()]; if ([grant[@"kind"] isEqual:@"cmoc"] && toolset >= 10 && [grant[@"playtest"] isEqual:@YES] && CFGetTypeID((__bridge CFTypeRef)grant[@"playtest"]) == CFBooleanGetTypeID() && [grant[@"playtestCallContext"] isEqual:@YES] && diff --git a/platforms/macos/Tools/MCP/test-helper.py b/platforms/macos/Tools/MCP/test-helper.py index 4376159..ec1a0c2 100644 --- a/platforms/macos/Tools/MCP/test-helper.py +++ b/platforms/macos/Tools/MCP/test-helper.py @@ -93,6 +93,8 @@ def check(helper): result = {"result": active["playtest_graphics"]} if request["tool"] == "capture_playtest_audio" and "playtest_audio" in active: result = {"result": active["playtest_audio"]} + if request["tool"] in ("start_playtest_video", "stop_playtest_video", "read_playtest_video") and "playtest_video" in active: + result = {"result": active["playtest_video"]} if request["tool"] == "get_build_log" and "build_log" in active: result = {"result": active["build_log"]} if request["tool"] == "get_debug_snapshot" and "debug_snapshot" in active: @@ -788,6 +790,56 @@ def check(helper): assert refused["isError"] and not any(x["type"] == "audio" for x in refused["content"]) del active["playtest_audio"] + video_tools = {"start_playtest_video", "stop_playtest_video", "read_playtest_video"} + for kind, toolset, play, video in (("cmoc", 11, True, True), ("assembly", 12, True, True), + ("cmoc", 12, False, True), ("cmoc", 12, 1, True), + ("cmoc", 12, True, False), ("cmoc", 12, True, 1), + ("cmoc", 12, True, "yes"), ("cmoc", 12, True, True)): + write_grant(kind=kind, toolset=toolset, playtest=play, playtestVideo=video, token=active["token"]) + with Client(helper, grant_file) as c: + c.handshake("2025-11-25") + catalog = {t["name"]: t for t in c.request("tools/list")["result"]["tools"]} + enabled = kind == "cmoc" and toolset >= 12 and play is True and video is True + assert video_tools.intersection(catalog) == (video_tools if enabled else set()) + if not enabled: + continue + assert catalog["start_playtest_video"]["annotations"]["readOnlyHint"] is False + assert catalog["stop_playtest_video"]["annotations"]["readOnlyHint"] is False + assert catalog["read_playtest_video"]["annotations"]["readOnlyHint"] is True + for tool in video_tools: + assert catalog[tool]["inputSchema"]["additionalProperties"] is False + active["playtest_video"] = {"run_id":"owned", "video_recording":{"status":"recording"}} + for args in ({"run_id":"owned", "request_id":"begin"}, + {"run_id":"owned", "request_id":"begin", "include_audio":False, "max_fields":3600}): + assert c.call("start_playtest_video", **args)["result"]["structuredContent"] == active["playtest_video"] + assert c.call("stop_playtest_video", run_id="owned", request_id="end")["result"]["structuredContent"] == active["playtest_video"] + count = len(active["requests"]) + for update in ({"max_fields":0}, {"max_fields":3601}, {"max_fields":True}, {"max_fields":1.5}, + {"include_audio":1}, {"include_audio":"yes"}, {"path":"/tmp/private"}): + args = {"run_id":"owned", "request_id":"bad", **update} + assert c.call("start_playtest_video", **args)["result"]["isError"], update + assert c.call("stop_playtest_video",run_id="owned",request_id="bad",path="/tmp/private")["result"]["isError"] + for update in ({"offset":-1}, {"offset":True}, {"offset":67108865}, {"limit":0}, + {"limit":65537}, {"limit":True}, {"path":"/tmp/private"}): + assert c.call("read_playtest_video",run_id="owned",clip_id="clip",**update)["result"]["isError"], update + assert count == len(active["requests"]), "Invalid video requests must never reach the host" + payload = b"\x00\x00\x00\x18ftypmp42" + bytes(range(256)) * 255 + chunk = dict(run_id="owned", clip_id="clip", video_chunk_base64=base64.b64encode(payload).decode(), + offset=0,next_offset=len(payload),byte_count=len(payload),eof=True, + sha256=hashlib.sha256(payload).hexdigest(),mime_type="video/mp4") + active["playtest_video"] = chunk + result = c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"] + assert result["structuredContent"] == chunk + assert json.loads(result["content"][0]["text"]) == chunk + for update in ({"video_chunk_base64":"!"}, {"next_offset":len(payload)+1}, {"byte_count":67108865}, + {"offset":1}, {"eof":False}, {"sha256":"x"*64}, {"clip_id":"foreign"}, + {"mime_type":"audio/wav"}, {"video_chunk_base64":"", "next_offset":0}): + active["playtest_video"] = {**chunk, **update} + assert c.call("read_playtest_video",run_id="owned",clip_id="clip")["result"]["isError"], update + active["playtest_video"] = {**chunk, "video_chunk_base64":"", "offset":len(payload), "next_offset":len(payload)} + assert c.call("read_playtest_video",run_id="owned",clip_id="clip",offset=len(payload))["result"]["structuredContent"]["eof"] is True + del active["playtest_video"] + write_grant(version=2, kind="archive", token=active["token"], canPropose=True, toolset=3) with Client(helper, grant_file) as c: c.handshake("2025-11-25") diff --git a/platforms/macos/Tools/Playtest/VideoWriter.swift b/platforms/macos/Tools/Playtest/VideoWriter.swift new file mode 100644 index 0000000..95ae903 --- /dev/null +++ b/platforms/macos/Tools/Playtest/VideoWriter.swift @@ -0,0 +1,60 @@ +// SPDX-License-Identifier: GPL-3.0-or-later +import Foundation +import CoreGraphics + +/// Only linked into the disposable helper. These waits never run in the Mac +/// application's main actor or machine controller. The codec implementation is +/// exactly the same bounded writer used by the native capture controls. +@objc(VCCPlaytestVideoWriter) +final class VCCPlaytestVideoWriter: NSObject { + private let encoder: CoCoVideoEncoder + private let directory: URL + private let includeAudio: Bool + private var sampleOffset: Int64 = 0 + + @objc init(directory: URL, includeAudio: Bool) throws { + self.directory = directory; self.includeAudio = includeAudio + encoder = try CoCoVideoEncoder(workingURL: directory.appendingPathComponent("Working.mov")) + super.init() + } + + private final class Reply: @unchecked Sendable { + let semaphore = DispatchSemaphore(value: 0) + private let lock = NSLock() + private var result: Result? + func complete(_ result: Result) { lock.lock(); self.result = result; lock.unlock(); semaphore.signal() } + func wait() throws -> T { + guard semaphore.wait(timeout: .now() + 20) == .success else { throw CoCoRecordingError.message("The disposable video writer timed out.") } + lock.lock(); defer { lock.unlock() } + guard let result else { throw CoCoRecordingError.message("The disposable video writer returned no result.") } + return try result.get() + } + } + + @objc func appendPixels(_ pixels: Data, area: CGRect, samples: Data) throws { + guard samples.count % 8 == 0, samples.count <= 16_384 * 8 else { throw CoCoRecordingError.message("Invalid disposable video audio interval.") } + let frame = CoCoVideoFrame(pixels: pixels, area: area, + audio: includeAudio ? samples : Data(count: samples.count), sampleOffset: sampleOffset) + encoder.append([frame]); sampleOffset += Int64(samples.count / 8) + let reply = Reply() + encoder.whenDrained { reply.complete($0) } + try reply.wait() + } + + @objc func finish() throws -> URL { + let reply = Reply() + encoder.finish { reply.complete($0) } + let working = try reply.wait() + let output = directory.appendingPathComponent("Clip.mp4") + let exported = Reply() + Task.detached { + do { try await CoCoVideoEncoder.exportMP4(from: working, to: output); exported.complete(.success(output)) } + catch { exported.complete(.failure(error)) } + } + let result = try exported.wait() + // Conversion verifies playable tracks/duration before removing only our + // known working file. Failures retain that file for explicit recovery. + try FileManager.default.removeItem(at: working) + return result + } +} diff --git a/platforms/macos/Tools/Playtest/main.mm b/platforms/macos/Tools/Playtest/main.mm index 75eee90..e3b49d6 100644 --- a/platforms/macos/Tools/Playtest/main.mm +++ b/platforms/macos/Tools/Playtest/main.mm @@ -11,9 +11,16 @@ #include #include #include +#include #include #include #include +// The class is implemented in Swift and shares CoCoVideoEncoder with the app. +@interface VCCPlaytestVideoWriter : NSObject +- (instancetype)initWithDirectory:(NSURL *)directory includeAudio:(BOOL)includeAudio error:(NSError **)error; +- (BOOL)appendPixels:(NSData *)pixels area:(CGRect)area samples:(NSData *)samples error:(NSError **)error; +- (NSURL *)finishAndReturnError:(NSError **)error; +@end using namespace VCC::Mac; namespace { constexpr size_t wireLimit = 1024 * 1024; @@ -21,6 +28,7 @@ constexpr uint64_t fieldBudget = 216000; constexpr size_t maximumDiskBytes = 512 * 1024; constexpr unsigned audioFieldLimit = 120; constexpr size_t audioSampleFrameLimit = 131072; +constexpr uint64_t videoByteLimit = 64 * 1024 * 1024; void little16(std::vector& bytes, uint16_t value) { bytes.push_back(value & 255); bytes.push_back(value >> 8); } @@ -274,6 +282,55 @@ class Playtest { void armStop() { armEvidence(stops, stopModule); } void armInspection() { armEvidence({}, {}); } uint64_t consumed = 0, fieldClock = 0, bootNumber = 0, mediaGeneration = 0; + VCCPlaytestVideoWriter *videoWriter = nil; + NSMutableDictionary *videoInfo = nil; + NSURL *videoDirectory = nil; + unsigned videoMaximumFields = 0; + uint64_t videoFirstField = 0, videoSamples = 0; + void finishVideo(NSString *reason) { + if (!videoWriter) return; + NSError *error = nil; + NSURL *output = nil; + if (videoSamples) output = [videoWriter finishAndReturnError:&error]; + videoWriter = nil; + videoInfo[@"field_end"] = @(fieldClock); + videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField); + videoInfo[@"sample_frames"] = @(videoSamples); + videoInfo[@"truncated"] = @(![reason isEqual:@"stopped"] && ![reason isEqual:@"run_stopped"]); + videoInfo[@"reason"] = reason; + videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO; + if (!output) { videoInfo[@"error"] = error.localizedDescription ?: @"No emulated audio/video interval was recorded."; return; } + NSData *data = [NSData dataWithContentsOfURL:output options:NSDataReadingMappedIfSafe error:&error]; + if (!data || data.length == 0 || data.length > videoByteLimit) { + videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_byte_limit"; return; + } + std::vector bytes(static_cast(data.bytes), static_cast(data.bytes) + data.length); + videoInfo[@"status"] = @"complete"; videoInfo[@"completed"] = @YES; + videoInfo[@"byte_count"] = @(data.length); videoInfo[@"sha256"] = sha256(bytes); + videoInfo[@"mime_type"] = @"video/mp4"; videoInfo[@"filename"] = @"Clip.mp4"; + } + void recordVideo(const std::vector& samples) { + if (!videoWriter || samples.empty()) return; + const auto snapshot = machine->snapshot(); + const auto frame = snapshot.frame; + if (!frame || frame->pixels.size() != Frame::width * Frame::height) { + finishVideo(@"picture_unavailable"); return; + } + const auto area = frame->activeArea; + NSError *error = nil; + const BOOL ok = [videoWriter appendPixels:[NSData dataWithBytes:frame->pixels.data() length:frame->pixels.size() * sizeof(uint32_t)] + area:CGRectMake(area.x, area.y, area.width, area.height) + samples:[NSData dataWithBytes:samples.data() length:samples.size() * sizeof(StereoSample)] error:&error]; + if (!ok) { + videoWriter = nil; videoInfo[@"status"] = @"failed"; videoInfo[@"completed"] = @NO; + videoInfo[@"error"] = error.localizedDescription ?: @"playtest_video_writer_failed"; return; + } + videoSamples += samples.size(); + videoInfo[@"field_end"] = @(fieldClock); videoInfo[@"fields_recorded"] = @(fieldClock - videoFirstField); + NSDictionary *attributes = [NSFileManager.defaultManager attributesOfItemAtPath:[videoDirectory URLByAppendingPathComponent:@"Working.mov"].path error:nil]; + if ([attributes fileSize] >= videoByteLimit - 1024 * 1024) finishVideo(@"byte_limit"); + else if (fieldClock - videoFirstField >= videoMaximumFields) finishVideo(@"field_limit"); + } Processor processor = Processor::MC6809; NSString *originalDiskHash = nil, *currentMediaID = nil; NSString *diskHash() const { @@ -332,8 +389,9 @@ class Playtest { if (consumed + n > fieldBudget) throw std::runtime_error("playtest_field_limit"); for (unsigned i = 0; i < n && machine->snapshot().state == RunState::Running; ++i) { const auto before = machine->snapshot().frames; - machine->advance(); machine->takeAudio(); ++consumed; + machine->advance(); ++consumed; fieldClock += machine->snapshot().frames - before; + auto samples = machine->takeAudio(); recordVideo(samples); } } void boot() { @@ -354,7 +412,7 @@ class Playtest { auto s = machine->snapshot(); const bool hd6309 = s.configuration.processor == Processor::HD6309; const auto *image = floppy->image(0); - return @{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809", + NSMutableDictionary *out = [@{ @"cpu": hd6309 ? @"6309" : @"6809", @"processor": hd6309 ? @"HD6309" : @"MC6809", @"execution_mode": hd6309 ? (s.cpu.IsNative6309 ? @"native" : @"emulation") : @"not_applicable", @"md_register": hd6309 ? (id)@(s.cpu.MD) : NSNull.null, @"ram_kb": @512, @"fields": @(fieldClock), @"field_clock": @(fieldClock), @"boot": @(bootNumber), @"machine_frame": @(s.frames), @@ -366,7 +424,9 @@ class Playtest { @"disk_present": @(image != nullptr), @"media_id": currentMediaID ?: (id)NSNull.null, @"media_generation": @(mediaGeneration), @"floppy_busy": @(floppy->snapshot().busy), @"disk_dirty": @(image && image->dirty()), @"disk_reads": @(floppy->readEvents(0)), - @"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) }; + @"disk_writes": @(floppy->writeEvents(0)), @"isolated": @YES, @"input":inputMetadata(s) } mutableCopy]; + if (videoInfo) out[@"video_recording"] = [videoInfo copy]; + return out; } NSDictionary *capture() const { NSMutableDictionary *out = [status() mutableCopy]; @@ -396,6 +456,7 @@ class Playtest { auto next = machine->takeAudio(); if (next.size() > audioSampleFrameLimit - samples.size()) throw std::runtime_error("playtest_audio_limit"); samples.insert(samples.end(), next.begin(), next.end()); + recordVideo(next); }; // Discard audio from earlier input/steps. A capture owns only this // explicit interval, including any normal leave-breakpoint CPU slice. @@ -452,6 +513,19 @@ public: for (NSDictionary *item in declared) { if (![item isKindOfClass:NSDictionary.class] || ![item[@"id"] isKindOfClass:NSString.class]) throw std::invalid_argument("invalid_modules"); DebugBankedModule module; module.identifier = [item[@"id"] UTF8String]; + id overlayGroup = item[@"overlay_group"], overlayOwner = item[@"overlay_owner"]; + if (overlayGroup || overlayOwner) { + if (![overlayGroup isKindOfClass:NSString.class] || ![overlayOwner isKindOfClass:NSString.class] || + ![overlayGroup length] || ![overlayOwner length] || + [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128 || + [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding] > 128) + throw std::invalid_argument("invalid_overlay_identity"); + const char *groupText = [overlayGroup UTF8String], *ownerText = [overlayOwner UTF8String]; + if (!groupText || !ownerText || std::strlen(groupText) != [overlayGroup lengthOfBytesUsingEncoding:NSUTF8StringEncoding] || + std::strlen(ownerText) != [overlayOwner lengthOfBytesUsingEncoding:NSUTF8StringEncoding]) + throw std::invalid_argument("invalid_overlay_identity"); + module.overlayGroup = groupText; module.overlayOwner = ownerText; + } NSArray *pages = item[@"pages"], *guards = item[@"guards"]; if (![pages isKindOfClass:NSArray.class] || pages.count == 0 || pages.count > 8 || ![guards isKindOfClass:NSArray.class] || guards.count == 0 || guards.count > 8192) throw std::invalid_argument("invalid_modules"); @@ -543,6 +617,32 @@ public: return exportMedia(); } if ([op isEqual:@"exchange_media"]) return exchangeMedia(r); + if ([op isEqual:@"video_start"]) { + if (r.count != 5 || ![r[@"clip_id"] isKindOfClass:NSString.class] || + ![r[@"directory"] isKindOfClass:NSString.class] || !r[@"include_audio"] || + CFGetTypeID((__bridge CFTypeRef)r[@"include_audio"]) != CFBooleanGetTypeID()) throw std::invalid_argument("invalid_arguments"); + if (videoWriter) throw std::runtime_error("playtest_video_active"); + NSUUID *identifier = [[NSUUID alloc] initWithUUIDString:r[@"clip_id"]]; + NSURL *directory = [NSURL fileURLWithPath:r[@"directory"] isDirectory:YES]; + if (!identifier || ![directory.lastPathComponent isEqual:identifier.UUIDString] || + ![NSFileManager.defaultManager fileExistsAtPath:directory.path]) throw std::invalid_argument("invalid_arguments"); + videoMaximumFields = number(r[@"max_fields"], 1, 3600); + NSError *error = nil; + videoWriter = [[VCCPlaytestVideoWriter alloc] initWithDirectory:directory includeAudio:[r[@"include_audio"] boolValue] error:&error]; + if (!videoWriter) throw std::runtime_error((error.localizedDescription ?: @"playtest_video_start_failed").UTF8String); + videoDirectory = directory; videoFirstField = fieldClock; videoSamples = 0; + machine->takeAudio(); + videoInfo = [@{@"clip_id":identifier.UUIDString, @"status":@"recording", @"include_audio":r[@"include_audio"], + @"max_fields":@(videoMaximumFields), @"field_start":@(fieldClock), @"field_end":@(fieldClock), + @"fields_recorded":@0, @"completed":@NO, @"truncated":@NO, @"boot":@(bootNumber), + @"ui_cues_included":@NO, @"microphone_included":@NO, @"host_audio_included":@NO} mutableCopy]; + return status(); + } + if ([op isEqual:@"video_stop"]) { + if (r.count != 1 || !videoInfo) throw std::runtime_error("playtest_video_unavailable"); + finishVideo(@"stopped"); + NSMutableDictionary *out = [status() mutableCopy]; out[@"video"] = [videoInfo copy]; return out; + } if ([op isEqual:@"input"]) { if (r.count != 2) throw std::invalid_argument("invalid_arguments"); unsigned total = 0; @@ -563,6 +663,7 @@ public: applied = machine->resumeWithInput(step.keys, step.joysticks); const auto advanced = machine->snapshot().frames - before.frames; fieldClock += advanced; consumed += advanced; + auto samples = machine->takeAudio(); recordVideo(samples); if (advanced > step.fields) throw std::runtime_error("playtest_input_timing"); } else { machine->setKeyboard(step.keys); @@ -621,15 +722,16 @@ public: return out; } if ([op isEqual:@"restart"]) { + if (videoWriter) throw std::runtime_error("playtest_video_active: stop the recording before restarting"); if (floppy->snapshot().busy) throw std::runtime_error("disk_busy"); boot(); return status(); } - if ([op isEqual:@"continue"]) { armInspection(); machine->resume(); return status(); } + if ([op isEqual:@"continue"]) { armInspection(); const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status(); } if ([op isEqual:@"pause"]) { machine->releaseInputs(); machine->pause(); return status(); } if ([op isEqual:@"step"]) { if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped"); const auto before = machine->snapshot().frames; - machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; return status(); + machine->debuggerStep(); fieldClock += machine->snapshot().frames - before; auto samples = machine->takeAudio(); recordVideo(samples); return status(); } if ([op isEqual:@"stop_at"]) { if (modules.empty() && flatGuards.empty()) throw std::runtime_error("unverified_stop"); @@ -643,7 +745,8 @@ public: } armEvidence({nextPoint}, nextModule); stops = {nextPoint}; stopModule = nextModule; - machine->resume(); return status(); + const auto before = machine->snapshot().frames; machine->resume(); fieldClock += machine->snapshot().frames - before; + auto samples = machine->takeAudio(); recordVideo(samples); return status(); } if ([op isEqual:@"debug"]) { if (machine->snapshot().state != RunState::Paused) throw std::runtime_error("playtest_not_stopped"); @@ -658,6 +761,7 @@ public: out[@"registers"] = registers; out[@"mapping_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerMappingFingerprint]; out[@"program_revision"] = @(machine->snapshot().debuggerProgramRevision); + out[@"residency_fingerprint"] = [NSString stringWithFormat:@"%llu",(unsigned long long)machine->snapshot().debuggerResidencyFingerprint]; out[@"attached"] = @(machine->snapshot().debuggerDevelopmentAttached); out[@"paused"] = @YES; out[@"logical_memory"] = [[NSData dataWithBytes:d.memory.data() length:d.memory.size()] base64EncodedStringWithOptions:0]; @@ -684,7 +788,9 @@ public: } if ([op isEqual:@"stop"]) { machine->releaseInputs(); machine->pause(); + finishVideo(@"run_stopped"); NSMutableDictionary *out = [status() mutableCopy]; + if (videoInfo) out[@"video"] = [videoInfo copy]; if (const auto *image = floppy->image(0)) { const auto& disk = image->bytes(); out[@"disk_base64"] = [[NSData dataWithBytes:disk.data() length:disk.size()] base64EncodedStringWithOptions:0]; diff --git a/platforms/macos/UITests/InteractionTests.swift b/platforms/macos/UITests/InteractionTests.swift index 61c3672..8c17e3a 100644 --- a/platforms/macos/UITests/InteractionTests.swift +++ b/platforms/macos/UITests/InteractionTests.swift @@ -1,6 +1,8 @@ // SPDX-License-Identifier: GPL-3.0-or-later import XCTest import AppKit +import CryptoKit +import AVFoundation // Run using the VCCUITests scheme: its separate app identity and mandatory // authored fixture keep personal ROMs, media, profiles and sessions untouched. @@ -11,6 +13,9 @@ final class InteractionTests: XCTestCase { private var diskEditorFixtureFolder: URL? private var projectSetupFixtureFolder: URL? private var audioGameFixtureFolder: URL? + private var captureFixtureFolder: URL? + private var coverFixtureFolder: URL? + private var continuityFixtureFolder: URL? private var originalClipboard: [NSPasteboardItem]? private var main: XCUIElement { app.windows["VCC UI Tests"] } private var display: XCUIElement { main.descendants(matching: .any)["coco-display"].firstMatch } @@ -87,6 +92,27 @@ final class InteractionTests: XCTestCase { return true } app.launchArguments = ["-ApplePersistenceIgnoreState", "YES", "-NSQuitAlwaysKeepsWindows", "NO"] + if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") { + try requireFullManualEdition() + let token = UUID().uuidString + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCContinuityRelaunch-" + token) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + try token.write(to: folder.appendingPathComponent("fixture-owner"), atomically: true, encoding: .utf8) + continuityFixtureFolder = folder + app.launchEnvironment["VCC_CONTINUITY_TEST_ROOT"] = folder.path + } + if name.contains("testPersonalLibraryCover") { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCoverUI-" + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + coverFixtureFolder = folder + app.launchEnvironment["VCC_COVER_DRAG_TRACE"] = folder.appendingPathComponent("drag-trace.txt").path + app.launchEnvironment["VCC_COVER_DRAG_SOURCE"] = folder.appendingPathComponent("Blue Cover.png").path + } + if name.contains("testCoCoCapture") { + let folder = FileManager.default.temporaryDirectory.appendingPathComponent("VCCCaptureUI-" + UUID().uuidString) + try FileManager.default.createDirectory(at: folder, withIntermediateDirectories: false) + captureFixtureFolder = folder; app.launchEnvironment["VCC_CAPTURE_TEST_DIRECTORY"] = folder.path + } if name.contains("CompactOS9") { app.launchArguments.append("--disk-editor-compact-fixture") } if name.contains("testDiskImageEditor") { let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() @@ -120,17 +146,36 @@ final class InteractionTests: XCTestCase { let repo = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() .deletingLastPathComponent().deletingLastPathComponent() let store = repo.appendingPathComponent("media/knowledge-base") - let index = store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite") + // Match normal packaging: prefer the prepared local index and avoid + // touching the optional external research volume during UI setup. + let localIndex = repo.appendingPathComponent("media/app-inputs/archive-library/ArchiveLibrary.sqlite") + let index = FileManager.default.fileExists(atPath: localIndex.path) ? localIndex : + store.appendingPathComponent("archive-library/ArchiveLibrary.sqlite") try XCTSkipUnless(FileManager.default.fileExists(atPath: index.path), "Stage the local Archive Library index.") let cache = FileManager.default.temporaryDirectory.appendingPathComponent("VCCArchiveReader-" + UUID().uuidString) try FileManager.default.createDirectory(at: cache, withIntermediateDirectories: false) archiveCache = cache func seed(_ relative: String, as filename: String) throws { - let original = store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative) + // Stage optional retained originals before launching XCTest when + // the research store is on a removable volume. File access in + // setUp must not wait indefinitely on an unseen system prompt. + let staged = repo.appendingPathComponent(".build/archive-ui-fixtures").appendingPathComponent(relative) + let original = FileManager.default.fileExists(atPath: staged.path) ? staged : + store.appendingPathComponent("originals/archive-documents").appendingPathComponent(relative) try XCTSkipUnless(FileManager.default.fileExists(atPath: original.path), "Stage the Archive fixture " + relative) - try FileManager.default.copyItem(at: original, to: cache.appendingPathComponent(filename)) + let data = try Data(contentsOf: original) + XCTAssertEqual(SHA256.hash(data: data).map { String(format: "%02x", $0) }.joined(), + (filename as NSString).deletingPathExtension, "Retained fixture must match the indexed original") + try data.write(to: cache.appendingPathComponent(filename), options: .atomic) } - if name.contains("testArchiveLibraryBrowsesTextAndImageInline") { + if name.contains("testArchiveLibraryAndManualsResumeAcrossProcessRelaunch") { + try seed("Magazines/MOTD/MOTD 1986 04.pdf", as: "917d4da1916fd14cd89f20da6fea5474e807a16e723f05055231992e430e6d33.pdf") + try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png", + as: "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5.png") + app.launchArguments += ["-archive-library.collection", "Walkthroughs/Sierra Games"] + } else if name.contains("testArchiveLibraryRelatedReferenceFromSoftware") { + try seed("Walkthroughs/Raaka-Tu Walkthrough (Tandy).txt", as: "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc.txt") + } else if name.contains("testArchiveLibraryBrowsesTextAndImageInline") { try seed("Walkthroughs/Sierra Games/AGI Quest I Walkthrough (Juha Terho).txt", as: "563a8fe2ba0e251227fb05c1ac6a4bfe965bc3e124bb91547f8bae493adab68a.txt") try seed("Walkthroughs/Sierra Games/King's Quest I Map (Sierra).png", @@ -200,6 +245,13 @@ final class InteractionTests: XCTestCase { if let diskEditorFixtureFolder { try? FileManager.default.removeItem(at: diskEditorFixtureFolder) } if let projectSetupFixtureFolder { try? FileManager.default.removeItem(at: projectSetupFixtureFolder) } if let audioGameFixtureFolder { try? FileManager.default.removeItem(at: audioGameFixtureFolder) } + if let captureFixtureFolder { try? FileManager.default.removeItem(at: captureFixtureFolder) } + if let coverFixtureFolder { try? FileManager.default.removeItem(at: coverFixtureFolder) } + if let continuityFixtureFolder { + let suite = continuityFixtureFolder.lastPathComponent + UserDefaults(suiteName: suite)?.removePersistentDomain(forName: suite) + try? FileManager.default.removeItem(at: continuityFixtureFolder) + } } if let app, app.state != .notRunning { if (testRun?.failureCount ?? 0) > 0 { @@ -4550,3 +4602,480 @@ extension InteractionTests { XCTAssertEqual(after[0], before[0]); XCTAssertEqual(after[2], before[2]); XCTAssertEqual(after[3], before[3]) } } + +extension InteractionTests { + func testCoCoCaptureHeaderScreenshotTimerAndMovie() async throws { + let before = session() + let root = try XCTUnwrap(captureFixtureFolder) + let documents = root.appendingPathComponent("Documents", isDirectory: true) + func files(_ dir: URL, _ ext: String) -> [URL] { + ((try? FileManager.default.contentsOfDirectory(at: dir, includingPropertiesForKeys: nil)) ?? []).filter { $0.pathExtension == ext && !$0.lastPathComponent.hasPrefix(".") } + } + func waitFor(_ predicate: @escaping () -> Bool, seconds: TimeInterval = 12) { + XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in predicate() }, object: nil)], timeout: seconds), .completed) + } + let camera = main.buttons["capture-now"], record = main.buttons["capture-record"] + let options = main.menuButtons["capture-options"] + func choose(_ label: String) { + options.click() + let item = app.menuItems[label].firstMatch + XCTAssertTrue(item.waitForExistence(timeout: 3)); item.click() + } + XCTAssertTrue(camera.waitForExistence(timeout: 5)); XCTAssertTrue(record.exists) + camera.click(); waitFor { files(root,"png").count == 1 } + let png = try XCTUnwrap(files(root,"png").first) + let picture = try XCTUnwrap(NSImage(contentsOf: png)) + XCTAssertLessThanOrEqual(picture.size.width, 640); XCTAssertLessThanOrEqual(picture.size.height, 480) + XCTAssertGreaterThan(picture.size.width, 200) + choose("10 Seconds") + let cancel = main.buttons["capture-countdown-cancel"] + XCTAssertFalse(cancel.exists, "Changing the timer must not start a capture") + XCTAssertEqual(files(root,"png").count, 1) + camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3)); cancel.click() + XCTAssertFalse(cancel.exists); XCTAssertEqual(files(root,"png").count, 1) + choose("5 Seconds") + XCTAssertFalse(cancel.exists, "Only the camera performs a capture") + camera.click(); XCTAssertTrue(cancel.waitForExistence(timeout: 3)) + waitFor({ files(root,"png").count == 2 }, seconds: 10) + choose("None") + choose("Documents") + // The chooser changes the one shared destination only on confirmation. + choose("Other Location…") + let chooser = app.windows["Save Screenshots and Videos To"] + XCTAssertTrue(chooser.waitForExistence(timeout: 4)) + chooser.buttons["Cancel"].click() + camera.click(); waitFor { files(documents,"png").count == 1 } + XCTAssertEqual(files(root,"png").count, 2) + choose("Include CoCo Audio in Video") + record.click() + waitFor { record.label == "Stop Recording" } + // Take another image while video is active. Its shutter is host-only. + camera.click(); waitFor { files(documents,"png").count == 2 } + choose("Include CoCo Audio in Video") // Changes the next recording only. + let deadline = Date().addingTimeInterval(1.2) + waitFor { Date() >= deadline } + record.click() + waitFor({ files(documents,"mp4").count == 1 }, seconds: 20) + let movie = try XCTUnwrap(files(documents,"mp4").first) + XCTAssertGreaterThan(try movie.resourceValues(forKeys: [.fileSizeKey]).fileSize ?? 0, 1000) + let asset = AVURLAsset(url: movie) + let tracks = try await asset.loadTracks(withMediaType: .audio) + let track = try XCTUnwrap(tracks.first) + let reader = try AVAssetReader(asset: asset) + let output = AVAssetReaderTrackOutput(track: track, outputSettings: [AVFormatIDKey: kAudioFormatLinearPCM, + AVLinearPCMIsFloatKey: true, AVLinearPCMBitDepthKey: 32, AVLinearPCMIsNonInterleaved: false]) + reader.add(output); XCTAssertTrue(reader.startReading()) + var peak: Float = 0, samples = 0 + while let sample = output.copyNextSampleBuffer() { + let buffer = try XCTUnwrap(CMSampleBufferGetDataBuffer(sample)) + var data = Data(count: CMBlockBufferGetDataLength(buffer)) + XCTAssertEqual(data.withUnsafeMutableBytes { CMBlockBufferCopyDataBytes(buffer, atOffset: 0, dataLength: $0.count, destination: $0.baseAddress!) }, noErr) + data.withUnsafeBytes { raw in + for value in raw.bindMemory(to: Float.self) { peak = max(peak, abs(value)); samples += 1 } + } + } + XCTAssertEqual(reader.status, .completed); XCTAssertGreaterThan(samples, 0) + XCTAssertLessThan(peak, 0.00001, "Local start/shutter cues must not leak into the silent video") + XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2]) + XCTAssertGreaterThan(session()[1], before[1]) + XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists) + let shot = XCTAttachment(screenshot: main.screenshot()); shot.name = "Shared capture controls"; shot.lifetime = .keepAlways; add(shot) + } +} + +extension InteractionTests { + func testArchiveLibraryAndManualsResumeAcrossProcessRelaunch() throws { + let fixture = try XCTUnwrap(continuityFixtureFolder) + let stateFile = fixture.appendingPathComponent("LibraryContinuity.json") + func state() -> [String: Any] { + guard let data = try? Data(contentsOf: stateFile), + let object = try? JSONSerialization.jsonObject(with: data) as? [String: Any] else { return [:] } + return object + } + func waitUntil(_ description: String, _ condition: @escaping () -> Bool) { + let predicate = NSPredicate { _, _ in condition() } + XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: predicate, object: nil)], timeout: 12), .completed, description) + } + func reading(_ key: String) -> [String: Any] { (state()["reading"] as? [String: [String: Any]])?[key] ?? [:] } + func bookmarks() -> [[String: Any]] { state()["bookmarks"] as? [[String: Any]] ?? [] } + func capture(_ window: XCUIElement, _ title: String) { + let image = XCTAttachment(screenshot: window.screenshot()); image.name = title; image.lifetime = .keepAlways; add(image) + } + func relaunch() { + app.activate() + app.typeKey("q", modifierFlags: .command) + waitUntil("The first isolated process must quit before launching its successor") { self.app.state == .notRunning } + app.launch() + XCTAssertTrue(main.waitForExistence(timeout: 15)) + waitUntil("The successor process must finish its authored machine startup") { + self.main.buttons["execution"].label == "Pause" && self.main.links["FD0 Authored FD0.dsk"].exists + } + } + menu("Media", "Software Library…") + let software = app.windows["Software Library"] + XCTAssertTrue(software.buttons["library-scope-all"].waitForExistence(timeout: 10)) + software.buttons["library-scope-all"].click() + let softwareSearch = software.descendants(matching: .any)["library-search"].firstMatch + softwareSearch.click(); app.typeText("Raaka-Tu") + let game = software.buttons["library-title-486dda54b9351ac926c382f70f328aa5"] + XCTAssertTrue(game.waitForExistence(timeout: 10)); game.click() + waitUntil("Software title and search must reach the continuity file") { + let browse = (state()["browse"] as? [String: [String: Any]])?["software-main"] + return browse?["selectedID"] as? String == "486dda54b9351ac926c382f70f328aa5" + } + + menu("Help", "Archive Library…") + let archive = app.windows["Archive Library"] + let map = archive.descendants(matching: .any)["archive-browse-list"].firstMatch.staticTexts["King's Quest I Map (Sierra)"] + XCTAssertTrue(map.waitForExistence(timeout: 10)); map.click() + XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10)) + archive.buttons["Zoom in"].click() + let mapID = "1ed75351da8136ed8c2eafb6c3b93d92af411bbdb8f616ced57282d155d1a5f5" + waitUntil("Archive image zoom must be checkpointed") { (reading("archive:" + mapID)["zoom"] as? Double ?? 0) > 1 } + let mapZoom = try XCTUnwrap(reading("archive:" + mapID)["zoom"] as? Double) + capture(archive, "Archive map before process relaunch") + + menu("Help", "Manual Library…") + let manual = app.windows["Manual Library"] + func follow(_ title: String) { + let link = manual.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch + XCTAssertTrue(link.waitForExistence(timeout: 10), title); link.click() + } + let firstBook = "meet-your-color-computer", secondBook = "back-at-the-coco" + func readAndBookmark(_ book: String) { + let chapter = book + (book == firstBook ? "/meet-the-machine.html" : "/familiar-hardware.html") + waitUntil("The selected chapter must finish loading") { + reading("manual-last")["relativePath"] as? String == chapter && manual.buttons["manual.bookmark-location"].isEnabled + } + manual.webViews.firstMatch.scroll(byDeltaX: 0, deltaY: -600) + waitUntil("Scrolling must record a reading position") { + let position = reading("manual-book:" + book) + return (position["offset"] as? Double ?? 0) > 0.001 || position["anchor"] as? String != nil + } + let bookmark = manual.buttons["manual.bookmark-location"] + XCTAssertTrue(bookmark.isEnabled); bookmark.click() + waitUntil("A bookmark in each book must be saved") { bookmarks().contains { $0["bookID"] as? String == book } } + } + follow("Open the first book"); follow("Start reading"); readAndBookmark(firstBook) + manual.buttons["manual.home"].click() + follow("Open Back at the CoCo"); follow("Start reading"); readAndBookmark(secondBook) + let firstPosition = reading("manual-book:" + firstBook), secondPosition = reading("manual-book:" + secondBook) + let firstMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == firstBook }?["id"] as? String) + let secondMark = try XCTUnwrap(bookmarks().first { $0["bookID"] as? String == secondBook }?["id"] as? String) + XCTAssertEqual(bookmarks().count, 2) + capture(manual, "Second manual before process relaunch") + relaunch() + + menu("Media", "Software Library…") + XCTAssertTrue(game.waitForExistence(timeout: 10)) + XCTAssertEqual(softwareSearch.value as? String, "Raaka-Tu") + XCTAssertTrue(software.links["library-reference-02587e81cceaec9ac0c11fe9"].waitForExistence(timeout: 10), "The selected software detail must resume") + capture(software, "Software selection and search after process relaunch") + menu("Help", "Archive Library…") + XCTAssertTrue(archive.images["archive-inline-image"].waitForExistence(timeout: 10), "The selected browse image must resume") + XCTAssertTrue(archive.buttons["Fit Image"].isEnabled, "The image must retain its zoom") + XCTAssertEqual(reading("archive:" + mapID)["zoom"] as? Double, mapZoom) + let archiveSearch = archive.textFields["archive-search"] + archiveSearch.click(); app.typeText("MOTD strip buffer") + let result = archive.outlines["archive-results-list"].descendants(matching: .outlineRow).containing(.staticText, identifier: "PDF page 12").firstMatch + XCTAssertTrue(result.waitForExistence(timeout: 10)); result.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).click() + let pdfPage = archive.textFields["PDF page number"] + waitUntil("The selected search result must show its cited page") { pdfPage.value as? String == "12" } + capture(archive, "Archive search before second process relaunch") + menu("Help", "Manual Library…") + waitUntil("The last active manual must resume") { reading("manual-last")["documentID"] as? String == secondBook && manual.buttons["manual.bookmark-location"].isEnabled } + XCTAssertEqual(reading("manual-last")["relativePath"] as? String, secondPosition["relativePath"] as? String) + XCTAssertEqual(reading("manual-last")["anchor"] as? String, secondPosition["anchor"] as? String) + manual.buttons["manual.bookmarks"].click() + manual.radioButtons["All Books"].click() + let firstEntry = manual.buttons["manual.bookmark-open-" + firstMark] + let secondEntry = manual.buttons["manual.bookmark-open-" + secondMark] + XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertTrue(secondEntry.exists) + capture(manual, "Two-book bookmarks after process relaunch") + // This journey verifies native scope actions and persistence. Focused + // keyboard/VoiceOver operation is qualified separately; clicking a Mac + // radio button alone does not establish keyboard focus for arrow keys. + manual.radioButtons["This Book"].click() + waitUntil("This Book must show only the active book's bookmark") { !firstEntry.exists && secondEntry.exists } + manual.radioButtons["All Books"].click() + waitUntil("All Books must show both saved bookmarks") { firstEntry.exists && secondEntry.exists } + firstEntry.click() + waitUntil("Explicit bookmark navigation must win over second-book resume") { reading("manual-last")["documentID"] as? String == firstBook } + XCTAssertEqual(reading("manual-last")["anchor"] as? String, firstPosition["anchor"] as? String) + manual.buttons["manual.bookmarks"].click() + manual.radioButtons["This Book"].click() + XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists) + firstEntry.click() + relaunch() + menu("Help", "Archive Library…") + XCTAssertEqual(archiveSearch.value as? String, "MOTD strip buffer") + waitUntil("The selected PDF search page must survive the second process relaunch") { pdfPage.value as? String == "12" } + capture(archive, "Archive search and cited page after process relaunch") + menu("Help", "Manual Library…") + waitUntil("The explicit first-book visit must become the new automatic resume") { reading("manual-last")["documentID"] as? String == firstBook && manual.buttons["manual.bookmark-location"].isEnabled } + manual.buttons["manual.bookmarks"].click() + XCTAssertTrue(firstEntry.waitForExistence(timeout: 5)); XCTAssertFalse(secondEntry.exists) + manual.radioButtons["All Books"].click(); XCTAssertTrue(secondEntry.exists) + XCTAssertEqual(bookmarks().count, 2) + capture(manual, "First manual and saved bookmark filter after second relaunch") + } + + func testManualLibraryBookmarksAndWindowResume() throws { + try requireFullManualEdition() + menu("Help", "Manual Library…") + let reader = app.windows["Manual Library"] + XCTAssertTrue(reader.waitForExistence(timeout: 8)) + for title in ["Open the first book", "Start reading"] { + let link = reader.links.containing(NSPredicate(format: "label CONTAINS[c] %@ OR title CONTAINS[c] %@", title, title)).firstMatch + XCTAssertTrue(link.waitForExistence(timeout: 8)); link.click() + } + let bookmark = reader.buttons["manual.bookmark-location"] + let ready = NSPredicate { _, _ in bookmark.exists && bookmark.isEnabled } + XCTAssertEqual(XCTWaiter.wait(for: [XCTNSPredicateExpectation(predicate: ready, object: nil)], timeout: 8), .completed) + bookmark.click(); reader.buttons["manual.bookmarks"].click() + let entry = reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).firstMatch + XCTAssertTrue(entry.waitForExistence(timeout: 5)) + reader.radioButtons["All Books"].click(); XCTAssertTrue(entry.exists) + reader.radioButtons["This Book"].click(); XCTAssertTrue(entry.exists) + let shot = XCTAttachment(screenshot: reader.screenshot()); shot.name = "Manual bookmarks — one list with filters"; shot.lifetime = .keepAlways; add(shot) + entry.click() + reader.buttons["manual.bookmark-location"].click() // recognizes the existing entry + XCTAssertTrue(entry.waitForExistence(timeout: 5)) + XCTAssertEqual(reader.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "manual.bookmark-open-")).count, 1) + entry.click() + reader.buttons[XCUIIdentifierCloseWindow].firstMatch.click() + menu("Help", "Manual Library…") + XCTAssertTrue(reader.buttons["manual.bookmark-location"].waitForExistence(timeout: 5)) + reader.buttons["manual.bookmarks"].click(); XCTAssertTrue(entry.waitForExistence(timeout: 5)) + } + + func testSoftwareLibraryPersonalImportPreservesGuest() throws { + let before = session() + menu("Media", "Software Library…") + let library = app.windows["Software Library"] + XCTAssertTrue(library.waitForExistence(timeout: 8)) + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let source = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk") + let original = try Data(contentsOf: source) + library.buttons["library-scope-personal"].click() + let addButton = library.buttons["library-personal-add"] + let addFirst = library.buttons["library-personal-add-first"] + XCTAssertTrue(addButton.waitForExistence(timeout: 5)) + XCTAssertTrue(addFirst.waitForExistence(timeout: 5)) + addFirst.click() + XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5)) + app.buttons["Cancel"].click() + XCTAssertTrue(addButton.waitForExistence(timeout: 5)) + addButton.click() + XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5)) + app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(source.path); app.typeKey(.return, modifierFlags: []) + app.buttons["Review Files"].click() + let field = library.textFields["personal-title"] + XCTAssertTrue(field.waitForExistence(timeout: 8)); field.click(); app.typeKey("a", modifierFlags: .command); app.typeText("Private Library UI Example") + let category = library.popUpButtons["personal-category"] + XCTAssertTrue(category.exists); XCTAssertEqual(category.value as? String, "Other") + category.click(); app.menuItems["Games"].click() + let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Add Personal Software — review before import"; shot.lifetime = .keepAlways; add(shot) + library.buttons["personal-save"].click() + let title = library.staticTexts["Private Library UI Example"].firstMatch + XCTAssertTrue(title.waitForExistence(timeout: 10)) + XCTAssertTrue(library.buttons["library-scope-personal"].exists) + XCTAssertTrue(addButton.exists, "Add Software stays available after the first import") + XCTAssertFalse(addFirst.exists, "A populated library must not show the first-item invitation") + let search = library.descendants(matching: .any)["library-search"].firstMatch + search.click(); app.typeText("No such personal title 370") + let clear = library.buttons["library-empty-clear-search"] + XCTAssertTrue(clear.waitForExistence(timeout: 5)) + XCTAssertFalse(addButton.exists, "The header search opens global results, outside the private-only browse scope") + XCTAssertFalse(addFirst.exists, "A filtered library is not an empty personal collection") + clear.click() + library.buttons["library-scope-getting-started"].click() + search.click(); app.typeText("Private Library UI Example") + let personalCard = library.buttons.matching(NSPredicate(format: "identifier BEGINSWITH %@", "library-title-personal:")).firstMatch + XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "Global search must find a private game from Getting Started") + XCTAssertTrue(personalCard.label.contains("Personal")) + library.buttons["Clear search"].click() + library.buttons["library-type-Games"].click() + XCTAssertTrue(personalCard.waitForExistence(timeout: 5), "The standard Games category includes the private game") + let grouped = XCTAttachment(screenshot: library.screenshot()); grouped.name = "Unified Games — Personal Library before Catalog"; grouped.lifetime = .keepAlways; add(grouped) + library.radioButtons["Table"].click() + let table = library.outlines["Software titles"] + XCTAssertTrue(table.waitForExistence(timeout: 5)) + table.scroll(byDeltaX: 0, deltaY: 1200) + let tableShot = XCTAttachment(screenshot: library.screenshot()); tableShot.name = "Unified Games — Table Personal badge"; tableShot.lifetime = .keepAlways; add(tableShot) + let firstRow = table.outlineRows.element(boundBy: 0) + let badge = firstRow.descendants(matching: .any)["library-personal-badge"].firstMatch + XCTAssertTrue(badge.waitForExistence(timeout: 5), "The first table row visibly identifies the personal entry") + XCTAssertFalse(addButton.exists, "Other categories keep personal import in Library Actions") + XCTAssertEqual(try Data(contentsOf: source), original) + XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2]) + XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists) + } + + func testPersonalLibraryCoverChooserCancelDropAndRemovePreserveGuest() throws { + try personalCoverJourney(includeDrop: true) + } + func testPersonalLibraryCoverChooserCancelAndRemovePreserveGuest() throws { + try personalCoverJourney(includeDrop: false) + } + private func personalCoverJourney(includeDrop: Bool) throws { + let manualDrag = includeDrop && ProcessInfo.processInfo.environment["VCC_UI_MANUAL_COVER_DRAG"] == "1" + var manualFinderWindow: XCUIElement? + defer { + if let window = manualFinderWindow, window.exists, + window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists { + window.buttons[XCUIIdentifierCloseWindow].firstMatch.click() + } + } + let before = session() + let folder = try XCTUnwrap(coverFixtureFolder) + defer { try? FileManager.default.removeItem(at: folder) } + func image(_ color: NSColor, name: String) throws -> URL { + let bitmap = try XCTUnwrap(NSBitmapImageRep(bitmapDataPlanes: nil, pixelsWide: 320, pixelsHigh: 200, + bitsPerSample: 8, samplesPerPixel: 4, hasAlpha: true, isPlanar: false, + colorSpaceName: .deviceRGB, bytesPerRow: 0, bitsPerPixel: 0)) + NSGraphicsContext.saveGraphicsState() + NSGraphicsContext.current = NSGraphicsContext(bitmapImageRep: bitmap) + color.setFill(); NSBezierPath(rect: NSRect(x: 0, y: 0, width: 320, height: 200)).fill() + NSGraphicsContext.restoreGraphicsState() + let url = folder.appendingPathComponent(name) + try XCTUnwrap(bitmap.representation(using: .png, properties: [:])).write(to: url) + return url + } + let red = try image(.red, name: "Red Cover.png"), blue = try image(.blue, name: "Blue Cover.png") + let redBytes = try Data(contentsOf: red), blueBytes = try Data(contentsOf: blue) + let mac = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent() + let disk = mac.appendingPathComponent("Tests/Fixtures/DiskEditor/DECB.dsk"), diskBytes = try Data(contentsOf: disk) + menu("Media", "Software Library…") + let library = app.windows["Software Library"] + XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-personal"].click() + library.buttons["library-personal-add"].click() + XCTAssertTrue(app.buttons["Review Files"].waitForExistence(timeout: 5)) + app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(disk.path); app.typeKey(.return, modifierFlags: []) + app.buttons["Review Files"].click() + XCTAssertTrue(library.buttons["personal-save"].waitForExistence(timeout: 8)); library.buttons["personal-save"].click() + let cover = library.descendants(matching: .any)["library-personal-cover"].firstMatch + XCTAssertTrue(cover.waitForExistence(timeout: 8)) + func choose(_ url: URL, prompt: String) { + XCTAssertTrue(app.buttons[prompt].waitForExistence(timeout: 5)) + app.typeKey("g", modifierFlags: [.command, .shift]); app.typeText(url.path); app.typeKey(.return, modifierFlags: []) + app.buttons[prompt].click() + } + func matches(_ element: XCUIElement, red: Bool) -> Bool { + guard element.exists, let pixels = NSBitmapImageRep(data: element.screenshot().pngRepresentation), + let color = pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2)?.usingColorSpace(.deviceRGB) else { return false } + // Native display captures carry the monitor's color transform; + // verify the authored dominant channel rather than raw PNG bytes. + return red ? color.redComponent > 0.7 && color.redComponent - max(color.greenComponent, color.blueComponent) > 0.4 + : color.blueComponent > 0.7 && color.blueComponent - max(color.greenComponent, color.redComponent) > 0.4 + } + func waitForColor(_ element: XCUIElement, red: Bool, timeout: TimeInterval = 15) { + let expectation = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in matches(element, red: red) }, object: nil) + let result = XCTWaiter.wait(for: [expectation], timeout: timeout) + if result != .completed { + let screenshot = element.screenshot() + let attachment = XCTAttachment(screenshot: screenshot); attachment.name = "Cover pixel assertion"; attachment.lifetime = .keepAlways; add(attachment) + if let pixels = NSBitmapImageRep(data: screenshot.pngRepresentation) { + print("Cover screenshot \(pixels.pixelsWide)x\(pixels.pixelsHigh), center \(String(describing: pixels.colorAt(x: pixels.pixelsWide / 2, y: pixels.pixelsHigh / 2))), frame \(element.frame)") + } + } + XCTAssertEqual(result, .completed) + } + library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Choose Cover Image…"].click() + choose(red, prompt: "Use Image"); waitForColor(cover, red: true) + library.buttons["Edit Details…"].click() + let chooseDraft = library.buttons["personal-cover-choose"] + XCTAssertTrue(chooseDraft.waitForExistence(timeout: 5)) + let preview = library.descendants(matching: .any)["personal-cover-preview"].firstMatch + let form = library.sheets.firstMatch.scrollViews.firstMatch + for _ in 0..<6 where !form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame) { + form.scroll(byDeltaX: 0, deltaY: -180) + } + XCTAssertTrue(form.frame.insetBy(dx: 8, dy: 8).contains(preview.frame), "Inspect the complete preview inside the form viewport") + chooseDraft.click(); choose(blue, prompt: "Choose Image") + waitForColor(preview, red: false) + let editorShot = XCTAttachment(screenshot: library.screenshot()); editorShot.name = "Personal cover — draft image preview"; editorShot.lifetime = .keepAlways; add(editorShot) + library.sheets.firstMatch.buttons["Cancel"].click(); waitForColor(cover, red: true) + + if includeDrop { + app.activate() + // The authored native source starts an actual NSDraggingSession with + // a file URL. It never calls the destination handler or changes model + // state; the normal decoder/store/render path must produce blue pixels. + let source = library.descendants(matching: .any)["personal-cover-drag-source"].firstMatch + XCTAssertTrue(source.waitForExistence(timeout: 5)) + let pasteboardGeneration = NSPasteboard(name: .drag).changeCount + if manualDrag { + let finder = XCUIApplication(bundleIdentifier: "com.apple.finder") + finder.activate(); finder.typeKey("n", modifierFlags: .command) + finder.typeKey("g", modifierFlags: [.command, .shift]); finder.typeText(folder.path); finder.typeKey(.return, modifierFlags: []) + let window = finder.windows[folder.lastPathComponent] + XCTAssertTrue(window.waitForExistence(timeout: 8)) + manualFinderWindow = window + print("VCC_COVER_MANUAL_DRAG_READY: Drag Blue Cover.png from Finder onto the red cover in Software Library") + fflush(stdout) + let delivered = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in + let log = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? "" + return log.contains("perform file-count=1") && matches(cover, red: false) + }, object: nil) + XCTAssertEqual(XCTWaiter.wait(for: [delivered], timeout: 180), .completed) + } else { + source.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)).press(forDuration: 0.25, + thenDragTo: cover.coordinate(withNormalizedOffset: CGVector(dx: 0.5, dy: 0.5)), withVelocity: .slow, thenHoldForDuration: 1) + } + XCTAssertGreaterThan(NSPasteboard(name: .drag).changeCount, pasteboardGeneration) + XCTAssertTrue(NSPasteboard(name: .drag).types?.contains(.fileURL) == true) + let trace = (try? String(contentsOf: folder.appendingPathComponent("drag-trace.txt"))) ?? "No native drag events" + print("Native cover drag: " + trace) + XCTAssertTrue(trace.contains("perform file-count=1")) + if !manualDrag { app.activate(); waitForColor(cover, red: false) } + let shot = XCTAttachment(screenshot: cover.screenshot()); shot.name = "Personal cover — native file drop replacement"; shot.lifetime = .keepAlways; add(shot) + } + if let window = manualFinderWindow, window.exists, + window.buttons[XCUIIdentifierCloseWindow].firstMatch.exists { + window.buttons[XCUIIdentifierCloseWindow].firstMatch.click() + manualFinderWindow = nil + app.activate() + } + library.menuButtons["library-personal-cover-menu"].click(); app.menuItems["Remove Cover"].click() + let removed = XCTNSPredicateExpectation(predicate: NSPredicate { _, _ in cover.label.hasSuffix(" category cover") }, object: nil) + XCTAssertEqual(XCTWaiter.wait(for: [removed], timeout: 10), .completed) + XCTAssertFalse(matches(cover, red: true)); XCTAssertFalse(matches(cover, red: false)) + XCTAssertEqual(try Data(contentsOf: red), redBytes); XCTAssertEqual(try Data(contentsOf: blue), blueBytes) + XCTAssertEqual(try Data(contentsOf: disk), diskBytes) + XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2]) + XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists) + } + + func testArchiveLibraryRelatedReferenceFromSoftware() throws { + let before = session() + menu("Media", "Software Library…") + let library = app.windows["Software Library"] + XCTAssertTrue(library.waitForExistence(timeout: 8)); library.buttons["library-scope-all"].click() + let search = library.descendants(matching: .any)["library-search"].firstMatch + search.click(); app.typeText("Raaka-Tu") + let game = library.buttons["library-title-486dda54b9351ac926c382f70f328aa5"] + XCTAssertTrue(game.waitForExistence(timeout: 8)); game.click() + let referenceID = "library-reference-02587e81cceaec9ac0c11fe9" + let link = library.links[referenceID] + XCTAssertTrue(link.waitForExistence(timeout: 8)) + let detail = library.scrollViews.containing(.link, identifier: referenceID).firstMatch + func guideVisible() -> Bool { + // macOS can report clipped content beneath the fixed footer as + // hittable. Require the complete link inside its actual viewport. + let frame = link.frame + return !frame.isEmpty && link.isHittable && detail.frame.insetBy(dx: 10, dy: 18).contains(frame) + } + for _ in 0..<8 where !guideVisible() { detail.scroll(byDeltaX: 0, deltaY: -250) } + XCTAssertTrue(guideVisible(), "Scroll the entire guide action clear of the fixed footer before opening it") + let shot = XCTAttachment(screenshot: library.screenshot()); shot.name = "Software Library — Raaka-Tu Guides & References"; shot.lifetime = .keepAlways; add(shot) + link.click() + let archive = app.windows["Archive Library"] + let text = archive.textViews["archive-inline-text"] + XCTAssertTrue(text.waitForExistence(timeout: 10)); XCTAssertGreaterThan((text.value as? String ?? "").count, 100) + XCTAssertEqual(text.label, "Raaka-Tu Walkthrough (Tandy)", "The loaded reader must identify the exact linked document") + let readerShot = XCTAttachment(screenshot: archive.screenshot()); readerShot.name = "Archive Library — linked Raaka-Tu walkthrough"; readerShot.lifetime = .keepAlways; add(readerShot) + XCTAssertEqual(session()[0], before[0]); XCTAssertEqual(session()[2], before[2]) + XCTAssertTrue(main.links["FD0 Authored FD0.dsk"].exists) + } +} diff --git a/platforms/macos/VCC.xcodeproj/project.pbxproj b/platforms/macos/VCC.xcodeproj/project.pbxproj index 3b5bdbd..7e79e08 100644 --- a/platforms/macos/VCC.xcodeproj/project.pbxproj +++ b/platforms/macos/VCC.xcodeproj/project.pbxproj @@ -5,6 +5,39 @@ }; "objectVersion" = 56; "objects" = { +"2464EE6BFE2AA97DBC5C2913" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoCaptureFeedback.swift"; sourceTree = SOURCE_ROOT; }; +"E4061E4E0AB7CA7A47624B27" = { isa = PBXBuildFile; fileRef = "2464EE6BFE2AA97DBC5C2913"; }; +"337343EA275BED13114792F9" = { isa = PBXBuildFile; fileRef = "2464EE6BFE2AA97DBC5C2913"; }; +"DC1C21A297BCCD34706DBEE1" = { isa = PBXFileReference; lastKnownFileType = folder; path = "Resources/CaptureSounds"; sourceTree = SOURCE_ROOT; }; +"B7A7B5BFA3C251D22DC8561A" = { isa = PBXBuildFile; fileRef = "DC1C21A297BCCD34706DBEE1"; }; +"17CB263DB27EF1128FBF12D4" = { isa = PBXBuildFile; fileRef = "DC1C21A297BCCD34706DBEE1"; }; + +"CCF46B90050E0BE77D1F5FAA" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/CoCoVideoBudgetTests.swift"; sourceTree = SOURCE_ROOT; }; +"9944B924F1F25A1C31E87133" = { isa = PBXBuildFile; fileRef = "CCF46B90050E0BE77D1F5FAA"; }; +"C3DEFD6B0A505C9AA2ADEB3B" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/CoCoCaptureTests.swift"; sourceTree = SOURCE_ROOT; }; +"03B7230E381C6D102C3BF95F" = { isa = PBXBuildFile; fileRef = "C3DEFD6B0A505C9AA2ADEB3B"; }; +"971F1C3D34CF84F153F037EC" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/SoftwareLibraryPersonalTests.swift"; sourceTree = SOURCE_ROOT; }; +"F97715060F4E2618EB80AFDE" = { isa = PBXBuildFile; fileRef = "971F1C3D34CF84F153F037EC"; }; + +"FFA296F39D044DC70C6FCFB7" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoCapture.swift"; sourceTree = SOURCE_ROOT; }; +"2921AED78693AE35B29C2B88" = { isa = PBXBuildFile; fileRef = "FFA296F39D044DC70C6FCFB7"; }; +"F770A2E6626B73FE7071CB9A" = { isa = PBXBuildFile; fileRef = "FFA296F39D044DC70C6FCFB7"; }; +"386691BEF25A11E0954243CD" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/CoCoVideoEncoder.swift"; sourceTree = SOURCE_ROOT; }; +"F69F722FBCDDA97A8FB48C96" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; }; +"A1DC73569D936F22FB4E554E" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; }; +"C9DF7704560822DA03677397" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/LibraryContinuity.swift"; sourceTree = SOURCE_ROOT; }; +"31E94EDA2FFA2E36C43113B4" = { isa = PBXBuildFile; fileRef = "C9DF7704560822DA03677397"; }; +"6229E570150FBFD4653A4E38" = { isa = PBXBuildFile; fileRef = "C9DF7704560822DA03677397"; }; +"F75B630AE8D4162CD9E45A75" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/SoftwareLibraryPersonal.swift"; sourceTree = SOURCE_ROOT; }; +"77B510203B32A69B19F95BAF" = { isa = PBXBuildFile; fileRef = "F75B630AE8D4162CD9E45A75"; }; +"B07B7E2C92770E75D506BABD" = { isa = PBXBuildFile; fileRef = "F75B630AE8D4162CD9E45A75"; }; +"9EA2B6271ECBBEC8E2BE5A67" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "App/SoftwareLibraryPersonalView.swift"; sourceTree = SOURCE_ROOT; }; +"AF8FCAD6F87C7AAA1B8398AF" = { isa = PBXBuildFile; fileRef = "9EA2B6271ECBBEC8E2BE5A67"; }; +"6EB73875746CB21BDF3E7AB3" = { isa = PBXBuildFile; fileRef = "9EA2B6271ECBBEC8E2BE5A67"; }; +"A1009AA9F3239FF614E22103" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tests/LibraryContinuityTests.swift"; sourceTree = SOURCE_ROOT; }; +"A8BC07BAEA1215B7503E9364" = { isa = PBXBuildFile; fileRef = "A1009AA9F3239FF614E22103"; }; +"1893D6FB6CB3BF8A429B887C" = { isa = PBXGroup; name = "3.7.0 Libraries and Capture"; sourceTree = ""; children = ("2464EE6BFE2AA97DBC5C2913","DC1C21A297BCCD34706DBEE1","CCF46B90050E0BE77D1F5FAA","C3DEFD6B0A505C9AA2ADEB3B","971F1C3D34CF84F153F037EC", "FFA296F39D044DC70C6FCFB7","386691BEF25A11E0954243CD","C9DF7704560822DA03677397","F75B630AE8D4162CD9E45A75","9EA2B6271ECBBEC8E2BE5A67","A1009AA9F3239FF614E22103" ); }; + "8BB8CC2C6D97EC712B6F9399" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "Tests/SoftwareLibraryPublishedGameTests.swift"; "sourceTree" = ""; }; "2716C73C955C5C8E0B2B6C1A" = { "isa" = "PBXBuildFile"; "fileRef" = "8BB8CC2C6D97EC712B6F9399"; }; "1A6A84C4CFAE563E14CE3FF0" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "App/SoftwareLibrarySourceImporter.swift"; "sourceTree" = ""; }; @@ -190,16 +223,20 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6 "CB17E83394A9C5DF26C5FFF1" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.swift"; "path" = "App/MCPPlaytest.swift"; "sourceTree" = ""; }; "05C12D61D4309FF67ECD44D8" = { "isa" = "PBXBuildFile"; "fileRef" = "CB17E83394A9C5DF26C5FFF1"; }; "F59D1FEA561570A5236F53C0" = { "isa" = "PBXBuildFile"; "fileRef" = "CB17E83394A9C5DF26C5FFF1"; }; + +"B1E09D51DE234384B03D6D01" = { isa = PBXFileReference; lastKnownFileType = sourcecode.swift; path = "Tools/Playtest/VideoWriter.swift"; sourceTree = SOURCE_ROOT; }; +"B1E09D51DE234384B03D6D02" = { isa = PBXBuildFile; fileRef = "B1E09D51DE234384B03D6D01"; }; +"B1E09D51DE234384B03D6D03" = { isa = PBXBuildFile; fileRef = "386691BEF25A11E0954243CD"; }; "D481BB9B31A0A44756A2C642" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "sourcecode.cpp.objcpp"; "path" = "Tools/Playtest/main.mm"; "sourceTree" = ""; }; "2CA37FF7143467180924EC4A" = { "isa" = "PBXFileReference"; "explicitFileType" = "compiled.mach-o.executable"; "path" = "vcc-playtest"; "sourceTree" = "BUILT_PRODUCTS_DIR"; }; "D0275CCCC6A237EF6D400FB5" = { "isa" = "PBXBuildFile"; "fileRef" = "D481BB9B31A0A44756A2C642"; }; "E4D502132B13D1D69821BEC7" = { "isa" = "PBXBuildFile"; "fileRef" = "BB79E6426D224A59088F8FC5"; }; -"D889C482CF734BE1E411EACC" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "D0275CCCC6A237EF6D400FB5" ); "runOnlyForDeploymentPostprocessing" = 0; }; +"D889C482CF734BE1E411EACC" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "D0275CCCC6A237EF6D400FB5", "B1E09D51DE234384B03D6D02", "B1E09D51DE234384B03D6D03" ); "runOnlyForDeploymentPostprocessing" = 0; }; "96EC2DA93CC1D27E9CE71ECB" = { "isa" = "PBXFrameworksBuildPhase"; "buildActionMask" = 2147483647; "files" = ( "E4D502132B13D1D69821BEC7" ); "runOnlyForDeploymentPostprocessing" = 0; }; "B26398CF1C4055136A0E5AD8" = { "isa" = "PBXTargetDependency"; "target" = "3289BA136C1065982C4C284C"; }; -"2F408F2A78A3A02A06B97DE3" = { "isa" = "XCBuildConfiguration"; "name" = "Debug"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; -"62FEB1115C3993DF5AE98912" = { "isa" = "XCBuildConfiguration"; "name" = "Release"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; -"BB186D2F0C21A9CDDC88F589" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; +"2F408F2A78A3A02A06B97DE3" = { "isa" = "XCBuildConfiguration"; "name" = "Debug"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; +"62FEB1115C3993DF5AE98912" = { "isa" = "XCBuildConfiguration"; "name" = "Release"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; +"BB186D2F0C21A9CDDC88F589" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "PRODUCT_NAME" = "vcc-playtest"; "SWIFT_VERSION" = "5.0"; "SWIFT_STRICT_CONCURRENCY" = "minimal"; "SKIP_INSTALL" = "YES"; "OTHER_LDFLAGS" = "$(inherited) -framework Foundation -framework AppKit"; }; }; "CC5600E33F7749FAC3723D73" = { "isa" = "XCConfigurationList"; "buildConfigurations" = ( "2F408F2A78A3A02A06B97DE3", "62FEB1115C3993DF5AE98912", "BB186D2F0C21A9CDDC88F589" ); "defaultConfigurationIsVisible" = 0; "defaultConfigurationName" = "Release"; }; "3F1A4FB64B04593F884782C9" = { "isa" = "PBXNativeTarget"; "name" = "vcc-playtest"; "productName" = "vcc-playtest"; "productReference" = "2CA37FF7143467180924EC4A"; "productType" = "com.apple.product-type.tool"; "buildConfigurationList" = "CC5600E33F7749FAC3723D73"; "buildPhases" = ( "D889C482CF734BE1E411EACC", "96EC2DA93CC1D27E9CE71ECB" ); "buildRules" = (); "dependencies" = ( "B26398CF1C4055136A0E5AD8" ); }; "2807D2B83250A4DAA977771A" = { "isa" = "PBXTargetDependency"; "target" = "3F1A4FB64B04593F884782C9"; }; @@ -657,7 +694,7 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6 "CEEB1C09197841D54A6AD5E8" = { "isa" = "PBXBuildFile"; "fileRef" = "2ECB4508563F3873B436B9EE"; }; "3AE8BC7E4A8F296EB0B7AEFD" = { "isa" = "PBXFileReference"; "lastKnownFileType" = "folder"; "path" = "Resources/About"; "sourceTree" = ""; }; "370CBA86395A91DC191231AB" = { "isa" = "PBXBuildFile"; "fileRef" = "3AE8BC7E4A8F296EB0B7AEFD"; }; - "53AAABD74B976C180137280A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "INFOPLIST_KEY_VCCCompanionProtocolVersion" = "1"; "COPY_PHASE_STRIP" = "NO"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG VCC_UI_TESTING"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2"; "INFOPLIST_FILE" = "App/Info.plist"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "ENABLE_USER_SCRIPT_SANDBOXING" = "NO"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC OSS UI Tests"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCC Plus OSS"; "PRODUCT_MODULE_NAME" = "VCCMac"; "OTHER_LDFLAGS" = "$(inherited) -larchive -framework Network"; "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.uitesting"; "CURRENT_PROJECT_VERSION" = "60"; }; }; + "53AAABD74B976C180137280A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "INFOPLIST_KEY_VCCCompanionProtocolVersion" = "1"; "COPY_PHASE_STRIP" = "NO"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG VCC_UI_TESTING"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0"; "INFOPLIST_FILE" = "App/Info.plist"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "ENABLE_USER_SCRIPT_SANDBOXING" = "NO"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC OSS UI Tests"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCC Plus OSS"; "PRODUCT_MODULE_NAME" = "VCCMac"; "OTHER_LDFLAGS" = "$(inherited) -larchive -framework Network"; "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.uitesting"; "CURRENT_PROJECT_VERSION" = "63"; }; }; "4478F567020A87952E7BF5BE" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "PRODUCT_NAME" = "VCCCore"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "SKIP_INSTALL" = "YES"; "ENABLE_TESTABILITY" = "YES"; "EXECUTABLE_PREFIX" = "lib"; "GCC_PREPROCESSOR_DEFINITIONS" = ( "$(inherited)", "USE_DEBUG_TESTS=false" ); }; }; "6E5C730B0C1F6F8D5EB8881A" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "ONLY_ACTIVE_ARCH" = "NO"; "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "CLANG_ENABLE_MODULES" = "YES"; "CODE_SIGN_IDENTITY" = "-"; "MACOSX_DEPLOYMENT_TARGET" = "14.0"; "CLANG_CXX_LANGUAGE_STANDARD" = "c++17"; "ENABLE_TESTABILITY" = "YES"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "ARCHS" = "$(ARCHS_STANDARD)"; "HEADER_SEARCH_PATHS" = ( "$(inherited)", "$(SRCROOT)/../../src/core", "$(SRCROOT)/../../src" ); "SDKROOT" = "macosx"; "SWIFT_VERSION" = "5.0"; "CODE_SIGN_STYLE" = "Manual"; "DEVELOPMENT_TEAM" = ""; "VCC_BUILD_CONTENT_PROFILE" = "source"; "CLANG_ENABLE_OBJC_ARC" = "YES"; "CLANG_CXX_LIBRARY" = "libc++"; }; }; "9D61CCD0757A3005AF102148" = { "isa" = "XCBuildConfiguration"; "name" = "UITesting"; "buildSettings" = { "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "$(PLATFORM_DIR)/Developer/Library/Frameworks" ); "SWIFT_ACTIVE_COMPILATION_CONDITIONS" = "$(inherited) DEBUG"; "DEBUG_INFORMATION_FORMAT" = "dwarf"; "ENABLE_TESTABILITY" = "YES"; "GENERATE_INFOPLIST_FILE" = "YES"; "SWIFT_OBJC_BRIDGING_HEADER" = "$(SRCROOT)/Bridge/VCCMac-Bridging-Header.h"; "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; "PRODUCT_NAME" = "VCCCoreTests"; "OTHER_LDFLAGS" = ( "$(inherited)", "-larchive", "-framework", "Network", "-framework", "XCTest" ); "FRAMEWORK_SEARCH_PATHS" = ( "$(inherited)", "$(PLATFORM_DIR)/Developer/Library/Frameworks" ); "PRODUCT_BUNDLE_IDENTIFIER" = "com.brianholman.vccplus.oss.mac.coretests"; "GCC_PREPROCESSOR_DEFINITIONS" = ( "$(inherited)", "DEBUG=1" ); }; }; @@ -1591,7 +1628,7 @@ DE524C5CEEB7201C899C173E = { isa = PBXBuildFile; fileRef = 2DDBE7F7A3DE72AD67CB6 "FEE92F734ED030D5B7F43539" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; - "files" = ( + "files" = ( "AF8FCAD6F87C7AAA1B8398AF", "77B510203B32A69B19F95BAF", "31E94EDA2FFA2E36C43113B4", "F69F722FBCDDA97A8FB48C96", "2921AED78693AE35B29C2B88", "E4061E4E0AB7CA7A47624B27", D802CE11D18A211CE0CE5350, 4F53DC2D981592B5A8E3FD11, @@ -1629,7 +1666,7 @@ CF5FFC06DB9D6CE02797B0DB, "buildActionMask" = 2147483647; "files" = ( "DA353EB8E8234292B4FCD1A9", "4D9D69AC7FDB3596BA58736A", "1E9C301114564D29D79F701A", "6E555C622A520877AB5EA78E", "6A46CA9A9BCDA42FDEDE0BFF", "370CBA86395A91DC191231AB", "296ADED30AE511DEAD130956", -"56FE1E32C4755CD5F5692180", "1069B9674C8A658B4902A323" ); +"56FE1E32C4755CD5F5692180", "1069B9674C8A658B4902A323", "B7A7B5BFA3C251D22DC8561A" ); "runOnlyForDeploymentPostprocessing" = 0; }; "730C02D607B0893E83B3D2EA" = { @@ -1661,8 +1698,8 @@ CF5FFC06DB9D6CE02797B0DB, "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC Plus OSS"; "INFOPLIST_FILE" = "App/Info.plist"; - "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2"; - "CURRENT_PROJECT_VERSION" = "60"; + "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0"; + "CURRENT_PROJECT_VERSION" = "63"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "GCC_OPTIMIZATION_LEVEL" = "0"; "SWIFT_OPTIMIZATION_LEVEL" = "-Onone"; @@ -1682,8 +1719,8 @@ CF5FFC06DB9D6CE02797B0DB, "INFOPLIST_KEY_LSApplicationCategoryType" = "public.app-category.entertainment"; "INFOPLIST_KEY_CFBundleDisplayName" = "VCC Plus OSS"; "INFOPLIST_FILE" = "App/Info.plist"; - "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.6.2"; - "CURRENT_PROJECT_VERSION" = "60"; + "VCC_BUILD_CONTENT_PROFILE" = "source"; "VCC_SOURCE_ROM_DIR" = ""; "MARKETING_VERSION" = "3.7.0"; + "CURRENT_PROJECT_VERSION" = "63"; "LD_RUNPATH_SEARCH_PATHS" = ( "$(inherited)", "@executable_path/../Frameworks" ); "GCC_OPTIMIZATION_LEVEL" = "2"; "SWIFT_OPTIMIZATION_LEVEL" = "-O"; @@ -1931,7 +1968,7 @@ CF5FFC06DB9D6CE02797B0DB, "E08DF13589706C56B1CA802C" = { "isa" = "PBXSourcesBuildPhase"; "buildActionMask" = 2147483647; - "files" = ( + "files" = ("9944B924F1F25A1C31E87133", "F97715060F4E2618EB80AFDE", "03B7230E381C6D102C3BF95F", "A8BC07BAEA1215B7503E9364", "6EB73875746CB21BDF3E7AB3", "B07B7E2C92770E75D506BABD", "6229E570150FBFD4653A4E38", "A1DC73569D936F22FB4E554E", "F770A2E6626B73FE7071CB9A", "337343EA275BED13114792F9", 9788522075DEBF3EFB11491B, @@ -1977,7 +2014,7 @@ B7E302195F6A9DD0DEDAAE81, "F69A6B3CA6DADD9644B13172", "E28A5CEB274AF11A9D4D64A7" "00749908191B1902B8091B7B" = { "isa" = "PBXResourcesBuildPhase"; "buildActionMask" = 2147483647; - "files" = ( "B7A5DC0C696900499A34C88C", "C61C0FB4458A570B13BABD15", "92E50AAAE9437FD82A2AEA5F", "204BF507804696BC356530AC", "321E79BF2EA9B8C75D314039", "E33F4A7F24184C7137E4A4B0" ); + "files" = ( "B7A5DC0C696900499A34C88C", "C61C0FB4458A570B13BABD15", "92E50AAAE9437FD82A2AEA5F", "204BF507804696BC356530AC", "321E79BF2EA9B8C75D314039", "E33F4A7F24184C7137E4A4B0", "17CB263DB27EF1128FBF12D4" ); "runOnlyForDeploymentPostprocessing" = 0; }; "C8D1DE9C6F7B72659C81D2D8" = { @@ -2058,8 +2095,8 @@ B7E302195F6A9DD0DEDAAE81, "F69A6B3CA6DADD9644B13172", "E28A5CEB274AF11A9D4D64A7" }; "DC76E9F0C0006E8F919E0C51" = { "isa" = "PBXGroup"; - "children" = ( -8C395B59B89AD94C577095CC, "01B2CD4F57507B2482FA993D", "BDB9AD06DF2962978FC5E007", "D481BB9B31A0A44756A2C642", "CB17E83394A9C5DF26C5FFF1", "C7751857B7E10600A291771F", "FAD4DB6739AE4807ADA3C27B", "91E042FFB6E1419B8931E646", "067A7A84E2E4F118095A8BB3", "9DCB740145E540C996E6692F", "312B00F5A13D4921AE264A2A", "5B5BB817A4524500B7E3CB1E", "53272DD2F81E40B2AF672610", "0F12DBE149CE0CD675AA66F8", "52B95FA5ED31A04909EFE857", "781F14A708182E90BDE108E3", "00B808A7780A251CC29CB06B", "7E6AA63365575C8888A99124", "C445DF085F7C807B908C19CB", "5421B06971D847A1A805F702", "9254269AE4824C5B8AAA4996", "16504192DF96663A78D5DFA8", "27644F1DECBC432E1B2768B8", "D333DD1A438EB4BC0A55464B", "C321FDC49814C39490B20F79", "0F7A6228BA94CC0C12A84F39", "16D176D2DB64F7417D6ACFC8", "530ADB2D5152809BD56B4BED", "5F75B5064C7FDFAC8800C0D3", "F12C3866E3125783A11526D4", "F797210E51F1F0B1CD8FF395", "49569D327A43047408F2DEAE", "5A3424F913D65182707784B8", "51E4344CADBA88EC0446EEA7", "792A514D818919EDF5F34717", "A1F993CAF2D203E517890FD7", "901D1E1FBB7B60F19AD95144", "07DA06A775F9267984E51EEC", "11A4CB4B8DF107985B0CB524", "7B1F352E41BE60388711F023", "9E3128773E24559995067F7F", "14868044C1345013A7F60685", "11EC6918F3B91AEE9FFB49F7", "9D6A737AD809CB34F0980691", "FFC326493D8F4603BD28BB6B", "C6A3EB89A975DDC859E73A36", "8BB8CC2C6D97EC712B6F9399", "EEEDC5273980EA83CBC757C5", "733493F7C9E00346B4010B62", "33C98A5D72682FD6AC0E5F62", "A748DE9CAD2C1300FF48663D", "F57F14F4BFF647EF7FDB64CC", "5BFFA01A19C5FC41EF60EE4A", "1B9725597009D3DE68DF62E3", "F80D3145FD907815FDAF4BA7", "1A6A84C4CFAE563E14CE3FF0", "58F6CDBEF369605DFC3FCA85", "F415937106477DDE7F72A7B8", "14F91CCC9DF1CB8D35001AEE", "EFF84673C3646AA99164A863", "5B72E96E835077666362CF7A", "A39C36931B6A59B325F0FB90", "B64B0E42CAB9E1342A8BD94F", "F0C6E8F2BD38C724C36913D6", "6CE23109A4C2422F878E5C78", "BCCC0E3132CFE859BA8542F6", "BB100B517FD5ADB833B0B9C0", "9426E9B4DB9CAF1E6EAFA927", "EF7750B1163369DD13DD5CE1", "A7B7BA8AEF5A062CF3C843DF", "F6B4DAA016C1911A09758E63", "5143771599404245B3DEA52E", "760BA2B4DE5F2E924A84BF1D", "C2646126B83489FB52DC1D6E", "14AE753173354D3EB5864563", "F82EC7B41E234EADA1CF84D1", "A3C1EA3C22CE43C8892A802C", "BA967E7658F745E1BC0ED7F2", "4F0596325DE3470A80EFE4EA", "3BDB3184317E405C82B06486", "5866911856DA41268827A601", "D168EF13EB20422AACCD96E2", "15ABD5DCBAFD4B6DAE418797", "BE84A652C2B04396BCBB921A", "455C6D7E1EB546C4B5A75AAF", "D70CBBA8530C6BC9B02AB379", "4B8AEF880E57EE0677BC1153", "F54CF4225FFCED7D7F647951", "67FB937B65ACB9D4278CFA4E", "3598AF219C2977DF6C4A5C2F", "F87E4A23CC0809CEA94F12E6", "E8ACFC9B89CAD012A308C316", "9DB93A677589CE78172A44A7", "4F76A349DB6B5A0F9E6A2C43", "E81B18C39152139A6105B84E", "25A93A2467BFAAED3F191E1B", "5BFC3293E94D0E3351244621", "D8248EBAF73CAB10C7C448FB", "217DC0F34A56DA5C4BB91E77", "A0DF98B8016880CAF0C0CD58", "42D841F636995F06C9332A0C", "31A4FF4E73AF3B5CFC309F60", "749C4BDB6AC37B600911C9C9", "39A991CE28D47963DE7E15F3", "A18B9CFC47DCA8A891571318", "1A65828188431AEC64A2EF1F", "C0CF07236765657B1CF3A441", "6DEBF620342B2A4B3AE5BCB1", "90FBFEB8BEE4D4B5EA4FF8B0", "6679E2C250A647804D193528", "8692D98EA40F7B2EE5EE136F", "3D4B95521A762F5E8B8ABB14", "EBC28D481E37A6D95550ED04", "9749C3A6E351964032384A3D", "79604D0603B58EC1CC2A9DA2", "91B7567AB5800567DAC343CD", "AFE25089ECEE6A77C768C432", "B4051C9774DFB5E15D886F79", "FB41D37D8F4F766B6F337A30", "5D4CCAE92059989714989D6B", "0F7F71696BF73C2A0921178C", "C05CBCBB0DDDF3E9B71ED4AB", "6E861FD0CA44590764FE438B", "C99C3267AC413B97551BD1EF", "472AC2CCB232639BB577696C", "A02293D0378FF4DA75C39EB5", "18267AA57F2798E15C7DEA3C", "4E1B73C4B6AD14CC00967423", "EDC3E15D86A8D4874AD0C180", "2711817C64CE46C182C5A8E9", "E5ADAD330B664E2BBC535C6A", "C6249A99265F026C199FD295", "5E52CBA4F430EC64E65E4239", "1AAB13C7AEC9576FCE909B30", "ACAA7FB0B84ABBE3CC50469D", "FC1ACF21BD5C46FC8CF22B60", "F147DB0A0B7B363C0181BBC4", "CE053132399860C266BA4115", "36D1A8AB53B6003A6A4B68D1", "45A42226A532DA306D381520", "29CCFF9C7E6B33DDB3DDA617", "EF0BA4677314B7DCCE726359", "68ABF5E4DB7DD34B8CC7EBA4", "2C765C18C64E564F954A7173", "9B68DF21D14BBFC0C977A0A8", "4C0DBA3B44DA84392AA3796A", "80C6105AD9495A0EB1F4A58C", "9F3C15DE610B4BFABF101002", "9F3C15DE610B4BFABF101003", "9F3C15DE610B4BFABF101001", "7339FE1A16674B2588333001", "3AE8BC7E4A8F296EB0B7AEFD", "2ECB4508563F3873B436B9EE", "277E06BEAA4F5310C0718CF2", "796FD8945B70098E2E2C7B92", + "children" = ( "1893D6FB6CB3BF8A429B887C", +8C395B59B89AD94C577095CC, "01B2CD4F57507B2482FA993D", "BDB9AD06DF2962978FC5E007", "D481BB9B31A0A44756A2C642", "B1E09D51DE234384B03D6D01", "CB17E83394A9C5DF26C5FFF1", "C7751857B7E10600A291771F", "FAD4DB6739AE4807ADA3C27B", "91E042FFB6E1419B8931E646", "067A7A84E2E4F118095A8BB3", "9DCB740145E540C996E6692F", "312B00F5A13D4921AE264A2A", "5B5BB817A4524500B7E3CB1E", "53272DD2F81E40B2AF672610", "0F12DBE149CE0CD675AA66F8", "52B95FA5ED31A04909EFE857", "781F14A708182E90BDE108E3", "00B808A7780A251CC29CB06B", "7E6AA63365575C8888A99124", "C445DF085F7C807B908C19CB", "5421B06971D847A1A805F702", "9254269AE4824C5B8AAA4996", "16504192DF96663A78D5DFA8", "27644F1DECBC432E1B2768B8", "D333DD1A438EB4BC0A55464B", "C321FDC49814C39490B20F79", "0F7A6228BA94CC0C12A84F39", "16D176D2DB64F7417D6ACFC8", "530ADB2D5152809BD56B4BED", "5F75B5064C7FDFAC8800C0D3", "F12C3866E3125783A11526D4", "F797210E51F1F0B1CD8FF395", "49569D327A43047408F2DEAE", "5A3424F913D65182707784B8", "51E4344CADBA88EC0446EEA7", "792A514D818919EDF5F34717", "A1F993CAF2D203E517890FD7", "901D1E1FBB7B60F19AD95144", "07DA06A775F9267984E51EEC", "11A4CB4B8DF107985B0CB524", "7B1F352E41BE60388711F023", "9E3128773E24559995067F7F", "14868044C1345013A7F60685", "11EC6918F3B91AEE9FFB49F7", "9D6A737AD809CB34F0980691", "FFC326493D8F4603BD28BB6B", "C6A3EB89A975DDC859E73A36", "8BB8CC2C6D97EC712B6F9399", "EEEDC5273980EA83CBC757C5", "733493F7C9E00346B4010B62", "33C98A5D72682FD6AC0E5F62", "A748DE9CAD2C1300FF48663D", "F57F14F4BFF647EF7FDB64CC", "5BFFA01A19C5FC41EF60EE4A", "1B9725597009D3DE68DF62E3", "F80D3145FD907815FDAF4BA7", "1A6A84C4CFAE563E14CE3FF0", "58F6CDBEF369605DFC3FCA85", "F415937106477DDE7F72A7B8", "14F91CCC9DF1CB8D35001AEE", "EFF84673C3646AA99164A863", "5B72E96E835077666362CF7A", "A39C36931B6A59B325F0FB90", "B64B0E42CAB9E1342A8BD94F", "F0C6E8F2BD38C724C36913D6", "6CE23109A4C2422F878E5C78", "BCCC0E3132CFE859BA8542F6", "BB100B517FD5ADB833B0B9C0", "9426E9B4DB9CAF1E6EAFA927", "EF7750B1163369DD13DD5CE1", "A7B7BA8AEF5A062CF3C843DF", "F6B4DAA016C1911A09758E63", "5143771599404245B3DEA52E", "760BA2B4DE5F2E924A84BF1D", "C2646126B83489FB52DC1D6E", "14AE753173354D3EB5864563", "F82EC7B41E234EADA1CF84D1", "A3C1EA3C22CE43C8892A802C", "BA967E7658F745E1BC0ED7F2", "4F0596325DE3470A80EFE4EA", "3BDB3184317E405C82B06486", "5866911856DA41268827A601", "D168EF13EB20422AACCD96E2", "15ABD5DCBAFD4B6DAE418797", "BE84A652C2B04396BCBB921A", "455C6D7E1EB546C4B5A75AAF", "D70CBBA8530C6BC9B02AB379", "4B8AEF880E57EE0677BC1153", "F54CF4225FFCED7D7F647951", "67FB937B65ACB9D4278CFA4E", "3598AF219C2977DF6C4A5C2F", "F87E4A23CC0809CEA94F12E6", "E8ACFC9B89CAD012A308C316", "9DB93A677589CE78172A44A7", "4F76A349DB6B5A0F9E6A2C43", "E81B18C39152139A6105B84E", "25A93A2467BFAAED3F191E1B", "5BFC3293E94D0E3351244621", "D8248EBAF73CAB10C7C448FB", "217DC0F34A56DA5C4BB91E77", "A0DF98B8016880CAF0C0CD58", "42D841F636995F06C9332A0C", "31A4FF4E73AF3B5CFC309F60", "749C4BDB6AC37B600911C9C9", "39A991CE28D47963DE7E15F3", "A18B9CFC47DCA8A891571318", "1A65828188431AEC64A2EF1F", "C0CF07236765657B1CF3A441", "6DEBF620342B2A4B3AE5BCB1", "90FBFEB8BEE4D4B5EA4FF8B0", "6679E2C250A647804D193528", "8692D98EA40F7B2EE5EE136F", "3D4B95521A762F5E8B8ABB14", "EBC28D481E37A6D95550ED04", "9749C3A6E351964032384A3D", "79604D0603B58EC1CC2A9DA2", "91B7567AB5800567DAC343CD", "AFE25089ECEE6A77C768C432", "B4051C9774DFB5E15D886F79", "FB41D37D8F4F766B6F337A30", "5D4CCAE92059989714989D6B", "0F7F71696BF73C2A0921178C", "C05CBCBB0DDDF3E9B71ED4AB", "6E861FD0CA44590764FE438B", "C99C3267AC413B97551BD1EF", "472AC2CCB232639BB577696C", "A02293D0378FF4DA75C39EB5", "18267AA57F2798E15C7DEA3C", "4E1B73C4B6AD14CC00967423", "EDC3E15D86A8D4874AD0C180", "2711817C64CE46C182C5A8E9", "E5ADAD330B664E2BBC535C6A", "C6249A99265F026C199FD295", "5E52CBA4F430EC64E65E4239", "1AAB13C7AEC9576FCE909B30", "ACAA7FB0B84ABBE3CC50469D", "FC1ACF21BD5C46FC8CF22B60", "F147DB0A0B7B363C0181BBC4", "CE053132399860C266BA4115", "36D1A8AB53B6003A6A4B68D1", "45A42226A532DA306D381520", "29CCFF9C7E6B33DDB3DDA617", "EF0BA4677314B7DCCE726359", "68ABF5E4DB7DD34B8CC7EBA4", "2C765C18C64E564F954A7173", "9B68DF21D14BBFC0C977A0A8", "4C0DBA3B44DA84392AA3796A", "80C6105AD9495A0EB1F4A58C", "9F3C15DE610B4BFABF101002", "9F3C15DE610B4BFABF101003", "9F3C15DE610B4BFABF101001", "7339FE1A16674B2588333001", "3AE8BC7E4A8F296EB0B7AEFD", "2ECB4508563F3873B436B9EE", "277E06BEAA4F5310C0718CF2", "796FD8945B70098E2E2C7B92", "445AFB9A10CBBAE48539A39F", "6BD293692BB0058E467291CC", "C015745C6395762B28454414", diff --git a/src/core/MachineSession.cpp b/src/core/MachineSession.cpp index d041b26..1545f2b 100644 --- a/src/core/MachineSession.cpp +++ b/src/core/MachineSession.cpp @@ -87,15 +87,55 @@ struct MachineSession::Impl final : MachineHost, VideoHost, CpuDebugHooks, Devic } return true; } + struct ResidencyProof { + std::map> matchingOwners; + std::uint64_t fingerprint = 0; + bool contains(const DebugBankedModule& module) const { + const auto found = matchingOwners.find(module.overlayGroup); + return found != matchingOwners.end() && found->second.size() == 1 && found->second.front() == module.overlayOwner; + } + }; + ResidencyProof bankedResidency(const MMUState& mmu) const { + // Re-read complete executable guards on the serialized machine queue. + // Guest stores do not increment the host program revision, and physical + // page identity alone cannot identify code that a loader has replaced. + std::map> owners; + for (const auto& module : developmentModules) if (!module.overlayGroup.empty()) { + auto& group = owners[module.overlayGroup]; + const auto inserted = group.emplace(module.overlayOwner, true); + inserted.first->second = bankedModuleMatches(module, mmu) && inserted.first->second; + } + ResidencyProof result; + if (owners.empty()) return result; + std::uint64_t hash = 14695981039346656037ull; + auto number = [&](std::uint64_t value) { + for (unsigned i = 0; i < 8; ++i) { hash ^= (value >> (8*i)) & 255; hash *= 1099511628211ull; } + }; + auto text = [&](const std::string& value) { + number(value.size()); for (unsigned char byte : value) { hash ^= byte; hash *= 1099511628211ull; } + }; + for (const auto& group : owners) { + auto& matches = result.matchingOwners[group.first]; + for (const auto& owner : group.second) if (owner.second) matches.push_back(owner.first); + text(group.first); number(matches.size()); + for (const auto& owner : matches) text(owner); + } + result.fingerprint = hash ? hash : 1; + return result; + } + bool residentModuleMatches(const DebugBankedModule& module, const MMUState& mmu, const ResidencyProof& proof) const { + return module.overlayGroup.empty() ? bankedModuleMatches(module, mmu) : proof.contains(module); + } bool bankedMatchesAt(std::uint16_t address, bool forBreakpoint = false) const { const auto mmu = GetMMUState(); + const auto residency = bankedResidency(mmu); return std::any_of(developmentModules.begin(), developmentModules.end(), [&](const auto& module) { if (forBreakpoint && module.breakpointAddresses && std::find(module.breakpointAddresses->begin(), module.breakpointAddresses->end(), address) == module.breakpointAddresses->end()) return false; return std::any_of(module.guards.begin(), module.guards.end(), [&](const auto& guard) { return address >= guard.address && std::size_t(address) - guard.address < guard.bytes.size(); - }) && bankedModuleMatches(module, mmu); + }) && residentModuleMatches(module, mmu, residency); }); } // Independent of breakpoint ownership: Run releases its temporary entry breakpoint. @@ -140,9 +180,10 @@ struct MachineSession::Impl final : MachineHost, VideoHost, CpuDebugHooks, Devic auto found = candidates.first; if (step.banked && found != candidates.second) { const auto mmu = GetMMUState(); + const auto residency = bankedResidency(mmu); found = std::find_if(candidates.first, candidates.second, [&](const auto& item) { return std::any_of(developmentModules.begin(), developmentModules.end(), [&](const auto& module) { - return module.identifier == item.second.moduleIdentifier && bankedModuleMatches(module, mmu); + return module.identifier == item.second.moduleIdentifier && residentModuleMatches(module, mmu, residency); }); }); if (found == candidates.second) { @@ -1436,6 +1477,9 @@ void MachineSession::debuggerArmBankedDevelopmentBreakpoints(const std::vector identifiers; std::vector> moduleCoverage; + using PhysicalSpan = std::pair; + std::vector> physicalCoverage; + std::map> overlayOwners; std::vector starts(65536, false); std::size_t total = 0; for (const auto& module : modules) { @@ -1443,6 +1487,13 @@ void MachineSession::debuggerArmBankedDevelopmentBreakpoints(const std::vector 128 || module.overlayOwner.size() > 128 || + module.overlayGroup.find('\0') != std::string::npos || module.overlayOwner.find('\0') != std::string::npos) + throw std::invalid_argument("Physical-code overlay modules require bounded group and owner identities together"); + if (!module.overlayGroup.empty()) { + auto& owners = overlayOwners[module.overlayGroup]; + if (std::find(owners.begin(), owners.end(), module.overlayOwner) == owners.end()) owners.push_back(module.overlayOwner); + } if (module.pages.empty() || module.pages.size() > 8 || module.guards.empty() || module.guards.size() > 65536) throw std::invalid_argument("Banked modules require physical page mappings and verified code"); std::array mapped{}; @@ -1452,6 +1503,7 @@ void MachineSession::debuggerArmBankedDevelopmentBreakpoints(const std::vector covered; + std::vector physical; for (const auto& guard : module.guards) { if (guard.bytes.empty() || std::size_t(guard.address) + guard.bytes.size() > 0xfe00) throw std::invalid_argument("Banked code requires nonwrapping RAM ranges below FE00"); @@ -1464,7 +1516,18 @@ void MachineSession::debuggerArmBankedDevelopmentBreakpoints(const std::vectorphysicalPage * 8192 + static_cast(at % 8192); + physical.emplace_back(start, start + static_cast(next - at)); + at = next; + } } + std::sort(physical.begin(), physical.end()); + for (std::size_t i = 1; i < physical.size(); ++i) + if (physical[i].first < physical[i-1].second) + throw std::invalid_argument("One module's executable code must not alias its own physical RAM"); if (module.breakpointAddresses) { if (module.breakpointAddresses->size() > 1024) throw std::invalid_argument("Too many module-qualified source breakpoints"); @@ -1480,16 +1543,32 @@ void MachineSession::debuggerArmBankedDevelopmentBreakpoints(const std::vector 64) + throw std::invalid_argument("Physical-code overlay declarations exceed 64 groups"); + for (const auto& group : overlayOwners) if (group.second.size() < 2) + throw std::invalid_argument("A physical-code overlay group requires executable modules for at least two owners"); for (auto point : breakpoints) if (!starts[point]) throw std::invalid_argument("Each banked breakpoint must name at least one qualified module code range"); // Validate everything before touching the running machine or its points. @@ -1687,6 +1766,7 @@ Snapshot MachineSession::snapshot() const { } result.debuggerMappingFingerprint = mappingFingerprint(GetMMUState()); result.debuggerBankedDevelopment = !impl->developmentModules.empty(); + if (result.debuggerBankedDevelopment) result.debuggerResidencyFingerprint = impl->bankedResidency(GetMMUState()).fingerprint; if (!result.debuggerBankedDevelopment && !impl->developmentGuards.empty() && impl->state == RunState::Paused && impl->developmentAttached && !impl->flatGuardsMatch()) impl->developmentAttached = false; result.debuggerDevelopmentAttached = result.debuggerBankedDevelopment ? impl->bankedMatchesAt(impl->CpuState().PC) : @@ -1991,13 +2071,16 @@ DebugGraphicsCapture MachineSession::debuggerGraphicsCapture(const std::optional void MachineSession::debuggerStepSource(SourceStepMode mode, const std::vector& instructions, std::uint64_t expectedGeneration, std::uint64_t expectedProgramRevision, std::uint64_t expectedMappingFingerprint, std::uint16_t expectedPC, - unsigned maximumInstructions, unsigned maximumFrames) { + unsigned maximumInstructions, unsigned maximumFrames, std::uint64_t expectedResidencyFingerprint) { if (!impl || impl->state != RunState::Paused) throw std::logic_error("Pause at a verified C source location before stepping"); if (mode != SourceStepMode::Into && mode != SourceStepMode::Over && mode != SourceStepMode::Out) throw std::invalid_argument("Unknown C stepping mode"); if (expectedGeneration != generation || expectedProgramRevision != debuggerProgramRevision || expectedMappingFingerprint != mappingFingerprint(GetMMUState()) || expectedPC != impl->CpuState().PC) throw std::invalid_argument("The paused program changed; refresh before C stepping"); + const auto residency = impl->bankedResidency(GetMMUState()); + if (residency.fingerprint != expectedResidencyFingerprint) + throw std::invalid_argument("The resident physical-code overlay changed; refresh before C stepping"); if (instructions.empty() || instructions.size() > 65536 || !maximumInstructions || maximumInstructions > 1000000 || !maximumFrames || maximumFrames > 600) throw std::invalid_argument("Invalid C step locations or execution limit"); Impl::SourceStep plan; @@ -2037,7 +2120,7 @@ void MachineSession::debuggerStepSource(SourceStepMode mode, const std::vectordevelopmentModules.begin(), impl->developmentModules.end(), [&](const auto& module) { - return module.identifier == item.second.moduleIdentifier && impl->bankedModuleMatches(module, mmu); + return module.identifier == item.second.moduleIdentifier && impl->residentModuleMatches(module, mmu, residency); }); }); } diff --git a/src/core/MachineSession.h b/src/core/MachineSession.h index cad90f7..ec7e8f2 100644 --- a/src/core/MachineSession.h +++ b/src/core/MachineSession.h @@ -49,6 +49,9 @@ struct Snapshot { std::uint64_t debuggerProgramRevision = 0, debuggerMappingFingerprint = 0; bool debuggerDevelopmentAttached = false, debuggerAssemblyAttached = false, debuggerSourceStepping = false; bool debuggerBankedDevelopment = false; + // Fresh group/owner residency proof, never inferred from a physical address. + // Zero identifies declarations without physical-code overlay groups. + std::uint64_t debuggerResidencyFingerprint = 0; bool basicDebugAttached = false; int basicStoppedLine = -1, basicSourceOffset = -1; unsigned basicSourceLength = 0; @@ -75,6 +78,7 @@ struct DebugBankedModule { // Absent preserves logical-point behavior. An explicit set qualifies only // these stops to this module; an empty set retains source/step evidence only. std::optional> breakpointAddresses = std::nullopt; + std::string overlayGroup = {}, overlayOwner = {}; }; enum class SourceStepMode { Into, Over, Out }; struct DebugSourceInstruction { @@ -257,7 +261,8 @@ public: void debuggerStepSource(SourceStepMode mode, const std::vector& instructions, std::uint64_t expectedGeneration, std::uint64_t expectedProgramRevision, std::uint64_t expectedMappingFingerprint, std::uint16_t expectedPC, - unsigned maximumInstructions = 1000000, unsigned maximumFrames = 600); + unsigned maximumInstructions = 1000000, unsigned maximumFrames = 600, + std::uint64_t expectedResidencyFingerprint = 0); void debuggerSetPC(std::uint16_t address); // paused only, same ForcePC semantics as Windows void debuggerSetBreakpoints(std::vector addresses); void debuggerConfigureBreakpoints(std::vector enabled, std::vector disabled); diff --git a/tests/core/BinaryChecks.cpp b/tests/core/BinaryChecks.cpp index 5a1df19..40c107e 100644 --- a/tests/core/BinaryChecks.cpp +++ b/tests/core/BinaryChecks.cpp @@ -264,6 +264,130 @@ void checkBankedDevelopment(Processor processor) { machine.debuggerClearDevelopmentBreakpoints(); require(!machine.snapshot().debuggerBankedDevelopment, "Explicit detach clears bank-qualified mode"); } +void checkPhysicalOverlayDevelopment(Processor processor) { + const Bytes a{0x12,0x86,0x11,0xb7,0x50,0x00,0x7e,0x11,0x00}; + const Bytes b{0x12,0x86,0x22,0xb7,0x50,0x00,0x7e,0x12,0x00}; + auto loader = [](unsigned source, unsigned count) -> Bytes { + // LDX #$4000; LDY #source; LDB #count; + // loop: LDA ,Y+; STA ,X+; DECB; BNE loop; JMP $4000. + return {0x8e,0x40,0x00,0x10,0x8e,std::uint8_t(source>>8),std::uint8_t(source),0xc6,std::uint8_t(count), + 0xa6,0xa0,0xa7,0x80,0x5a,0x26,0xf9,0x7e,0x40,0x00}; + }; + const auto loadA = loader(0x2000, unsigned(a.size())); + const auto loadB = loader(0x2100, unsigned(b.size())); + auto modules = [&] { + return std::vector{ + {"a",{{2,2}},{{0x4000,a}},std::nullopt,"game","A"}, + {"b",{{2,2}},{{0x4000,b}},std::nullopt,"game","B"}, + {"loader",{{0,0}},{{0x1000,loadA},{0x1100,loadB},{0x1200,loadA}}} + }; + }; + auto load = [&](MachineSession& machine, const Bytes& next, unsigned count) { + machine.loadDiagnostic(processor); + MmuSetMapType(1); Set_MmuEnabled(1); + for (unsigned page=0;page<8;++page) SetMmuRegister(page,page); + Bytes image; + block(image,0x1000,loadA); block(image,0x1100,loader(0x2100,count)); block(image,0x1200,loadA); + block(image,0x2000,a); block(image,0x2100,next); block(image,0x4800,{0xaa}); + finish(image,0x1000); machine.debuggerLoadBinary(image,0x1000); + }; + auto run = [](MachineSession& machine) { + machine.resume(); + for (unsigned n=0;n<10 && machine.snapshot().state==RunState::Running;++n) machine.advance(); + require(machine.snapshot().state==RunState::Paused && machine.snapshot().cpu.PC==0x4000, + "Guest overlay loader reaches its qualified or independent manual entry stop"); + }; + { + MachineSession machine; load(machine,b,unsigned(b.size())); + const auto evidence = modules(); + machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},evidence); + run(machine); const auto first=machine.snapshot(); + require(first.debuggerDevelopmentAttached && first.debuggerResidencyFingerprint!=0 && MemRead8(0x4002)==0x11, + "Actual guest stores install owner A in declared shared physical RAM on both CPUs"); + run(machine); const auto second=machine.snapshot(); + require(second.debuggerDevelopmentAttached && second.debuggerResidencyFingerprint!=first.debuggerResidencyFingerprint && MemRead8(0x4002)==0x22 && + second.debuggerMappingFingerprint==first.debuggerMappingFingerprint && second.debuggerProgramRevision==first.debuggerProgramRevision, + "Replacing shared physical code changes residency without a mapping or host program epoch change"); + run(machine); const auto third=machine.snapshot(); + require(third.debuggerDevelopmentAttached && third.debuggerResidencyFingerprint==first.debuggerResidencyFingerprint && MemRead8(0x4002)==0x11, + "Actual guest A-to-B-to-A copies reestablish current byte ownership rather than a cached last owner"); + machine.debuggerArmBankedDevelopmentBreakpoints({},evidence); + const std::vector steps{{0x4000,10,{0x12},"a"},{0x4000,20,{0x12},"b"}}; + rejects([&] { machine.debuggerStepSource(SourceStepMode::Into,steps,third.generation,third.debuggerProgramRevision, + third.debuggerMappingFingerprint,third.cpu.PC,1000000,600,second.debuggerResidencyFingerprint); }); + machine.debuggerStepSource(SourceStepMode::Into,steps,third.generation,third.debuggerProgramRevision, + third.debuggerMappingFingerprint,third.cpu.PC,1000000,600,third.debuggerResidencyFingerprint); + machine.advance(); + require(machine.snapshot().state==RunState::Paused && machine.snapshot().cpu.PC==0x4000 && MemRead8(0x4002)==0x22 && + machine.snapshot().debuggerDevelopmentAttached && machine.debuggerSnapshot().stopReason=="C source location reached", + "C stepping crosses an executing physical-overlay copy and identifies the newly resident owner despite identical entry opcodes"); + auto qualified=evidence; qualified[0].breakpointAddresses=std::vector{0x4000}; qualified[1].breakpointAddresses=std::vector{}; + machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},qualified); + run(machine); + require(MemRead8(0x4002)==0x11 && machine.snapshot().debuggerDevelopmentAttached, + "An owner A breakpoint ignores B at the same physical and logical entry"); + auto invalid=evidence; invalid[1].overlayOwner="A"; + rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},invalid); }); + invalid=evidence; invalid[1].overlayGroup="other"; + rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},invalid); }); + invalid=evidence; invalid[1].overlayGroup.clear(); invalid[1].overlayOwner.clear(); + rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},invalid); }); + for (unsigned boundary=0;boundary<4;++boundary) { + invalid=evidence; + if (boundary==0) { invalid[0].overlayGroup+='\0'; invalid[1].overlayGroup+='\0'; } + if (boundary==1) invalid[0].overlayOwner+='\0'; + if (boundary==2) { invalid[0].overlayGroup=std::string(129,'g'); invalid[1].overlayGroup=invalid[0].overlayGroup; } + if (boundary==3) invalid[0].overlayOwner=std::string(129,'o'); + rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},invalid); }); + } + std::vector manyGroups; + for (unsigned group=0;group<65;++group) for (unsigned owner=0;owner<2;++owner) { + const auto id=std::to_string(group); + manyGroups.push_back({id+"-"+std::to_string(owner),{{1,1}},{{std::uint16_t(0x2000+group),{std::uint8_t(0x12+owner)}}}, + std::nullopt,"group-"+id,owner ? "B" : "A"}); + } + rejects([&] { machine.debuggerArmBankedDevelopmentBreakpoints({},manyGroups); }); + require(machine.snapshot().debuggerDevelopmentAttached && machine.snapshot().debuggerResidencyFingerprint==first.debuggerResidencyFingerprint, + "Rejected alias declarations preserve the existing verified overlay attachment"); + manyGroups.pop_back(); manyGroups.pop_back(); + machine.debuggerArmBankedDevelopmentBreakpoints({},manyGroups); + require(machine.snapshot().debuggerResidencyFingerprint!=0, + "Exactly 64 declared physical-code overlay groups remain within the supported contract"); + } + // All modifications below are executed by the guest loader, never debugger + // writes, register edits or host copies into a running program's RAM. + for (unsigned scenario=0;scenario<4;++scenario) { + MachineSession machine; + auto payload=b; if (scenario==1) payload[4]=0x51; + const unsigned count=scenario==0 ? 3 : unsigned(payload.size()); + load(machine,payload,count); + auto evidence=modules(); evidence[2].guards[1].bytes=loader(0x2100,count); + if (scenario==2) evidence[1].guards=evidence[0].guards; // Two owners fit the same complete code. + if (scenario==3) { + evidence.push_back({"a-helper",{{2,2}},{{0x4800,{0xaa}}},std::vector{},"game","A"}); + evidence.push_back({"b-helper",{{2,2}},{{0x4800,{0xbb}}},std::vector{},"game","B"}); + } + machine.debuggerSetBreakpoints({0x4000}); // Independent manual point must survive source refusal. + machine.debuggerArmBankedDevelopmentBreakpoints({0x4000},evidence); + run(machine); + if (scenario==2) { + require(!machine.snapshot().debuggerDevelopmentAttached, + "Multiple complete matching owners make physical overlay identity ambiguous, never first-match selected"); + } else { + const auto before=machine.snapshot(); require(before.debuggerDevelopmentAttached,"Owner A is initially verified"); + run(machine); const auto after=machine.snapshot(); + require(!after.debuggerDevelopmentAttached && after.debuggerResidencyFingerprint!=before.debuggerResidencyFingerprint && + after.debuggerMappingFingerprint==before.debuggerMappingFingerprint, + "Partial, corrupt or incompletely installed multi-module owners invalidate source attachment after actual guest stores"); + const std::vector steps{{0x4000,10,{0x12},"a"},{0x4000,20,{0x12},"b"}}; + rejects([&] { machine.debuggerStepSource(SourceStepMode::Into,steps,after.generation,after.debuggerProgramRevision, + after.debuggerMappingFingerprint,after.cpu.PC,1000000,600,after.debuggerResidencyFingerprint); }); + } + machine.debuggerClearDevelopmentBreakpoints(); + require(machine.debuggerSnapshot().breakpoints==std::vector{0x4000}, + "Detaching physical-overlay evidence preserves the independent manual breakpoint"); + } +} void checkAssemblyInstructionBoundary(Processor processor) { MachineSession machine; machine.loadDiagnostic(processor); @@ -392,6 +516,8 @@ void CheckBinaryMappedWrites() { checkCurrentGimeCanvases(Processor::HD6309); checkBankedDevelopment(Processor::MC6809); checkBankedDevelopment(Processor::HD6309); + checkPhysicalOverlayDevelopment(Processor::MC6809); + checkPhysicalOverlayDevelopment(Processor::HD6309); checkAssemblyInstructionBoundary(Processor::MC6809); checkAssemblyInstructionBoundary(Processor::HD6309); for (auto cpu : {Processor::MC6809, Processor::HD6309}) { diff --git a/tools/catalog/curation/related-archive.json b/tools/catalog/curation/related-archive.json new file mode 100644 index 0000000..9aa9852 --- /dev/null +++ b/tools/catalog/curation/related-archive.json @@ -0,0 +1,165 @@ +{ + "schema_version": 1, + "relationships": [ + { + "id": "02587e81cceaec9ac0c11fe9", + "title_id": "486dda54b9351ac926c382f70f328aa5", + "software_title": "Raaka-Tu", + "title": "Raaka-Tu Walkthrough (Tandy)", + "document_id": "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc", + "sha256": "e55b30ce36985c0ff35ade23152828e090014bae1b8ddcadd50b02b90f72c7dc", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Raaka-Tu%20Walkthrough%20(Tandy).txt", + "role": "Walkthrough", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed the indexed command-by-command solution, including item acquisition and movement; separate from the game manual." + }, + { + "id": "66aa0cf28072b0be9a60f72b", + "title_id": "2a384f275ebcae78dca310d3312e9cdf", + "software_title": "Bedlam", + "title": "Bedlam Walkthrough (Tandy)", + "document_id": "a10ac100f61319832afb5ff9ca2f2114977e5c82a85b7bdd69229b21dd22ea71", + "sha256": "a10ac100f61319832afb5ff9ca2f2114977e5c82a85b7bdd69229b21dd22ea71", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Bedlam%20Walkthrough%20(Tandy).txt", + "role": "Walkthrough", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed the indexed solution sequence and conditional dog/injection advice; useful game-specific help." + }, + { + "id": "7e3c07f0d050240f97445e03", + "title_id": "bced2c52bb9d1f1e864cb8cc7d2ce9e5", + "software_title": "Pyramid 2000", + "title": "Pyramid 2000 Walkthrough (Tandy)", + "document_id": "9e2d4b3de4547f809920acafa48a57ed0272e5cf458c5bc313f73d3c9edef3c6", + "sha256": "9e2d4b3de4547f809920acafa48a57ed0272e5cf458c5bc313f73d3c9edef3c6", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Pyramid%202000%20Walkthrough%20(Tandy).txt", + "role": "Solution", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed the indexed numbered puzzle/movement solution and score completion; separate spoiler material." + }, + { + "id": "91bc669a5429e19f33e23496", + "title_id": "e0af7e3113d4a0666c4d735df8b70e59", + "software_title": "Calixto Island", + "title": "Calixto Island Walkthrough (Mark Data Products)", + "document_id": "3c0e7e7a94357a6fe97b6d59ded462d4988c3cc8f6edca512bc332701ae06acb", + "sha256": "3c0e7e7a94357a6fe97b6d59ded462d4988c3cc8f6edca512bc332701ae06acb", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Calixto%20Island%20Walkthrough%20(Mark%20Data%20Products).txt", + "role": "Walkthrough", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed the indexed command sequence covering island equipment, boat and temple progression." + }, + { + "id": "1f432b0ab98df3b00911d53f", + "title_id": "e0af7e3113d4a0666c4d735df8b70e59", + "software_title": "Calixto Island", + "title": "Calixto Island Map (Mark Data Products)", + "document_id": "afd0c53c3a8ae5dd685258c754a5b161863a7f1d824870c12d660c6410c1e18f", + "sha256": "afd0c53c3a8ae5dd685258c754a5b161863a7f1d824870c12d660c6410c1e18f", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Calixto%20Island%20Map%20(Mark%20Data%20Products).jpg", + "role": "Map", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Visually inspected the retained map: named Calixto Island rooms, island/boat links and item annotations." + }, + { + "id": "53bbd42bf0b5e6edb01c7085", + "title_id": "dbd7d8cd515b8f6f4bc58fa25482ab7c", + "software_title": "Madness and the Minotaur", + "title": "Madness and the Minotaur Hints (Tandy)", + "document_id": "11925450e2d10999099cc4e589fb96e8ef18a66ab70bc221c92445599c709702", + "sha256": "11925450e2d10999099cc4e589fb96e8ef18a66ab70bc221c92445599c709702", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Madness%20and%20the%20Minotaur%20Hints%20(Tandy).txt", + "role": "Hints", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed indexed room-coded hints about the lamp, spells, creatures and randomized room details." + }, + { + "id": "c8daed0e01578988d888a866", + "title_id": "255cf6ae5ff4eb045362b0afa2c68de9", + "software_title": "Sands of Egypt", + "title": "Sands of Egypt - Help & Maps (Tandy)", + "document_id": "76ed8a92c8ff6c6d6903977d16d8c9e4ecdc2a66f443abf6a413e3e62a48e07d", + "sha256": "76ed8a92c8ff6c6d6903977d16d8c9e4ecdc2a66f443abf6a413e3e62a48e07d", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Sands%20of%20Egypt%20-%20Help%20%26%20Maps%20(Tandy).txt", + "role": "Guide", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed indexed introduction and preposition/input guidance; the article explicitly supplements the adventure with syntax help and maps." + }, + { + "id": "820e2bff9f157f837edf18b2", + "title_id": "d3167ac84f010c802cb8a5f1ec35c7b5", + "software_title": "Syzygy", + "title": "Syzygy Hints (Spectral Associates)", + "document_id": "5f9f440af190cf1e32750a35ba6db14d166afe82f06a58fb8cdf856f68165b5c", + "sha256": "5f9f440af190cf1e32750a35ba6db14d166afe82f06a58fb8cdf856f68165b5c", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Syzygy%20Hints%20(Spectral%20Associates).txt", + "role": "Hints", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed indexed coordinate-entry guidance and destinations; software-specific puzzle assistance." + }, + { + "id": "9640d9703099d24f76ad781c", + "title_id": "3d23047f748cdb3eb7cced8f29ad7182", + "software_title": "Trekboer", + "title": "Trekboer Walkthrough (Mark Data Products)", + "document_id": "e5b50515cd52d95d5f5ed660bb9684658bf9dafb1ae6e6484a750ba994c2e10f", + "sha256": "e5b50515cd52d95d5f5ed660bb9684658bf9dafb1ae6e6484a750ba994c2e10f", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Walkthroughs/Trekboer%20Walkthrough%20(Mark%20Data%20Products).TXT", + "role": "Solution", + "spoiler": true, + "order": 999, + "page": null, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed indexed complete Mark-Data adventure solution and command sequence." + }, + { + "id": "2be433ec8a3a9c61002d22ab", + "title_id": "b7debb76ab93b3d0a2bf9c3abfdbb284", + "software_title": "Deskmate 3", + "title": "DeskMate Quick Reference Quide (Tandy)", + "document_id": "8856b2abd5e76971e3c87bb2ea28a2a34c127a82c36937fa0af7022a01d5665e", + "sha256": "8856b2abd5e76971e3c87bb2ea28a2a34c127a82c36937fa0af7022a01d5665e", + "source_url": "https://colorcomputerarchive.com/repo/Documents/Manuals/Applications/DeskMate%20Quick%20Reference%20Quide%20(Tandy).pdf", + "role": "Reference", + "spoiler": false, + "order": 999, + "page": 1, + "disposition": "accepted", + "reviewed_at": "2026-11-13", + "evidence": "Reviewed indexed first page: Color Computer 3 DeskMate title, general keys, menus and mouse/joystick techniques; selected base DeskMate 3 title only." + } + ] +} diff --git a/tools/catalog/package.py b/tools/catalog/package.py index aa75b90..24b32e5 100644 --- a/tools/catalog/package.py +++ b/tools/catalog/package.py @@ -105,8 +105,10 @@ def source_catalog(output): releases=0, assets=0, thumbnails=0, empty=True) -def package(source, output, require_full=False, *, content_profile='normal'): +def package(source, output, require_full=False, *, content_profile='normal', suppression_manifest=None, rights_cache=None): if resolve_content_profile(content_profile) == 'source': + if suppression_manifest is not None: + raise ValueError('A rights manifest applies to a full candidate, not the empty source-content profile') if require_full: raise ValueError('--require-full cannot be combined with the source content profile') return source_catalog(output) @@ -128,6 +130,16 @@ def package(source, output, require_full=False, *, content_profile='normal'): else: print('warning: Full Software Library catalog is absent; bundling an empty development catalog. See tools/catalog/README.md.') empty_catalog(temporary) + # Derived metadata is prepared from tracked reviewed associations; the + # source catalog remains unchanged. Retained rights exclusions never + # expire during offline builds; a fresh LIVE gate governs publication. + from related_archive import apply_curated + from rights import apply_cached, read_json + with closing(sqlite3.connect(temporary)) as candidate: + apply_curated(candidate) + manifest = read_json(suppression_manifest) if isinstance(suppression_manifest, (str, Path)) else suppression_manifest + apply_cached(candidate, cache_path=rights_cache, extra=manifest) + candidate.commit() counts = validate(temporary, require_full=require_full) digest = hashlib.sha256(temporary.read_bytes()).hexdigest() os.chmod(temporary, 0o444) @@ -250,12 +262,16 @@ def main(): parser.add_argument('--output', type=Path) parser.add_argument('--check-only', action='store_true', help='Validate input without staging a resource') parser.add_argument('--require-full', action='store_true') + parser.add_argument('--suppression-manifest', type=Path, help='Explicit fresh reviewed rights-withdrawal manifest for candidate preparation') + parser.add_argument('--rights-cache', type=Path, help='Retained exclusion cache override; ordinary full preparation uses the persistent maintainer cache') args = parser.parse_args() if not args.check_only and args.output is None: parser.error('--output is required unless --check-only is used') try: profile = resolve_content_profile(args.content_profile) if profile == 'source': + if args.suppression_manifest is not None: + raise ValueError('A rights manifest applies to a full candidate, not the empty source-content profile') if args.require_full: raise ValueError('--require-full cannot be combined with the source content profile') if args.check_only: @@ -265,7 +281,14 @@ def main(): result = source_catalog(args.output) else: source = args.source if args.source is not None else DEFAULT_SOURCE - result = validate(source, args.require_full) if args.check_only else package(source, args.output, args.require_full) + if args.check_only: + validate(source, args.require_full) + with tempfile.TemporaryDirectory(prefix='vcc-suppression-check-') as temporary: + result = package(source, Path(temporary) / 'catalog.sqlite', args.require_full, + suppression_manifest=args.suppression_manifest, rights_cache=args.rights_cache) + result['suppression_checked'] = True + else: + result = package(source, args.output, args.require_full, suppression_manifest=args.suppression_manifest, rights_cache=args.rights_cache) if not args.check_only: artwork = args.output.parent / 'Artwork' if artwork.is_symlink(): raise ValueError('Artwork destination must not be a symlink') diff --git a/tools/catalog/related_archive.py b/tools/catalog/related_archive.py new file mode 100644 index 0000000..103ae9a --- /dev/null +++ b/tools/catalog/related_archive.py @@ -0,0 +1,144 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Apply reviewed software-to-Archive links without modifying source databases. + +The curation file is maintainer input. Filename matches are candidates only; +accepted links bind an existing software identity and exact indexed document. +""" +import argparse +import hashlib +import json +from pathlib import Path +import re +import os +import tempfile +import sqlite3 +from contextlib import closing + +CURATION = Path(__file__).with_name('curation') / 'related-archive.json' +ROLES = ('Guide', 'Tutorial', 'Reference', 'Hints', 'Walkthrough', 'Solution', 'Map') +SHA = re.compile(r'^[0-9a-f]{64}$') + + +def load_curation(path=CURATION): + data = json.loads(Path(path).read_text()) + if data.get('schema_version') != 1 or not isinstance(data.get('relationships'), list): + raise ValueError('Unsupported related Archive curation contract') + ids = set() + for row in data['relationships']: + if row.get('id') in ids or not isinstance(row.get('id'), str) or not row['id']: + raise ValueError('Missing or duplicate relationship identity') + ids.add(row['id']) + if row.get('disposition') not in ('accepted', 'rejected', 'ambiguous'): + raise ValueError('Relationship needs an explicit review disposition') + if row['disposition'] != 'accepted': + continue + if not row.get('title_id') or not row.get('evidence') or not row.get('title'): + raise ValueError('Accepted relationship needs a title and review evidence') + if not SHA.fullmatch(row.get('document_id', '')) or row.get('sha256') != row['document_id']: + raise ValueError('Archive identity must bind exact indexed bytes') + if row.get('role') not in ROLES: + raise ValueError('Unknown related-document role') + page = row.get('page') + if page is not None and (isinstance(page, bool) or not isinstance(page, int) or page < 1): + raise ValueError('Page/section location must be a positive physical location') + if not isinstance(row.get('spoiler', False), bool) or not isinstance(row.get('order', 999), int): + raise ValueError('Invalid relationship presentation metadata') + return data + + +def apply_curated(db, curation=CURATION, archive=None, strict=False): + """Apply accepted links in caller transaction; never execute/download content.""" + data = load_curation(curation) + titles = {row[0] for row in db.execute('SELECT id FROM title')} + releases = {row[0]: row[1] for row in db.execute('SELECT id,title_id FROM release')} + groups = {} + for row in data['relationships']: + if row['disposition'] != 'accepted': + continue + title_id = row['title_id'] + if title_id not in titles: + if strict: + raise ValueError('Related reference has an unknown software title: ' + title_id) + continue # Empty/source or scoped catalog omits titles deliberately. + edition_ids = row.get('edition_ids', []) + if not isinstance(edition_ids, list) or any(releases.get(i) != title_id for i in edition_ids): + raise ValueError('Related reference has an unknown or conflicting edition') + if archive is not None: + record = archive.execute('SELECT page_count FROM document WHERE sha256=?', (row['document_id'],)).fetchone() + if record is None or (row.get('page') or 1) > record[0]: + raise ValueError('Related reference is missing or its location no longer exists') + selected = edition_ids or [i for i, title in releases.items() if title == title_id] + for release in selected: + projected = {key: row[key] for key in ('id', 'title', 'document_id', 'sha256', 'role')} + projected.update(page=row.get('page'), spoiler=row.get('spoiler', False), order=row.get('order', 999)) + group = groups.setdefault(release, []) + if any((r['document_id'], r['page']) == (projected['document_id'], projected['page']) for r in group): + raise ValueError('Duplicate accepted related-document target') + group.append(projected) + for release, in db.execute('SELECT id FROM release').fetchall(): + original = db.execute('SELECT metadata_json FROM release WHERE id=?', (release,)).fetchone()[0] + metadata = json.loads(original) + previous = dict(metadata) + # Reviewed curation is authoritative for this capability. Later guesses + # cannot promote rejected or removed relationships by reusing old output. + metadata.pop('related_archive', None) + metadata.pop('related_archive_contract', None) + if release in groups: + metadata['related_archive_contract'] = 1 + metadata['related_archive'] = groups[release] + if metadata != previous: + db.execute('UPDATE release SET metadata_json=? WHERE id=?', (json.dumps(metadata, ensure_ascii=False, sort_keys=True), release)) + if groups and db.execute("SELECT value FROM metadata WHERE key='related_archive_contract'").fetchone() != ('1',): + db.execute("INSERT OR REPLACE INTO metadata VALUES('related_archive_contract','1')") + return {'relationships': sum(map(len, groups.values())), 'editions': len(groups), + 'titles': len({releases[i] for i in groups})} + + +def candidates(catalog, archive): + def normal(text): + return re.sub(r'[^a-z0-9]', '', re.sub(r'^the\s+', '', text.lower())) + titles = catalog.execute('SELECT id,name FROM title').fetchall() + rows = [] + for doc, title, collection, source in archive.execute("SELECT sha256,title,collection,source_url FROM document WHERE category IN ('Walkthroughs','Maps') ORDER BY title"): + prefix = re.split(r'\b(?:walktrough|walkthrough|hints|map|solution|help|spell book)\b|\(', title, maxsplit=1, flags=re.I)[0] + key = normal(prefix) + matches = [{'id': i, 'title': name} for i, name in titles if normal(name) == key] + rows.append({'document_id': doc, 'title': title, 'collection': collection, 'source_url': source, + 'candidate_titles': matches, 'status': 'candidate-only' if matches else 'unmatched'}) + return rows + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument('catalog', type=Path) + parser.add_argument('--archive', required=True, type=Path) + parser.add_argument('--curation', default=CURATION, type=Path) + parser.add_argument('--output', type=Path) + parser.add_argument('--candidate-report', type=Path) + args = parser.parse_args() + with closing(sqlite3.connect(args.catalog.resolve().as_uri() + '?mode=ro', uri=True)) as source, closing(sqlite3.connect(args.archive.resolve().as_uri() + '?mode=ro', uri=True)) as archive: + if args.candidate_report: + args.candidate_report.parent.mkdir(parents=True, exist_ok=True) + rows = candidates(source, archive) + args.candidate_report.write_text(json.dumps({'schema_version': 1, 'status': 'candidates-not-approved', 'documents': rows}, indent=2) + '\n') + if args.output: + if args.output.exists() or args.output.is_symlink() or args.output.resolve() == args.catalog.resolve(): + raise ValueError('Choose a new candidate catalog output') + args.output.parent.mkdir(parents=True, exist_ok=True) + descriptor, name = tempfile.mkstemp(prefix='.related-candidate-', suffix='.sqlite', dir=args.output.parent) + os.close(descriptor) + temporary = Path(name) + try: + with closing(sqlite3.connect(temporary)) as output: + source.backup(output) + report = apply_curated(output, args.curation, archive, strict=True) + output.commit() + # Exclusive promotion: a concurrent process cannot be overwritten. + os.link(temporary, args.output) + print(json.dumps(report)) + finally: + temporary.unlink(missing_ok=True) + +if __name__ == '__main__': + main() diff --git a/tools/catalog/rights.py b/tools/catalog/rights.py new file mode 100644 index 0000000..d66c810 --- /dev/null +++ b/tools/catalog/rights.py @@ -0,0 +1,234 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Retain rights exclusions offline and inventory an actual portable app catalog. + +Refresh consumes an explicitly obtained authenticated snapshot; this tool does +not authenticate, contact servers, publish content or infer rights authority. +""" +import argparse +from contextlib import closing +from datetime import datetime, timezone +import fcntl +import hashlib +import json +import os +from pathlib import Path +import sqlite3 +import tempfile +from urllib.parse import urlsplit + +ROOT = Path(__file__).resolve().parents[2] +DEFAULT_CACHE = ROOT / 'media/software-library-full/curation/rights-suppressions.json' +DEFAULT_CATALOG = ROOT / 'media/software-library-full/prepared/app-catalog.sqlite' +MAX_CACHE_BYTES = 8 * 1024 * 1024 +MAX_INVENTORY_BYTES = 16 * 1024 * 1024 +MAX_CASES = 10000 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def read_json(path, maximum=MAX_CACHE_BYTES): + path = Path(path) + require(path.is_file() and not path.is_symlink() and path.stat().st_size <= maximum, + 'Rights input must be a bounded regular nonsymlink file') + with path.open('rb') as stream: + data = stream.read(maximum + 1) + require(len(data) <= maximum, 'Rights input exceeds its byte limit') + return json.loads(data) + + +def normalize(value, *, as_of=None, fresh=False): + from submission_intake import suppressions, time_value + require(isinstance(value, dict), 'Invalid rights snapshot') + records = value.get('suppressions') + require(isinstance(records, list) and len(records) <= MAX_CASES, 'Rights case count exceeds bounds') + require(all(isinstance(item, dict) for item in records), 'Invalid rights case') + suppressions(value, as_of, require_fresh=fresh) + result = [] + for item in records: + scope = {} + for key, values in item['scope'].items(): + require(all(len(x.encode('utf-8')) <= 4096 and '\0' not in x for x in values), 'Rights scope identity exceeds bounds') + if values: + scope[key] = sorted(set(values)) + result.append({'case_reference': item['case_reference'], + 'effective_at': time_value(item['effective_at']).isoformat(), 'scope': scope}) + unique = {json.dumps(item, sort_keys=True, separators=(',', ':')): item for item in result} + document = {'schema_version': 1, 'suppressions': [unique[key] for key in sorted(unique)]} + if 'generated_at' in value: + document['generated_at'] = time_value(value['generated_at']).isoformat() + require(len(json.dumps(document, ensure_ascii=False).encode()) <= MAX_CACHE_BYTES, 'Rights cache exceeds byte limit') + return document + + +def cached(path=None): + path = Path(path) if path is not None else DEFAULT_CACHE + if not path.exists() and not path.is_symlink(): + return {'schema_version': 1, 'suppressions': []} + return normalize(read_json(path)) + + +def combine(*documents): + records = {} + for document in documents: + for item in normalize(document)['suppressions']: + records[json.dumps(item, sort_keys=True, separators=(',', ':'))] = item + # No omission, changed timestamp or narrowed replacement scope revokes an + # earlier exclusion. Future cases remain retained until they take effect. + return normalize({'schema_version': 1, 'suppressions': list(records.values())}) + + +def apply_cached(db, *, cache_path=None, extra=None, as_of=None): + from submission_intake import apply_suppressions + document = combine(cached(cache_path), *([extra] if extra is not None else [])) + return apply_suppressions(db, document, as_of) + + +def _atomic_json(path, value, maximum, *, replace=False): + path = Path(path) + require(not path.is_symlink() and (replace or not path.exists()), 'Rights output already exists or is a symlink') + data = (json.dumps(value, ensure_ascii=False, sort_keys=True, indent=2) + '\n').encode() + require(len(data) <= maximum, 'Rights output exceeds byte limit') + path.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix='.rights-', dir=path.parent) + try: + with os.fdopen(fd, 'wb') as stream: + stream.write(data); stream.flush(); os.fsync(stream.fileno()) + if replace: + require(not path.is_symlink(), 'Rights output became a symlink') + os.replace(temporary, path) + else: + os.link(temporary, path) # Exclusive promotion, including racing writers. + finally: + Path(temporary).unlink(missing_ok=True) + + +def _hash(value, *, optional=False): + import re + require((optional and value is None) or isinstance(value, str) and re.fullmatch('[a-f0-9]{64}', value), 'Invalid catalog inventory hash') + return value + + +def _identity(value): + require(isinstance(value, str) and 0 < len(value.encode('utf-8')) <= 4096 and '\0' not in value, + 'Invalid catalog inventory identity') + return value + + +def _urls(values): + result = sorted(set(value for value in values if value)) + require(len(result) <= 64, 'Catalog inventory URL count exceeds bounds') + for url in result: + _identity(url) + parsed = urlsplit(url) + require(parsed.scheme in ('http', 'https') and parsed.hostname and parsed.username is None and parsed.password is None + and not any(ord(c) < 32 for c in url), 'Catalog inventory requires public HTTP references without credentials') + return result + + +def inventory(catalog): + """Read only the actual app export, never a maintainer DB or media corpus.""" + from package import validate + from submission_intake import digest + catalog = Path(catalog) + validate(catalog) + before = digest(catalog) + result = {'schema_version': 1, 'catalog_sha256': before, 'releases': [], 'assets': []} + with closing(sqlite3.connect(catalog.resolve().as_uri() + '?mode=ro', uri=True)) as db: + db.execute('PRAGMA query_only=ON') + require(db.execute('SELECT count(*) FROM release').fetchone()[0] <= 50000 + and db.execute('SELECT count(*) FROM asset').fetchone()[0] <= 100000, 'Catalog inventory row count exceeds bounds') + for title, identity, sha, url, metadata in db.execute('SELECT title_id,id,package_sha256,source_url,metadata_json FROM release ORDER BY id'): + reference = json.loads(metadata).get('submission_reference') + if reference is not None: + from submission_intake import REFERENCE + require(isinstance(reference, str) and REFERENCE.fullmatch(reference), 'Invalid inventory submission reference') + urls = _urls([url] + [r[0] for r in db.execute('SELECT url FROM download_location WHERE package_sha256=? ORDER BY url', (sha,))]) + result['releases'].append({'title_id': _identity(title), 'id': _identity(identity), 'package_sha256': _hash(sha), + 'source_url': url, 'source_urls': urls, 'submission_reference': reference}) + for identity, sha, source, manual, thumbnail, thumbnail_sha in db.execute( + 'SELECT a.id,a.sha256,a.source_url,d.manual_url,d.thumbnail_url,d.thumbnail_sha256 FROM asset a LEFT JOIN asset_delivery d ON d.asset_id=a.id ORDER BY a.id'): + row = {'id': _identity(identity), 'sha256': _hash(sha, optional=True), 'source_urls': _urls([source, manual, thumbnail])} + if thumbnail_sha is not None: + row['thumbnail_sha256'] = _hash(thumbnail_sha) + result['assets'].append(row) + require(digest(catalog) == before, 'Catalog changed while exporting rights inventory') + require(len(json.dumps(result, ensure_ascii=False).encode()) <= MAX_INVENTORY_BYTES, 'Catalog inventory exceeds byte limit') + return result + + +def _bind_observed_bytes(document, catalog): + """Preserve exact matching bytes/aliases through later title or URL renames. + + Never promote a package-only scope to an entire title/submission. No fuzzy + name matching or new rights authority is inferred from a catalog. + """ + from submission_intake import applies + observed = inventory(catalog) + rows = [] + for item in document['suppressions']: + scope = item['scope'] + hashes, urls = set(scope.get('package_sha256', [])), set(scope.get('source_urls', [])) + for row in observed['releases']: + if applies(scope, row): + hashes.add(row['package_sha256']); urls.update(row['source_urls']) + for row in observed['assets']: + if set(row['source_urls']) & set(scope.get('source_urls', [])) or {row.get('sha256'), row.get('thumbnail_sha256')} & set(scope.get('package_sha256', [])): + hashes.update(h for h in (row.get('sha256'), row.get('thumbnail_sha256')) if h); urls.update(row['source_urls']) + # Scope arrays have a 100-value limit. Keep the original exact scope and + # retain bounded additional records rather than dropping observed aliases. + rows.append(item) + for key, values in [('package_sha256', sorted(hashes)), ('source_urls', sorted(urls))]: + for start in range(0, len(values), 100): + rows.append({**item, 'scope': {key: values[start:start+100]}}) + return combine({'schema_version': 1, 'suppressions': rows}) + + +def refresh(snapshot, cache_path=None, *, catalog=None, as_of=None): + document = normalize(snapshot, as_of=as_of, fresh=True) + path = Path(cache_path) if cache_path is not None else DEFAULT_CACHE + path.parent.mkdir(parents=True, exist_ok=True) + lock = path.with_name('.' + path.name + '.lock') + with os.fdopen(os.open(lock, os.O_RDWR | os.O_CREAT | os.O_NOFOLLOW, 0o600), 'a+b') as stream: + fcntl.flock(stream, fcntl.LOCK_EX) + retained = combine(cached(path), document) + if catalog is not None: + retained = _bind_observed_bytes(retained, catalog) + retained['generated_at'] = document['generated_at'] + _atomic_json(path, retained, MAX_CACHE_BYTES, replace=True) + return retained + + +def export_inventory(catalog, output): + result = inventory(catalog) + _atomic_json(output, result, MAX_INVENTORY_BYTES) + return {'catalog_sha256': result['catalog_sha256'], 'inventory_sha256': hashlib.sha256(Path(output).read_bytes()).hexdigest(), + 'releases': len(result['releases']), 'assets': len(result['assets'])} + + +def main(): + parser = argparse.ArgumentParser(description=__doc__) + sub = parser.add_subparsers(dest='command', required=True) + update = sub.add_parser('refresh', help='Monotonically retain a fresh authenticated suppression snapshot') + update.add_argument('--snapshot', required=True, type=Path) + update.add_argument('--cache', type=Path, default=DEFAULT_CACHE) + update.add_argument('--catalog', type=Path, help='Current app catalog for binding matching bytes and aliases; defaults to the prepared catalog when present') + export = sub.add_parser('inventory', help='Export a SHA-bound rights inventory from an actual app catalog') + export.add_argument('catalog', type=Path); export.add_argument('--output', required=True, type=Path) + args = parser.parse_args() + try: + if args.command == 'refresh': + catalog = args.catalog if args.catalog is not None else DEFAULT_CATALOG if DEFAULT_CATALOG.exists() else None + result = refresh(read_json(args.snapshot), args.cache, catalog=catalog) + print(json.dumps({'retained_suppressions': len(result['suppressions'])})) + else: + print(json.dumps(export_inventory(args.catalog, args.output))) + except (ValueError, OSError, sqlite3.DatabaseError) as error: + parser.exit(1, 'error: Rights catalog: ' + str(error) + '\n') + + +if __name__ == '__main__': + main() diff --git a/tools/catalog/submission_intake.py b/tools/catalog/submission_intake.py new file mode 100644 index 0000000..a906d5d --- /dev/null +++ b/tools/catalog/submission_intake.py @@ -0,0 +1,314 @@ +#!/usr/bin/env python3 +# SPDX-License-Identifier: GPL-3.0-or-later +"""Explicit, offline intake of exact approved software into a NEW app catalog. + +No download, execution, extraction into a project, publication or installed-media +mutation. Fresh approval/suppression snapshots come from the authenticated website +maintenance channel. Originals and permission records remain in ignored storage. +""" +import argparse +from contextlib import closing +from datetime import datetime, timezone +import hashlib +import json +import os +from pathlib import Path, PurePosixPath +import re +import shutil +import sqlite3 +import stat +import tempfile +from urllib.parse import urlsplit, unquote +import zipfile + +HASH = re.compile(r'[a-f0-9]{64}') +REFERENCE = re.compile(r'SW-[0-9]{4}-[0-9]+') +MAX_PACKAGE = 256 * 1024 * 1024 +MAX_EXPANDED = 256 * 1024 * 1024 +MAX_MEMBERS = 4096 + + +def require(condition, message): + if not condition: + raise ValueError(message) + + +def encoded(value): + return json.dumps(value, ensure_ascii=False, separators=(',', ':'), sort_keys=True) + + +def digest(path): + h = hashlib.sha256() + with Path(path).open('rb') as stream: + for chunk in iter(lambda: stream.read(1024 * 1024), b''): + h.update(chunk) + return h.hexdigest() + + +def time_value(value): + require(isinstance(value, str), 'A timezone-aware timestamp is required') + result = datetime.fromisoformat(value.replace('Z', '+00:00')) + require(result.tzinfo is not None, 'Timestamp requires a timezone') + return result + + +def load(path, maximum=8 * 1024 * 1024): + path = Path(path) + require(path.is_file() and not path.is_symlink() and path.stat().st_size <= maximum, + 'Use a bounded regular JSON file') + return json.loads(path.read_text()) + + +def approval(manifest, current, as_of=None): + now = as_of or datetime.now(timezone.utc) + require(manifest.get('schema_version') == 1 and REFERENCE.fullmatch(manifest.get('submission_reference', '')), + 'Unsupported approved submission manifest') + snapshot = manifest.get('approval_snapshot_json') + require(isinstance(snapshot, str) and HASH.fullmatch(manifest.get('approval_sha256', '')), + 'Exact immutable approval snapshot is required') + require(hashlib.sha256(snapshot.encode()).hexdigest() == manifest['approval_sha256'], 'Approval snapshot changed') + original = json.loads(snapshot) + require({k: v for k, v in manifest.items() if k not in ('approval_snapshot_json', 'approval_sha256')} == original, + 'Manifest disagrees with its approved snapshot') + require(current.get('state') in ('claimed', 'ready') and current.get('manifest', {}).get('approval_sha256') == manifest['approval_sha256'] + and current['manifest'].get('submission_reference') == manifest['submission_reference'] + and current['manifest'].get('approval_revision') == manifest.get('approval_revision'), + 'Current claimed approval must match; withdrawn/stale approvals are refused') + checked = time_value(current.get('checked_at')) + require(0 <= (now - checked).total_seconds() <= 900, 'Approval check expired; refresh the authenticated claim') + permission = manifest.get('permission', {}) + require(permission.get('operator') == 'Dezota LLC' and permission.get('record_reference') + and HASH.fullmatch(permission.get('terms_sha256', '')) and isinstance(permission.get('terms_text'), str) + and hashlib.sha256(permission['terms_text'].encode()).hexdigest() == permission['terms_sha256'], + 'Missing or changed permission record') + assets = manifest.get('assets') + require(isinstance(assets, list) and 1 <= len(assets) <= 4, 'Approved asset descriptors required') + require(sum(a.get('role') == 'package' for a in assets) == 1, 'Exactly one approved package is required') + for asset in assets: + require(asset.get('role') in ('package', 'manual', 'image') and HASH.fullmatch(asset.get('sha256', '')) + and type(asset.get('byte_size')) is int and asset['byte_size'] > 0, 'Invalid approved asset') + return manifest + + +def suppressions(value, as_of=None, require_fresh=False): + now = as_of or datetime.now(timezone.utc) + require(value.get('schema_version') == 1 and isinstance(value.get('suppressions'), list), 'Unsupported suppression manifest') + if require_fresh: + age = (now - time_value(value.get('generated_at'))).total_seconds() + require(0 <= age <= 900, 'Suppression check expired; refresh it before intake') + result = [] + for item in value['suppressions']: + require(isinstance(item.get('case_reference'), str) and re.fullmatch(r'FB-[0-9]{4}-[0-9]+',item['case_reference']), 'Rights case reference required') + scope = item.get('scope') + require(isinstance(scope, dict) and set(scope) <= {'title_ids', 'release_ids', 'package_sha256', 'source_urls', 'submission_references'}, 'Invalid withdrawal scope') + require(any(scope.values()) and all(isinstance(v, list) and len(v) <= 100 and all(isinstance(x, str) and x for x in v) for v in scope.values()), 'Empty or invalid withdrawal scope') + require(all(HASH.fullmatch(v) for v in scope.get('package_sha256', [])), 'Invalid withdrawal hash') + if time_value(item.get('effective_at')) <= now: + result.append(scope) + return result + + +def applies(scope, row): + return (row.get('title_id') in scope.get('title_ids', []) + or row.get('id') in scope.get('release_ids', []) + or row.get('package_sha256') in scope.get('package_sha256', []) + or row.get('source_url') in scope.get('source_urls', []) + or bool(set(row.get('source_urls', [])) & set(scope.get('source_urls', []))) + or row.get('submission_reference') in scope.get('submission_references', [])) + + +def apply_suppressions(db, manifest, as_of=None): + """Remove only scoped catalog rows in caller transaction; never touch files. + + Requires explicit suppression data. Feed this at each candidate preparation; + publication additionally requires a freshly authenticated suppression check. + Future-dated exclusions remain in the manifest and become effective by time. + """ + scopes = suppressions(manifest, as_of) + removed = [] + affected_titles = set() + affected_assets = set() + columns = [row[1] for row in db.execute('PRAGMA table_info(release)')] + for raw in db.execute('SELECT * FROM release').fetchall(): + row = dict(zip(columns, raw)) + meta = json.loads(row.get('metadata_json') or '{}') + row['submission_reference'] = meta.get('submission_reference') + row['source_urls'] = [u[0] for u in db.execute('SELECT url FROM download_location WHERE package_sha256=?', (row['package_sha256'],))] + if any(applies(scope, row) for scope in scopes): + release_id = row['id'] + affected_titles.add(row['title_id']) + affected_assets.update(a[0] for a in db.execute('SELECT asset_id FROM release_asset WHERE release_id=?', (release_id,))) + for table in ('release_asset', 'setup', 'member', 'source_hint'): + if db.execute("SELECT 1 FROM sqlite_master WHERE type='table' AND name=?", (table,)).fetchone(): + db.execute(f'DELETE FROM {table} WHERE release_id=?', (release_id,)) + db.execute('DELETE FROM release WHERE id=?', (release_id,)) + removed.append(release_id) + empty = [title_id for title_id in sorted(affected_titles) if not db.execute('SELECT 1 FROM release WHERE title_id=?', (title_id,)).fetchone()] + for title_id in empty: + db.execute('DELETE FROM title WHERE id=?', (title_id,)) + # Asset-only exclusions remove only supporting assets, retaining unrelated software. + # Match both upstream/original and hosted derivative URLs, including old catalogs. + asset_columns = [r[1] for r in db.execute('PRAGMA table_info(asset)')] + for raw in db.execute('SELECT * FROM asset').fetchall(): + asset = dict(zip(asset_columns, raw)) + delivery = db.execute('SELECT manual_url,thumbnail_url,thumbnail_sha256 FROM asset_delivery WHERE asset_id=?', (asset['id'],)).fetchone() + urls = {asset['source_url'], *(delivery[:2] if delivery else [])} + hashes = {asset.get('sha256'), delivery[2] if delivery else None} + if any(urls & set(scope.get('source_urls', [])) or hashes & set(scope.get('package_sha256', [])) for scope in scopes): + db.execute('DELETE FROM release_asset WHERE asset_id=?', (asset['id'],)) + affected_assets.add(asset['id']) + removed_assets = [] + for asset_id in sorted(affected_assets): + if not db.execute('SELECT 1 FROM release_asset WHERE asset_id=?', (asset_id,)).fetchone(): + db.execute('DELETE FROM asset_delivery WHERE asset_id=?', (asset_id,)) + db.execute('DELETE FROM asset WHERE id=?', (asset_id,)) + removed_assets.append(asset_id) + return {'removed_release_ids': removed, 'removed_title_ids': empty, 'removed_asset_ids': removed_assets} + + +def inspect_zip(path): + require(path.stat().st_size <= MAX_PACKAGE, 'Package exceeds size limit') + members = [] + seen = set() + with zipfile.ZipFile(path) as archive: + infos = archive.infolist() + require(1 <= len(infos) <= MAX_MEMBERS, 'ZIP member count is outside bounds') + require(sum(i.file_size for i in infos) <= MAX_EXPANDED, 'ZIP expansion exceeds bounds') + for info in infos: + name = PurePosixPath(info.filename) + require(not name.is_absolute() and '\\' not in info.filename and not any(p in ('..', '.', '') for p in name.parts) + and not any(p in ('', '.', '..') for p in info.filename.rstrip('/').split('/')) and '\x00' not in info.filename and ':' not in info.filename and not info.flag_bits & 1, 'Unsafe ZIP member path or encrypted entry') + require(not stat.S_ISLNK(info.external_attr >> 16), 'ZIP links are refused') + key = info.filename.casefold() + require(key not in seen, 'ZIP contains colliding member names') + seen.add(key) + if info.is_dir(): + continue + require(info.file_size <= MAX_EXPANDED and (not info.file_size or info.file_size <= max(1, info.compress_size) * 4096), 'ZIP expansion ratio exceeds bounds') + h = hashlib.sha256() + count = 0 + with archive.open(info) as stream: + while chunk := stream.read(1024 * 1024): + count += len(chunk) + require(count <= info.file_size, 'ZIP expanded beyond declared member size') + h.update(chunk) + require(count == info.file_size, 'ZIP member is truncated') + kind = {'.dsk': 'disk', '.os9': 'disk', '.vhd': 'hard_disk', '.img': 'hard_disk', '.ccc': 'cartridge', '.cas': 'cassette', '.wav': 'cassette', '.bin': 'binary'}.get(name.suffix.lower(), 'supporting') + members.append({'path': info.filename, 'sha256': h.hexdigest(), 'byte_size': count, 'kind': kind}) + require(any(m['kind'] != 'supporting' for m in members), 'Package contains no recognized CoCo media') + return members + + +def hosted_url(url, role): + parsed = urlsplit(url) + path = unquote(parsed.path) + require(parsed.scheme == 'https' and parsed.netloc == 'vccplus.brianholman.com' and not parsed.query and not parsed.fragment and '\\' not in path and '\x00' not in path and all(p not in ('.', '..') for p in path.split('/')), 'Invalid hosted software location') + base = '/dl/software/CoCoLibrary/' + prefix, extensions = {'package': (base, ('.zip',)), 'manual': (base + 'Documents/Manuals/', ('.pdf',)), 'image': (base + 'Artwork/Originals/', ('.png', '.jpg', '.jpeg')), 'thumbnail': (base + 'Artwork/Thumbnails/', ('.png',))}[role] + require(path.startswith(prefix) and path.lower().endswith(extensions), 'Invalid hosted software location for ' + role) + return url + + +def verified_locations(receipt, assets): + require(receipt.get('state') == 'verified' and isinstance(receipt.get('artifacts'), list), 'Verified hosting receipt required') + result = {} + for asset in assets: + matches = [r for r in receipt['artifacts'] if r.get('sha256') == asset['sha256'] and r.get('byte_size') == asset['byte_size'] and r.get('status') == 200] + require(len(matches) == 1, 'Missing or ambiguous verified publication for an approved asset') + result[asset['sha256']] = {'url': hosted_url(matches[0].get('url', ''), asset['role'])} + derived = receipt.get('derived_artifacts', []) + require(isinstance(derived, list), 'Invalid derived artwork receipt') + for artifact in derived: + source = artifact.get('source_sha256') + require(any(a['role'] == 'image' and a['sha256'] == source for a in assets), 'Derived thumbnail must identify approved original artwork') + require(artifact.get('role') == 'thumbnail' and artifact.get('status') == 200 and isinstance(artifact.get('sha256'), str) and HASH.fullmatch(artifact['sha256']) and type(artifact.get('byte_size')) is int and 0 < artifact['byte_size'] <= 2 * 1024 * 1024, 'Invalid prepared PNG thumbnail receipt') + require('thumbnail' not in result[source], 'Ambiguous prepared thumbnail receipt') + result[source]['thumbnail'] = {**artifact, 'url': hosted_url(artifact.get('url', ''), 'thumbnail')} + return result + + +def prepare_catalog(source, destination, manifest, current, suppression_manifest, files, hosting_receipt, as_of=None, *, rights_cache=None): + manifest = approval(manifest, current, as_of) + suppressions(suppression_manifest, as_of, require_fresh=True) + from rights import cached, combine + retained_suppressions = combine(cached(rights_cache), suppression_manifest) + require(Path(source).is_file() and not Path(source).is_symlink(), 'Use an existing regular prepared app catalog') + destination = Path(destination) + require(destination.resolve() != Path(source).resolve() and not destination.exists(), 'Create a NEW catalog; existing source/output is never replaced') + assets = manifest['assets'] + paths = {} + for asset in assets: + path = Path(files.get(asset['sha256'], '')) + require(path.is_file() and not path.is_symlink() and path.stat().st_size == asset['byte_size'] and digest(path) == asset['sha256'], 'Approved original bytes are missing or changed') + paths[asset['sha256']] = path + package = next(a for a in assets if a['role'] == 'package') + members = inspect_zip(paths[package['sha256']]) + locations = verified_locations(hosting_receipt, assets) + ref = manifest['submission_reference'] + title_id = 'direct-' + ref.lower() + release_id = title_id + '-r' + str(manifest['approval_revision']) + row = {'id': release_id, 'title_id': title_id, 'package_sha256': package['sha256'], 'source_url': locations[package['sha256']]['url'], 'submission_reference': ref} + require(not any(applies(s, row) for s in suppressions(retained_suppressions, as_of)), 'A rights withdrawal blocks this submission') + destination.parent.mkdir(parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(prefix='.submission-', suffix='.sqlite', dir=destination.parent) + os.close(fd) + try: + with closing(sqlite3.connect(f'file:{Path(source).resolve()}?mode=ro', uri=True)) as original, closing(sqlite3.connect(temporary)) as db: + original.backup(db) + db.execute('PRAGMA foreign_keys=ON') + require(db.execute('PRAGMA user_version').fetchone()[0] == 1, 'Unsupported app catalog version') + with db: + prior = db.execute('SELECT package_sha256 FROM release WHERE id=?', (release_id,)).fetchone() + require(prior is None or prior[0] == package['sha256'], 'Existing submission identity conflicts') + if prior is None: + primary = next(m for m in members if m['kind'] != 'supporting') + media = {'hard_disk': 'hard-disk'}.get(primary['kind'], primary['kind']) + metadata = {'origin': 'direct_submission', 'submission_reference': ref, 'approval_revision': manifest['approval_revision'], 'author': manifest['author'], 'publisher': manifest['author'], 'software_version': manifest['software_version'], 'license': manifest['metadata']['end_user_terms'], 'project_url': manifest['metadata'].get('project_url', ''), 'description': manifest['description'], 'permission_operator': 'Dezota LLC'} + db.execute('INSERT OR IGNORE INTO title VALUES(?,?,?)', (title_id, manifest['title'], 'reviewed-direct-submission')) + db.execute('INSERT OR IGNORE INTO package VALUES(?,?)', (package['sha256'], package['byte_size'])) + db.execute('INSERT INTO release VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?)', (release_id,title_id,manifest['software_version'],'Uncategorized',media,'software',locations[package['sha256']]['url'],None,None,None,package['sha256'],'unknown',encoded(metadata))) + db.execute('INSERT OR IGNORE INTO download_location VALUES(?,?,?)', (package['sha256'],locations[package['sha256']]['url'],0)) + for member in members: + db.execute('INSERT INTO member VALUES(?,?,?,?,?,?)', (release_id,member['path'],member['sha256'],member['byte_size'],member['kind'],'software' if member['kind'] != 'supporting' else 'supporting')) + db.execute('INSERT INTO setup VALUES(?,?,?,?,?,?,?,?)', (release_id,'manual-setup','{}','[]',None,manifest['metadata'].get('setup') or 'Review media and configure the CoCo manually.',encoded(['Direct submission: automatic setup is not runtime-qualified.']),encoded({'scope':'manual-setup','approval_reference':ref}))) + for number, asset in enumerate(a for a in assets if a['role'] != 'package'): + asset_id = release_id + '-asset-' + str(number) + kind = 'manual' if asset['role'] == 'manual' else 'cover' + db.execute('INSERT INTO asset VALUES(?,?,?,?,?,?,?)',(asset_id,asset['name'],kind,locations[asset['sha256']]['url'],asset['sha256'],asset['byte_size'],manifest['author'])) + db.execute('INSERT INTO release_asset VALUES(?,?,?,?)',(release_id,asset_id,'reviewed','Approved direct-submission supporting asset')) + thumb = locations[asset['sha256']].get('thumbnail', {}) + db.execute('INSERT INTO asset_delivery VALUES(?,?,?,?,?,?)',(asset_id,locations[asset['sha256']]['url'] if kind=='manual' else None,thumb.get('url'),thumb.get('sha256'),thumb.get('byte_size'),0)) + exclusions = apply_suppressions(db,retained_suppressions,as_of) + db.execute('INSERT OR REPLACE INTO metadata VALUES(?,?)',('submission_approval:'+ref,manifest['approval_sha256'])) + require(db.execute('PRAGMA integrity_check').fetchone()[0] == 'ok', 'Candidate catalog integrity failed') + # Exclusive hardlink promotion never replaces an output created by a racing operation. + os.link(temporary,destination) + finally: + Path(temporary).unlink(missing_ok=True) + return {'schema_version':1,'submission_reference':ref,'approval_revision':manifest['approval_revision'],'title_id':title_id,'release_id':release_id,'catalog_sha256':digest(destination),'hosting_receipt':hosting_receipt,'target_release':manifest.get('target_release',''),'qualification_record':'Prepared with manual setup; runtime qualification pending.','suppression_result':exclusions} + + +def main(): + parser=argparse.ArgumentParser(description=__doc__) + parser.add_argument('source',type=Path) + parser.add_argument('--output',required=True,type=Path) + parser.add_argument('--manifest',required=True,type=Path) + parser.add_argument('--approval-check',required=True,type=Path) + parser.add_argument('--suppressions',required=True,type=Path) + parser.add_argument('--files',required=True,type=Path,help='Private JSON mapping approved SHA-256 to local retained file path') + parser.add_argument('--hosting-receipt',required=True,type=Path) + parser.add_argument('--result',required=True,type=Path) + parser.add_argument('--rights-cache',type=Path,help='Persistent exclusion cache override; refresh merges instead of replacing previous exclusions') + args=parser.parse_args() + from rights import refresh + snapshot = load(args.suppressions) + # This explicit file/CLI boundary retains authenticated exclusions. The pure + # preparation helper above reads the cache but never writes global state. + refresh(snapshot,args.rights_cache,catalog=args.source) + result=prepare_catalog(args.source,args.output,load(args.manifest),load(args.approval_check),snapshot,load(args.files),load(args.hosting_receipt),rights_cache=args.rights_cache) + args.result.parent.mkdir(parents=True,exist_ok=True) + with os.fdopen(os.open(args.result, os.O_WRONLY | os.O_CREAT | os.O_EXCL, 0o600), 'w') as stream:stream.write(json.dumps(result,indent=2)+'\n') + print('New catalog candidate prepared; runtime qualification/publication remain separate.') + + +if __name__=='__main__':main() diff --git a/tools/tests/test_build_content.py b/tools/tests/test_build_content.py index 7f050b4..70ed57f 100644 --- a/tools/tests/test_build_content.py +++ b/tools/tests/test_build_content.py @@ -17,6 +17,12 @@ RESOURCES = ( ('tools/catalog/package.py', 'tools/catalog/app-schema.sql', 'SoftwareLibrary/catalog.sqlite'), ('tools/knowledge/package_archive.py', 'tools/knowledge/archive-library.sql', 'ArchiveLibrary/ArchiveLibrary.sqlite'), ) +CATALOG_PACKAGE_INPUTS = ( + 'tools/catalog/related_archive.py', + 'tools/catalog/curation/related-archive.json', + 'tools/catalog/rights.py', + 'tools/catalog/submission_intake.py', +) class BuildContentTests(unittest.TestCase): @@ -26,7 +32,8 @@ class BuildContentTests(unittest.TestCase): self.root = Path(temporary.name) self.source = self.root / 'Source With Spaces' self.build = self.root / 'Build With Spaces' - for relative in ['tools/build_content.py', *(p for r in RESOURCES for p in r[:2])]: + for relative in ['tools/build_content.py', *(p for r in RESOURCES for p in r[:2]), + *CATALOG_PACKAGE_INPUTS]: destination = self.source / relative destination.parent.mkdir(parents=True, exist_ok=True) shutil.copyfile(ROOT / relative, destination)