commit fe6f2bfe76daa0b671209f05bd15e1d9dc19eb9a Author: David Gwilliam Date: Wed Nov 4 19:19:53 2026 -0800 Browser patch editor for Pure Data (closes #1) Open a .pd file, drag boxes and pull cords, save it back as a file Pd will load. Dragging is Dragology: `d.vary` moves a box, and a cord drag is `d.closest(...).whenFar(vary)` over every inlet in the patch, so the plug snaps to an inlet and cancels on empty space. The parser is a byte-exact round trip. Two Pd format details that matter: `#X connect` indices count comments, and `;;` (an empty record) is not the same as a blank line. Anything unmodelled — arrays, `#X declare`, subpatches — is preserved verbatim. Tests run real Pd: patches round trip, an edited patch loads in `pd -nogui` without new complaints, and the bridge carries a message into a running Pd and back. The bridge writes to server/patches/ and runs `pd -nogui` itself, so saving and hearing the patch is one button. diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2110f54 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +node_modules +dist +server/patches diff --git a/README.md b/README.md new file mode 100644 index 0000000..28a8d1f --- /dev/null +++ b/README.md @@ -0,0 +1,110 @@ +# dragology-pd + +A browser patch editor for [Pure Data](https://puredata.info/), built on +[Dragology](https://declarative-dragging.github.io/). + +Drag boxes around, pull cords out of outlets, and save the result as a `.pd` +file that Pd itself will open. Optionally run it: a small WebSocket bridge +starts `pd -nogui` and streams its stdout back into the page, so you hear what +you just wired. + +``` + browser ──WebSocket──▶ bridge ──UDP/FUDI──▶ pd + ▲ │ + └──────UDP/FUDI──────┘ +``` + +## Running it + +```sh +pnpm install +pnpm dev # http://localhost:5174 +pnpm bridge # optional, in a second terminal +``` + +Then click **Connect** in the sidebar, hit **Save & run in pd**, and the patch +is written to `server/patches/` and opened with `pd -nogui`. Pd's output — +including "couldn't create" errors — appears in the sidebar. + +`pnpm bridge --silent` passes `-nosound` to Pd, which is handy when you want to +check that a patch loads without waking the neighbours. + +## What works + +- **Open / save `.pd` files.** Parsing and serialisation are byte-exact round + trips, so opening a patch and saving it unchanged produces the same file. + Anything the editor does not model — arrays, `#X declare`, subpatches — + survives untouched. +- **Drag boxes.** Positions update live and snap to the grid you pick. +- **Pull cords.** Grab an outlet nub and drag: the plug follows the pointer, + and snaps onto an inlet when you get close. Drop in empty space to cancel. +- **Add and delete objects.** Type the object text, click *Add object*, then + click the canvas. Select and press Delete to remove an object and its cords. +- **Warn about broken files.** Records Pd will reject are kept verbatim and + flagged in the toolbar instead of being quietly dropped. + +Not there yet: editing an object's text in place, undo, subpatch navigation, +and re-patching an existing cord by its destination end. + +## How the dragging works + +Three Dragology behaviours do the work, in `src/editor/PatchCanvas.tsx`: + +| Interaction | Spec | +|---|---| +| Move a box | `d.vary(state, [param("nodes", id, "x"), param("nodes", id, "y")])` | +| Pull a cord | `d.closest(inletBranches).whenFar(d.vary(state, [param("drag", "x"), param("drag", "y")]), { gap: 34 })` | +| Drop | `.onDrop(commitDrag)` — turns the drag's snap target into a real cord | + +The cord drag is the interesting one. Every inlet in the patch becomes a +candidate state in which the plug sits on that inlet and records it; `closest` +picks the branch by how near the pointer is, and `whenFar` hands control back +to a free-floating `vary` when no inlet is close. The drop reads `drag.snap` +and builds the cord, so no half-made connections ever reach the document. + +## Layout + +``` +src/pd/ .pd parsing, serialisation, box geometry +src/editor/ Dragology draggable, pure state operations +src/bridge/ WebSocket client +server/bridge.mjs FUDI <-> WebSocket bridge, pd process runner +test/ parser round trips, pd integration, bridge loop +``` + +## Tests + +```sh +pnpm test +``` + +15 tests. The interesting ones run real Pd: + +- every patch in `~/Arduino/sketches/uno-q-audio-synth/pd` round trips byte + for byte; +- a patch edited by the app (moved box, new cord, new object) loads in + `pd -nogui` without producing a complaint the original did not; +- the bridge carries a message from a WebSocket client into a running Pd and + receives one back on UDP. + +## Notes on the Pd format + +Two things cost time and are worth writing down: + +- **Comments occupy an index.** `#X connect` numbers refer to the object list + *including* comments, so a cord that skips them is rejected with + `(text->osc~) connection failed`. Verified against Pd 0.57. +- **`;;` is not a blank line.** Pd writes an empty record as `;;` on one line + and a section break as a blank line. Both are preserved. + +## A bug in the sample patches + +`synth.pd` (and its generator) writes + +``` +# DO NOT EDIT — generated by scripts/gen_synth_pd.py; +``` + +Pd treats a bare `#` record as an object and prints +`error: #: no such object`. A comment should be `#X text x y ...`. The editor +keeps the line and shows a warning rather than rewriting it for you. diff --git a/index.html b/index.html new file mode 100644 index 0000000..b34f3d3 --- /dev/null +++ b/index.html @@ -0,0 +1,12 @@ + + + + + + dragology-pd + + +
+ + + diff --git a/package.json b/package.json new file mode 100644 index 0000000..8544ab5 --- /dev/null +++ b/package.json @@ -0,0 +1,29 @@ +{ + "name": "dragology-pd", + "private": true, + "version": "0.0.1", + "type": "module", + "description": "A browser patch editor for Pure Data, built with Dragology", + "scripts": { + "dev": "vite", + "build": "tsc -p tsconfig.json && vite build", + "typecheck": "tsc -p tsconfig.json", + "test": "node --test --experimental-strip-types test/*.test.ts", + "bridge": "node server/bridge.mjs" + }, + "dependencies": { + "dragology": "^0.1.7", + "react": "^19.2.0", + "react-dom": "^19.2.0" + }, + "devDependencies": { + "@types/node": "^25.2.3", + "@types/react": "^19.2.4", + "@types/react-dom": "^19.2.3", + "@types/ws": "^8.5.13", + "@vitejs/plugin-react": "^6.0.1", + "typescript": "^5.9.3", + "vite": "^8.0.3", + "ws": "^8.18.0" + } +} diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml new file mode 100644 index 0000000..d74c765 --- /dev/null +++ b/pnpm-lock.yaml @@ -0,0 +1,672 @@ +lockfileVersion: '9.0' + +settings: + autoInstallPeers: true + excludeLinksFromLockfile: false + +importers: + + .: + dependencies: + dragology: + specifier: ^0.1.7 + version: 0.1.7(react-dom@19.3.1(react@19.3.1))(react@19.3.1) + react: + specifier: ^19.2.0 + version: 19.3.1 + react-dom: + specifier: ^19.2.0 + version: 19.3.1(react@19.3.1) + devDependencies: + '@types/node': + specifier: ^25.2.3 + version: 25.9.9 + '@types/react': + specifier: ^19.2.4 + version: 19.3.0 + '@types/react-dom': + specifier: ^19.2.3 + version: 19.3.0(@types/react@19.3.0) + '@types/ws': + specifier: ^8.5.13 + version: 8.18.2 + '@vitejs/plugin-react': + specifier: ^6.0.1 + version: 6.2.1(vite@8.3.5(@types/node@25.9.9)) + typescript: + specifier: ^5.9.3 + version: 5.9.3 + vite: + specifier: ^8.0.3 + version: 8.3.5(@types/node@25.9.9) + ws: + specifier: ^8.18.0 + version: 8.22.1 + +packages: + + '@joshuahhh/pretty-print@0.0.7': + resolution: {integrity: sha512-6G8lMKk7/yA1N5rccIo84tanf1oiYcWsPxHxXs0P3Cqjtvl9js2A8CmCpMMdStPmoOeiHhLccR1YRits+yz72Q==} + peerDependencies: + react: '>=17' + + '@oxc-project/types@0.156.0': + resolution: {integrity: sha512-1Duyg48TdJNdyhEB8Xn1L36bT9Pv6GUtlKjHxOys8xkaF/rQq3XJE+bAurSK/AgIz5mGFsb77cn9Pb20+WCScw==} + + '@rolldown/binding-android-arm-eabi@1.2.16': + resolution: {integrity: sha512-ia3DwAs0OsMGS7+IConptSiyk9pEXkOx/AbJ2n/lAGxH3QkWQus1t8d7gnAT38FCU2sQu8lUbeR6AiZFv4JxaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [android] + + '@rolldown/binding-android-arm64@1.2.16': + resolution: {integrity: sha512-kx5wBiMB6E7TEvpl2B9gjLU004BkvEm2Dr941BFjx/SontPwSzNuQUIoVKxHHoSjpFIfHMmcguyLOtyn0hObRg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [android] + + '@rolldown/binding-darwin-arm64@1.2.16': + resolution: {integrity: sha512-qslZrXnKJU4cUpjoAmtAo/KQM9e2IRMlmpig6Zpwj+8KWxW8v+nkAf9216Bsek9lOC1jvg2yCjygCFo2f83msQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [darwin] + + '@rolldown/binding-darwin-x64@1.2.16': + resolution: {integrity: sha512-FdF+y48ND13eAyM2mQn+85kvAqNlvRWROy2rhgA463X/0Gv4vGtazZtfaF1mRBLscYvtOlh4QnLjOWiFzX69OQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [darwin] + + '@rolldown/binding-freebsd-x64@1.2.16': + resolution: {integrity: sha512-ddjqFM5e95AgLbUPtKIS7V1KTVlA0RUgCVr5mn+/IEhsdy3pr+Vuj/HZ7nlMN2FyxIwUktOH1LEPIQXO1v9y1Q==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [freebsd] + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + resolution: {integrity: sha512-tHdKWbFkFBI687iim3LIyIvyL7j66VvQYkDPss5Stn/qyE2tWkR1YD0dXmXPFKKqT/o5ZEJVsaRsWS2meQwGOA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm] + os: [linux] + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + resolution: {integrity: sha512-FJiLGAblPBMlBEdbOqw6kW6QcXDWAf/oJu7gYs9ZJZwmg+K+/zjFLxPTIY9izJUzxzc24FHvmseyA0IvJSl17w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-arm64-musl@1.2.16': + resolution: {integrity: sha512-hrJpblMsrQ58U9veWpbXzkhV5zStunds6HWLprqq1qauvgBr1E6P+24kLj6lSLI9vjRn/RYpjprhkHQPKGWpNg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [linux] + libc: [musl] + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + resolution: {integrity: sha512-qJd/dC6j6CwLG9/s/RP2nb1RZ0GIgj7Ioj7x/SYa3RzjVrlzrmH0fhIOpfvqQDeIsdP0loi+kHaMhJzY1PBIaA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [ppc64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + resolution: {integrity: sha512-Vx7Xg5uUJuNcujJjI70OICaH0EYj80BtOLZTSN7uOYg8QOLlyKnaG0IW7Fn/J0IpJsaKzmDKMhOQv1JBM9m9vg==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [s390x] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-gnu@1.2.16': + resolution: {integrity: sha512-TNKhgE3uJTsTzatUSSYt0Kgo+Oa2uSlSjz4r1aEIea7HX6ULBym4fAlYUhG1i6pjNf2njfCUAfKwr6C3E9Xg1w==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [glibc] + + '@rolldown/binding-linux-x64-musl@1.2.16': + resolution: {integrity: sha512-7chXdpjXZ8qG0+mIxECN3cT9kvhZ3/oZhMX6Pp876P7CDrIy8nJswva6Mq357JR7eYXfuskwZxMeV1SzoZdHrA==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [linux] + libc: [musl] + + '@rolldown/binding-openharmony-arm64@1.2.16': + resolution: {integrity: sha512-Kwjt+7uNTJK5/MDkGWGVO2KQPnj8yAV75dMpfwyHZrJSXWHrniOB0aUEWlVYf3H1hOqFLIStLdM5QXq6bnKmOQ==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [openharmony] + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + resolution: {integrity: sha512-/LH6WfjDRXXJz/p5xl4TmU+jpcnwcxbKEQBW/GZE0JHfN0lGIyTtsUEGaQ/q/GikkGJ2yLKe6pwm7AnEWO8pdw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [arm64] + os: [win32] + + '@rolldown/binding-win32-x64-msvc@1.2.16': + resolution: {integrity: sha512-1lv1KvX0Z871zfk7vw+dnXMMnHNyDwMzWG8Kv3HxDXMOhzCX4SHc7HK319fInP0i+0p9D8brkfzL7pJOaGl+tw==} + engines: {node: ^20.19.0 || >=22.12.0} + cpu: [x64] + os: [win32] + + '@rolldown/pluginutils@1.0.1': + resolution: {integrity: sha512-2j9bGt5Jh8hj+vPtgzPtl72j0yRxHAyumoo6TNfAjsLB04UtpSvPbPcDcBMxz7n+9CYB0c1GxQFxYRg2jimqGw==} + + '@types/node@25.9.9': + resolution: {integrity: sha512-b4e2xxj/yMeT2hNlD6x7zNFiQK2Dlmkb9CQ6v3/1G2RezKN4YS2lcEv8lzGm1mhs4f2lM4yNAMI/zUDBZBBt7w==} + + '@types/react-dom@19.3.0': + resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==} + peerDependencies: + '@types/react': ^19.3.0 + + '@types/react@19.3.0': + resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==} + + '@types/ws@8.18.2': + resolution: {integrity: sha512-67MQl+fpWKVTT1NYdnmo3U4sc/xPo/zQBncVnI74qmQa0z/b+1g6iYqNmGCPbxO+zz2aklb08a0oHfegiVd0/w==} + + '@vitejs/plugin-react@6.2.1': + resolution: {integrity: sha512-9KyWCij3r0+qLG3Q62vBmv0VyevmYibAtxaCIVK9o0k6CXgaajZRIe8tpfchQcdZArJ5b/7OrIz4W3b2uxVRDA==} + engines: {node: ^20.19.0 || >=22.12.0} + peerDependencies: + '@rolldown/plugin-babel': ^0.1.7 || ^0.2.0 || ^0.3.0 + babel-plugin-react-compiler: ^1.0.0 + oxc-transform-react: '>=0.152.0 <0.157.0' + vite: ^8.0.0 + peerDependenciesMeta: + '@rolldown/plugin-babel': + optional: true + babel-plugin-react-compiler: + optional: true + oxc-transform-react: + optional: true + + csstype@3.2.3: + resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==} + + d3-color@3.1.1: + resolution: {integrity: sha512-lfab8x0Bj0UO7SNsY8dZSbNIA6ipbkE3X0NG9nqjCu6CfCHZseuDnOSJY7hidKrjpP++i1M2qT+FlAdPKYRilA==} + engines: {node: '>=12'} + + d3-delaunay@6.0.6: + resolution: {integrity: sha512-DMQIEvSJhZCB6pwedcXaAlQ+MeKU5LlM2XakKtc73b/VM+RBiI1SRXycOEOKg2jsKj4zZ9F0KGYG6nCGwwWu/g==} + engines: {node: '>=12'} + + d3-ease@3.0.2: + resolution: {integrity: sha512-B5znKqRmKROAN4oHWQ50W/qisVjA9GXh2WMsVKdFVp4DxWmcrOsweqgUOUVsv5th96kwaZlokU6SlV4J3gak1w==} + engines: {node: '>=12'} + + d3-interpolate-path@2.3.0: + resolution: {integrity: sha512-tZYtGXxBmbgHsIc9Wms6LS5u4w6KbP8C09a4/ZYc4KLMYYqub57rRBUgpUr2CIarIrJEpdAWWxWQvofgaMpbKQ==} + + d3-interpolate@3.0.2: + resolution: {integrity: sha512-IRzGU62DtxhvsnSTWMQIdnoZ6gA+BCWwBon1EJI6SjoN595799b6z/QRBzXfFhE8iupUPp3042yBNo0STPqnzQ==} + engines: {node: '>=12'} + + delaunator@5.1.0: + resolution: {integrity: sha512-AGrQ4QSgssa1NGmWmLPqN5NY2KajF5MqxetNEO+o0n3ZwZZeTmt7bBnvzHWrmkZFxGgr4HdyFgelzgi06otLuQ==} + + detect-libc@2.1.2: + resolution: {integrity: sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==} + engines: {node: '>=8'} + + dragology@0.1.7: + resolution: {integrity: sha512-ynaalmQ063q6xAmiW8dhAb2331Ltj2d2JbKu3L9s+LkMATapWSIl6lcP1+9oE2QoPh3Lx7udaQQXOyKxQJIIUw==} + peerDependencies: + react: ^18 || ^19 + react-dom: ^18 || ^19 + + fdir@6.5.0: + resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} + engines: {node: '>=12.0.0'} + peerDependencies: + picomatch: ^3 || ^4 + peerDependenciesMeta: + picomatch: + optional: true + + fsevents@2.3.3: + resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==} + engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0} + os: [darwin] + + immer@11.2.9: + resolution: {integrity: sha512-IQ4UEtXjZjyefyWjtLEDXUSrF6T2hwjKPi6BIJl3bY/2XXW24d6cNGdXJSBOA/+KNnuiXkZY6DR0C3efolhitA==} + + lightningcss-android-arm64@1.33.0: + resolution: {integrity: sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [android] + + lightningcss-darwin-arm64@1.33.0: + resolution: {integrity: sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [darwin] + + lightningcss-darwin-x64@1.33.0: + resolution: {integrity: sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [darwin] + + lightningcss-freebsd-x64@1.33.0: + resolution: {integrity: sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [freebsd] + + lightningcss-linux-arm-gnueabihf@1.33.0: + resolution: {integrity: sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm] + os: [linux] + + lightningcss-linux-arm64-gnu@1.33.0: + resolution: {integrity: sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [glibc] + + lightningcss-linux-arm64-musl@1.33.0: + resolution: {integrity: sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [linux] + libc: [musl] + + lightningcss-linux-x64-gnu@1.33.0: + resolution: {integrity: sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [glibc] + + lightningcss-linux-x64-musl@1.33.0: + resolution: {integrity: sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [linux] + libc: [musl] + + lightningcss-win32-arm64-msvc@1.33.0: + resolution: {integrity: sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==} + engines: {node: '>= 12.0.0'} + cpu: [arm64] + os: [win32] + + lightningcss-win32-x64-msvc@1.33.0: + resolution: {integrity: sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==} + engines: {node: '>= 12.0.0'} + cpu: [x64] + os: [win32] + + lightningcss@1.33.0: + resolution: {integrity: sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==} + engines: {node: '>= 12.0.0'} + + lodash@4.18.1: + resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==} + + nanoid@3.3.20: + resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==} + engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1} + hasBin: true + + picocolors@1.1.1: + resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==} + + picomatch@4.0.7: + resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==} + engines: {node: '>=12'} + + postcss@8.5.32: + resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==} + engines: {node: ^10 || ^12 || >=14} + + prettier@3.9.10: + resolution: {integrity: sha512-skGHTH1Yb9QvaTC4hWnRTzEYtCpApF0UMBPz+t/0ZPzP8ihefo/btKd+QA7pUE0fEwA1SbS/NmhyEcstdXOIdA==} + engines: {node: '>=14'} + hasBin: true + + qrcode-generator@2.0.4: + resolution: {integrity: sha512-mZSiP6RnbHl4xL2Ap5HfkjLnmxfKcPWpWe/c+5XxCuetEenqmNFf1FH/ftXPCtFG5/TDobjsjz6sSNL0Sr8Z9g==} + + react-dom@19.3.1: + resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==} + peerDependencies: + react: ^19.3.1 + + react@19.3.1: + resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==} + engines: {node: '>=0.10.0'} + + robust-predicates@3.0.3: + resolution: {integrity: sha512-NS3levdsRIUOmiJ8FZWCP7LG3QpJyrs/TE0Zpf1yvZu8cAJJ6QMW92H1c7kWpdIHo8RvmLxN/o2JXTKHp74lUA==} + + rolldown@1.2.16: + resolution: {integrity: sha512-bWvlMpFKiTfDKfnK7FC2MPgPeWCf/Kpwsq49ApdW+FQaBZb6O6dZ4MAPbPUjp7hYQrw/RobqCzn64BRrQecGHw==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + + scheduler@0.28.0: + resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==} + + source-map-js@1.2.2: + resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==} + engines: {node: '>=0.10.0'} + + tinyglobby@0.2.17: + resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==} + engines: {node: '>=12.0.0'} + + typescript@5.9.3: + resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} + engines: {node: '>=14.17'} + hasBin: true + + undici-types@7.24.6: + resolution: {integrity: sha512-WRNW+sJgj5OBN4/0JpHFqtqzhpbnV0GuB+OozA9gCL7a993SmU+1JBZCzLNxYsbMfIeDL+lTsphD5jN5N+n0zg==} + + vite@8.3.5: + resolution: {integrity: sha512-z1YpjieJ9g0ebTmQpLBv/oq9E3F9EIlOe+7LahW8SrE3LTiG3udBRUXQOlYXP9b+IC2q2phHeVxj9xGlw34OEQ==} + engines: {node: ^20.19.0 || >=22.12.0} + hasBin: true + peerDependencies: + '@types/node': ^20.19.0 || >=22.12.0 + '@vitejs/devtools': ^0.7.1 || ^0.8.0 + esbuild: ^0.27.0 || ^0.28.0 + jiti: '>=1.21.0' + less: ^4.0.0 + sass: ^1.70.0 + sass-embedded: ^1.70.0 + stylus: '>=0.54.8' + sugarss: ^5.0.0 + terser: ^5.16.0 + tsx: ^4.8.1 + yaml: ^2.4.2 + peerDependenciesMeta: + '@types/node': + optional: true + '@vitejs/devtools': + optional: true + esbuild: + optional: true + jiti: + optional: true + less: + optional: true + sass: + optional: true + sass-embedded: + optional: true + stylus: + optional: true + sugarss: + optional: true + terser: + optional: true + tsx: + optional: true + yaml: + optional: true + + ws@8.22.1: + resolution: {integrity: sha512-oyL6OPYme/CmiFvNuGzeoxCJ4nOrZE2O1FwM9MWM1AsGri6nLXB2pg+lNA8aLeXMSav0J6eIVS1j6vUPzUtK9g==} + engines: {node: '>=10.0.0'} + peerDependencies: + bufferutil: ^4.0.1 + utf-8-validate: '>=5.0.2' + peerDependenciesMeta: + bufferutil: + optional: true + utf-8-validate: + optional: true + +snapshots: + + '@joshuahhh/pretty-print@0.0.7(react@19.3.1)': + dependencies: + prettier: 3.9.10 + react: 19.3.1 + + '@oxc-project/types@0.156.0': {} + + '@rolldown/binding-android-arm-eabi@1.2.16': + optional: true + + '@rolldown/binding-android-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-arm64@1.2.16': + optional: true + + '@rolldown/binding-darwin-x64@1.2.16': + optional: true + + '@rolldown/binding-freebsd-x64@1.2.16': + optional: true + + '@rolldown/binding-linux-arm-gnueabihf@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-arm64-musl@1.2.16': + optional: true + + '@rolldown/binding-linux-ppc64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-s390x-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-gnu@1.2.16': + optional: true + + '@rolldown/binding-linux-x64-musl@1.2.16': + optional: true + + '@rolldown/binding-openharmony-arm64@1.2.16': + optional: true + + '@rolldown/binding-win32-arm64-msvc@1.2.16': + optional: true + + '@rolldown/binding-win32-x64-msvc@1.2.16': + optional: true + + '@rolldown/pluginutils@1.0.1': {} + + '@types/node@25.9.9': + dependencies: + undici-types: 7.24.6 + + '@types/react-dom@19.3.0(@types/react@19.3.0)': + dependencies: + '@types/react': 19.3.0 + + '@types/react@19.3.0': + dependencies: + csstype: 3.2.3 + + '@types/ws@8.18.2': + dependencies: + '@types/node': 25.9.9 + + '@vitejs/plugin-react@6.2.1(vite@8.3.5(@types/node@25.9.9))': + dependencies: + '@rolldown/pluginutils': 1.0.1 + vite: 8.3.5(@types/node@25.9.9) + + csstype@3.2.3: {} + + d3-color@3.1.1: {} + + d3-delaunay@6.0.6: + dependencies: + delaunator: 5.1.0 + + d3-ease@3.0.2: {} + + d3-interpolate-path@2.3.0: {} + + d3-interpolate@3.0.2: + dependencies: + d3-color: 3.1.1 + + delaunator@5.1.0: + dependencies: + robust-predicates: 3.0.3 + + detect-libc@2.1.2: {} + + dragology@0.1.7(react-dom@19.3.1(react@19.3.1))(react@19.3.1): + dependencies: + '@joshuahhh/pretty-print': 0.0.7(react@19.3.1) + d3-color: 3.1.1 + d3-delaunay: 6.0.6 + d3-ease: 3.0.2 + d3-interpolate: 3.0.2 + d3-interpolate-path: 2.3.0 + immer: 11.2.9 + lodash: 4.18.1 + qrcode-generator: 2.0.4 + react: 19.3.1 + react-dom: 19.3.1(react@19.3.1) + + fdir@6.5.0(picomatch@4.0.7): + optionalDependencies: + picomatch: 4.0.7 + + fsevents@2.3.3: + optional: true + + immer@11.2.9: {} + + lightningcss-android-arm64@1.33.0: + optional: true + + lightningcss-darwin-arm64@1.33.0: + optional: true + + lightningcss-darwin-x64@1.33.0: + optional: true + + lightningcss-freebsd-x64@1.33.0: + optional: true + + lightningcss-linux-arm-gnueabihf@1.33.0: + optional: true + + lightningcss-linux-arm64-gnu@1.33.0: + optional: true + + lightningcss-linux-arm64-musl@1.33.0: + optional: true + + lightningcss-linux-x64-gnu@1.33.0: + optional: true + + lightningcss-linux-x64-musl@1.33.0: + optional: true + + lightningcss-win32-arm64-msvc@1.33.0: + optional: true + + lightningcss-win32-x64-msvc@1.33.0: + optional: true + + lightningcss@1.33.0: + dependencies: + detect-libc: 2.1.2 + optionalDependencies: + lightningcss-android-arm64: 1.33.0 + lightningcss-darwin-arm64: 1.33.0 + lightningcss-darwin-x64: 1.33.0 + lightningcss-freebsd-x64: 1.33.0 + lightningcss-linux-arm-gnueabihf: 1.33.0 + lightningcss-linux-arm64-gnu: 1.33.0 + lightningcss-linux-arm64-musl: 1.33.0 + lightningcss-linux-x64-gnu: 1.33.0 + lightningcss-linux-x64-musl: 1.33.0 + lightningcss-win32-arm64-msvc: 1.33.0 + lightningcss-win32-x64-msvc: 1.33.0 + + lodash@4.18.1: {} + + nanoid@3.3.20: {} + + picocolors@1.1.1: {} + + picomatch@4.0.7: {} + + postcss@8.5.32: + dependencies: + nanoid: 3.3.20 + picocolors: 1.1.1 + source-map-js: 1.2.2 + + prettier@3.9.10: {} + + qrcode-generator@2.0.4: {} + + react-dom@19.3.1(react@19.3.1): + dependencies: + react: 19.3.1 + scheduler: 0.28.0 + + react@19.3.1: {} + + robust-predicates@3.0.3: {} + + rolldown@1.2.16: + dependencies: + '@oxc-project/types': 0.156.0 + '@rolldown/pluginutils': 1.0.1 + optionalDependencies: + '@rolldown/binding-android-arm-eabi': 1.2.16 + '@rolldown/binding-android-arm64': 1.2.16 + '@rolldown/binding-darwin-arm64': 1.2.16 + '@rolldown/binding-darwin-x64': 1.2.16 + '@rolldown/binding-freebsd-x64': 1.2.16 + '@rolldown/binding-linux-arm-gnueabihf': 1.2.16 + '@rolldown/binding-linux-arm64-gnu': 1.2.16 + '@rolldown/binding-linux-arm64-musl': 1.2.16 + '@rolldown/binding-linux-ppc64-gnu': 1.2.16 + '@rolldown/binding-linux-s390x-gnu': 1.2.16 + '@rolldown/binding-linux-x64-gnu': 1.2.16 + '@rolldown/binding-linux-x64-musl': 1.2.16 + '@rolldown/binding-openharmony-arm64': 1.2.16 + '@rolldown/binding-win32-arm64-msvc': 1.2.16 + '@rolldown/binding-win32-x64-msvc': 1.2.16 + + scheduler@0.28.0: {} + + source-map-js@1.2.2: {} + + tinyglobby@0.2.17: + dependencies: + fdir: 6.5.0(picomatch@4.0.7) + picomatch: 4.0.7 + + typescript@5.9.3: {} + + undici-types@7.24.6: {} + + vite@8.3.5(@types/node@25.9.9): + dependencies: + lightningcss: 1.33.0 + picomatch: 4.0.7 + postcss: 8.5.32 + rolldown: 1.2.16 + tinyglobby: 0.2.17 + optionalDependencies: + '@types/node': 25.9.9 + fsevents: 2.3.3 + + ws@8.22.1: {} diff --git a/public/samples/controller.pd b/public/samples/controller.pd new file mode 100644 index 0000000..2954a2e --- /dev/null +++ b/public/samples/controller.pd @@ -0,0 +1,90 @@ +#N canvas 0 0 900 500 10; +#X obj 5 5 loadbang; +#X msg 5 25 pd dsp 1; +#X connect 0 0 1 0; + +#X text 20 10 -- NOTE BUTTONS (click to play) --; + +#X text 22 50 C3; +#X obj 20 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 20 100 48 100; +#X obj 20 130 noteout; +#X connect 4 0 5 0; +#X connect 5 0 6 0; + +#X text 62 50 D3; +#X obj 60 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 60 100 50 100; +#X obj 60 130 noteout; +#X connect 8 0 9 0; +#X connect 9 0 10 0; + +#X text 102 50 E3; +#X obj 100 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 100 100 52 100; +#X obj 100 130 noteout; +#X connect 12 0 13 0; +#X connect 13 0 14 0; + +#X text 142 50 F3; +#X obj 140 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 140 100 53 100; +#X obj 140 130 noteout; +#X connect 16 0 17 0; +#X connect 17 0 18 0; + +#X text 182 50 G3; +#X obj 180 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 180 100 55 100; +#X obj 180 130 noteout; +#X connect 20 0 21 0; +#X connect 21 0 22 0; + +#X text 222 50 A3; +#X obj 220 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 220 100 57 100; +#X obj 220 130 noteout; +#X connect 24 0 25 0; +#X connect 25 0 26 0; + +#X text 262 50 B3; +#X obj 260 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 260 100 59 100; +#X obj 260 130 noteout; +#X connect 28 0 29 0; +#X connect 29 0 30 0; + +#X text 302 50 C4; +#X obj 300 70 bng 15 15 0 1 0 0 empty empty -2 -8 0 10 -262144 -1 -1; +#X msg 300 100 60 100; +#X obj 300 130 noteout; +#X connect 32 0 33 0; +#X connect 33 0 34 0; + +#X text 20 180 -- MPK MINI PASSTHROUGH (forward all incoming to board) --; +#X obj 30 200 notein; +#X obj 30 230 pack f f; +#X obj 30 260 noteout; +#X obj 130 200 ctlin; +#X obj 130 230 ctlout; +#X connect 36 0 37 0; +#X connect 36 1 37 1; +#X connect 37 0 38 0; +#X connect 39 0 40 0; + +#X text 20 280 -- CONTROLS --; +#X obj 30 300 hsl 128 15 0 127 64 0 0 0 empty Filter-CC -2 -8 0 10 -262144 -1 -1 7200 1; +#X obj 30 340 ctlout 74; +#X connect 42 0 43 0; + +#X text 20 380 -- AUDIO MONITOR --; +#X obj 30 400 adc~ 1; +#X obj 30 440 *~; +#X obj 30 480 dac~ 1 2; +#X obj 140 400 hsl 128 15 0 100 50 0 0 0 empty Monitor-Volume -2 -8 0 10 -262144 -1 -1 7200 1; +#X obj 140 440 / 100; +#X connect 45 0 46 0; +#X connect 46 0 47 0; +#X connect 46 0 47 1; +#X connect 48 0 49 0; +#X connect 49 0 46 1; diff --git a/public/samples/mpk-mini-sim.pd b/public/samples/mpk-mini-sim.pd new file mode 100644 index 0000000..41afddb --- /dev/null +++ b/public/samples/mpk-mini-sim.pd @@ -0,0 +1,449 @@ +#N canvas 0 0 950 490 10; +# DO NOT EDIT — generated by scripts/gen_mpk_sim.py; +#X obj 10 10 loadbang ; +#X msg 10 30 ;; +#X msg 10 50 connect 192.168.9.167 8081;; +#X obj 10 80 netsend -u -b; +#X text 200 30 ← edit this line to change target IP:port; +#X text 10 440 Click keys to play. Knobs send CC on change. IPS (192.168.9.167:8081); +#X text 10 460 MIDI ch: 144=note-on ch1, 128=note-off ch1, 176=CC ch1; +#X text 20 120 -- KEYBOARD --; +#X text 30 140 C3; +#X obj 30 154 bng 15 25 0 1 0 0 empty k48 -2 -8 0 10 -262144 -1 -1; +#X obj 30 184 t b b; +#X msg 30 204 midi 144 48 100;; +#X msg 30 222 midi 128 48 0;; +#X obj 30 240 del 300; +#X text 76 140 C#3; +#X obj 76 154 bng 15 25 0 1 0 0 empty k49 -2 -8 0 10 -262144 -1 -1; +#X obj 76 184 t b b; +#X msg 76 204 midi 144 49 100;; +#X msg 76 222 midi 128 49 0;; +#X obj 76 240 del 300; +#X text 122 140 D3; +#X obj 122 154 bng 15 25 0 1 0 0 empty k50 -2 -8 0 10 -262144 -1 -1; +#X obj 122 184 t b b; +#X msg 122 204 midi 144 50 100;; +#X msg 122 222 midi 128 50 0;; +#X obj 122 240 del 300; +#X text 168 140 D#3; +#X obj 168 154 bng 15 25 0 1 0 0 empty k51 -2 -8 0 10 -262144 -1 -1; +#X obj 168 184 t b b; +#X msg 168 204 midi 144 51 100;; +#X msg 168 222 midi 128 51 0;; +#X obj 168 240 del 300; +#X text 214 140 E3; +#X obj 214 154 bng 15 25 0 1 0 0 empty k52 -2 -8 0 10 -262144 -1 -1; +#X obj 214 184 t b b; +#X msg 214 204 midi 144 52 100;; +#X msg 214 222 midi 128 52 0;; +#X obj 214 240 del 300; +#X text 260 140 F3; +#X obj 260 154 bng 15 25 0 1 0 0 empty k53 -2 -8 0 10 -262144 -1 -1; +#X obj 260 184 t b b; +#X msg 260 204 midi 144 53 100;; +#X msg 260 222 midi 128 53 0;; +#X obj 260 240 del 300; +#X text 306 140 F#3; +#X obj 306 154 bng 15 25 0 1 0 0 empty k54 -2 -8 0 10 -262144 -1 -1; +#X obj 306 184 t b b; +#X msg 306 204 midi 144 54 100;; +#X msg 306 222 midi 128 54 0;; +#X obj 306 240 del 300; +#X text 352 140 G3; +#X obj 352 154 bng 15 25 0 1 0 0 empty k55 -2 -8 0 10 -262144 -1 -1; +#X obj 352 184 t b b; +#X msg 352 204 midi 144 55 100;; +#X msg 352 222 midi 128 55 0;; +#X obj 352 240 del 300; +#X text 398 140 G#3; +#X obj 398 154 bng 15 25 0 1 0 0 empty k56 -2 -8 0 10 -262144 -1 -1; +#X obj 398 184 t b b; +#X msg 398 204 midi 144 56 100;; +#X msg 398 222 midi 128 56 0;; +#X obj 398 240 del 300; +#X text 444 140 A3; +#X obj 444 154 bng 15 25 0 1 0 0 empty k57 -2 -8 0 10 -262144 -1 -1; +#X obj 444 184 t b b; +#X msg 444 204 midi 144 57 100;; +#X msg 444 222 midi 128 57 0;; +#X obj 444 240 del 300; +#X text 490 140 A#3; +#X obj 490 154 bng 15 25 0 1 0 0 empty k58 -2 -8 0 10 -262144 -1 -1; +#X obj 490 184 t b b; +#X msg 490 204 midi 144 58 100;; +#X msg 490 222 midi 128 58 0;; +#X obj 490 240 del 300; +#X text 536 140 B3; +#X obj 536 154 bng 15 25 0 1 0 0 empty k59 -2 -8 0 10 -262144 -1 -1; +#X obj 536 184 t b b; +#X msg 536 204 midi 144 59 100;; +#X msg 536 222 midi 128 59 0;; +#X obj 536 240 del 300; +#X text 582 140 C4; +#X obj 582 154 bng 15 25 0 1 0 0 empty k60 -2 -8 0 10 -262144 -1 -1; +#X obj 582 184 t b b; +#X msg 582 204 midi 144 60 100;; +#X msg 582 222 midi 128 60 0;; +#X obj 582 240 del 300; +#X text 30 200 C#4; +#X obj 30 214 bng 15 25 0 1 0 0 empty k61 -2 -8 0 10 -262144 -1 -1; +#X obj 30 244 t b b; +#X msg 30 264 midi 144 61 100;; +#X msg 30 282 midi 128 61 0;; +#X obj 30 300 del 300; +#X text 76 200 D4; +#X obj 76 214 bng 15 25 0 1 0 0 empty k62 -2 -8 0 10 -262144 -1 -1; +#X obj 76 244 t b b; +#X msg 76 264 midi 144 62 100;; +#X msg 76 282 midi 128 62 0;; +#X obj 76 300 del 300; +#X text 122 200 D#4; +#X obj 122 214 bng 15 25 0 1 0 0 empty k63 -2 -8 0 10 -262144 -1 -1; +#X obj 122 244 t b b; +#X msg 122 264 midi 144 63 100;; +#X msg 122 282 midi 128 63 0;; +#X obj 122 300 del 300; +#X text 168 200 E4; +#X obj 168 214 bng 15 25 0 1 0 0 empty k64 -2 -8 0 10 -262144 -1 -1; +#X obj 168 244 t b b; +#X msg 168 264 midi 144 64 100;; +#X msg 168 282 midi 128 64 0;; +#X obj 168 300 del 300; +#X text 214 200 F4; +#X obj 214 214 bng 15 25 0 1 0 0 empty k65 -2 -8 0 10 -262144 -1 -1; +#X obj 214 244 t b b; +#X msg 214 264 midi 144 65 100;; +#X msg 214 282 midi 128 65 0;; +#X obj 214 300 del 300; +#X text 260 200 F#4; +#X obj 260 214 bng 15 25 0 1 0 0 empty k66 -2 -8 0 10 -262144 -1 -1; +#X obj 260 244 t b b; +#X msg 260 264 midi 144 66 100;; +#X msg 260 282 midi 128 66 0;; +#X obj 260 300 del 300; +#X text 306 200 G4; +#X obj 306 214 bng 15 25 0 1 0 0 empty k67 -2 -8 0 10 -262144 -1 -1; +#X obj 306 244 t b b; +#X msg 306 264 midi 144 67 100;; +#X msg 306 282 midi 128 67 0;; +#X obj 306 300 del 300; +#X text 352 200 G#4; +#X obj 352 214 bng 15 25 0 1 0 0 empty k68 -2 -8 0 10 -262144 -1 -1; +#X obj 352 244 t b b; +#X msg 352 264 midi 144 68 100;; +#X msg 352 282 midi 128 68 0;; +#X obj 352 300 del 300; +#X text 398 200 A4; +#X obj 398 214 bng 15 25 0 1 0 0 empty k69 -2 -8 0 10 -262144 -1 -1; +#X obj 398 244 t b b; +#X msg 398 264 midi 144 69 100;; +#X msg 398 282 midi 128 69 0;; +#X obj 398 300 del 300; +#X text 444 200 A#4; +#X obj 444 214 bng 15 25 0 1 0 0 empty k70 -2 -8 0 10 -262144 -1 -1; +#X obj 444 244 t b b; +#X msg 444 264 midi 144 70 100;; +#X msg 444 282 midi 128 70 0;; +#X obj 444 300 del 300; +#X text 490 200 B4; +#X obj 490 214 bng 15 25 0 1 0 0 empty k71 -2 -8 0 10 -262144 -1 -1; +#X obj 490 244 t b b; +#X msg 490 264 midi 144 71 100;; +#X msg 490 282 midi 128 71 0;; +#X obj 490 300 del 300; +#X text 536 200 C5; +#X obj 536 214 bng 15 25 0 1 0 0 empty k72 -2 -8 0 10 -262144 -1 -1; +#X obj 536 244 t b b; +#X msg 536 264 midi 144 72 100;; +#X msg 536 282 midi 128 72 0;; +#X obj 536 300 del 300; +#X text 680 120 -- PADS --; +#X text 680 140 C2; +#X obj 680 154 bng 15 15 0 1 0 0 empty p36 -2 -8 0 10 -262144 -1 -1; +#X obj 680 172 t b b; +#X msg 680 192 midi 144 36 100;; +#X msg 680 210 midi 128 36 0;; +#X obj 680 228 del 200; +#X text 735 140 C#2; +#X obj 735 154 bng 15 15 0 1 0 0 empty p37 -2 -8 0 10 -262144 -1 -1; +#X obj 735 172 t b b; +#X msg 735 192 midi 144 37 100;; +#X msg 735 210 midi 128 37 0;; +#X obj 735 228 del 200; +#X text 790 140 D2; +#X obj 790 154 bng 15 15 0 1 0 0 empty p38 -2 -8 0 10 -262144 -1 -1; +#X obj 790 172 t b b; +#X msg 790 192 midi 144 38 100;; +#X msg 790 210 midi 128 38 0;; +#X obj 790 228 del 200; +#X text 845 140 D#2; +#X obj 845 154 bng 15 15 0 1 0 0 empty p39 -2 -8 0 10 -262144 -1 -1; +#X obj 845 172 t b b; +#X msg 845 192 midi 144 39 100;; +#X msg 845 210 midi 128 39 0;; +#X obj 845 228 del 200; +#X text 680 195 E2; +#X obj 680 209 bng 15 15 0 1 0 0 empty p40 -2 -8 0 10 -262144 -1 -1; +#X obj 680 227 t b b; +#X msg 680 247 midi 144 40 100;; +#X msg 680 265 midi 128 40 0;; +#X obj 680 283 del 200; +#X text 735 195 F2; +#X obj 735 209 bng 15 15 0 1 0 0 empty p41 -2 -8 0 10 -262144 -1 -1; +#X obj 735 227 t b b; +#X msg 735 247 midi 144 41 100;; +#X msg 735 265 midi 128 41 0;; +#X obj 735 283 del 200; +#X text 790 195 F#2; +#X obj 790 209 bng 15 15 0 1 0 0 empty p42 -2 -8 0 10 -262144 -1 -1; +#X obj 790 227 t b b; +#X msg 790 247 midi 144 42 100;; +#X msg 790 265 midi 128 42 0;; +#X obj 790 283 del 200; +#X text 845 195 G2; +#X obj 845 209 bng 15 15 0 1 0 0 empty p43 -2 -8 0 10 -262144 -1 -1; +#X obj 845 227 t b b; +#X msg 845 247 midi 144 43 100;; +#X msg 845 265 midi 128 43 0;; +#X obj 845 283 del 200; +#X text 20 280 -- KNOBS --; +#X text 30 300 CC1 Mod; +#X obj 30 315 hsl 50 10 0 127 64 0 0 empty cc1 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 30 330 midi 176 1 $1;; +#X text 115 300 CC71 Reson; +#X obj 115 315 hsl 50 10 0 127 64 0 0 empty cc71 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 115 330 midi 176 71 $1;; +#X text 200 300 CC72 Release; +#X obj 200 315 hsl 50 10 0 127 64 0 0 empty cc72 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 200 330 midi 176 72 $1;; +#X text 285 300 CC73 Attack; +#X obj 285 315 hsl 50 10 0 127 64 0 0 empty cc73 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 285 330 midi 176 73 $1;; +#X text 370 300 CC74 Cutoff; +#X obj 370 315 hsl 50 10 0 127 100 0 0 empty cc74 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 370 330 midi 176 74 $1;; +#X text 455 300 CC75 Decay; +#X obj 455 315 hsl 50 10 0 127 64 0 0 empty cc75 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 455 330 midi 176 75 $1;; +#X text 540 300 CC76 LFO Rate; +#X obj 540 315 hsl 50 10 0 127 64 0 0 empty cc76 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 540 330 midi 176 76 $1;; +#X text 625 300 CC77 LFO Depth; +#X obj 625 315 hsl 50 10 0 127 64 0 0 empty cc77 -2 -8 0 10 -262144 -1 -1 7200 1; +#X msg 625 330 midi 176 77 $1;; +#X connect 2 0 3 0; +#X connect 9 0 10 0; +#X connect 10 0 11 0; +#X connect 11 0 3 0; +#X connect 10 1 13 0; +#X connect 13 0 12 0; +#X connect 12 0 3 0; +#X connect 15 0 16 0; +#X connect 16 0 17 0; +#X connect 17 0 3 0; +#X connect 16 1 19 0; +#X connect 19 0 18 0; +#X connect 18 0 3 0; +#X connect 21 0 22 0; +#X connect 22 0 23 0; +#X connect 23 0 3 0; +#X connect 22 1 25 0; +#X connect 25 0 24 0; +#X connect 24 0 3 0; +#X connect 27 0 28 0; +#X connect 28 0 29 0; +#X connect 29 0 3 0; +#X connect 28 1 31 0; +#X connect 31 0 30 0; +#X connect 30 0 3 0; +#X connect 33 0 34 0; +#X connect 34 0 35 0; +#X connect 35 0 3 0; +#X connect 34 1 37 0; +#X connect 37 0 36 0; +#X connect 36 0 3 0; +#X connect 39 0 40 0; +#X connect 40 0 41 0; +#X connect 41 0 3 0; +#X connect 40 1 43 0; +#X connect 43 0 42 0; +#X connect 42 0 3 0; +#X connect 45 0 46 0; +#X connect 46 0 47 0; +#X connect 47 0 3 0; +#X connect 46 1 49 0; +#X connect 49 0 48 0; +#X connect 48 0 3 0; +#X connect 51 0 52 0; +#X connect 52 0 53 0; +#X connect 53 0 3 0; +#X connect 52 1 55 0; +#X connect 55 0 54 0; +#X connect 54 0 3 0; +#X connect 57 0 58 0; +#X connect 58 0 59 0; +#X connect 59 0 3 0; +#X connect 58 1 61 0; +#X connect 61 0 60 0; +#X connect 60 0 3 0; +#X connect 63 0 64 0; +#X connect 64 0 65 0; +#X connect 65 0 3 0; +#X connect 64 1 67 0; +#X connect 67 0 66 0; +#X connect 66 0 3 0; +#X connect 69 0 70 0; +#X connect 70 0 71 0; +#X connect 71 0 3 0; +#X connect 70 1 73 0; +#X connect 73 0 72 0; +#X connect 72 0 3 0; +#X connect 75 0 76 0; +#X connect 76 0 77 0; +#X connect 77 0 3 0; +#X connect 76 1 79 0; +#X connect 79 0 78 0; +#X connect 78 0 3 0; +#X connect 81 0 82 0; +#X connect 82 0 83 0; +#X connect 83 0 3 0; +#X connect 82 1 85 0; +#X connect 85 0 84 0; +#X connect 84 0 3 0; +#X connect 87 0 88 0; +#X connect 88 0 89 0; +#X connect 89 0 3 0; +#X connect 88 1 91 0; +#X connect 91 0 90 0; +#X connect 90 0 3 0; +#X connect 93 0 94 0; +#X connect 94 0 95 0; +#X connect 95 0 3 0; +#X connect 94 1 97 0; +#X connect 97 0 96 0; +#X connect 96 0 3 0; +#X connect 99 0 100 0; +#X connect 100 0 101 0; +#X connect 101 0 3 0; +#X connect 100 1 103 0; +#X connect 103 0 102 0; +#X connect 102 0 3 0; +#X connect 105 0 106 0; +#X connect 106 0 107 0; +#X connect 107 0 3 0; +#X connect 106 1 109 0; +#X connect 109 0 108 0; +#X connect 108 0 3 0; +#X connect 111 0 112 0; +#X connect 112 0 113 0; +#X connect 113 0 3 0; +#X connect 112 1 115 0; +#X connect 115 0 114 0; +#X connect 114 0 3 0; +#X connect 117 0 118 0; +#X connect 118 0 119 0; +#X connect 119 0 3 0; +#X connect 118 1 121 0; +#X connect 121 0 120 0; +#X connect 120 0 3 0; +#X connect 123 0 124 0; +#X connect 124 0 125 0; +#X connect 125 0 3 0; +#X connect 124 1 127 0; +#X connect 127 0 126 0; +#X connect 126 0 3 0; +#X connect 129 0 130 0; +#X connect 130 0 131 0; +#X connect 131 0 3 0; +#X connect 130 1 133 0; +#X connect 133 0 132 0; +#X connect 132 0 3 0; +#X connect 135 0 136 0; +#X connect 136 0 137 0; +#X connect 137 0 3 0; +#X connect 136 1 139 0; +#X connect 139 0 138 0; +#X connect 138 0 3 0; +#X connect 141 0 142 0; +#X connect 142 0 143 0; +#X connect 143 0 3 0; +#X connect 142 1 145 0; +#X connect 145 0 144 0; +#X connect 144 0 3 0; +#X connect 147 0 148 0; +#X connect 148 0 149 0; +#X connect 149 0 3 0; +#X connect 148 1 151 0; +#X connect 151 0 150 0; +#X connect 150 0 3 0; +#X connect 153 0 154 0; +#X connect 154 0 155 0; +#X connect 155 0 3 0; +#X connect 154 1 157 0; +#X connect 157 0 156 0; +#X connect 156 0 3 0; +#X connect 160 0 161 0; +#X connect 161 0 162 0; +#X connect 162 0 3 0; +#X connect 161 1 164 0; +#X connect 164 0 163 0; +#X connect 163 0 3 0; +#X connect 166 0 167 0; +#X connect 167 0 168 0; +#X connect 168 0 3 0; +#X connect 167 1 170 0; +#X connect 170 0 169 0; +#X connect 169 0 3 0; +#X connect 172 0 173 0; +#X connect 173 0 174 0; +#X connect 174 0 3 0; +#X connect 173 1 176 0; +#X connect 176 0 175 0; +#X connect 175 0 3 0; +#X connect 178 0 179 0; +#X connect 179 0 180 0; +#X connect 180 0 3 0; +#X connect 179 1 182 0; +#X connect 182 0 181 0; +#X connect 181 0 3 0; +#X connect 184 0 185 0; +#X connect 185 0 186 0; +#X connect 186 0 3 0; +#X connect 185 1 188 0; +#X connect 188 0 187 0; +#X connect 187 0 3 0; +#X connect 190 0 191 0; +#X connect 191 0 192 0; +#X connect 192 0 3 0; +#X connect 191 1 194 0; +#X connect 194 0 193 0; +#X connect 193 0 3 0; +#X connect 196 0 197 0; +#X connect 197 0 198 0; +#X connect 198 0 3 0; +#X connect 197 1 200 0; +#X connect 200 0 199 0; +#X connect 199 0 3 0; +#X connect 202 0 203 0; +#X connect 203 0 204 0; +#X connect 204 0 3 0; +#X connect 203 1 206 0; +#X connect 206 0 205 0; +#X connect 205 0 3 0; +#X connect 209 0 210 0; +#X connect 210 0 3 0; +#X connect 212 0 213 0; +#X connect 213 0 3 0; +#X connect 215 0 216 0; +#X connect 216 0 3 0; +#X connect 218 0 219 0; +#X connect 219 0 3 0; +#X connect 221 0 222 0; +#X connect 222 0 3 0; +#X connect 224 0 225 0; +#X connect 225 0 3 0; +#X connect 227 0 228 0; +#X connect 228 0 3 0; +#X connect 230 0 231 0; +#X connect 231 0 3 0; diff --git a/public/samples/synth.pd b/public/samples/synth.pd new file mode 100644 index 0000000..f686707 --- /dev/null +++ b/public/samples/synth.pd @@ -0,0 +1,72 @@ +#N canvas 0 0 900 550 10; +# DO NOT EDIT — generated by scripts/gen_synth_pd.py; +#X obj 20 20 notein; +#X obj 80 50 pack 0 0; +#X obj 80 80 unpack 0 0; +#X obj 20 110 s midi-pitch; +#X obj 80 110 s midi-vel; +#X obj 400 20 netreceive -u 8081; +#X obj 400 60 route midi; +#X obj 400 100 route 144 128; +#X obj 400 140 unpack 0 0; +#X obj 480 140 unpack 0 0; +#X obj 400 180 s midi-pitch; +#X obj 480 180 s midi-vel; +#X obj 20 160 r midi-vel; +#X obj 20 190 r midi-pitch; +#X obj 20 220 stripnote; +#X obj 20 260 mtof; +#X obj 140 260 osc~; +#X obj 140 290 *~ 0.3; +#X obj 220 260 osc~; +#X obj 220 290 *~ 0.3; +#X obj 180 330 +~; +#X obj 180 360 *~ 0.5; +#X obj 180 400 lop~; +#X obj 180 460 *~; +#X obj 320 460 *~; +#X obj 250 530 dac~ 1; +#X obj 20 290 line~ 0 50; +#X obj 20 330 *~ 0.0055; +#X obj 100 370 *~; +#X obj 350 300 loadbang; +#X obj 350 320 float 10000; +#X obj 350 400 loadbang; +#X obj 350 420 float 80; +#X obj 350 450 / 100; +#X connect 0 0 1 0; +#X connect 0 1 1 1; +#X connect 1 0 2 0; +#X connect 2 0 3 0; +#X connect 2 1 4 0; +#X connect 5 0 6 0; +#X connect 6 0 7 0; +#X connect 7 0 8 0; +#X connect 7 1 9 0; +#X connect 8 0 10 0; +#X connect 8 1 11 0; +#X connect 9 0 10 0; +#X connect 9 1 11 0; +#X connect 12 0 14 1; +#X connect 13 0 14 0; +#X connect 14 0 15 0; +#X connect 15 0 16 0; +#X connect 15 0 18 0; +#X connect 16 0 17 0; +#X connect 18 0 19 0; +#X connect 17 0 20 0; +#X connect 19 0 20 1; +#X connect 20 0 21 0; +#X connect 21 0 22 0; +#X connect 22 0 23 0; +#X connect 14 1 26 0; +#X connect 26 0 27 0; +#X connect 27 0 28 0; +#X connect 23 0 28 1; +#X connect 28 0 24 0; +#X connect 29 0 30 0; +#X connect 30 0 22 1; +#X connect 31 0 32 0; +#X connect 32 0 33 0; +#X connect 33 0 24 1; +#X connect 24 0 25 0; diff --git a/server/bridge.mjs b/server/bridge.mjs new file mode 100644 index 0000000..26bb3b1 --- /dev/null +++ b/server/bridge.mjs @@ -0,0 +1,212 @@ +/** + * Bridge between the browser editor and a real Pure Data. + * + * browser --WebSocket--> bridge --UDP/FUDI--> Pd + * ^ | + * +------ UDP/FUDI ------+ + * + * Pd talks to us with `netreceive -u 8091` / `netsend -u localhost 8091`, and + * we talk to it on the patch's own receiver (`netreceive -u 8081`). + * + * node server/bridge.mjs [--port 8090] [--to-pd 8081] [--from-pd 8091] + * [--pd /usr/bin/pd] [--silent] + */ +import { spawn } from "node:child_process"; +import { mkdirSync, writeFileSync } from "node:fs"; +import { dirname, join, resolve } from "node:path"; +import { fileURLToPath } from "node:url"; +import dgram from "node:dgram"; +import { WebSocketServer } from "ws"; + +const HERE = dirname(fileURLToPath(import.meta.url)); + +function arg(name, fallback) { + const i = process.argv.indexOf(`--${name}`); + return i >= 0 && process.argv[i + 1] ? process.argv[i + 1] : fallback; +} +const flag = (name) => process.argv.includes(`--${name}`); + +const PORT = Number(arg("port", 8090)); +const TO_PD = Number(arg("to-pd", 8081)); +const FROM_PD = Number(arg("from-pd", 8091)); +const PD_BIN = arg("pd", "pd"); +const SILENT = flag("silent"); +const PATCH_DIR = resolve(arg("dir", join(HERE, "patches"))); + +mkdirSync(PATCH_DIR, { recursive: true }); + +// --- FUDI ------------------------------------------------------------------ + +/** Parse `a b c;` into atoms. Pd escapes `;, \$` with a backslash. */ +function parseFudi(buffer) { + const messages = []; + for (const record of buffer.toString("utf8").split(";")) { + if (!record.trim()) continue; + const atoms = []; + let buf = ""; + for (let i = 0; i < record.length; i++) { + const c = record[i]; + if (c === "\\") { + buf += record[++i] ?? ""; + continue; + } + if (c === " " || c === "\n" || c === "\r" || c === "\t") { + if (buf) atoms.push(buf); + buf = ""; + continue; + } + buf += c; + } + if (buf) atoms.push(buf); + if (atoms.length) messages.push({ receiver: atoms[0], args: atoms.slice(1) }); + } + return messages; +} + +/** Atoms that need no escaping, and numbers, go out bare. */ +function quoteAtom(atom) { + const s = String(atom); + if (/^-?\d+(\.\d+)?$/.test(s)) return s; + return s.replace(/([\\;,])/g, "\\$1"); +} + +function formatFudi(receiver, args) { + return `${[receiver, ...args].map(quoteAtom).join(" ")};\n`; +} + +// --- state ----------------------------------------------------------------- + +const udpToPd = dgram.createSocket("udp4"); +const udpFromPd = dgram.createSocket("udp4"); +const wss = new WebSocketServer({ port: PORT }); + +let pd = null; +let pdFile = null; +const logRing = []; +const MAX_LOG = 400; + +function broadcast(message) { + const data = JSON.stringify(message); + for (const client of wss.clients) { + if (client.readyState === 1) client.send(data); + } +} + +function log(stream, line) { + const entry = { type: "log", stream, line }; + logRing.push(entry); + if (logRing.length > MAX_LOG) logRing.shift(); + broadcast(entry); +} + +function stopPd() { + if (!pd) return; + const child = pd; + pd = null; + child.kill("SIGTERM"); +} + +function startPd(file) { + stopPd(); + const args = ["-nogui", "-open", file]; + if (SILENT) args.push("-nosound"); + const child = spawn(PD_BIN, args, { stdio: ["ignore", "pipe", "pipe"] }); + pd = child; + pdFile = file; + log("stderr", `$ ${PD_BIN} ${args.join(" ")}`); + + const pipe = (stream) => (chunk) => { + for (const line of String(chunk).split("\n")) { + if (line.trim()) log(stream, line); + } + }; + child.stdout.on("data", pipe("stdout")); + child.stderr.on("data", pipe("stderr")); + child.on("exit", (code) => { + if (pd === child) { + pd = null; + pdFile = null; + } + log("stderr", `pd exited with code ${code}`); + broadcast({ type: "pd-status", running: false, file: null }); + }); + child.on("error", (err) => log("stderr", `failed to start pd: ${err.message}`)); + + broadcast({ type: "pd-status", running: true, file }); +} + +// --- sockets --------------------------------------------------------------- + +udpFromPd.on("message", (msg) => { + for (const { receiver, args } of parseFudi(msg)) { + broadcast({ type: "from-pd", receiver, args }); + } +}); +udpFromPd.bind(FROM_PD, "127.0.0.1"); + +wss.on("connection", (socket) => { + socket.send( + JSON.stringify({ + type: "hello", + pdRunning: Boolean(pd), + toPdPort: TO_PD, + fromPdPort: FROM_PD, + }), + ); + for (const entry of logRing) socket.send(JSON.stringify(entry)); + + socket.on("message", (data) => { + let message; + try { + message = JSON.parse(String(data)); + } catch { + return; + } + + switch (message.type) { + case "send": { + const text = formatFudi(message.receiver, message.args ?? []); + udpToPd.send(text, TO_PD, "127.0.0.1"); + break; + } + case "raw": { + udpToPd.send(`${message.message};\n`, TO_PD, "127.0.0.1"); + break; + } + case "save": { + // Keep the name a leaf: the browser must not write outside patches/. + const name = String(message.name || "patch.pd").replace(/[^\w.-]/g, "_"); + const file = join(PATCH_DIR, name.endsWith(".pd") ? name : `${name}.pd`); + writeFileSync(file, String(message.text)); + log("stderr", `saved ${file}`); + socket.send(JSON.stringify({ type: "saved", file })); + break; + } + case "run": { + const name = String(message.file || "").replace(/[^\w.-]/g, "_"); + const file = join(PATCH_DIR, name); + startPd(file); + break; + } + case "stop": + stopPd(); + broadcast({ type: "pd-status", running: false, file: null }); + break; + default: + socket.send(JSON.stringify({ type: "error", message: `unknown message ${message.type}` })); + } + }); +}); + +console.log(`dragology-pd bridge`); +console.log(` browser ws://127.0.0.1:${PORT}`); +console.log(` -> pd udp 127.0.0.1:${TO_PD}`); +console.log(` <- pd udp 127.0.0.1:${FROM_PD}`); +console.log(` patches ${PATCH_DIR}`); + +for (const signal of ["SIGINT", "SIGTERM"]) { + process.on(signal, () => { + stopPd(); + process.exit(0); + }); +} diff --git a/src/App.tsx b/src/App.tsx new file mode 100644 index 0000000..c265648 --- /dev/null +++ b/src/App.tsx @@ -0,0 +1,297 @@ +import { DraggableRenderer } from "dragology"; +import { useCallback, useEffect, useMemo, useRef, useState } from "react"; + +import { Bridge, type BridgeMessage, type BridgeStatus } from "./bridge/client.ts"; +import { + addNode, + canvasExtent, + deleteNode, + newNodeId, + type PatchState, + reconcile, + stateFromPatch, +} from "./editor/ops.ts"; +import { patchDraggable } from "./editor/PatchCanvas.tsx"; +import { parsePd } from "./pd/parse.ts"; +import { serializePd } from "./pd/serialize.ts"; + +const BRIDGE_URL = "ws://127.0.0.1:8090"; +const SAMPLES = ["synth.pd", "mpk-mini-sim.pd", "controller.pd"]; + +export function App() { + const [state, setState] = useState(null); + const [placing, setPlacing] = useState(false); + const [objectText, setObjectText] = useState("osc~ 440"); + const [sendTarget, setSendTarget] = useState("midi-pitch"); + const [log, setLog] = useState([]); + const [status, setStatus] = useState("disconnected"); + const [pdRunning, setPdRunning] = useState(false); + /** Bumped on every load so the renderer mounts fresh for a new document. */ + const [docEpoch, setDocEpoch] = useState(0); + const bridge = useMemo(() => new Bridge(BRIDGE_URL), []); + const fileInput = useRef(null); + + useEffect(() => { + const offStatus = bridge.onStatus(setStatus); + const offMessage = bridge.onMessage((message: BridgeMessage) => { + if (message.type === "log") { + append(`${message.stream}: ${message.line}`); + } else if (message.type === "from-pd") { + append(`<- ${message.receiver} ${message.args.join(" ")}`); + } else if (message.type === "pd-status") { + setPdRunning(message.running); + } else if (message.type === "hello") { + setPdRunning(message.pdRunning); + } + }); + return () => { + offStatus(); + offMessage(); + }; + }, [bridge]); + + const append = useCallback((line: string) => { + setLog((prev) => [...prev.slice(-199), line]); + }, []); + + const load = useCallback((text: string, name: string) => { + setState(stateFromPatch(parsePd(text, name))); + // Two documents have nothing in common to interpolate between; starting + // the renderer over avoids dragology trying to lerp a comment into a box. + setDocEpoch((n) => n + 1); + }, []); + + const loadSample = useCallback( + async (name: string) => { + const response = await fetch(`/samples/${name}`); + if (response.ok) load(await response.text(), name); + }, + [load], + ); + + // Open a sample on first load so the page is never empty. + const booted = useRef(false); + useEffect(() => { + if (booted.current) return; + booted.current = true; + void loadSample(SAMPLES[0]); + }, [loadSample]); + + const save = useCallback(() => { + if (!state) return; + const blob = new Blob([serializePd(state)], { type: "text/plain" }); + const link = document.createElement("a"); + link.href = URL.createObjectURL(blob); + link.download = state.name || "patch.pd"; + link.click(); + URL.revokeObjectURL(link.href); + }, [state]); + + const saveAndRun = useCallback(() => { + if (!state) return; + bridge.send({ type: "save", name: state.name, text: serializePd(state) }); + bridge.send({ type: "run", file: state.name }); + }, [state, bridge]); + + useEffect(() => { + const onKey = (event: KeyboardEvent) => { + const target = event.target as HTMLElement | null; + if (target && /^(INPUT|TEXTAREA|SELECT)$/.test(target.tagName)) return; + if (event.key === "Escape") setPlacing(false); + if (event.key !== "Delete" && event.key !== "Backspace") return; + if (!state?.selection) return; + event.preventDefault(); + setState(deleteNode(state, state.selection)); + }; + window.addEventListener("keydown", onKey); + return () => window.removeEventListener("keydown", onKey); + }, [state]); + + const placeAt = useCallback( + (clientX: number, clientY: number, rect: DOMRect) => { + if (!state || !placing) return; + const id = newNodeId(); + const text = objectText.trim(); + setState( + addNode(state, { + id, + kind: "obj", + x: Math.round(clientX - rect.left), + y: Math.round(clientY - rect.top), + head: "#X obj", + tail: ` ${text}`, + text, + }), + ); + setPlacing(false); + }, + [state, placing, objectText], + ); + + if (!state) { + return ( +
+

dragology-pd

+

Open a .pd file, or wait for the sample to load.

+ + { + const file = e.target.files?.[0]; + if (file) void file.text().then((text) => load(text, file.name)); + }} + /> +
+ ); + } + + const extent = canvasExtent(state.header, state.nodes); + + return ( +
+
+ dragology-pd + {state.name} + + + { + const file = e.target.files?.[0]; + if (file) void file.text().then((text) => load(text, file.name)); + }} + /> + + + + + + + + + setObjectText(e.target.value)} + placeholder="object text" + /> + + + + + {state.warnings.length > 0 ? ( + + ⚠ {state.warnings.length} line{state.warnings.length > 1 ? "s" : ""} pd will reject + + ) : null} + + +
+ +
+
+ setState(reconcile(next))} + /> + {placing ? ( +
+ placeAt(e.clientX, e.clientY, e.currentTarget.getBoundingClientRect()) + } + /> + ) : null} +
+ + +
+
+ ); +} diff --git a/src/bridge/client.ts b/src/bridge/client.ts new file mode 100644 index 0000000..8fad24e --- /dev/null +++ b/src/bridge/client.ts @@ -0,0 +1,76 @@ +import type { PatchState } from "../editor/ops.ts"; + +export type BridgeMessage = + | { type: "hello"; pdRunning: boolean; toPdPort: number; fromPdPort: number } + | { type: "from-pd"; receiver: string; args: string[] } + | { type: "log"; stream: "stdout" | "stderr"; line: string } + | { type: "pd-status"; running: boolean; file: string | null } + | { type: "error"; message: string }; + +export type BridgeStatus = "disconnected" | "connecting" | "open"; + +/** + * Thin WebSocket client for `server/bridge.mjs`. + * + * The bridge is optional: the editor works on files alone, and the socket + * only exists to run a patch in a real Pd and to poke named receivers. + */ +export class Bridge { + private ws: WebSocket | null = null; + private listeners = new Set<(m: BridgeMessage) => void>(); + private statusListeners = new Set<(s: BridgeStatus) => void>(); + + constructor(private url: string) {} + + onMessage(fn: (m: BridgeMessage) => void) { + this.listeners.add(fn); + return () => this.listeners.delete(fn); + } + + onStatus(fn: (s: BridgeStatus) => void) { + this.statusListeners.add(fn); + return () => this.statusListeners.delete(fn); + } + + private emitStatus(status: BridgeStatus) { + for (const fn of this.statusListeners) fn(status); + } + + connect() { + if (this.ws) return; + this.emitStatus("connecting"); + const ws = new WebSocket(this.url); + this.ws = ws; + ws.onopen = () => this.emitStatus("open"); + ws.onclose = () => { + this.ws = null; + this.emitStatus("disconnected"); + }; + ws.onerror = () => this.emitStatus("disconnected"); + ws.onmessage = (event) => { + let message: BridgeMessage; + try { + message = JSON.parse(String(event.data)); + } catch { + return; + } + for (const fn of this.listeners) fn(message); + }; + } + + disconnect() { + this.ws?.close(); + this.ws = null; + this.emitStatus("disconnected"); + } + + send(message: unknown): boolean { + if (this.ws?.readyState !== WebSocket.OPEN) return false; + this.ws.send(JSON.stringify(message)); + return true; + } + + get isOpen() { + return this.ws?.readyState === WebSocket.OPEN; + } +} diff --git a/src/editor/PatchCanvas.tsx b/src/editor/PatchCanvas.tsx new file mode 100644 index 0000000..d2c1f7d --- /dev/null +++ b/src/editor/PatchCanvas.tsx @@ -0,0 +1,372 @@ +import { type DragSpecBuilder, param, translate, type Draggable } from "dragology"; + +import { + BOX_PADDING, + GUI_CLASSES, + inletPoint, + nodePorts, + nodeSize, + objectClass, + objectLabel, + outletPoint, +} from "../pd/geometry.ts"; +import type { PdNode } from "../pd/types.ts"; +import { canvasExtent, commitDrag, type PatchState, roundNode } from "./ops.ts"; + + +export const theme = { + canvas: "#e9e9e6", + ink: "#151515", + box: "#fdfdfb", + messageBox: "#fffdf0", + cord: "#8a8f98", + cordActive: "#d9480f", + nub: "#7a7f87", + nubActive: "#d9480f", + selection: "#0b7bd6", + comment: "#3d3d3d", +}; + +/** Nodes in Pd's object order — the order the file uses. */ +export function orderedNodes(state: PatchState): PdNode[] { + const out: PdNode[] = []; + for (const record of state.records) { + if (record.kind !== "node") continue; + const node = state.nodes[record.id]; + if (node) out.push(node); + } + return out; +} + +function cordEnds(state: PatchState, cordId: string) { + const cord = state.cords[cordId]; + if (!cord) return null; + const from = state.nodes[cord.from]; + const to = state.nodes[cord.to]; + if (!from || !to) return null; + return { + a: outletPoint(from, cord.outlet, nodePorts(from).outlets, state.fontSize), + b: inletPoint(to, cord.inlet, nodePorts(to).inlets, state.fontSize), + }; +} + +/** + * Signal cords in Pd are drawn as vertical-tangent curves; the control point + * offset grows with the vertical gap so short hops stay tight and long ones + * bow out. + */ +export function cordPath(a: { x: number; y: number }, b: { x: number; y: number }): string { + const bow = Math.max(18, Math.abs(b.y - a.y) * 0.5); + return `M ${a.x} ${a.y} C ${a.x} ${a.y + bow}, ${b.x} ${b.y - bow}, ${b.x} ${b.y}`; +} + +function cordSpec( + state: PatchState, + d: DragSpecBuilder, + from: string, + outlet: number, + start: { x: number; y: number }, +) { + const base: PatchState = { + ...state, + drag: { kind: "cord", from, outlet, x: start.x, y: start.y, snap: null }, + }; + + // Every inlet in the patch is a candidate drop target. In each branch the + // plug sits exactly on that inlet and remembers it, so `d.closest` can pick + // the branch by how near the pointer is and the drop knows what to build. + const branches: PatchState[] = []; + for (const node of orderedNodes(state)) { + const { inlets } = nodePorts(node); + for (let k = 0; k < inlets; k++) { + const p = inletPoint(node, k, inlets, state.fontSize); + branches.push({ + ...base, + drag: { + kind: "cord", + from, + outlet, + x: p.x, + y: p.y, + snap: { node: node.id, inlet: k }, + }, + }); + } + } + + const free = d.vary(base, [param("drag", "x"), param("drag", "y")]); + if (branches.length === 0) return free.onDrop(commitDrag); + + // Near an inlet the plug snaps onto it; further away it follows the pointer + // and the connection is simply not made. + return d.closest(branches).whenFar(free, { gap: 34 }).onDrop(commitDrag); +} + +function boxFor(node: PdNode, fontSize: number) { + const { width, height } = nodeSize(node, fontSize); + return ( + + ); +} + +/** + * GUI objects paint themselves, not their text. A believable placeholder is + * better than the raw `hsl 128 15 0 127 64 ...` argument soup. + */ +function guiBody(node: PdNode, w: number, h: number, fontSize: number) { + const cls = objectClass(node); + const a = node.text.split(" ").filter(Boolean); + const numbers = a.slice(1).map(Number); + const finite = (n: number) => Number.isFinite(n); + + switch (cls) { + case "bng": + return ( + + + + + ); + case "tgl": + return ( + + + {numbers[1] ? ( + + ) : null} + + ); + case "hsl": + case "hdl": { + const [min, max, , init] = [numbers[2], numbers[3], numbers[4], numbers[5]]; + const frac = finite(min) && finite(max) && max > min ? (init - min) / (max - min) : 0.5; + const x = 3 + Math.min(1, Math.max(0, finite(frac) ? frac : 0.5)) * (w - 6); + return ( + + + + + + ); + } + case "vsl": + case "vdl": { + const [min, max, , init] = [numbers[2], numbers[3], numbers[4], numbers[5]]; + const frac = finite(min) && finite(max) && max > min ? (init - min) / (max - min) : 0.5; + const y = h - 3 - Math.min(1, Math.max(0, finite(frac) ? frac : 0.5)) * (h - 6); + return ( + + + + + + ); + } + case "nbx": + return ( + + + + {finite(numbers[5]) ? numbers[5] : 0} + + + ); + default: + return ( + + + + ); + } +} + +function nodeBody(node: PdNode, w: number, h: number, fontSize: number) { + if (node.kind === "text") { + return ( + + {node.text} + + ); + } + if (GUI_CLASSES.has(objectClass(node))) return guiBody(node, w, h, fontSize); + + // Atom boxes store their formatting, not their contents. + const label = + node.kind === "floatatom" ? "0" + : node.kind === "symbolatom" ? "symbol" + : node.kind === "listbox" ? "list" + : node.kind === "subpatch" ? `${node.text} [subpatch]` + : objectLabel(node); + + return ( + + {boxFor(node, fontSize)} + + {label} + + + ); +} + +export const patchDraggable: Draggable = ({ state, d, draggedId, setState }) => { + const { width, height } = canvasExtent(state.header, state.nodes); + const nodes = orderedNodes(state); + const drag = state.drag; + + return ( + + setState({ ...state, selection: null }, { transition: false })} + /> + + {/* Cords sit under the boxes. */} + + {Object.keys(state.cords).map((id) => { + const ends = cordEnds(state, id); + if (!ends) return null; + return ( + + ); + })} + + + {/* The cord being pulled out of an outlet. */} + {cordInFlight(state, "cord-in-flight")} + + + {nodes.map((node) => { + const { width: w, height: h } = nodeSize(node, state.fontSize); + const fontSize = state.fontSize; + const ports = nodePorts(node); + const isSelected = state.selection === node.id; + + return ( + setState({ ...state, selection: node.id }, { transition: false })} + dragologyOnDrag={() => + d + .vary(state, [param("nodes", node.id, "x"), param("nodes", node.id, "y")]) + .onDrop((s) => roundNode(s, node.id, state.grid)) + } + > + {node.kind === "text" ? ( + + {node.text} + + ) : ( + + {nodeBody(node, w, h, fontSize)} + {isSelected ? ( + + ) : null} + + )} + + {Array.from({ length: ports.inlets }).map((_, i) => { + const p = inletPoint(node, i, ports.inlets, state.fontSize); + return ( + + ); + })} + + {Array.from({ length: ports.outlets }).map((_, i) => { + const p = outletPoint(node, i, ports.outlets, state.fontSize); + const active = drag.kind === "cord" && drag.from === node.id && drag.outlet === i; + return ( + cordSpec(state, d, node.id, i, p)} + /> + ); + })} + + ); + })} + + + ); +}; + +/** + * The rubber-band cord between the outlet and the plug being dragged. + * + * A plain function, not a component: Dragology has to see inside it to + * interpolate the path mid-drag. + */ +function cordInFlight(state: PatchState, id: string) { + const drag = state.drag; + if (drag.kind !== "cord" || !drag.from) return null; + const node = state.nodes[drag.from]; + if (!node) return null; + const a = outletPoint(node, drag.outlet, nodePorts(node).outlets, state.fontSize); + return ( + + ); +} diff --git a/src/editor/ops.ts b/src/editor/ops.ts new file mode 100644 index 0000000..54951ab --- /dev/null +++ b/src/editor/ops.ts @@ -0,0 +1,192 @@ +import { headerFontSize } from "../pd/geometry.ts"; +import type { PdCord, PdNode, PatchRecord, PdPatch } from "../pd/types.ts"; + +/** + * `x`/`y` are always present so `param("drag", "x")` stays a simple path; the + * kind decides whether they are being used. + */ +export interface DragState { + kind: "idle" | "cord"; + from: string | null; + outlet: number; + x: number; + y: number; + /** Set while the plug sits on an inlet, so the drop can commit it. */ + snap: { node: string; inlet: number } | null; +} + +export const IDLE_DRAG: DragState = { + kind: "idle", + from: null, + outlet: -1, + x: 0, + y: 0, + snap: null, +}; + +export interface PatchState { + /** Live positions: the bits a drag can change. */ + nodes: Record; + cords: Record; + /** Canvas as a record sequence; `drag` never touches it. */ + records: PatchRecord[]; + header: string; + name: string; + drag: DragState; + selection: string | null; + /** Drop grid in pixels; 1 means no snapping. */ + grid: number; + /** Canvas font size from the `#N canvas` header. */ + fontSize: number; + /** Lines Pd will choke on, carried over from the file. */ + warnings: string[]; +} + +let nodeCounter = 0; +let cordCounter = 0; + +/** Fresh opaque ids. Dragology requires globally unique SVG ids, no slashes. */ +export function newNodeId(): string { + return `new-${Date.now().toString(36)}-${nodeCounter++}`; +} + +export function newCordId(): string { + return `newcord-${Date.now().toString(36)}-${cordCounter++}`; +} + +export function stateFromPatch(patch: PdPatch): PatchState { + return { + nodes: { ...patch.nodes }, + cords: { ...patch.cords }, + records: [...patch.records], + header: patch.header, + name: patch.name, + drag: IDLE_DRAG, + selection: null, + grid: 1, + fontSize: headerFontSize(patch.header), + warnings: [...patch.warnings], + }; +} + +export function patchFromState(state: PatchState): PdPatch { + return { + header: state.header, + nodes: state.nodes, + cords: state.cords, + records: state.records, + name: state.name, + warnings: state.warnings, + }; +} + +/** + * Bring `records` back in line with `nodes`/`cords`. + * + * A drag only ever writes to those two maps, so the record sequence can drift: + * a new cord has no record yet, and a deleted node leaves a record behind. + * Existing records keep their positions; new cords go after the last existing + * cord record, which is where Pd expects them. + */ +export function reconcile(state: PatchState): PatchState { + const nodeIds = new Set(Object.keys(state.nodes)); + const cordIds = new Set(Object.keys(state.cords)); + + const records = state.records.filter((r) => + r.kind === "node" ? nodeIds.has(r.id) : r.kind === "cord" ? cordIds.has(r.id) : true, + ); + + const placed = new Set(records.flatMap((r) => (r.kind === "cord" ? [r.id] : []))); + const missing = Object.keys(state.cords) + .filter((id) => !placed.has(id)) + .map((id) => ({ kind: "cord", id })); + + if (missing.length > 0) { + let insertAt = records.length; + for (let i = records.length - 1; i >= 0; i--) { + if (records[i].kind === "cord") { + insertAt = i + 1; + break; + } + } + records.splice(insertAt, 0, ...missing); + } + return { ...state, records }; +} + +/** Insert a node record where Pd expects objects: before the first cord. */ +export function addNode(state: PatchState, node: PdNode): PatchState { + const records = [...state.records]; + let insertAt = records.findIndex((r) => r.kind === "cord"); + if (insertAt === -1) insertAt = records.length; + records.splice(insertAt, 0, { kind: "node", id: node.id }); + return { + ...state, + nodes: { ...state.nodes, [node.id]: node }, + records, + selection: node.id, + }; +} + +export function deleteNode(state: PatchState, id: string): PatchState { + const nodes = { ...state.nodes }; + delete nodes[id]; + const cords = Object.fromEntries( + Object.entries(state.cords).filter(([, c]) => c.from !== id && c.to !== id), + ); + return reconcile({ ...state, nodes, cords, selection: null }); +} + +export function addCord( + state: PatchState, + from: string, + outlet: number, + to: string, + inlet: number, +): PatchState { + const id = newCordId(); + return reconcile({ + ...state, + cords: { ...state.cords, [id]: { id, from, outlet, to, inlet } }, + }); +} + +/** + * End a cord drag: if the plug landed on an inlet, that connection becomes a + * real cord. Dropping in empty space simply cancels. + */ +export function commitDrag(state: PatchState): PatchState { + const drag = state.drag; + const idle: PatchState = { ...state, drag: IDLE_DRAG }; + if (drag.kind !== "cord" || !drag.from || !drag.snap) return idle; + return addCord(idle, drag.from, drag.outlet, drag.snap.node, drag.snap.inlet); +} + +export function deleteCord(state: PatchState, id: string): PatchState { + const cords = { ...state.cords }; + delete cords[id]; + return reconcile({ ...state, cords }); +} + +/** Apply the grid the user asked for at drop time, not mid-drag. */ +export function roundNode(state: PatchState, id: string, grid: number): PatchState { + const node = state.nodes[id]; + if (!node) return state; + const snap = (v: number) => (grid > 1 ? Math.round(v / grid) * grid : Math.round(v)); + return { + ...state, + nodes: { ...state.nodes, [id]: { ...node, x: snap(node.x), y: snap(node.y) } }, + }; +} + +/** Canvas extent: Pd's window size, grown to cover anything dragged outside. */ +export function canvasExtent(header: string, nodes: Record) { + const parts = header.split(" "); + let width = Number(parts[4]) || 800; + let height = Number(parts[5]) || 600; + for (const node of Object.values(nodes)) { + width = Math.max(width, node.x + 240); + height = Math.max(height, node.y + 120); + } + return { width, height }; +} diff --git a/src/main.tsx b/src/main.tsx new file mode 100644 index 0000000..7452407 --- /dev/null +++ b/src/main.tsx @@ -0,0 +1,11 @@ +import { StrictMode } from "react"; +import { createRoot } from "react-dom/client"; + +import { App } from "./App.tsx"; +import "./styles.css"; + +createRoot(document.getElementById("root")!).render( + + + , +); diff --git a/src/pd/geometry.ts b/src/pd/geometry.ts new file mode 100644 index 0000000..7e540c4 --- /dev/null +++ b/src/pd/geometry.ts @@ -0,0 +1,212 @@ +import type { PdNode } from "./types.ts"; + +/** + * Pd draws a box around its text and puts nubs on the edges. The width Pd + * computed is not in the file, so we measure the same string with the same + * font the browser will use. Without a DOM (tests) we fall back to an + * estimate of the 12px monospace advance. + */ +export const DEFAULT_FONT_SIZE = 12; +const CHAR_WIDTH = 0.6; +export const BOX_PADDING = 9; +export const MIN_BOX_WIDTH = 22; + +let context: CanvasRenderingContext2D | null | undefined; +let contextFont = ""; + +export function textWidth(text: string, fontSize = DEFAULT_FONT_SIZE): number { + if (context === undefined) { + context = + typeof document === "undefined" + ? null + : document.createElement("canvas").getContext("2d"); + } + if (!context) return text.length * fontSize * CHAR_WIDTH; + const font = `${fontSize}px ui-monospace, "DejaVu Sans Mono", monospace`; + if (font !== contextFont) { + context.font = font; + contextFont = font; + } + return context.measureText(text).width; +} + +/** Objects that draw their own contents instead of showing their text. */ +export const GUI_CLASSES = new Set([ + "bng", "tgl", "nbx", "hsl", "vsl", "hdl", "vdl", "hradio", "vradio", "cnv", "vu", +]); + +export function objectClass(node: PdNode): string { + return node.text.split(" ")[0] ?? ""; +} + +/** The label Pd paints inside a box, which is empty for GUI objects. */ +export function objectLabel(node: PdNode): string { + if (GUI_CLASSES.has(objectClass(node))) return ""; + return node.text; +} + +/** GUI objects store their own pixel size in their arguments. */ +const GUI_SIZE: Record = { + bng: { w: 1, h: 2 }, + tgl: { w: 1, h: 1 }, + nbx: { w: 1, h: 2 }, + hsl: { w: 1, h: 2 }, + vsl: { w: 1, h: 2 }, + hslider: { w: 1, h: 2 }, + vslider: { w: 1, h: 2 }, + hdl: { w: 1, h: 2 }, + vdl: { w: 1, h: 2 }, + hradio: { w: 1, h: 1 }, + vradio: { w: 1, h: 1 }, +}; + +export interface NodeSize { + width: number; + height: number; +} + +function args(node: PdNode): string[] { + return node.text.split(" ").filter((a) => a !== ""); +} + +/** Pd stores the canvas font size as the last field of the `#N canvas` line. */ +export function headerFontSize(header: string): number { + const parts = header.split(" "); + const size = Number(parts[6]); + return Number.isFinite(size) && size > 0 && size < 40 ? size : DEFAULT_FONT_SIZE; +} + +/** Box height tracks the font, the way Pd's does. */ +export function boxHeight(fontSize = DEFAULT_FONT_SIZE): number { + return Math.round(fontSize * 1.5); +} + +export function nodeSize(node: PdNode, fontSize = DEFAULT_FONT_SIZE): NodeSize { + if (node.kind === "text") { + return { width: textWidth(node.text, fontSize), height: boxHeight(fontSize) }; + } + const a = args(node); + const gui = GUI_SIZE[a[0]]; + if (gui) { + const w = Number(a[gui.w]); + const h = Number(a[gui.h]); + if (Number.isFinite(w) && Number.isFinite(h) && w > 0 && h > 0) { + return { width: w, height: h }; + } + } + const label = objectLabel(node); + const width = Math.max(MIN_BOX_WIDTH, textWidth(label, fontSize) + BOX_PADDING * 2); + return { width, height: boxHeight(fontSize) }; +} + +/** Inlet/outlet counts, keyed by object class. */ +const PORTS: Record = { + // arithmetic, comparison, logic: two in, one out + "+": [2, 1], "-": [2, 1], "*": [2, 1], "/": [2, 1], "%": [2, 1], "pow": [2, 1], + "max": [2, 1], "min": [2, 1], "mod": [2, 1], "div": [2, 1], + ">": [2, 1], "<": [2, 1], "==": [2, 1], "!=": [2, 1], ">=": [2, 1], "<=": [2, 1], + "&&": [2, 1], "||": [2, 1], "&": [2, 1], "|": [2, 1], "<<": [2, 1], ">>": [2, 1], + // signal versions of the same + "+~": [2, 1], "-~": [2, 1], "*~": [2, 1], "/~": [2, 1], "max~": [2, 1], "min~": [2, 1], + "clip": [3, 1], "clip~": [3, 1], "line": [3, 1], "line~": [2, 1], + // audio + "osc~": [2, 1], "phasor~": [2, 1], "cos~": [1, 1], "noise~": [0, 1], + "lop~": [2, 1], "hip~": [2, 1], "bp~": [3, 1], "vcf~": [2, 2], "biquad~": [6, 1], + "dac~": [2, 0], "adc~": [0, 2], "outlet~": [1, 0], "inlet~": [0, 1], + "sig~": [1, 1], "env~": [1, 1], "snapshot~": [1, 1], "bang~": [0, 1], + "delread~": [1, 1], "delwrite~": [2, 0], "vd~": [2, 1], + "tabread~": [1, 1], "tabwrite~": [1, 0], "tabplay~": [1, 1], + "readsf~": [1, 2], "writesf~": [1, 0], "samplerate~": [0, 1], + "catch~": [0, 1], "throw~": [1, 0], "send~": [1, 0], "receive~": [0, 1], + "sqrt~": [1, 1], "wrap~": [1, 1], "fft~": [2, 2], "ifft~": [2, 2], + "sigmund~": [1, 3], "bonk~": [1, 3], + // messages + "send": [1, 0], "s": [1, 0], "receive": [0, 1], "r": [0, 1], + "print": [1, 0], "bang": [1, 1], "b": [1, 1], + "float": [2, 1], "f": [2, 1], "int": [2, 1], "i": [2, 1], "symbol": [2, 1], "list": [2, 1], + "loadbang": [0, 1], "loadmsg": [0, 1], + "metro": [2, 1], "delay": [2, 1], "del": [2, 1], "timer": [2, 1], "cputime": [0, 1], + "mtof": [1, 1], "ftom": [1, 1], "dbtorms": [1, 1], "rmstodb": [1, 1], + "stripnote": [2, 2], "makenote": [3, 2], + "notein": [0, 3], "noteout": [3, 0], "ctlin": [0, 3], "ctlout": [3, 0], + "pgmin": [0, 2], "pgmout": [2, 0], "bendin": [0, 2], "bendout": [2, 0], + "touchin": [0, 2], "touchout": [2, 0], "midiin": [0, 1], "midiout": [1, 0], + "polytouchin": [0, 3], "polytouchout": [3, 0], "sysexin": [0, 1], + "spigot": [2, 1], "moses": [2, 2], "swap": [2, 2], "until": [2, 1], + "select": [1, 2], "sel": [1, 2], "route": [1, 2], + "netreceive": [0, 1], "netsend": [1, 0], + "inlet": [0, 1], "outlet": [1, 0], + "openpanel": [1, 1], "savepanel": [1, 1], "soundfiler": [1, 2], + "expr": [1, 1], "expr~": [1, 1], "fexpr~": [1, 1], + // gui + "bng": [1, 1], "tgl": [1, 1], "nbx": [1, 1], "hsl": [1, 1], "vsl": [1, 1], + "hdl": [1, 1], "vdl": [1, 1], "hradio": [1, 1], "vradio": [1, 1], "vu": [0, 1], + "cnv": [1, 1], +}; + +export function nodePorts(node: PdNode): { inlets: number; outlets: number } { + if (node.kind === "text") return { inlets: 0, outlets: 0 }; + if (node.kind === "msg") return { inlets: 1, outlets: 1 }; + if (node.kind === "floatatom" || node.kind === "symbolatom" || node.kind === "listbox") { + return { inlets: 1, outlets: 1 }; + } + if (node.kind === "subpatch") return { inlets: 1, outlets: 1 }; + + const a = args(node); + const cls = a[0] ?? ""; + + // `dac~ 1` has one inlet and `dac~ 1 2` has two — Pd rejects a connect to + // an inlet that is not there, so getting this wrong lets the editor build + // patches Pd refuses to load. + if (cls === "dac~") return { inlets: Math.max(1, a.length - 1 || 2), outlets: 0 }; + if (cls === "adc~") return { inlets: 0, outlets: Math.max(1, a.length - 1 || 2) }; + + const known = PORTS[cls]; + if (known) return { inlets: known[0], outlets: known[1] }; + + // Outlet count from the arguments. `route`/`select` add a pass-through + // outlet at the end; `trigger` and `unpack` do not. + const fanOut: Record = { + t: 0, trigger: 0, unpack: 0, + route: 1, select: 1, sel: 1, + }; + if (cls in fanOut) { + const n = Math.max(1, a.length - 1); + return { inlets: 1, outlets: n + fanOut[cls] }; + } + const fanIn: Record = { pack: 1 }; + if (cls in fanIn) { + return { inlets: Math.max(1, a.length - 1), outlets: 1 }; + } + + // `+~ 0.5` style aliases, and anything ending in ~ is a signal object. + if (cls.endsWith("~")) return { inlets: 2, outlets: 1 }; + return { inlets: 1, outlets: 1 }; +} + +export interface Point { + x: number; + y: number; +} + +/** Where inlet `i` of `count` sits, in patch coordinates. */ +export function inletPoint( + node: PdNode, + i: number, + count: number, + fontSize = DEFAULT_FONT_SIZE, +): Point { + const { width } = nodeSize(node, fontSize); + return { x: node.x + (width * (i + 1)) / (count + 1), y: node.y }; +} + +/** Where outlet `i` of `count` sits, in patch coordinates. */ +export function outletPoint( + node: PdNode, + i: number, + count: number, + fontSize = DEFAULT_FONT_SIZE, +): Point { + const { width, height } = nodeSize(node, fontSize); + return { x: node.x + (width * (i + 1)) / (count + 1), y: node.y + height }; +} diff --git a/src/pd/parse.ts b/src/pd/parse.ts new file mode 100644 index 0000000..845dcb5 --- /dev/null +++ b/src/pd/parse.ts @@ -0,0 +1,275 @@ +import type { NodeKind, PatchRecord, PdCord, PdNode, PdPatch } from "./types.ts"; + +/** + * Split a file into records on unescaped `;`, preserving escapes. + * + * `null` stands for a blank line — a separator with no record of its own. + * Both have to survive, because a file with `;;` in it is not the same as a + * file with a blank line, and Pd writes both. + */ +export function splitRecords(text: string): (string | null)[] { + const out: (string | null)[] = []; + let buf = ""; + let found = false; + let newlines = 0; + + for (let i = 0; i < text.length; i++) { + const c = text[i]; + if (c === "\\") { + buf += c + (text[i + 1] ?? ""); + i++; + found = true; + continue; + } + if (c === ";") { + out.push(found ? buf : ""); + buf = ""; + found = false; + newlines = 0; + continue; + } + if (c === "\n" || c === "\r") { + if (!found) newlines++; + continue; + } + if (!found) { + // One newline is the ordinary separator; each extra one is a blank line. + while (newlines > 1) { + out.push(null); + newlines--; + } + } + buf += c; + found = true; + } + if (found) out.push(buf); + return out; +} + +/** Split a record into atoms on whitespace, unescaping `\` to ``. */ +export function splitAtoms(raw: string): string[] { + const out: string[] = []; + let buf = ""; + let found = false; + for (let i = 0; i < raw.length; i++) { + const c = raw[i]; + if (c === "\\") { + buf += raw[i + 1] ?? ""; + i++; + found = true; + continue; + } + if (c === " " || c === "\t" || c === "\n" || c === "\r") { + if (found) { + out.push(buf); + buf = ""; + found = false; + } + continue; + } + buf += c; + found = true; + } + if (found) out.push(buf); + return out; +} + +export function escapeAtom(s: string): string { + let out = ""; + for (const c of s) { + out += c === "\\" || c === ";" || c === "," || c === "$" || c === " " ? "\\" + c : c; + } + return out; +} + +const ATOM_KINDS: Record = { + obj: "obj", + msg: "msg", + text: "text", + floatatom: "floatatom", + symbolatom: "symbolatom", + listbox: "listbox", +}; + +/** The part of `raw` that follows its n-th whitespace-delimited token. */ +function tailAfterToken(raw: string, n: number): string { + let skipped = 0; + let inToken = false; + for (let i = 0; i < raw.length; i++) { + const c = raw[i]; + if (c === "\\") { + i++; + inToken = true; + continue; + } + if (c === " " || c === "\t") { + if (inToken) { + skipped++; + inToken = false; + if (skipped === n) { + // Keep the run of spaces that followed the token. + let j = i; + while (j < raw.length && (raw[j] === " " || raw[j] === "\t")) j++; + return raw.slice(j - 1); + } + } + continue; + } + inToken = true; + } + return ""; +} + +function num(atom: string | undefined, fallback = 0): number { + const n = Number(atom); + return Number.isFinite(n) ? n : fallback; +} + +/** + * Parse a `.pd` file. + * + * Only the outermost canvas is modelled. A nested subpatch comes back as one + * opaque node holding the entire `#N canvas ... #X restore` block, so its + * inner `#X connect` indices never collide with ours. + * + * `order` is Pd's own object index space: comments and subpatches count, and + * cords index into it. (Verified against Pd 0.57 — a cord that targets a + * comment is rejected with `(text->osc~) connection failed`.) + */ +export function parsePd(text: string, name = "untitled.pd"): PdPatch { + const raw = splitRecords(text); + const nodes: Record = {}; + const cords: Record = {}; + const records: PatchRecord[] = []; + const order: string[] = []; + const warnings: string[] = []; + /** connect records resolve after we know the full object order. */ + const unresolved: { id: string; src: number; outlet: number; dst: number; inlet: number }[] = []; + let header = "#N canvas 0 0 800 600 10"; + let headerSeen = false; + let nextId = 0; + + let i = 0; + while (i < raw.length) { + const record = raw[i]; + if (record === null) { + records.push({ kind: "blank" }); + i++; + continue; + } + const atoms = splitAtoms(record); + if (atoms.length === 0) { + // An empty record, e.g. the second `;` of `;;`. + records.push({ kind: "raw", text: "" }); + i++; + continue; + } + + // --- canvas header, or a nested subpatch ------------------------------- + if (atoms[0] === "#N" && atoms[1] === "canvas") { + if (!headerSeen) { + header = record.trim(); + headerSeen = true; + i++; + continue; + } + let depth = 0; + let block = ""; + let restore: string[] = []; + let j = i; + for (; j < raw.length; j++) { + const segment = raw[j]; + if (segment === null) { + block += "\n"; + continue; + } + const inner = splitAtoms(segment); + if (inner[0] === "#N" && inner[1] === "canvas") depth++; + else if (inner[0] === "#X" && inner[1] === "restore") depth--; + block += segment + ";\n"; + if (depth === 0) { + restore = inner; + break; + } + } + const id = `node-${nextId++}`; + nodes[id] = { + id, + kind: "subpatch", + x: num(restore[2]), + y: num(restore[3]), + head: "#N canvas", + tail: "", + text: restore.find((a, k) => k > 4) ?? "subpatch", + raw: block, + }; + order.push(id); + records.push({ kind: "node", id }); + i = j + 1; + continue; + } + + if (atoms[0] === "#X") { + const kind = ATOM_KINDS[atoms[1]]; + if (kind) { + const id = `node-${nextId++}`; + const tail = tailAfterToken(record, 4); + nodes[id] = { + id, + kind, + x: num(atoms[2]), + y: num(atoms[3]), + head: `#X ${atoms[1]}`, + tail, + text: splitAtoms(tail).join(" "), + }; + order.push(id); + records.push({ kind: "node", id }); + i++; + continue; + } + if (atoms[1] === "connect") { + const id = `cord-${nextId++}`; + cords[id] = { id, from: "", outlet: num(atoms[3]), to: "", inlet: num(atoms[5]) }; + unresolved.push({ + id, + src: num(atoms[2]), + outlet: num(atoms[3]), + dst: num(atoms[4]), + inlet: num(atoms[5]), + }); + records.push({ kind: "cord", id }); + i++; + continue; + } + } + + records.push({ kind: "raw", text: record }); + // A `#` record Pd does not know about becomes a failed object creation, + // e.g. a bare `# some comment;` line. Keep it in the file, but say so. + if (record.trimStart().startsWith("#") && !/^#(A|F)\b/.test(record.trimStart())) { + warnings.push(`Pd cannot parse this line: ${record.trim()}`); + } + i++; + } + + for (const c of unresolved) { + const from = order[c.src]; + const to = order[c.dst]; + if (!from || !to) { + // Pd would reject this too; drop it rather than emit a broken file. + delete cords[c.id]; + continue; + } + cords[c.id] = { ...cords[c.id], from, to }; + } + + return { + header, + nodes, + cords, + records: records.filter((r) => r.kind !== "cord" || Boolean(cords[r.id])), + name, + warnings, + }; +} diff --git a/src/pd/serialize.ts b/src/pd/serialize.ts new file mode 100644 index 0000000..0088e36 --- /dev/null +++ b/src/pd/serialize.ts @@ -0,0 +1,76 @@ +import type { PdNode, PdPatch } from "./types.ts"; + +/** Emit the `#X obj x y ...` style record for a node. */ +export function nodeRecord(node: PdNode): string { + if (node.kind === "subpatch") { + return patchSubpatchPosition(node); + } + return `${node.head} ${Math.round(node.x)} ${Math.round(node.y)}${node.tail}`; +} + +/** + * Move a subpatch by rewriting the coordinates on its `#X restore` record — + * the only place the parent canvas stores the subpatch's position. + */ +function patchSubpatchPosition(node: PdNode): string { + if (!node.raw) return ""; + return node.raw.replace( + /#X restore (-?[\d.]+) (-?[\d.]+)/, + () => `#X restore ${Math.round(node.x)} ${Math.round(node.y)}`, + ); +} + +/** + * Serialize a patch back to `.pd` text. + * + * Records are emitted in their original sequence, so re-saving a patch you + * merely looked at produces the same bytes you loaded. + */ +export function serializePd(patch: PdPatch): string { + const lines: string[] = [`${patch.header};`]; + + // Pd closes a record with `;` and starts a new line. An *empty* record + // (the `;;` in a file) has no line of its own: its `;` lands directly after + // the previous one, so it appends instead of pushing. + const emit = (text: string) => { + if (text === "" && lines.length > 0) lines[lines.length - 1] += ";"; + else lines.push(`${text};`); + }; + + for (const record of patch.records) { + if (record.kind === "blank") { + lines.push(""); + continue; + } + if (record.kind === "raw") { + emit(record.text); + continue; + } + if (record.kind === "node") { + const node = patch.nodes[record.id]; + if (!node) continue; + const text = nodeRecord(node); + if (node.kind === "subpatch") lines.push(text.replace(/\n$/, "")); + else emit(text); + continue; + } + const cord = patch.cords[record.id]; + if (!cord) continue; + emit( + `#X connect ${nodePosition(patch, cord.from)} ${cord.outlet} ${nodePosition(patch, cord.to)} ${cord.inlet}`, + ); + } + return lines.join("\n") + "\n"; +} + +/** Pd object index of a node id. */ +export function nodePosition(patch: PdPatch, id: string): number { + let n = -1; + for (const record of patch.records) { + if (record.kind === "node") { + n++; + if (record.id === id) return n; + } + } + return -1; +} diff --git a/src/pd/types.ts b/src/pd/types.ts new file mode 100644 index 0000000..e8c3f6c --- /dev/null +++ b/src/pd/types.ts @@ -0,0 +1,86 @@ +/** + * Data model for a Pure Data canvas (a single .pd file, top-level only). + * + * Two things are deliberately kept in their original textual form: + * + * - `PdNode.tail` — the record text after the `x y` coordinates, escapes + * intact. Rewriting a node means re-emitting `head x y tail`, so atoms we + * do not understand (escaped semicolons, `$0` variables, commas) survive + * untouched. + * - `raw` records — anything we do not model (arrays, `#X declare`, + * subpatches, unknown additions to the format). + * + * That makes `parse` -> `serialize` a byte-exact round trip, which is the + * property the tests lean on. + */ + +export type NodeKind = + | "obj" + | "msg" + | "text" + | "floatatom" + | "symbolatom" + | "listbox" + | "subpatch"; + +export interface PdNode { + id: string; + kind: NodeKind; + /** Top-left corner, in patch coordinates. */ + x: number; + y: number; + /** The record head, e.g. `#X obj` or `#X floatatom`. */ + head: string; + /** Record text strictly after the `y` token, leading space included. */ + tail: string; + /** Human-readable content: for obj/msg/text the message, else the tail. */ + text: string; + /** For a subpatch, the whole `#N canvas ... #X restore` block. */ + raw?: string; +} + +export interface PdCord { + id: string; + /** Node ids. Pd stores numeric indices; we resolve them at parse time. */ + from: string; + outlet: number; + to: string; + inlet: number; +} + +/** + * The canvas is a *sequence* of records, not a set. Pd is order-sensitive: + * object order defines the indices cords refer to, and `#N canvas` / + * `#X restore` pairs have to stay where they are. Keeping the sequence lets + * us add a cord without shuffling the file. + */ +export type PatchRecord = + | { kind: "node"; id: string } + | { kind: "cord"; id: string } + | { kind: "raw"; text: string } + /** A blank line. Pd writes these between sections; they carry no record. */ + | { kind: "blank" }; + +export interface PdPatch { + /** `#N canvas ...` for this canvas, without the leading `#N `. */ + header: string; + nodes: Record; + cords: Record; + records: PatchRecord[]; + /** Where the patch came from, for the UI title and for saving. */ + name: string; + /** + * Records Pd will not understand. They are preserved byte for byte, but Pd + * will print an error for each one, so it is worth surfacing. + */ + warnings: string[]; +} + +export function nodeOrder(patch: PdPatch): string[] { + return patch.records.flatMap((r) => (r.kind === "node" ? [r.id] : [])); +} + +/** Position of a node in Pd's object index space. */ +export function nodeIndex(patch: PdPatch, id: string): number { + return nodeOrder(patch).indexOf(id); +} diff --git a/src/styles.css b/src/styles.css new file mode 100644 index 0000000..8728bb2 --- /dev/null +++ b/src/styles.css @@ -0,0 +1,222 @@ +:root { + --ink: #16181c; + --muted: #6b7280; + --line: #d6d8dc; + --panel: #fbfbfa; + --accent: #0b7bd6; + font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", sans-serif; +} + +* { + box-sizing: border-box; +} + +body { + margin: 0; + color: var(--ink); + background: #f2f2ef; +} + +button, +select, +input { + font: inherit; + font-size: 13px; + padding: 4px 9px; + border: 1px solid var(--line); + border-radius: 6px; + background: #fff; + color: inherit; +} + +button { + cursor: pointer; +} + +button:hover:not(:disabled) { + border-color: #9aa2ad; +} + +button:disabled { + opacity: 0.45; + cursor: default; +} + +button.armed { + background: #fff3e0; + border-color: #e08a2e; +} + +.app { + display: flex; + flex-direction: column; + height: 100vh; +} + +.toolbar { + display: flex; + align-items: center; + gap: 8px; + padding: 8px 12px; + border-bottom: 1px solid var(--line); + background: var(--panel); + flex-wrap: wrap; +} + +.toolbar .muted { + color: var(--muted); + font-size: 13px; + margin-right: 4px; +} + +.toolbar .sep { + width: 1px; + height: 22px; + background: var(--line); + margin: 0 4px; +} + +.toolbar .grow { + flex: 1; +} + +.toolbar .inline { + display: flex; + align-items: center; + gap: 6px; + font-size: 13px; + color: var(--muted); +} + +.obj-input { + width: 150px; +} + +.warning { + font-size: 12px; + color: #8a4b00; + background: #fff4e0; + border: 1px solid #f0c68a; + border-radius: 6px; + padding: 3px 8px; + cursor: help; +} + +.body { + flex: 1; + display: flex; + min-height: 0; +} + +.stage { + flex: 1; + overflow: auto; + padding: 16px; + position: relative; +} + +.stage.placing { + cursor: crosshair; +} + +.stage > div, +.stage svg { + display: block; +} + +.place-catcher { + position: absolute; + inset: 0; + cursor: crosshair; +} + +.side { + width: 320px; + border-left: 1px solid var(--line); + background: var(--panel); + overflow: auto; + display: flex; + flex-direction: column; +} + +.side section { + padding: 12px 14px; + border-bottom: 1px solid var(--line); + display: flex; + flex-direction: column; + gap: 8px; +} + +.side h2 { + margin: 0; + font-size: 12px; + letter-spacing: 0.08em; + text-transform: uppercase; + color: var(--muted); +} + +.side .row { + display: flex; + align-items: center; + gap: 8px; + flex-wrap: wrap; +} + +.side .row input { + flex: 1; + min-width: 90px; +} + +.hint { + margin: 0; + font-size: 12px; + line-height: 1.45; + color: var(--muted); +} + +.hint code { + background: #ececea; + padding: 0 3px; + border-radius: 3px; +} + +.dot { + width: 9px; + height: 9px; + border-radius: 50%; + background: #c9ccd1; +} + +.dot.open { + background: #22a06b; +} + +.dot.connecting { + background: #e0a02e; +} + +.side .console { + flex: 1; + min-height: 160px; +} + +.side pre { + margin: 0; + flex: 1; + overflow: auto; + font-family: ui-monospace, "DejaVu Sans Mono", monospace; + font-size: 11.5px; + line-height: 1.45; + white-space: pre-wrap; + word-break: break-word; + color: #34383f; +} + +.empty { + display: flex; + flex-direction: column; + align-items: center; + justify-content: center; + height: 100vh; + gap: 10px; +} diff --git a/test/bridge.test.ts b/test/bridge.test.ts new file mode 100644 index 0000000..040c37a --- /dev/null +++ b/test/bridge.test.ts @@ -0,0 +1,165 @@ +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { mkdtempSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; +import { WebSocket } from "ws"; + +const HERE = join(import.meta.dirname, ".."); +const hasPd = spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null; + +/** + * A patch that proves both directions of the bridge: + * + * - anything arriving on :8081 is printed, and pd's stdout is forwarded to + * the browser as log lines; + * - a second after loading, it sends `pin 42` back to the bridge on :8091. + * + * (`netsend` only accepts its own methods, so arbitrary data has to go + * through a `send ...` message rather than being piped in raw.) + */ +const LOOPBACK_PATCH = `#N canvas 0 0 400 300 10; +#X obj 20 20 netreceive -u 8081; +#X msg 20 50 connect 127.0.0.1 8091; +#X obj 20 80 netsend -u; +#X obj 120 20 loadbang; +#X obj 120 50 print in; +#X obj 220 20 del 400; +#X msg 220 50 send pin 42; +#X obj 220 0 loadbang; +#X connect 3 0 1 0; +#X connect 1 0 2 0; +#X connect 0 0 4 0; +#X connect 7 0 5 0; +#X connect 5 0 6 0; +#X connect 6 0 2 0; +`; + +function startBridge(dir: string, port: number) { + const child = spawn( + process.execPath, + [join(HERE, "server", "bridge.mjs"), "--port", String(port), "--silent", "--dir", dir], + { stdio: ["ignore", "pipe", "pipe"] }, + ); + let output = ""; + child.stdout.on("data", (c) => (output += String(c))); + child.stderr.on("data", (c) => (output += String(c))); + return { child, log: () => output }; +} + +async function waitForPort(port: number, timeoutMs = 5000) { + const deadline = Date.now() + timeoutMs; + while (Date.now() < deadline) { + const ok = await new Promise((resolve) => { + const socket = new WebSocket(`ws://127.0.0.1:${port}`); + socket.on("open", () => { + socket.close(); + resolve(true); + }); + socket.on("error", () => resolve(false)); + }); + if (ok) return; + await new Promise((r) => setTimeout(r, 100)); + } + throw new Error("bridge never accepted a connection"); +} + +/** Collect bridge messages until `match` is satisfied. */ +function collect(socket: WebSocket) { + const messages: unknown[] = []; + const waiters: { match: (m: any) => boolean; resolve: (m: any) => void }[] = []; + socket.on("message", (data) => { + const message = JSON.parse(String(data)); + messages.push(message); + for (const waiter of [...waiters]) { + if (waiter.match(message)) { + waiters.splice(waiters.indexOf(waiter), 1); + waiter.resolve(message); + } + } + }); + return { + messages, + next(match: (m: any) => boolean, timeoutMs = 5000): Promise { + const existing = messages.find(match); + if (existing) return Promise.resolve(existing); + return new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error("timed out waiting for message")), timeoutMs); + waiters.push({ + match, + resolve: (m) => { + clearTimeout(timer); + resolve(m); + }, + }); + }); + }, + }; +} + +test("bridge round trips a message through a running pd", async (t) => { + if (!hasPd) return t.skip("pd not installed"); + + const port = 8300 + Math.floor(Math.random() * 400); + const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-")); + const bridge = startBridge(dir, port); + let socket: WebSocket | null = null; + + try { + await waitForPort(port); + socket = new WebSocket(`ws://127.0.0.1:${port}`); + // Attach before the socket opens: the bridge sends `hello` immediately, + // and a message emitted with no listener is lost. + const inbox = collect(socket); + await new Promise((r) => socket!.on("open", r)); + + const hello = await inbox.next((m) => m.type === "hello"); + assert.equal(hello.pdRunning, false); + assert.equal(hello.toPdPort, 8081); + assert.equal(hello.fromPdPort, 8091); + + socket.send(JSON.stringify({ type: "save", name: "loop.pd", text: LOOPBACK_PATCH })); + await inbox.next((m) => m.type === "log" && /saved/.test(m.line)); + + socket.send(JSON.stringify({ type: "run", file: "loop.pd" })); + const running = await inbox.next((m) => m.type === "pd-status" && m.running === true, 8000); + assert.match(running.file, /loop\.pd$/); + + // pd announces itself once the patch has loaded. + const echoed = await inbox.next((m) => m.type === "from-pd" && m.receiver === "pin", 10000); + assert.deepEqual(echoed.args, ["42"]); + + // And a message from the browser reaches the patch's netreceive. + socket.send(JSON.stringify({ type: "send", receiver: "pin", args: [42] })); + const printed = await inbox.next( + (m) => m.type === "log" && /in: pin 42/.test(m.line), + 8000, + ); + assert.match(printed.line, /in: pin 42/); + } finally { + socket?.close(); + bridge.child.kill("SIGTERM"); + } +}); + +test("bridge refuses to write outside its patches directory", async () => { + const port = 8700 + Math.floor(Math.random() * 200); + const dir = mkdtempSync(join(tmpdir(), "dragology-bridge-")); + const bridge = startBridge(dir, port); + let socket: WebSocket | null = null; + try { + await waitForPort(port); + socket = new WebSocket(`ws://127.0.0.1:${port}`); + // Attach before the socket opens: the bridge sends `hello` immediately, + // and a message emitted with no listener is lost. + const inbox = collect(socket); + await new Promise((r) => socket!.on("open", r)); + socket.send(JSON.stringify({ type: "save", name: "../../escape.pd", text: "#N canvas 0 0 1 1 10;\n" })); + const saved = await inbox.next((m) => m.type === "saved"); + assert.equal(saved.file.startsWith(dir), true, `wrote to ${saved.file}`); + } finally { + socket?.close(); + bridge.child.kill("SIGTERM"); + } +}); diff --git a/test/integration.test.ts b/test/integration.test.ts new file mode 100644 index 0000000..5c325fd --- /dev/null +++ b/test/integration.test.ts @@ -0,0 +1,174 @@ +import assert from "node:assert/strict"; +import { spawn, spawnSync } from "node:child_process"; +import { mkdtempSync, readFileSync, writeFileSync } from "node:fs"; +import { tmpdir } from "node:os"; +import { join } from "node:path"; +import test from "node:test"; + +import { addNode, deleteNode, newCordId, reconcile, stateFromPatch } from "../src/editor/ops.ts"; +import { nodePorts } from "../src/pd/geometry.ts"; +import { parsePd } from "../src/pd/parse.ts"; +import { serializePd } from "../src/pd/serialize.ts"; + +const SAMPLES = join(import.meta.dirname, "..", "public", "samples"); +const SYNTH = join(SAMPLES, "synth.pd"); + +/** + * Load a patch in real Pd and report anything it complains about. + * Pd has no batch mode, so we let it start and then kill it. + */ +function pdFeedback(file: string): Promise { + return new Promise((resolve) => { + const child = spawn("pd", ["-nogui", "-nosound", "-open", file], { + stdio: ["ignore", "pipe", "pipe"], + }); + let output = ""; + const collect = (chunk: Buffer) => { + output += String(chunk); + }; + child.stdout.on("data", collect); + child.stderr.on("data", collect); + child.on("error", () => resolve("")); + const timer = setTimeout(() => { + child.kill("SIGTERM"); + resolve(output); + }, 2500); + child.on("exit", () => { + clearTimeout(timer); + resolve(output); + }); + }); +} + +/** Pd's own chatter, not a problem with the patch. */ +function complaints(output: string): string[] { + return output + .split("\n") + .map((line) => line.trim()) + .filter((line) => line.length > 0) + .filter((line) => !/priority \d+ scheduling failed/.test(line)) + .filter((line) => !/^Pd-\d/.test(line)); +} + +function hasPd(): boolean { + return spawnSync("pd", ["-version"], { encoding: "utf8" }).status !== null; +} + +function scratch(name: string, text: string): string { + const dir = mkdtempSync(join(tmpdir(), "dragology-pd-")); + const file = join(dir, name); + writeFileSync(file, text); + return file; +} + +/** + * The shipped sample contains a line Pd rejects on purpose, so the baseline is + * not empty: we assert that what we write adds nothing new. That is the claim + * a patch editor has to be able to make. + */ +async function assertNoNewComplaints(file: string, label: string) { + const baseline = complaints(await pdFeedback(file)); + const copy = scratch("copy.pd", serializePd(stateFromPatch(parsePd(readFileSync(file, "utf8"), "copy.pd")))); + const fresh = complaints(await pdFeedback(copy)).filter((line) => !baseline.includes(line)); + assert.deepEqual(fresh, [], `${label}: pd said something new\n${await pdFeedback(copy)}`); +} + +test("saving an untouched patch adds no pd complaints", async (t) => { + if (!hasPd()) return t.skip("pd not installed"); + await assertNoNewComplaints(SYNTH, "synth.pd"); +}); + +test("an edited patch still parses the way pd wants", async (t) => { + if (!hasPd()) return t.skip("pd not installed"); + + let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "edited.pd")); + const osc = Object.values(state.nodes).find((n) => n.text === "osc~"); + const dac = Object.values(state.nodes).find((n) => n.text.startsWith("dac~")); + assert.ok(osc && dac, "sample has an osc~ and a dac~"); + + // A cord that was not there before, a moved box, and a new box. + const cordId = newCordId(); + state = { + ...state, + cords: { ...state.cords, [cordId]: { id: cordId, from: osc.id, outlet: 0, to: dac.id, inlet: 0 } }, + nodes: { ...state.nodes, [osc.id]: { ...osc, x: osc.x + 40, y: osc.y + 12 } }, + }; + state = addNode(state, { + id: "added-1", + kind: "obj", + x: 600, + y: 400, + head: "#X obj", + tail: " osc~ 220", + text: "osc~ 220", + }); + + const text = serializePd(reconcile(state)); + assert.match(text, /#X obj 600 400 osc~ 220;/); + assert.match(text, new RegExp(`#X obj ${osc.x + 40} ${osc.y + 12} osc~;`)); + + const baseline = complaints(await pdFeedback(SYNTH)); + const fresh = complaints(await pdFeedback(scratch("edited.pd", text))).filter( + (line) => !baseline.includes(line), + ); + assert.deepEqual(fresh, [], "editing introduced a pd error"); +}); + +test("deleting a node drops its record and its cords", () => { + let state = stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd")); + const victim = Object.values(state.nodes).find((n) => + Object.values(state.cords).some((c) => c.to === n.id), + ); + assert.ok(victim); + + const before = Object.keys(state.cords).length; + const attached = Object.values(state.cords).filter( + (c) => c.to === victim.id || c.from === victim.id, + ).length; + assert.ok(attached > 0); + + state = deleteNode(state, victim.id); + assert.equal(Object.keys(state.cords).length, before - attached); + assert.equal(state.nodes[victim.id], undefined); + assert.ok(!state.records.some((r) => r.kind === "node" && r.id === victim.id)); + assert.equal( + Object.values(state.cords).some((c) => c.to === victim.id || c.from === victim.id), + false, + ); +}); + +test("adding a node puts it where pd expects objects", () => { + const state = addNode(stateFromPatch(parsePd(readFileSync(SYNTH, "utf8"), "x.pd")), { + id: "added-1", + kind: "obj", + x: 10, + y: 10, + head: "#X obj", + tail: " print hello", + text: "print hello", + }); + const records = state.records; + const nodeAt = records.findIndex((r) => r.kind === "node" && r.id === "added-1"); + const firstCord = records.findIndex((r) => r.kind === "cord"); + assert.ok(nodeAt >= 0); + assert.ok(nodeAt < firstCord, "node record goes before the connect records"); +}); + +test("the parser flags the line pd rejects", () => { + const patch = parsePd(readFileSync(SYNTH, "utf8"), "synth.pd"); + assert.equal(patch.warnings.length, 1); + assert.match(patch.warnings[0], /DO NOT EDIT/); +}); + +test("inlet counts follow the object's arguments", () => { + const node = (text: string) => + ({ id: "n", kind: "obj", x: 0, y: 0, head: "#X obj", tail: ` ${text}`, text }) as const; + assert.deepEqual(nodePorts(node("dac~")), { inlets: 2, outlets: 0 }); + assert.deepEqual(nodePorts(node("dac~ 1")), { inlets: 1, outlets: 0 }); + assert.deepEqual(nodePorts(node("dac~ 1 2")), { inlets: 2, outlets: 0 }); + assert.deepEqual(nodePorts(node("adc~ 1")), { inlets: 0, outlets: 1 }); + assert.deepEqual(nodePorts(node("route midi")), { inlets: 1, outlets: 2 }); + assert.deepEqual(nodePorts(node("t b b b")), { inlets: 1, outlets: 3 }); + assert.deepEqual(nodePorts(node("pack 0 0")), { inlets: 2, outlets: 1 }); + assert.deepEqual(nodePorts(node("r midi-vel")), { inlets: 0, outlets: 1 }); +}); diff --git a/test/pd.test.ts b/test/pd.test.ts new file mode 100644 index 0000000..16c1126 --- /dev/null +++ b/test/pd.test.ts @@ -0,0 +1,89 @@ +import assert from "node:assert/strict"; +import { readdirSync, readFileSync } from "node:fs"; +import { join } from "node:path"; +import test from "node:test"; + +import { parsePd, splitAtoms, splitRecords } from "../src/pd/parse.ts"; +import { nodePosition, serializePd } from "../src/pd/serialize.ts"; + +const SYNTH_PD = "/home/david/Arduino/sketches/uno-q-audio-synth/pd"; + +test("records split on unescaped semicolons only", () => { + assert.deepEqual(splitRecords("#X msg 0 0 a \\; b;"), ["#X msg 0 0 a \\; b"]); +}); + +test("atoms unescape", () => { + assert.deepEqual(splitAtoms("#X msg 0 0 a\\;b \\, \\$0"), [ + "#X", + "msg", + "0", + "0", + "a;b", + ",", + "$0", + ]); +}); + +const patch = `#N canvas 0 0 400 300 10; +#X text 10 10 a comment; +#X obj 50 50 osc~ 440; +#X obj 50 90 dac~; +#X obj 120 50 \\;does\\,not\\$exist; +#X connect 1 0 2 0; +#X connect 1 0 2 1; +`; + +test("comments occupy an index in the connect space", () => { + const parsed = parsePd(patch); + const cords = Object.values(parsed.cords); + assert.equal(cords.length, 2); + for (const cord of cords) { + assert.equal(parsed.nodes[cord.from].text, "osc~ 440"); + assert.equal(parsed.nodes[cord.to].text, "dac~"); + } +}); + +test("round trip is byte exact", () => { + const parsed = parsePd(patch); + assert.equal(serializePd(parsed), patch); +}); + +test("moving a node only changes its coordinates", () => { + const parsed = parsePd(patch); + const node = Object.values(parsed.nodes).find((n) => n.text === "osc~ 440"); + assert.ok(node); + node.x = 200; + node.y = 210; + const out = serializePd(parsed); + assert.equal(out, patch.replace("#X obj 50 50 osc~ 440", "#X obj 200 210 osc~ 440")); +}); + +test("escaped atoms survive a move", () => { + const parsed = parsePd(patch); + const node = Object.values(parsed.nodes).find((n) => n.text === ";does,not$exist"); + assert.ok(node, "escaped object text parsed"); + node.y = 300; + assert.match(serializePd(parsed), /#X obj 120 300 \\;does\\,not\\\$exist;/); +}); + +test("every real patch in the synth project round trips", (t) => { + let files: string[]; + try { + files = readdirSync(SYNTH_PD).filter((f) => f.endsWith(".pd")); + } catch { + t.skip("synth project not present"); + return; + } + assert.ok(files.length > 0); + for (const file of files) { + const text = readFileSync(join(SYNTH_PD, file), "utf8"); + const parsed = parsePd(text, file); + assert.equal(serializePd(parsed), text, `${file} round trip`); + // Every cord must resolve to a real object, never a comment. + for (const cord of Object.values(parsed.cords)) { + assert.notEqual(parsed.nodes[cord.from].kind, "text", `${file}: cord from comment`); + assert.notEqual(parsed.nodes[cord.to].kind, "text", `${file}: cord to comment`); + assert.ok(nodePosition(parsed, cord.from) >= 0); + } + } +}); diff --git a/tsconfig.json b/tsconfig.json new file mode 100644 index 0000000..6ba87b8 --- /dev/null +++ b/tsconfig.json @@ -0,0 +1,17 @@ +{ + "compilerOptions": { + "target": "es2022", + "lib": ["ES2022", "DOM", "DOM.Iterable"], + "module": "ESNext", + "moduleResolution": "bundler", + "jsx": "react-jsx", + "strict": true, + "noEmit": true, + "isolatedModules": true, + "allowImportingTsExtensions": true, + "verbatimModuleSyntax": true, + "types": ["vite/client", "node"], + "skipLibCheck": false + }, + "include": ["src", "test", "server"] +} diff --git a/vite.config.ts b/vite.config.ts new file mode 100644 index 0000000..fc9abc0 --- /dev/null +++ b/vite.config.ts @@ -0,0 +1,7 @@ +import react from "@vitejs/plugin-react"; +import { defineConfig } from "vite"; + +export default defineConfig({ + plugins: [react()], + server: { port: 5174 }, +});