From a74ae22c0ee0baf3ff4d8f583834b07823fb72e7 Mon Sep 17 00:00:00 2001 From: Jeff Crouse Date: Fri, 13 Nov 2026 16:52:09 -0500 Subject: [PATCH 1/4] Run interfaces on a real table over TUIO The desktop app can now be what runs on the table. It listens for TUIO 1.1 (pucks as 2Dobj, fingers as 2Dcur) in the main process, maps printed tags to the logical markerIds interfaces already use, applies calibration, and feeds the result into TableModel like any other input. Interfaces need no changes and the wire protocol stays at version 1. - Present mode: kiosk fullscreen on the table's display, device scale factor forced to 1, no chrome, native touch ignored. Chosen at launch by table.json or --present. - A control puck opens an interface picker on the table; fingers used on it never reach the interface. - Table > Assign Pucks and Table > Calibrate, applied live, stored per machine in table.json (versioned, with migrations). - Workspaces are upgraded on open: reference files the app wrote are refreshed if unedited, edited ones get a .new copy beside them, deletions are respected, interfaces are never touched. 0.1.x workspaces are matched against recorded hashes of what those releases shipped. - SDK_VERSION now follows package.json and the release check enforces it. - npm test: unit tests for OSC, TUIO frames, table.json and upgrades. - Smoke covers upgrade, TUIO, enrollment, calibration and a present-mode launch. - docs/TABLE.md: preparing the table's computer and setting a table up. Co-Authored-By: Claude Opus 5.5 --- .github/workflows/ci.yml | 2 + .prettierignore | 5 + CHANGELOG.md | 31 ++ CLAUDE.md | 25 +- docs/API.md | 2 +- docs/DESIGN-RULES.md | 4 +- docs/DISTRIBUTION.md | 15 +- docs/PROTOCOL.md | 33 +- docs/TABLE.md | 243 +++++++++++ docs/WORKSPACE-INTRO.md | 17 + electron/main.js | 176 +++++++- electron/osc.js | 200 +++++++++ electron/preload.cjs | 14 + electron/table-config.js | 159 +++++++ electron/tuio.js | 411 ++++++++++++++++++ electron/workspace-upgrade.js | 277 +++++++++++++ index.html | 95 +++++ package.json | 2 + scripts/build-seed.mjs | 11 + scripts/check-version.mjs | 10 +- scripts/seed-history.json | 44 ++ scripts/seed-history.mjs | 47 +++ scripts/smoke-desktop.mjs | 484 +++++++++++++++++++++- scripts/sync-sdk-version.mjs | 34 ++ scripts/tuio-send.mjs | 143 +++++++ src/host/appframe.ts | 42 +- src/host/appsource.ts | 18 + src/host/enroll.ts | 224 ++++++++++ src/host/inspector.ts | 48 ++- src/host/main.ts | 86 +++- src/host/notice.ts | 73 ++++ src/host/present.ts | 222 ++++++++++ src/host/table-ui.ts | 45 ++ src/host/tuio.ts | 122 ++++++ src/sdk/transport.ts | 2 +- test/fixtures/seed-0.1.0/types/units.d.ts | 19 + test/tuio.test.mjs | 251 +++++++++++ test/workspace-upgrade.test.mjs | 252 +++++++++++ 38 files changed, 3835 insertions(+), 53 deletions(-) create mode 100644 docs/TABLE.md create mode 100644 electron/osc.js create mode 100644 electron/table-config.js create mode 100644 electron/tuio.js create mode 100644 electron/workspace-upgrade.js create mode 100644 scripts/seed-history.json create mode 100644 scripts/seed-history.mjs create mode 100644 scripts/sync-sdk-version.mjs create mode 100644 scripts/tuio-send.mjs create mode 100644 src/host/enroll.ts create mode 100644 src/host/notice.ts create mode 100644 src/host/present.ts create mode 100644 src/host/table-ui.ts create mode 100644 src/host/tuio.ts create mode 100644 test/fixtures/seed-0.1.0/types/units.d.ts create mode 100644 test/tuio.test.mjs create mode 100644 test/workspace-upgrade.test.mjs diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index fe7397c..26abd42 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -30,6 +30,7 @@ jobs: - run: npm run lint - run: npm run format:check - run: npm run check + - run: npm test - run: npm run build - run: npm run build:seed # Opens a real window; GitHub's macOS runners have a desktop session. @@ -52,6 +53,7 @@ jobs: - run: npm run lint - run: npm run format:check - run: npm run check + - run: npm test - run: npm run build - run: npm run build:seed - run: npm run smoke diff --git a/.prettierignore b/.prettierignore index 84021d3..dab93cc 100644 --- a/.prettierignore +++ b/.prettierignore @@ -23,3 +23,8 @@ public/favicon.svg site/_build site/.cache site/reel/guests + +# Byte-for-byte records of what released versions shipped. Workspace upgrades +# compare hashes against these, so reformatting either one would break them. +scripts/seed-history.json +test/fixtures diff --git a/CHANGELOG.md b/CHANGELOG.md index 308786f..73cb8aa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -10,6 +10,37 @@ from one version to the next. ## [Unreleased] +### Added + +- **Run interfaces on a real table.** The desktop app listens for TUIO 1.1 from + a table's tracker (pucks and fingers) and feeds it to interfaces exactly as + the simulator does, so they need no changes. Off unless switched on in + **Settings > Table input**; a designer's machine never opens a socket. See + `docs/TABLE.md`. +- **Present mode** for the table's own computer: fullscreen on the table's + display at one table pixel per screen pixel whatever the display scaling, no + authoring chrome, native touch ignored. **Table > Enter Present Mode**, or + `"present": true` in `table.json` to boot into it. +- **A control puck** that opens an interface picker on the table: put it down, + turn it, touch an interface to open it. +- **Table > Assign Pucks** maps the tags printed on a table's pucks to the + marker numbers interfaces use, and **Table > Calibrate** lines the tracker up + with the screen. Both apply live. Stored per computer in `table.json`. +- `scripts/tuio-send.mjs`, a stand-in tracker for working without a table. +- `npm test`: unit tests for OSC decoding, TUIO frames, `table.json` and + workspace upgrades, gating CI on both runners. + +### Changed + +- **Workspaces are now kept up to date.** Opening a workspace refreshes its + reference docs, SDK types and agent guidance when the app has newer ones. A + file you edited is kept, with the new version written beside it + (`API.new.md`); anything you deleted stays deleted; interfaces and examples + are never overwritten. A notice says what changed. Works for workspaces + created by 0.1.0 and 0.1.1. +- `table.version` and the SDK's `hello` now report the app's version. They said + 0.1.0 in every release so far. + ### Fixed - On Windows, editing an interface did not reload it when the workspace path diff --git a/CLAUDE.md b/CLAUDE.md index 4db9253..7fac1c7 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -8,6 +8,7 @@ and [`docs/API.md`](docs/API.md) instead; almost nothing here applies to that. npm run check # TypeScript npm run lint # oxlint, and the only static checking electron/ gets npm run format # prettier, code only: prose, html and css are hand-formatted + npm test # unit tests for the pure parts: OSC, TUIO, table.json, upgrades npm run smoke # launches the real desktop shell and drives it over CDP ## Shape of the thing @@ -22,11 +23,12 @@ Four parts, and the boundaries between them are load-bearing: the other way round. - **`examples//`** are example interfaces, served as static files. - **`electron/`** is a shell: a custom `planchette://` protocol, a workspace folder on - disk, and a file watcher. It adds distribution, not behaviour. + disk, a file watcher, and the TUIO listener for a real table (`tuio.js`, + configured per machine by `table.json`; see [`docs/TABLE.md`](docs/TABLE.md)). Host and interface communicate **only** over `postMessage`. That is the seam that lets the same interface code run against the simulator, standalone in a browser, -and eventually against real hardware over a socket. +and on a real table, where the host is fed by TUIO instead of the mouse. ## Invariants worth not breaking @@ -62,6 +64,17 @@ is wrong. a `requestAnimationFrame` loop, and Chromium throttles rAF hard once it decides a window is occluded. A designer watching the simulator while typing in another app would otherwise see it freeze. +8. **A real table's input arrives already meaning something.** Tag-to-`markerId` + mapping, calibration and the control puck are all applied in + `electron/tuio.js`, so the renderer and interfaces only ever see logical + marker ids. Changing the mapping re-announces everything from the raw data + held there, because trackers send positions only for things that move; a + puck sitting still would otherwise vanish until touched. For the same reason + TUIO pucks are never persisted to `sessionStorage` (6): the tracker replays them. +9. **The app only overwrites workspace files it wrote and nobody edited.** That + is what `.planchette/seed.json` is for. Never write into a designer's + workspace any other way, and never edit `scripts/seed-history.json`: it is + the record of what 0.1.x shipped, and legacy upgrades are judged against it. ## Bare specifiers @@ -124,6 +137,14 @@ rather than a bug. Taking a screenshot forces frames to run. in `scripts/build-seed.mjs` to ship it to designers. - **Change the event API**: `src/sdk/types.ts` first, then the host, then `docs/PROTOCOL.md` and `docs/API.md`. Keep TUIO alignment in mind. +- **Change what a workspace gets**: edit `scripts/build-seed.mjs` or the docs it + copies. Existing workspaces pick the change up on their next open, through + the upgrade (invariant 9); there is nothing else to do. +- **Change `table.json`'s shape**: bump `TABLE_CONFIG_VERSION` in + `electron/table-config.js` and add a step to `MIGRATIONS`, so a table's + enrollment survives the upgrade. +- **Work on the TUIO path without a table**: `node scripts/tuio-send.mjs`, with + table input on in Settings. - **Anything a user would notice**: add it under `## [Unreleased]` in `CHANGELOG.md`. At release time that section is retitled to the version, and `scripts/release-body.mjs` publishes it above the durable install guidance in diff --git a/docs/API.md b/docs/API.md index 6303c7c..0c17c2d 100644 --- a/docs/API.md +++ b/docs/API.md @@ -112,7 +112,7 @@ interface SurfaceInfo { interface Puck { id: number // session id, stable only while continuously tracked - markerId: number // physical marker. Key your own state by THIS. + markerId: number // which puck this is (1, 2, 3...). Key your own state by THIS. x: number; y: number // normalized 0..1, y axis down mmX: number; mmY: number angle: number // radians, 0 = up, clockwise positive, range [0, 2*PI) diff --git a/docs/DESIGN-RULES.md b/docs/DESIGN-RULES.md index a1ecead..9659ff2 100644 --- a/docs/DESIGN-RULES.md +++ b/docs/DESIGN-RULES.md @@ -28,7 +28,9 @@ decide whether an interface survives contact with the real table. rather than destroying state immediately. - **Key by `markerId`, not by `id`.** `id` is a tracking session and changes whenever the tracker re-acquires a marker. `markerId` is the physical identity - of the object. The tradeoff is that two pucks carrying the same marker collapse + of the object: puck 1, puck 2, and so on. Each real table maps its printed tags + onto those same small numbers, so puck 1 in the simulator is puck 1 on the + table. The tradeoff is that two pucks carrying the same marker collapse onto one thing; if you hand out duplicate markers, key by `id` and use `markerId` plus last-known position to re-associate after a dropout. - **Never let an event handler depend on your render loop.** This bites in two diff --git a/docs/DISTRIBUTION.md b/docs/DISTRIBUTION.md index 7ed1aac..10e9dd1 100644 --- a/docs/DISTRIBUTION.md +++ b/docs/DISTRIBUTION.md @@ -12,6 +12,17 @@ run the app seeds it with two example apps, SDK type declarations, a `jsconfig.json`, and a `CLAUDE.md` carrying the design rules. A coworker can open that folder in any editor or coding agent and start working. +**Existing workspaces are upgraded, carefully.** Seeding happens once, so +without help a workspace's reference docs, SDK types and agent guidance would +stay at whatever version created it. `build-seed.mjs` records the hash of every +file the app owns in `.planchette/seed.json`, and each time a workspace is +opened `electron/workspace-upgrade.js` brings it up to date: a file still as the +app wrote it is replaced; a file the designer edited is kept, with the new one +written beside it (`API.new.md`); anything they deleted stays deleted; examples +and interfaces are never overwritten. Workspaces from 0.1.x, which have no +manifest, are matched against `scripts/seed-history.json`, the hashes of what +those releases shipped. A folder the app never seeded is left alone. + The app watches the workspace. Saving a file reloads just the app iframe, and the puck arrangement survives, so the loop is: arrange pucks once, then edit freely. @@ -22,7 +33,9 @@ puck arrangement survives, so the loop is: arrange pucks once, then edit freely. | `electron/main.js` | Serves everything over `planchette://`, owns the workspace and watcher. | | `electron/preload.cjs` | The whole renderer-to-disk surface. Nothing else crosses. | | `src/host/appsource.ts` | Hides whether interfaces come from Vite or the workspace. | -| `scripts/build-seed.mjs` | Assembles `workspace-seed/`, what a fresh workspace gets. | +| `scripts/build-seed.mjs` | Assembles `workspace-seed/`, what a fresh workspace gets, and its manifest. | +| `electron/workspace-upgrade.js` | Brings an older workspace up to the current seed without touching edits. | +| `electron/tuio.js` | TUIO from a real table; see `TABLE.md`. | | `scripts/adhoc-sign.cjs` | Ad-hoc signs the macOS app so it will launch. | The host UI and the interfaces share one origin, `planchette://host`: the UI from diff --git a/docs/PROTOCOL.md b/docs/PROTOCOL.md index e3efbbc..43a7f76 100644 --- a/docs/PROTOCOL.md +++ b/docs/PROTOCOL.md @@ -112,20 +112,29 @@ millimetre sizing stays honest and you are simply working on a smaller table. ## Mapping to real hardware -Not built (see the non-goals in the plan), but the schema is shaped for it. -MultiTaction's stack can emit TUIO: add a `TuioSender` block to `config.txt`, or -point the on-screen display at a TUIO listener, then run `MTServer`, which -forwards display events to your application. - -The bridge is then UDP to WebSocket, and drops in behind `src/sdk/transport.ts` -with no change to any app: +The desktop app takes TUIO 1.1 from a real table and feeds it into the same +model the mouse drives, so an interface cannot tell the difference and needs no +changes. Setting a table up is in [`TABLE.md`](TABLE.md); this is the mapping. | TUIO | This API | | ---- | -------- | -| `/tuio/2Dobj set s i x y a X Y A m r` | `Puck`: `s`=`id`, `i`=`markerId`, `x`/`y`, `a`=`angle`, `X`/`Y`=`vx`/`vy`, `A`=`vAngle` | -| `/tuio/2Dcur set s x y X Y m` | `Touch`: `s`=`id`, `x`/`y`, `X`/`Y` | -| `alive` / `fseq` | Presence and frame sequencing, which become add/remove events | +| `/tuio/2Dobj set s i x y a X Y A m r` | `Puck`: `x`/`y` and `a`=`angle`, after the table's calibration. `i`, the printed tag, becomes `markerId` through the table's assignments. | +| `/tuio/2Dcur set s x y X Y m` | `Touch`: `x`/`y`. 2Dcur carries no size, so `radiusMm` is a fixed 9mm. | +| `alive` / `fseq` | Presence and frame order, which become add and remove events. Late frames are dropped by TUIO's own rule. | + +**`markerId` is logical.** Pucks carry whatever tag ids were printed on them. +Each table assigns its tags to the small numbers interfaces use (1, 2, 3...), so +an interface written against puck 1 in the simulator gets puck 1 on any table, +whatever is printed on it. Until a table has any assignments, raw tag ids pass +through unchanged. + +`id` is assigned by the host, as it is for a simulated puck. It changes whenever +the tracker re-acquires a marker, exactly as TUIO's own session id does. + +A table may reserve one tag as a **control puck**, which opens the host's +interface picker. It never reaches an interface. -Existing JavaScript TUIO clients worth borrowing from rather than reimplementing: -[`InteractiveScapeGmbH/tuio_client_js`](https://github.com/InteractiveScapeGmbH/tuio_client_js) +Not read yet: `/tuio/2Dblb` (contact size, which palm rejection would want) and +TUIO 2.0. Existing JavaScript TUIO clients, if those are ever wanted in the +browser: [`InteractiveScapeGmbH/tuio_client_js`](https://github.com/InteractiveScapeGmbH/tuio_client_js) (TUIO 1.1 and 2.0) and [`Tuio.js`](https://github.com/fe9lix/Tuio.js). diff --git a/docs/TABLE.md b/docs/TABLE.md new file mode 100644 index 0000000..1dba959 --- /dev/null +++ b/docs/TABLE.md @@ -0,0 +1,243 @@ +# Running interfaces on a real table + +The desktop app is also what runs on the table. On the table's computer it runs +in **present mode**: fullscreen on the table's display, no authoring chrome, with +pucks and fingers coming from the table's tracker over TUIO instead of from the +mouse. Interfaces run unchanged; to them a real puck and a simulated one are the +same thing. + +This is for whoever sets a table up. Designers do not need any of it. + +Anything below about specific hardware is *unconfirmed* until it has been tried +on that hardware. The [on-site checklist](#on-site-checklist) is how it gets +confirmed. + +## What it needs + +- The table's computer, running Windows (the `Planchette--setup.exe` + from the GitHub release) or macOS. +- A tracker that sends **TUIO 1.1** over UDP: objects as `/tuio/2Dobj`, fingers + as `/tuio/2Dcur`. MultiTaction's stack can: add a `TuioSender` block to + `config.txt`, or point the on-screen display at a TUIO listener, then run + `MTServer` (*unconfirmed*; check the MultiTaction documentation for the exact + block). reacTIVision and the TUIO simulators also work. +- A workspace folder holding the interfaces, the same kind designers use. See + [Getting interfaces onto the table](#getting-interfaces-onto-the-table). + +## Preparing the table's computer + +Do this once, before setting up Planchette itself. Most of it is about stopping +Windows from doing things a person at a desk wants and a table does not. The +menu paths are Windows 11's and move between versions, so they are *unconfirmed* +for any particular table until someone has done them there. + +Some of these settings (signing in automatically, delaying updates) may not be +ours to change on a client's computer. Check with whoever owns the machine +before changing them. + +### Install Planchette + +Use the installer, `Planchette--setup.exe` from the GitHub release, not +the portable `.exe`: the installer puts the app in a fixed place, so the startup +shortcut below keeps working through upgrades. The build is unsigned, so the +first run shows *Windows protected your PC*; click **More info**, then +**Run anyway**. Once per machine. + +Upgrading later is the same: run the new installer. `table.json` (puck +assignments, calibration) lives in Planchette's settings folder, not in the app, +so it survives. + +### Make the table the main display + +If the computer has more than one screen, open **Settings > System > Display**, +select the table, and tick **Make this my main display**. Present mode opens on +the main display, so this is all it needs; `display` in `table.json` exists for +when that is not possible, but its numbering is not guaranteed to match the +numbers Windows shows. + +Set the table's resolution to its native one (3840 x 2160 for the 55 inch +panel). Windows display *scaling* does not matter: present mode overrides it. + +### Stop touch from reaching Windows + +The table's fingers reach interfaces through TUIO, but if the panel also reports +touch to Windows, a hand on the table edge can open Windows' own panels. + +- **Edge swipes.** On Pro and Enterprise editions: run `gpedit.msc`, go to + **Computer Configuration > Administrative Templates > Windows Components > + Edge UI**, and set **Allow edge swipe** to **Disabled**. +- **Touch gestures.** **Settings > Bluetooth & devices > Touch**: turn off + three- and four-finger touch gestures. +- **The touch keyboard.** **Settings > Time & language > Typing > Touch + keyboard**: set it never to show. +- If the panel's touch can be switched off at the hardware or driver level + entirely, leaving only the TUIO output, that is the cleanest of all. + +### Keep it awake and quiet + +- **Sleep and screen.** **Settings > System > Power** (or **Power & battery**): + set the screen and sleep to **Never** when plugged in. From an administrator + command prompt, the same thing: + + powercfg /change monitor-timeout-ac 0 + powercfg /change standby-timeout-ac 0 + +- **Notifications.** **Settings > System > Notifications**: turn them off, so + nothing appears over the interface. +- **Updates.** **Settings > Windows Update > Advanced options > Active hours**: + cover the hours the table is in use, so Windows does not restart in the + middle of them. Better still, agree an update window with the machine's + owner. + +### Start Planchette when the computer starts + +1. Press `Win+R`, type `shell:startup`, and press Enter. A folder opens. +2. Put a shortcut to Planchette in it (right-drag Planchette from the Start + menu into the folder and choose **Create shortcut here**, or copy the one + from the desktop). +3. Once the table is set up, set `"present": true` in `table.json` (step 6 + below), so it starts straight into present mode. + +This only runs once someone signs in. For a table that should come back by +itself after a power cut, the account also has to sign in automatically, which +is a security decision for the machine's owner. Microsoft's Sysinternals +*Autologon* tool is the usual way, if they agree. + +### Getting interfaces onto the table + +Planchette on the table reads interfaces from a workspace folder, exactly as on +a designer's laptop. + +- **Simplest:** copy the designers' workspace folder onto the table's computer, + then in Planchette open **Settings** and **Add…** that folder. To update, + copy again. Planchette notices changed files and reloads by itself. +- **A synced folder** (Google Drive, Dropbox, a git checkout) also works, and + then designers' saves appear on the table. That is handy during a build and + risky during an event: a half-synced change shows up live. Freeze it, or + switch to a copy, before the table is in front of the public. + +The interface picker on the table lists every folder in the workspace except +those starting with `_`, so remove experiments the public should not see. + +## Setting a table up + +1. **Point the tracker at Planchette.** By default Planchette listens on + `127.0.0.1:3333`, the TUIO default, which suits a tracker on the same + computer. If the tracker is on another machine, set `tuio.host` to + `0.0.0.0` in `table.json` (below) and expect a firewall prompt the first time. +2. **Turn on table input.** **Settings** (`Ctrl+,`) > **Table input**. The status + line should say *Listening* and show packets arriving. +3. **Assign the pucks.** **Table > Assign Pucks…** Put one puck down; it appears + as *Tag 117* (or whatever is printed on it). Click **Make it puck 1**. Lift it, + put the next one down, and so on. These numbers are what interfaces use, so + match what the designers built against; give each a label so the next person + knows which is which. +4. **Choose a control puck** (optional, recommended). In the same dialog, put a + spare puck down and click **Make it the control puck**. On the table, putting + it down opens the interface picker. It never reaches an interface. +5. **Calibrate.** **Table > Calibrate…** Each puck is drawn where Planchette + thinks it is, with a line for its north. Slide a puck along each edge; if it + is mirrored, use the flips. Turn it; if the line turns the wrong way, use + **Reverse rotation**. Then point a puck's arrow at the top edge of the screen + and click **The puck now points at the top edge**. +6. **Enter present mode.** **Table > Enter Present Mode** (`Ctrl+Shift+F`). The + app restarts fullscreen. To make the table boot straight into it, set + `"present": true` in `table.json` (**Table > Show table.json**, edit, save, + restart Planchette), and add Planchette to the computer's startup items + ([above](#start-planchette-when-the-computer-starts)). + +Every change in steps 3 to 5 is saved and applied at once, including to pucks +already sitting on the table. + +## In present mode + +- **Changing interface:** put the control puck down. The interfaces appear in a + ring around it; turning the puck highlights one, and touching any of them + opens it. Lift the puck to close the ring (it waits a moment, because tracking + flickers). With a keyboard: `Ctrl+Shift+P`, arrows, `Enter`, `Esc`. +- **Leaving:** **Table > Leave Present Mode**, or `Ctrl+Shift+F`. Launching with + `--no-present` also overrides `table.json`, for when a table that boots into + present mode needs the authoring UI. +- The surface is drawn at exactly one table pixel per screen pixel, whatever the + operating system's display scaling. If the display does not match the surface + preset, an orange banner says so; the sizes on screen are then not the sizes + the interfaces were designed for. +- Native touch is ignored. Fingers reach interfaces through TUIO only, so they + are never counted twice. + +## `table.json` + +Per computer, in Planchette's settings folder. **Table > Show table.json** +reveals it. The dialogs write it; editing by hand is fine, and a file with a +typo is copied to `table.json.broken` before anything overwrites it. + +```json +{ + "version": 1, + "present": false, + "display": null, + "surface": "table55-4k", + "tuio": { "enabled": false, "host": "127.0.0.1", "port": 3333, "staleMs": 2000 }, + "calibration": { "flipX": false, "flipY": false, "angleOffsetDeg": 0, "angleReversed": false }, + "pucks": [{ "markerId": 1, "tag": 117, "label": "red" }], + "control": { "tag": 900 }, + "unmapped": "ignore" +} +``` + +| Field | Meaning | +| ----- | ------- | +| `present` | Boot into present mode. | +| `display` | Which display present mode uses, as an index into the system's list. `null` is the primary display. | +| `surface` | A surface preset id (`src/host/surface.ts`). Must match the panel, or sizes are wrong. | +| `tuio.host`, `tuio.port` | Where to listen. `127.0.0.1` accepts only this computer; `0.0.0.0` accepts the network. | +| `tuio.staleMs` | If the tracker sends nothing for this long, everything is lifted off the table. `0` turns this off. | +| `calibration` | Applied to every position and angle before anything else sees it. | +| `pucks` | Printed tag to the `markerId` interfaces use. One tag per puck, one puck per tag. | +| `control.tag` | The control puck's tag, or `null`. | +| `unmapped` | A tag with no assignment: `ignore` it, or `passthrough` as its own number. Until anything is assigned, tags always pass through, so a new table does something. | + +## Trying it without a table + +`scripts/tuio-send.mjs` sends TUIO the way a tracker does: + + node scripts/tuio-send.mjs # two pucks (tags 117, 42) and a finger, moving + node scripts/tuio-send.mjs place 117 0.3 0.6 45 + node scripts/tuio-send.mjs flicker 117 # lost and found every second + +Turn on table input in Settings first. Present mode can be tried on a laptop +too (it will show the not-1:1 banner). + +## Troubleshooting + +| Symptom | Likely cause | +| ------- | ------------ | +| Status says *port 3333 is already in use* | Another TUIO listener is running, often the vendor's own demo app. Close it, or move one of them to another port. | +| Listening, but 0 packets | The tracker is sending somewhere else (check its host and port), or it is on another machine and `tuio.host` is still `127.0.0.1`. | +| Pucks show in the inspector as *unmapped* and nothing happens | They have no assignment. **Table > Assign Pucks…** | +| Every puck vanishes every couple of seconds while sitting still | The tracker sends nothing while nothing moves (*unconfirmed* for any given tracker). Set `tuio.staleMs` to `0`. | +| After starting Planchette, pucks already on the table do not appear until moved | The tracker only sends positions for things that move. Nudge them. | +| Everything is mirrored, or turns the wrong way | **Table > Calibrate…** | +| Orange *Not 1:1* banner | `surface` does not match the display, or present mode is on the wrong display (`display`). | + +## On-site checklist + +The first time on a new kind of table, go through these and record what was +found in this document, replacing the *unconfirmed* notes above. + +1. The computer is prepared: a hand dragged in from each edge opens nothing + of Windows', no touch keyboard appears, and the screen stays on past its + usual timeout. Note the Windows edition and version, and correct the menu + paths above if they differ. +2. Settings shows packets arriving with nothing on the table. If not, note + whether this tracker only sends on change, and set `staleMs` to `0` if so. +3. Assign every puck and the control puck. Note the tag numbers on the pucks. +4. Calibrate: each edge, each corner, rotation direction, north. +5. Each example interface responds to pucks and fingers as it does in the + simulator, with four people touching at once. +6. Put a hand flat over a puck and lift it: the interface should treat it as a + brief absence, not a removal. +7. Unplug the tracker's connection (or stop `MTServer`): the table clears within + `staleMs`, and recovers when it comes back. +8. Reboot: the computer comes back into present mode, on the right display, with + the last interface. diff --git a/docs/WORKSPACE-INTRO.md b/docs/WORKSPACE-INTRO.md index 71f3bbe..598016b 100644 --- a/docs/WORKSPACE-INTRO.md +++ b/docs/WORKSPACE-INTRO.md @@ -61,11 +61,28 @@ moments. Both see the same table. | `dial-demo/` | A puck as a rotary dial. Start here; it is short. | | `radial-atlas/` | Nested radial menus, and loading images and text from disk. | | `arcane-table/` | A Three.js showcase: bloom, particles, arcs between pucks. | +| `.planchette/` | What the app wrote here and when, so it can update these files safely. Leave it be. | + +When Planchette is updated, it refreshes the reference files above if you have +not edited them. If you have, yours is kept and the new version is put beside it, +as `API.new.md` for example. Your interfaces are never touched. Bare specifiers `@planchette/sdk` and `three` resolve with no install. Beyond that an interface folder is a normal static site: reference any local file at any depth, and remote `https` URLs too. +## On the real table + +The same interface runs on the table with no changes. The table's computer runs +Planchette in present mode, taking pucks and fingers from the table's tracker, +and each table maps the tags printed on its pucks to the numbers you used here: +puck 1 in the simulator is puck 1 on the table. Test with the marker numbers your +interface expects, and say which ones it uses. + +Two things only show up on real hardware, which is why the rules below insist on +them: a puck briefly disappears when a sleeve passes over it, and several people +touch at once. + ## Driving it from the console **View › Toggle Developer Tools**, then `window.sim` takes millimetres and diff --git a/electron/main.js b/electron/main.js index 11186f9..5b226bb 100644 --- a/electron/main.js +++ b/electron/main.js @@ -16,12 +16,15 @@ * between the two. */ -import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, shell } from 'electron' +import { app, BrowserWindow, dialog, ipcMain, Menu, nativeImage, protocol, screen, shell } from 'electron' import fs from 'node:fs' import fsp from 'node:fs/promises' import path from 'node:path' import { Readable } from 'node:stream' import { fileURLToPath } from 'node:url' +import { readTableConfig, writeTableConfig } from './table-config.js' +import { createTuioListener } from './tuio.js' +import { HISTORY_FILE, MANIFEST_DIR, upgradeWorkspace } from './workspace-upgrade.js' const HERE = path.dirname(fileURLToPath(import.meta.url)) const DIST = path.join(HERE, '..', 'dist') @@ -92,6 +95,62 @@ function writeSettings(next) { let workspace = '' +/* ------------------------------------------------------------------ * + * The physical table + * ------------------------------------------------------------------ */ + +/** + * Per machine, not per workspace: which printed tag is on which puck, how the + * tracker lines up, whether to listen for TUIO at all. A designer's laptop has + * none of this and the defaults leave the app exactly as it was. Read + * synchronously because present mode has to be known before the app is ready. + */ +const tableConfigPath = () => path.join(app.getPath('userData'), 'table.json') +let tableConfig = readTableConfig(tableConfigPath()) + +/** + * Present mode: the app is the table's display. Fullscreen on the table's + * screen, no authoring chrome, input from TUIO. + * + * Chosen at launch, by table.json or `--present`, because one part of it can + * only be set before the app is ready: a device scale factor of 1. Windows + * commonly runs a 4K panel at 150%, which would make the window 2560 CSS + * pixels wide, and the whole promise that one CSS pixel is one table pixel + * would quietly break. `--no-present` overrides the file, so an operator can + * always get the authoring UI back on a machine that boots into the table. + */ +const PRESENT = !process.argv.includes('--no-present') && (process.argv.includes('--present') || tableConfig.present) +if (PRESENT) app.commandLine.appendSwitch('force-device-scale-factor', '1') + +/** Switching mode means a fresh process, since the scale factor is fixed at launch. */ +function relaunch(present) { + const args = process.argv.slice(1).filter((a) => a !== '--present' && a !== '--no-present') + args.push(present ? '--present' : '--no-present') + app.relaunch({ args }) + app.exit(0) +} + +/** Created once the app is ready. Opens no socket unless table.json enables TUIO. */ +let tuio = null + +function startTuio() { + tuio = createTuioListener({ + frame: (f) => send('tuio:frame', f), + control: (e) => send('tuio:control', e), + status: (s) => send('tuio:status', s), + }) + tuio.configure(tableConfig) +} + +/** A renderer that just loaded has an empty model, while the pucks are still on the table. */ +function replayTuio() { + if (!tuio) return + const { frame, controls } = tuio.snapshot() + send('tuio:frame', frame) + for (const c of controls) send('tuio:control', c) + send('tuio:status', tuio.status()) +} + /** Most recent first. Enough to cover a few concurrent client projects. */ const MAX_RECENT = 8 @@ -156,17 +215,46 @@ async function listApps() { } } +/** + * What the last upgrade did, per workspace path, for the renderer to report. + * Pulled rather than pushed: at startup the upgrade runs before any window exists. + */ +const upgradeReports = new Map() + async function ensureWorkspace() { await fsp.mkdir(workspace, { recursive: true }) - if ((await listApps()).length > 0) return - const seed = seedDir() if (!fs.existsSync(seed)) { console.error(`[planchette] no workspace seed at ${seed}; run npm run build:seed`) return } - // Never clobber: a folder with no apps may still hold a designer's notes. - await fsp.cp(seed, workspace, { recursive: true, force: false, errorOnExist: false }) + + if ((await listApps()).length > 0) { + // In dev the workspace is the repo's own examples/ folder, which must never + // receive generated reference files. + if (DEV_URL) return + try { + const report = await upgradeWorkspace(workspace, seed, app.getVersion()) + if (report.status === 'upgraded') { + upgradeReports.set(workspace, report) + console.info(`[planchette] workspace upgraded from ${report.from} to ${report.to}`, report) + } + } catch (err) { + // A failed upgrade must never stop the designer opening their work. + console.error('[planchette] workspace upgrade failed', err) + } + return + } + + // Never clobber: a folder with no apps may still hold a designer's notes. The + // seed history is only for upgrading older workspaces, so it stays behind. + const history = path.join(seed, MANIFEST_DIR, HISTORY_FILE) + await fsp.cp(seed, workspace, { + recursive: true, + force: false, + errorOnExist: false, + filter: (src) => path.resolve(src) !== path.resolve(history), + }) } /* ------------------------------------------------------------------ * @@ -554,6 +642,28 @@ function registerIpc() { return menu ? describe(menu.items) : null }) ipcMain.handle('workspace:path', () => workspace) + + ipcMain.handle('table:get', () => tableConfig) + ipcMain.handle('table:path', () => tableConfigPath()) + ipcMain.handle('tuio:status', () => tuio?.status() ?? null) + + /** + * The renderer saves the whole config; normalise() inside writeTableConfig is + * what makes that safe. Applied live, so enrolling a puck takes effect at once. + */ + ipcMain.handle('table:save', (_e, next) => { + tableConfig = writeTableConfig(tableConfigPath(), next) + tuio?.configure(tableConfig) + send('table:changed', tableConfig) + return tableConfig + }) + + /** Hand over the current workspace's upgrade report once, then forget it. */ + ipcMain.handle('workspace:upgrade-report', () => { + const report = upgradeReports.get(workspace) ?? null + upgradeReports.delete(workspace) + return report + }) ipcMain.handle('workspace:list', () => ({ current: workspace, recent: reachableWorkspaces() })) ipcMain.handle('workspace:use', async (_e, dir) => { @@ -719,22 +829,59 @@ function buildMenu() { { role: 'togglefullscreen' }, ], }, + { + label: 'Table', + submenu: [ + { + label: 'Choose Interface…', + accelerator: 'CmdOrCtrl+Shift+P', + enabled: PRESENT, + click: () => send('app:picker'), + }, + { type: 'separator' }, + { label: 'Assign Pucks…', click: () => send('app:enroll') }, + { label: 'Calibrate…', click: () => send('app:calibrate') }, + { + label: 'Show table.json', + click: () => { + // Written out first, so there is a file to show even on a machine + // that has only ever run on defaults. + if (!fs.existsSync(tableConfigPath())) writeTableConfig(tableConfigPath(), tableConfig) + shell.showItemInFolder(tableConfigPath()) + }, + }, + { type: 'separator' }, + { + label: PRESENT ? 'Leave Present Mode' : 'Enter Present Mode', + accelerator: 'CmdOrCtrl+Shift+F', + click: () => relaunch(!PRESENT), + }, + ], + }, { role: 'windowMenu' }, ] Menu.setApplicationMenu(Menu.buildFromTemplate(template)) } +/** The table's screen: the one table.json names, or the primary display. */ +function presentBounds() { + const all = screen.getAllDisplays() + const chosen = (tableConfig.display !== null && all[tableConfig.display]) || screen.getPrimaryDisplay() + return chosen.bounds +} + async function createWindow() { const icon = devIcon() const win = new BrowserWindow({ // Ignored on macOS, which uses the bundle or the dock icon set below. This // is what gives Windows and Linux a real window and taskbar icon in dev. ...(icon ? { icon } : {}), - width: 1600, - height: 1000, - minWidth: 1100, - minHeight: 700, - backgroundColor: '#14161a', + ...(PRESENT + ? // Kiosk rather than plain fullscreen: no taskbar, no dock, nothing for an + // elbow on the table edge to open. The menu's accelerators still work. + { ...presentBounds(), kiosk: true, frame: false, autoHideMenuBar: true } + : { width: 1600, height: 1000, minWidth: 1100, minHeight: 700 }), + backgroundColor: PRESENT ? '#000000' : '#14161a', title: 'Planchette', show: false, webPreferences: { @@ -755,6 +902,8 @@ async function createWindow() { }) win.once('ready-to-show', () => win.show()) + // Every load, not once: Reload Simulator gives the renderer an empty model. + win.webContents.on('did-finish-load', replayTuio) buildMenu() watchWorkspace() @@ -772,7 +921,9 @@ async function createWindow() { if (!url.startsWith(DEV_URL ?? `${ORIGIN}/`)) event.preventDefault() }) - await win.loadURL(DEV_URL ?? `${ORIGIN}/`) + // The renderer learns its mode from the URL, so a reload keeps it. + const base = DEV_URL ?? `${ORIGIN}/` + await win.loadURL(PRESENT ? `${base}?present=1&surface=${encodeURIComponent(tableConfig.surface)}` : base) return win } @@ -824,6 +975,8 @@ app.on('window-all-closed', () => { app.on('before-quit', () => { watcher?.close() watcher = null + tuio?.close() + tuio = null }) app.whenReady().then(async () => { @@ -839,6 +992,7 @@ app.whenReady().then(async () => { if (!DEV_URL && !WORKSPACE_OVERRIDE) rememberWorkspace(workspace) registerProtocol() registerIpc() + startTuio() // macOS reads the dock icon from the bundle, which an unpackaged run has not // got, so set it explicitly. Once, not per window. diff --git a/electron/osc.js b/electron/osc.js new file mode 100644 index 0000000..41b8278 --- /dev/null +++ b/electron/osc.js @@ -0,0 +1,200 @@ +/** + * Just enough OSC 1.0 for TUIO: messages and bundles, with the argument types a + * TUIO tracker sends (int32, float32, string, blob) plus the common extras so an + * unexpected one is skipped rather than derailing the whole packet. + * + * The decoder is the listener's, the encoder the fake sender's and the tests'. + * Both live here so they cannot disagree about the wire format. + */ + +const BUNDLE = '#bundle' + +/* ------------------------------------------------------------------ * + * Decoding + * ------------------------------------------------------------------ */ + +class Reader { + constructor(buf, start = 0, end = buf.length) { + this.buf = buf + this.pos = start + this.end = end + } + + need(n) { + if (this.pos + n > this.end) throw new Error('OSC packet truncated') + } + + string() { + const zero = this.buf.indexOf(0, this.pos) + if (zero === -1 || zero >= this.end) throw new Error('OSC string not terminated') + const s = this.buf.toString('utf8', this.pos, zero) + this.pos = (zero + 4) & ~3 + return s + } + + int32() { + this.need(4) + const v = this.buf.readInt32BE(this.pos) + this.pos += 4 + return v + } + + float32() { + this.need(4) + const v = this.buf.readFloatBE(this.pos) + this.pos += 4 + return v + } + + int64() { + this.need(8) + const v = Number(this.buf.readBigInt64BE(this.pos)) + this.pos += 8 + return v + } + + double() { + this.need(8) + const v = this.buf.readDoubleBE(this.pos) + this.pos += 8 + return v + } + + blob() { + const n = this.int32() + if (n < 0) throw new Error('OSC blob has negative size') + this.need(n) + const v = this.buf.subarray(this.pos, this.pos + n) + this.pos = (this.pos + n + 3) & ~3 + return v + } +} + +function decodeMessage(r) { + const address = r.string() + const args = [] + if (r.pos >= r.end) return { address, args } + const tags = r.string() + if (!tags.startsWith(',')) return { address, args } + for (const t of tags.slice(1)) { + switch (t) { + case 'i': + args.push(r.int32()) + break + case 'f': + args.push(r.float32()) + break + case 's': + case 'S': + args.push(r.string()) + break + case 'b': + args.push(r.blob()) + break + case 'h': + args.push(r.int64()) + break + case 'd': + args.push(r.double()) + break + case 't': + args.push(r.int64()) + break + case 'c': + case 'r': + case 'm': + args.push(r.int32()) + break + case 'T': + args.push(true) + break + case 'F': + args.push(false) + break + case 'N': + args.push(null) + break + case 'I': + args.push(Infinity) + break + default: + // Unknown type: its size is unknowable, so nothing after it can be read. + throw new Error(`OSC type tag '${t}' not supported`) + } + } + return { address, args } +} + +function decodeInto(r, out) { + const first = r.buf.toString('utf8', r.pos, Math.min(r.pos + 7, r.end)) + if (first === BUNDLE) { + r.string() // "#bundle" + r.need(8) + r.pos += 8 // time tag, unused: TUIO frames are ordered by fseq + while (r.pos < r.end) { + const size = r.int32() + if (size < 0 || size % 4 !== 0) throw new Error('OSC bundle element has a bad size') + r.need(size) + decodeInto(new Reader(r.buf, r.pos, r.pos + size), out) + r.pos += size + } + } else { + out.push(decodeMessage(r)) + } +} + +/** Every message in a packet, bundles flattened, in order. Throws on a malformed packet. */ +export function decodePacket(buf) { + const out = [] + decodeInto(new Reader(buf), out) + return out +} + +/* ------------------------------------------------------------------ * + * Encoding + * ------------------------------------------------------------------ */ + +function pad(buf) { + const extra = (4 - (buf.length % 4)) % 4 + return extra ? Buffer.concat([buf, Buffer.alloc(extra)]) : buf +} + +const oscString = (s) => pad(Buffer.from(`${s}\0`, 'utf8')) + +/** + * Encode one message. Numbers are int32 unless given as `{ f: n }`; strings are + * strings. That is the whole of what TUIO needs. + */ +export function encodeMessage(address, args = []) { + let tags = ',' + const parts = [] + for (const a of args) { + if (typeof a === 'string') { + tags += 's' + parts.push(oscString(a)) + } else if (a && typeof a === 'object' && 'f' in a) { + tags += 'f' + const b = Buffer.alloc(4) + b.writeFloatBE(a.f) + parts.push(b) + } else if (Number.isInteger(a)) { + tags += 'i' + const b = Buffer.alloc(4) + b.writeInt32BE(a) + parts.push(b) + } else { + throw new Error(`cannot encode OSC argument ${String(a)}`) + } + } + return Buffer.concat([oscString(address), oscString(tags), ...parts]) +} + +export function encodeBundle(elements) { + const parts = [oscString(BUNDLE), Buffer.from([0, 0, 0, 0, 0, 0, 0, 1])] + for (const el of elements) { + const size = Buffer.alloc(4) + size.writeInt32BE(el.length) + parts.push(size, el) + } + return Buffer.concat(parts) +} diff --git a/electron/preload.cjs b/electron/preload.cjs index 26cbae5..bd0c3d2 100644 --- a/electron/preload.cjs +++ b/electron/preload.cjs @@ -8,6 +8,7 @@ const { contextBridge, ipcRenderer } = require('electron') contextBridge.exposeInMainWorld('planchette', { listApps: () => ipcRenderer.invoke('apps:list'), workspacePath: () => ipcRenderer.invoke('workspace:path'), + upgradeReport: () => ipcRenderer.invoke('workspace:upgrade-report'), listWorkspaces: () => ipcRenderer.invoke('workspace:list'), useWorkspace: (dir) => ipcRenderer.invoke('workspace:use', dir), forgetWorkspace: (dir) => ipcRenderer.invoke('workspace:forget', dir), @@ -16,6 +17,19 @@ contextBridge.exposeInMainWorld('planchette', { createInterface: (name) => ipcRenderer.invoke('interface:create', name), describeMenu: () => ipcRenderer.invoke('menu:describe'), + // The physical table. Pucks and fingers arrive already mapped and calibrated. + tableConfig: () => ipcRenderer.invoke('table:get'), + tableConfigPath: () => ipcRenderer.invoke('table:path'), + saveTableConfig: (config) => ipcRenderer.invoke('table:save', config), + tuioStatus: () => ipcRenderer.invoke('tuio:status'), + onTuioFrame: (cb) => ipcRenderer.on('tuio:frame', (_e, frame) => cb(frame)), + onTuioControl: (cb) => ipcRenderer.on('tuio:control', (_e, ev) => cb(ev)), + onTuioStatus: (cb) => ipcRenderer.on('tuio:status', (_e, status) => cb(status)), + onTableChanged: (cb) => ipcRenderer.on('table:changed', (_e, config) => cb(config)), + onPicker: (cb) => ipcRenderer.on('app:picker', () => cb()), + onEnroll: (cb) => ipcRenderer.on('app:enroll', () => cb()), + onCalibrate: (cb) => ipcRenderer.on('app:calibrate', () => cb()), + onAppsChanged: (cb) => ipcRenderer.on('apps:changed', (_e, appId) => cb(appId)), onReloadApp: (cb) => ipcRenderer.on('app:reload', () => cb()), onChooseWorkspace: (cb) => ipcRenderer.on('app:choose-workspace', () => cb()), diff --git a/electron/table-config.js b/electron/table-config.js new file mode 100644 index 0000000..6d3a470 --- /dev/null +++ b/electron/table-config.js @@ -0,0 +1,159 @@ +/** + * Per-machine table configuration: `table.json` in the app's userData folder. + * + * Everything that is a fact about one physical table rather than about anyone's + * interfaces lives here: whether to listen for TUIO, which printed tag is on + * which puck, how the tracker's axes line up with the screen, and whether this + * machine boots straight into present mode. It is deliberately not in the + * workspace. A designer's laptop never has one, and the defaults below mean an + * app without one behaves exactly as it always has. + * + * Versioned, so that a later shape can migrate an older file instead of + * discarding a table's enrollment. `normalise` is the only way in: whatever is + * on disk, or comes over IPC from the renderer, is passed through it. + * + * Free of Electron imports so it can be unit tested. + */ + +import fs from 'node:fs' +import path from 'node:path' + +export const TABLE_CONFIG_VERSION = 1 + +export function defaults() { + return { + version: TABLE_CONFIG_VERSION, + /** Boot fullscreen with no authoring chrome, taking input from TUIO. */ + present: false, + /** Index into the system's display list for present mode; null is the primary display. */ + display: null, + /** A surface preset id from src/host/surface.ts; unknown ids fall back to the default there. */ + surface: 'table55-4k', + tuio: { + enabled: false, + /** Loopback by default: no firewall prompt, and nothing on the network can inject input. */ + host: '127.0.0.1', + port: 3333, + /** Clear everything if the tracker goes silent this long. 0 disables. */ + staleMs: 2000, + }, + calibration: { flipX: false, flipY: false, angleOffsetDeg: 0, angleReversed: false }, + /** Physical tag (TUIO class id) to the logical markerId interfaces see. Empty means pass tags through. */ + pucks: [], + /** A tag reserved for the host: opens the interface picker, never reaches an interface. */ + control: { tag: null }, + /** What to do with a tag not in `pucks`, once any are mapped: 'ignore' or 'passthrough'. */ + unmapped: 'ignore', + } +} + +/* ------------------------------------------------------------------ * + * Validation + * ------------------------------------------------------------------ */ + +const isInt = (v) => Number.isInteger(v) +const bool = (v, d) => (typeof v === 'boolean' ? v : d) +const int = (v, d, min = -Infinity, max = Infinity) => (isInt(v) && v >= min && v <= max ? v : d) +const num = (v, d) => (typeof v === 'number' && Number.isFinite(v) ? v : d) + +/** Older shapes, upgraded in order. Each takes the previous version and returns the next. */ +const MIGRATIONS = { + // 0 -> 1: a file with no version is taken to be version 1 written by hand. + 0: (raw) => ({ ...raw, version: 1 }), +} + +/** + * Bring anything (a parsed file, an IPC payload, nothing at all) to a valid + * current config. Bad fields fall back to defaults one by one, so a single typo + * in a hand-edited file does not throw away the table's enrollment. + */ +export function normalise(input) { + let raw = input && typeof input === 'object' ? { ...input } : {} + let v = int(raw.version, 0, 0) + if (v > TABLE_CONFIG_VERSION) { + // Written by a newer app. Read what we understand, and say so. + console.warn(`[planchette] table.json is version ${v}; this app understands ${TABLE_CONFIG_VERSION}`) + v = TABLE_CONFIG_VERSION + } + while (v < TABLE_CONFIG_VERSION) { + raw = MIGRATIONS[v](raw) + v = raw.version + } + + const d = defaults() + const tuio = raw.tuio && typeof raw.tuio === 'object' ? raw.tuio : {} + const cal = raw.calibration && typeof raw.calibration === 'object' ? raw.calibration : {} + + // Later entries lose to earlier ones on a clash, in both directions: one tag + // cannot be two pucks, and two tags cannot both claim one markerId. + const seenTags = new Set() + const seenMarkers = new Set() + const pucks = [] + for (const p of Array.isArray(raw.pucks) ? raw.pucks : []) { + if (!p || !isInt(p.tag) || p.tag < 0 || !isInt(p.markerId) || p.markerId < 1) continue + if (seenTags.has(p.tag) || seenMarkers.has(p.markerId)) continue + seenTags.add(p.tag) + seenMarkers.add(p.markerId) + pucks.push({ markerId: p.markerId, tag: p.tag, label: typeof p.label === 'string' ? p.label.slice(0, 40) : '' }) + } + pucks.sort((a, b) => a.markerId - b.markerId) + + let controlTag = raw.control && isInt(raw.control.tag) && raw.control.tag >= 0 ? raw.control.tag : null + // The control puck must never also be an interface's puck. + if (controlTag !== null && seenTags.has(controlTag)) controlTag = null + + return { + version: TABLE_CONFIG_VERSION, + present: bool(raw.present, d.present), + display: raw.display === null ? null : int(raw.display, d.display, 0), + surface: typeof raw.surface === 'string' && raw.surface ? raw.surface : d.surface, + tuio: { + enabled: bool(tuio.enabled, d.tuio.enabled), + host: typeof tuio.host === 'string' && tuio.host ? tuio.host : d.tuio.host, + port: int(tuio.port, d.tuio.port, 1, 65535), + staleMs: int(tuio.staleMs, d.tuio.staleMs, 0, 600000), + }, + calibration: { + flipX: bool(cal.flipX, false), + flipY: bool(cal.flipY, false), + angleOffsetDeg: num(cal.angleOffsetDeg, 0) % 360, + angleReversed: bool(cal.angleReversed, false), + }, + pucks, + control: { tag: controlTag }, + unmapped: raw.unmapped === 'passthrough' ? 'passthrough' : 'ignore', + } +} + +/* ------------------------------------------------------------------ * + * Disk + * ------------------------------------------------------------------ */ + +/** Synchronous on purpose: present mode has to be known before the app is ready. */ +export function readTableConfig(file) { + try { + return normalise(JSON.parse(fs.readFileSync(file, 'utf8'))) + } catch (err) { + if (err?.code !== 'ENOENT') { + // Most likely a typo in a hand edit. Keep the file: the next save from the + // UI would otherwise overwrite a table's whole enrollment with defaults. + const kept = `${file}.broken` + try { + fs.copyFileSync(file, kept) + } catch { + /* unreadable too; nothing to keep */ + } + console.error(`[planchette] could not read ${file}; using defaults. A copy is at ${kept}`, err) + } + return defaults() + } +} + +export function writeTableConfig(file, config) { + const clean = normalise(config) + fs.mkdirSync(path.dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + fs.writeFileSync(tmp, JSON.stringify(clean, null, 2) + '\n') + fs.renameSync(tmp, file) + return clean +} diff --git a/electron/tuio.js b/electron/tuio.js new file mode 100644 index 0000000..9840669 --- /dev/null +++ b/electron/tuio.js @@ -0,0 +1,411 @@ +/** + * TUIO 1.1 input for a real table. + * + * A tracker (MultiTaction's MTServer, reacTIVision, a TUIO simulator) sends OSC + * over UDP. Browsers cannot receive UDP, so this runs in the main process and + * hands the renderer finished frames, already in the vocabulary of the table + * model: pucks with logical marker ids, normalized positions with y down, angles + * in radians, 0 up, clockwise positive. + * + * Two layers: + * - `TuioTracker` is pure: TUIO messages in, frame diffs out. Mapping a printed + * tag to the markerId interfaces know, calibration, and the control puck all + * happen here, so the renderer never sees a raw tag it would have to ignore. + * - `createTuioListener` owns the socket, the stale-tracker watchdog, and status. + * + * Only the 2Dobj (pucks) and 2Dcur (fingers) profiles are read. 2Dblb, which + * would give finger size, and TUIO 2.0 are not yet. + */ + +import dgram from 'node:dgram' +import { decodePacket } from './osc.js' + +const TAU = Math.PI * 2 +const wrap = (a) => ((a % TAU) + TAU) % TAU +const clamp01 = (v) => Math.min(1, Math.max(0, v)) + +/** How long an unmapped tag stays in the status list after it was last seen. */ +const UNKNOWN_TTL_MS = 10_000 + +/* ------------------------------------------------------------------ * + * Tracker: messages to frames + * ------------------------------------------------------------------ */ + +const PROFILES = { '/tuio/2Dobj': 'obj', '/tuio/2Dcur': 'cur' } + +function emptyFrame() { + return { + pucks: { added: [], moved: [], removed: [] }, + touches: { added: [], moved: [], removed: [] }, + } +} + +const frameIsEmpty = (f) => + !f.pucks.added.length && + !f.pucks.moved.length && + !f.pucks.removed.length && + !f.touches.added.length && + !f.touches.moved.length && + !f.touches.removed.length + +/** TUIO's late-frame rule: newer, explicitly unordered (-1), or far enough back that the tracker restarted. */ +function acceptFseq(last, f) { + return last === null || f === -1 || f > last || last - f > 100 +} + +export class TuioTracker { + /** + * @param {object} config a normalised table config + * @param {{ frame(f: object): void, control(e: object): void }} out + */ + constructor(config, out) { + this.out = out + /** `${source}|${profile}` -> { lastFseq, pending, live: Map } */ + this.streams = new Map() + /** tag -> last seen, for tags with no mapping */ + this.unknown = new Map() + this.setConfig(config) + } + + /** + * New mapping or calibration. Everything on the surface is withdrawn and + * re-announced under the new meaning, from the raw data already held: trackers + * usually send `set` only for objects that moved, so waiting for fresh data + * would leave a puck that is sitting still invisible until someone touched it. + */ + setConfig(config) { + const frame = emptyFrame() + for (const stream of this.streams?.values() ?? []) { + for (const rec of stream.live.values()) this.retire(rec, frame) + } + + this.cal = config.calibration + this.controlTag = config.control.tag + this.byTag = new Map(config.pucks.map((p) => [p.tag, p.markerId])) + // Nothing enrolled yet: show raw tags, so a table that has never been set up + // still does something. Once anything is enrolled, the setting decides. + this.passthrough = config.pucks.length === 0 || config.unmapped === 'passthrough' + this.unknown?.clear() + + for (const stream of this.streams?.values() ?? []) { + for (const [sid, rec] of stream.live) { + const next = this.place(stream, rec.raw, undefined) + stream.live.set(sid, next) + this.announce(next, undefined, frame) + } + } + if (this.out && !frameIsEmpty(frame)) this.out.frame(frame) + } + + /** + * Everything on the surface as if it had just arrived. For a renderer that + * reloaded and lost its model while the pucks stayed put. + */ + snapshot() { + const frame = emptyFrame() + const controls = [] + for (const stream of this.streams.values()) { + for (const rec of stream.live.values()) { + if (rec.role === 'control') controls.push({ type: 'add', key: rec.key, x: rec.x, y: rec.y, angle: rec.angle }) + else this.announce(rec, undefined, frame) + } + } + return { frame, controls } + } + + /** Everything currently on the surface leaves, and the tracker is forgotten. Used on silence and shutdown. */ + reset() { + const frame = emptyFrame() + for (const stream of this.streams.values()) { + for (const rec of stream.live.values()) this.retire(rec, frame) + } + this.streams.clear() + if (!frameIsEmpty(frame)) this.out.frame(frame) + } + + hasContacts() { + for (const s of this.streams.values()) if (s.live.size) return true + return false + } + + /** Raw tags on the surface right now, with what each one means. For status and enrollment. */ + tagsPresent() { + const out = [] + for (const s of this.streams.values()) { + for (const rec of s.live.values()) { + if (rec.kind !== 'obj') continue + out.push({ tag: rec.tag, markerId: rec.markerId ?? null, control: rec.role === 'control' }) + } + } + return out.sort((a, b) => a.tag - b.tag) + } + + unknownTags(now = Date.now()) { + for (const [tag, at] of this.unknown) if (now - at > UNKNOWN_TTL_MS) this.unknown.delete(tag) + return [...this.unknown.keys()].sort((a, b) => a - b) + } + + /** Feed one decoded packet. `origin` distinguishes trackers sending from different addresses. */ + handlePacket(messages, origin = '') { + // A TUIO 1.1 `source` message names the tracker for the rest of its bundle. + let source = origin + for (const m of messages) { + const profile = PROFILES[m.address] + if (!profile) continue + const [cmd, ...args] = m.args + if (cmd === 'source') { + source = `${origin}|${args[0]}` + continue + } + const key = `${source}|${profile}` + let stream = this.streams.get(key) + if (!stream) { + stream = { key, profile, lastFseq: null, pending: { alive: null, sets: new Map() }, live: new Map() } + this.streams.set(key, stream) + } + if (cmd === 'alive') { + stream.pending.alive = new Set(args.filter(Number.isInteger)) + } else if (cmd === 'set') { + const rec = profile === 'obj' ? parseObj(args) : parseCur(args) + if (rec) stream.pending.sets.set(rec.sid, rec) + } else if (cmd === 'fseq') { + const f = args[0] + if (Number.isInteger(f) && acceptFseq(stream.lastFseq, f)) { + if (f !== -1) stream.lastFseq = f + this.commit(stream) + } + stream.pending = { alive: null, sets: new Map() } + } + } + } + + commit(stream) { + const { alive, sets } = stream.pending + // A frame with set messages but no alive list cannot say what left. TUIO + // always sends alive, so this is a malformed or partial bundle: skip it. + if (!alive) return + const frame = emptyFrame() + + for (const [sid, rec] of stream.live) { + if (!alive.has(sid)) { + stream.live.delete(sid) + this.retire(rec, frame) + } + } + + for (const sid of alive) { + const raw = sets.get(sid) + const prev = stream.live.get(sid) + if (!raw && !prev) continue // alive before its first set: wait for the data + if (!raw) continue // alive and unchanged + const rec = this.place(stream, raw, prev) + stream.live.set(sid, rec) + this.announce(rec, prev, frame) + } + + if (!frameIsEmpty(frame)) this.out.frame(frame) + } + + /** Apply calibration and mapping to raw tracker values. */ + place(stream, raw, prev) { + const c = this.cal + const x = clamp01(c.flipX ? 1 - raw.x : raw.x) + const y = clamp01(c.flipY ? 1 - raw.y : raw.y) + const rec = { kind: stream.profile, key: `${stream.key}|${raw.sid}`, x, y, raw } + if (stream.profile === 'cur') return rec + + const a = (c.angleReversed ? -raw.a : raw.a) + (c.angleOffsetDeg * Math.PI) / 180 + rec.angle = wrap(a) + rec.tag = raw.tag + // A session keeps its role for life: TUIO never changes a session's tag. + const role = prev ?? this.classify(raw.tag) + rec.role = role.role + rec.markerId = role.markerId + if (raw.tag !== this.controlTag && !this.byTag.has(raw.tag)) this.unknown.set(raw.tag, Date.now()) + return rec + } + + classify(tag) { + if (tag === this.controlTag) return { role: 'control', markerId: undefined } + if (this.byTag.has(tag)) return { role: 'puck', markerId: this.byTag.get(tag) } + if (this.passthrough) return { role: 'puck', markerId: tag } + return { role: 'ignored', markerId: undefined } + } + + announce(rec, prev, frame) { + if (rec.kind === 'cur') { + const t = { key: rec.key, x: rec.x, y: rec.y } + ;(prev ? frame.touches.moved : frame.touches.added).push(t) + return + } + if (rec.role === 'ignored') return + if (rec.role === 'control') { + this.out.control({ type: prev ? 'move' : 'add', key: rec.key, x: rec.x, y: rec.y, angle: rec.angle }) + return + } + const p = { key: rec.key, markerId: rec.markerId, tag: rec.tag, x: rec.x, y: rec.y, angle: rec.angle } + ;(prev ? frame.pucks.moved : frame.pucks.added).push(p) + } + + retire(rec, frame) { + if (rec.kind === 'cur') frame.touches.removed.push(rec.key) + else if (rec.role === 'control') this.out.control({ type: 'remove', key: rec.key }) + else if (rec.role === 'puck') frame.pucks.removed.push(rec.key) + } +} + +/** `/tuio/2Dobj set s i x y a X Y A m r` */ +function parseObj(args) { + const [sid, tag, x, y, a] = args + if (!Number.isInteger(sid) || !Number.isInteger(tag)) return null + if (![x, y, a].every((v) => typeof v === 'number' && Number.isFinite(v))) return null + return { sid, tag, x, y, a } +} + +/** `/tuio/2Dcur set s x y X Y m` */ +function parseCur(args) { + const [sid, x, y] = args + if (!Number.isInteger(sid)) return null + if (![x, y].every((v) => typeof v === 'number' && Number.isFinite(v))) return null + return { sid, x, y } +} + +/* ------------------------------------------------------------------ * + * Listener: socket, watchdog, status + * ------------------------------------------------------------------ */ + +/** + * @param {{ frame(f): void, control(e): void, status(s): void }} out + * @returns {{ configure(config): void, close(): void, status(): object }} + */ +export function createTuioListener(out) { + let config = null + let socket = null + let bound = null // `${host}:${port}` while listening + let state = { state: 'off', host: null, port: null, error: null } + let lastPacket = 0 + let packets = 0 + let rate = 0 + let badPackets = 0 + let lastStatusJson = '' + + const tracker = new TuioTracker( + // Placeholder until configure() runs; nothing arrives before then anyway. + { + calibration: { flipX: false, flipY: false, angleOffsetDeg: 0, angleReversed: false }, + control: { tag: null }, + pucks: [], + unmapped: 'ignore', + }, + { frame: (f) => out.frame(f), control: (e) => out.control(e) }, + ) + + function status() { + return { + ...state, + packetsPerSec: rate, + badPackets, + lastPacketAgoMs: lastPacket ? Date.now() - lastPacket : null, + tags: tracker.tagsPresent(), + unknownTags: tracker.unknownTags(), + } + } + + /** Only when something a person would notice changed; the packet age always changes. */ + function publish(force = false) { + const s = status() + const { lastPacketAgoMs: _age, ...stable } = s + const json = JSON.stringify(stable) + if (force || json !== lastStatusJson) { + lastStatusJson = json + out.status(s) + } + } + + function closeSocket() { + if (!socket) return + try { + socket.close() + } catch { + /* already closed */ + } + socket = null + bound = null + } + + function open(host, port) { + closeSocket() + state = { state: 'starting', host, port, error: null } + const s = dgram.createSocket({ type: 'udp4', reuseAddr: true }) + socket = s + s.on('message', (buf, rinfo) => { + lastPacket = Date.now() + packets++ + try { + tracker.handlePacket(decodePacket(buf), `${rinfo.address}:${rinfo.port}`) + } catch { + // One bad packet must not take the table down. Counted, so it shows. + badPackets++ + } + }) + s.on('error', (err) => { + if (socket !== s) return + state = { + state: 'error', + host, + port, + error: err.code === 'EADDRINUSE' ? `port ${port} is already in use` : String(err.message || err), + } + closeSocket() + tracker.reset() + publish(true) + }) + s.bind(port, host, () => { + if (socket !== s) return + bound = `${host}:${port}` + state = { state: 'listening', host, port, error: null } + publish(true) + }) + } + + // Once a second: packet rate, stale-tracker watchdog, and status if it changed. + const timer = setInterval(() => { + rate = packets + packets = 0 + const stale = config?.tuio.staleMs + if (stale && tracker.hasContacts() && Date.now() - lastPacket > stale) tracker.reset() + publish() + }, 1000) + timer.unref?.() + + /** The parts of the config that change what a tag means. A change re-reads everything on the surface. */ + const meaning = (c) => JSON.stringify([c.pucks, c.control, c.unmapped, c.calibration]) + + return { + configure(next) { + const prev = config + config = next + if (!prev || meaning(prev) !== meaning(next)) tracker.setConfig(next) + + if (!next.tuio.enabled) { + if (socket || state.state !== 'off') { + closeSocket() + tracker.reset() + state = { state: 'off', host: null, port: null, error: null } + publish(true) + } + return + } + const want = `${next.tuio.host}:${next.tuio.port}` + if (bound !== want || state.state === 'error' || !socket) open(next.tuio.host, next.tuio.port) + else publish(true) + }, + close() { + clearInterval(timer) + closeSocket() + tracker.reset() + }, + snapshot: () => tracker.snapshot(), + status, + } +} diff --git a/electron/workspace-upgrade.js b/electron/workspace-upgrade.js new file mode 100644 index 0000000..cfb6e35 --- /dev/null +++ b/electron/workspace-upgrade.js @@ -0,0 +1,277 @@ +/** + * Bringing an existing workspace up to date with the app that opened it. + * + * A workspace is seeded once, when it is empty. Before 0.2.0 that was the end of + * it: the reference docs, the SDK type declarations and the agent guidance stayed + * at whatever version first created the folder, so a designer's coding agent kept + * reading an API that the app no longer had. This module refreshes those files. + * + * The rule is that the app only ever replaces what it wrote and nobody touched + * since. Every file the seed owns is recorded with its hash in + * `.planchette/seed.json`. On upgrade: + * + * - a file still matching what was written is replaced with the new version; + * - a file the designer edited is kept, and the new version is written beside it + * (`API.md` -> `API.new.md`) for them to merge; + * - a file or example the designer deleted stays deleted; + * - something new in this seed, which the workspace never had, is added; + * - examples are never overwritten, only added when new. + * + * Workspaces from 0.1.x have no manifest. For those, the hashes of every file as + * shipped in each 0.1.x release (`history`) stand in for it. + * + * Deliberately free of Electron imports, so the build scripts and the unit tests + * can use it directly. + */ + +import { createHash } from 'node:crypto' +import fs from 'node:fs' +import fsp from 'node:fs/promises' +import path from 'node:path' + +export const MANIFEST_DIR = '.planchette' +export const MANIFEST_FILE = 'seed.json' +/** Lives in the seed only. Never copied into a workspace. */ +export const HISTORY_FILE = 'history.json' + +/* ------------------------------------------------------------------ * + * Building a manifest + * ------------------------------------------------------------------ */ + +export function hashBuffer(buf) { + return createHash('sha256').update(buf).digest('hex') +} + +async function hashFile(file) { + return hashBuffer(await fsp.readFile(file)) +} + +/** Forward slashes on every platform, so manifests compare across machines. */ +const toPosix = (p) => p.split(path.sep).join('/') +const fromPosix = (p) => p.split('/').join(path.sep) + +async function walk(dir, base = dir) { + const out = [] + for (const e of await fsp.readdir(dir, { withFileTypes: true })) { + const full = path.join(dir, e.name) + if (e.isDirectory()) out.push(...(await walk(full, base))) + else if (e.isFile()) out.push(toPosix(path.relative(base, full))) + } + return out +} + +/** A top-level folder holding an index.html is an interface, and belongs to the designer once copied. */ +async function isInterfaceDir(root, name) { + return fs.existsSync(path.join(root, name, 'index.html')) +} + +/** + * Describe a seed folder: the hash of every file the app owns, and the names of + * the example interfaces. The manifest's own folder is never part of it. + */ +export async function buildManifest(seedDir, seedVersion) { + const examples = [] + const files = {} + for (const e of await fsp.readdir(seedDir, { withFileTypes: true })) { + if (e.name === MANIFEST_DIR) continue + if (e.isDirectory() && (await isInterfaceDir(seedDir, e.name))) { + examples.push(e.name) + continue + } + const rels = e.isDirectory() ? (await walk(path.join(seedDir, e.name))).map((r) => `${e.name}/${r}`) : [e.name] + for (const rel of rels) files[rel] = await hashFile(path.join(seedDir, fromPosix(rel))) + } + return { seedVersion, files: sortKeys(files), examples: examples.sort() } +} + +function sortKeys(o) { + return Object.fromEntries(Object.entries(o).sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))) +} + +/* ------------------------------------------------------------------ * + * Versions + * ------------------------------------------------------------------ */ + +/** Compare dotted numeric versions. Anything after a dash is ignored. */ +export function compareVersions(a, b) { + const pa = String(a).split('-')[0].split('.').map(Number) + const pb = String(b).split('-')[0].split('.').map(Number) + for (let i = 0; i < Math.max(pa.length, pb.length); i++) { + const d = (pa[i] || 0) - (pb[i] || 0) + if (d) return Math.sign(d) + } + return 0 +} + +/* ------------------------------------------------------------------ * + * Upgrading + * ------------------------------------------------------------------ */ + +async function readJson(file) { + try { + return JSON.parse(await fsp.readFile(file, 'utf8')) + } catch { + return null + } +} + +/** `API.md` -> `API.new.md`, `types/index.d.ts` -> `types/index.new.d.ts`. */ +export function sidecarName(rel) { + const dir = path.posix.dirname(rel) + const base = path.posix.basename(rel) + const m = /^(.+?)((?:\.d)?\.[^.]+)?$/.exec(base) + // A dotfile such as `.editorconfig` has no stem to put `.new` in front of. + const name = m && m[1] && !m[1].startsWith('.') ? `${m[1]}.new${m[2] ?? ''}` : `${base}.new` + return dir === '.' ? name : `${dir}/${name}` +} + +/** Write via a temp file and a rename, so a crash never leaves half a file. */ +async function writeAtomic(file, data) { + await fsp.mkdir(path.dirname(file), { recursive: true }) + const tmp = `${file}.${process.pid}.tmp` + await fsp.writeFile(tmp, data) + await fsp.rename(tmp, file) +} + +/** + * What the workspace was seeded with: its own manifest, or for a 0.1.x workspace + * the union of everything those releases shipped. Returns null for a folder the + * app never seeded, which it then leaves alone. + */ +async function priorState(workspace, newManifest, history) { + const manifest = await readJson(path.join(workspace, MANIFEST_DIR, MANIFEST_FILE)) + if (manifest && typeof manifest.files === 'object') { + return { + legacy: false, + seedVersion: String(manifest.seedVersion ?? '0.0.0'), + known: (rel) => (manifest.files[rel] ? [manifest.files[rel]] : []), + hadFile: (rel) => rel in manifest.files, + hadExample: (name) => Array.isArray(manifest.examples) && manifest.examples.includes(name), + } + } + + const versions = Object.values(history ?? {}) + const known = (rel) => versions.map((v) => v.files?.[rel]).filter(Boolean) + + // Only a folder holding at least one seeded file was ever seeded. A folder of + // the designer's own, added as a workspace, never received the reference files, + // and an upgrade is no reason to start writing into it now. + const owned = new Set([...versions.flatMap((v) => Object.keys(v.files ?? {})), ...Object.keys(newManifest.files)]) + const anyPresent = [...owned].some((rel) => fs.existsSync(path.join(workspace, fromPosix(rel)))) + if (!anyPresent) return null + + return { + legacy: true, + seedVersion: '0.1.x', + known, + hadFile: (rel) => known(rel).length > 0, + hadExample: (name) => versions.some((v) => v.examples?.includes(name)), + } +} + +/** + * Bring `workspace` up to the seed in `seedDir`. + * + * Returns a report: `{ status, from, to, added, updated, kept, removed, examplesAdded }`. + * `status` is `upgraded`, `current` (nothing to do), `newer` (the workspace came + * from a later app, so it is left alone), or `unseeded` (not a folder the app + * seeded). `kept` lists `{ path, newCopy }` for each file the designer edited. + */ +export async function upgradeWorkspace(workspace, seedDir, appVersion) { + const report = { + status: 'current', + from: null, + to: appVersion, + added: [], + updated: [], + kept: [], + removed: [], + examplesAdded: [], + } + + const next = await readJson(path.join(seedDir, MANIFEST_DIR, MANIFEST_FILE)) + if (!next?.files) return { ...report, status: 'no-seed' } + const history = await readJson(path.join(seedDir, MANIFEST_DIR, HISTORY_FILE)) + + const prior = await priorState(workspace, next, history) + if (!prior) return { ...report, status: 'unseeded' } + report.from = prior.seedVersion + + if (!prior.legacy) { + const cmp = compareVersions(prior.seedVersion, next.seedVersion) + if (cmp > 0) return { ...report, status: 'newer' } + } + + for (const [rel, newHash] of Object.entries(next.files)) { + const dest = path.join(workspace, fromPosix(rel)) + const src = path.join(seedDir, fromPosix(rel)) + + if (!fs.existsSync(dest)) { + // Deleted by the designer: respect it. Never had it: add it. + if (prior.hadFile(rel)) continue + await writeAtomic(dest, await fsp.readFile(src)) + report.added.push(rel) + continue + } + + const current = await hashFile(dest) + if (current === newHash) continue + const known = prior.known(rel) + if (known.includes(current)) { + await writeAtomic(dest, await fsp.readFile(src)) + report.updated.push(rel) + } else if (known.length && known.every((h) => h === newHash)) { + // Edited, but the app's version has not changed since they last got it, so + // there is nothing new to offer. Without this, every launch would write a + // fresh `.new` copy beside every file a designer had ever touched. + continue + } else { + const side = sidecarName(rel) + await writeAtomic(path.join(workspace, fromPosix(side)), await fsp.readFile(src)) + report.kept.push({ path: rel, newCopy: side }) + } + } + + // Files an earlier seed owned that this one dropped. Removed only if untouched. + if (!prior.legacy) { + const manifest = await readJson(path.join(workspace, MANIFEST_DIR, MANIFEST_FILE)) + for (const [rel, oldHash] of Object.entries(manifest.files)) { + if (rel in next.files) continue + const dest = path.join(workspace, fromPosix(rel)) + if (!fs.existsSync(dest)) continue + if ((await hashFile(dest)) === oldHash) { + await fsp.rm(dest) + report.removed.push(rel) + } + } + } + + for (const name of next.examples ?? []) { + const dest = path.join(workspace, name) + if (fs.existsSync(dest) || prior.hadExample(name)) continue + await fsp.cp(path.join(seedDir, name), dest, { recursive: true, force: false, errorOnExist: false }) + report.examplesAdded.push(name) + } + + // Last, so an interrupted run simply runs again next time. + await writeManifest(workspace, next) + + const changed = + report.added.length + + report.updated.length + + report.kept.length + + report.removed.length + + report.examplesAdded.length + const versionMoved = prior.legacy || compareVersions(prior.seedVersion, next.seedVersion) !== 0 + report.status = changed || versionMoved ? 'upgraded' : 'current' + return report +} + +/** Record what a workspace now holds. History stays in the seed. */ +export async function writeManifest(workspace, manifest) { + const { seedVersion, files, examples } = manifest + await writeAtomic( + path.join(workspace, MANIFEST_DIR, MANIFEST_FILE), + JSON.stringify({ seedVersion, files, examples }, null, 2) + '\n', + ) +} diff --git a/index.html b/index.html index 4581627..67c4158 100644 --- a/index.html +++ b/index.html @@ -108,6 +108,7 @@ th { text-align: left; color: var(--dim); font-weight: 500; padding: 2px 4px; border-bottom: 1px solid var(--line); } td { padding: 2px 4px; border-bottom: 1px solid #22262d; } td.hi { color: var(--accent); } + td .tag { color: var(--dim); } tr.empty td { color: #5a6170; text-align: center; padding: 8px; font-style: italic; } #log { height: 220px; overflow-y: auto; overflow-x: hidden; @@ -154,6 +155,55 @@ mouse while a visitor is dragging a puck. */ body.embed #stage { overflow: hidden; } + /* ---- present mode ---- + The table's own display: the surface and nothing else. */ + body.present #topbar, + body.present #inspector, + body.present #overlay { display: none; } + body.present #app { grid-template-columns: 1fr; grid-template-rows: 1fr; } + body.present #stage { padding: 0; overflow: hidden; background: #000; cursor: none; } + body.present #surface { box-shadow: none; cursor: none; } + /* Fingers reach the interface through TUIO only. Native touch would double them. */ + body.present #appframe { pointer-events: none; } + #present-scale { + position: absolute; left: 0; top: 0; padding: 12px 18px; font: 600 28px/1.3 system-ui, sans-serif; + background: #b4530a; color: #fff; transform: scale(var(--inv-fit, 1)); transform-origin: top left; + } + #present-scale[hidden] { display: none; } + + /* The interface picker, in table pixels; --mm is set per surface. */ + #picker { + position: absolute; top: 0; left: 0; background: rgba(0, 0, 0, .55); + font-family: system-ui, sans-serif; + } + #picker[hidden] { display: none; } + .picker-item { + position: absolute; top: 0; left: 0; display: grid; place-items: center; text-align: center; + border-radius: calc(12 * var(--mm)); padding: 0 calc(4 * var(--mm)); + background: #1b1e24; color: #d8dde5; border: calc(.8 * var(--mm)) solid #2b3038; + font-size: calc(6 * var(--mm)); overflow: hidden; white-space: nowrap; text-overflow: ellipsis; + } + .picker-item.on { background: #4da3ff; border-color: #4da3ff; color: #06111f; font-weight: 600; } + + /* ---- table setup dialogs ---- */ + dialog.setup { + position: fixed; inset: 16px auto auto 16px; margin: 0; z-index: 20; + border: 1px solid var(--line); border-radius: 10px; padding: 0; + background: var(--panel); color: var(--ink); box-shadow: 0 24px 80px #000a; + } + /* At one table pixel per screen pixel, UI sized for a laptop is about 4mm tall. */ + body.present dialog { zoom: 2; } + body.present dialog, body.present dialog * { cursor: auto; } + .enroll-body { display: flex; flex-direction: column; gap: 10px; } + .enroll-row { display: flex; align-items: center; gap: 6px; flex-wrap: wrap; } + .enroll-row span { font-family: var(--mono); font-size: 12px; min-width: 70px; } + .enroll-waiting p { margin: 0; color: var(--dim); font-size: 12px; } + .enroll-table input { width: 100%; } + .enroll-table tr.present td:first-child { color: var(--puck); } + .enroll-close { margin-top: 16px; } + /* Calibration is judged against the overlay, so it shows even on the table. */ + body.present.calibrating #overlay { display: block; pointer-events: none; } + /* ---- settings ---- */ #settings { border: 1px solid var(--line); border-radius: 10px; padding: 0; @@ -170,6 +220,11 @@ } .settings-inner section { padding-bottom: 6px; } #settings-close { margin-top: 18px; } + #table-settings { margin-top: 14px; padding-top: 14px; border-top: 1px solid var(--line); } + .check { display: flex; align-items: center; gap: 6px; font-size: 12px; } + .hint { margin: 8px 0 0; font-size: 11px; color: var(--dim); } + #tuio-state:not(:empty) { margin-top: 4px; font-size: 11px; color: var(--dim); } + #tuio-state.bad { color: #e08b6a; } /* ---- about ---- */ #about { @@ -192,6 +247,17 @@ .about-facts dt { color: var(--dim); text-align: right; } .about-facts dd { margin: 0; font-family: var(--mono); text-align: left; } #about-close { margin-top: 26px; } + /* ---- workspace upgrade notice ---- */ + #ws-notice { + position: fixed; right: 16px; bottom: 16px; z-index: 10; width: 380px; max-width: calc(100vw - 32px); + background: var(--panel); border: 1px solid var(--line); border-radius: 10px; + padding: 14px 16px; box-shadow: 0 16px 50px #000a; font-size: 12px; + } + #ws-notice h3 { margin: 0 0 8px; font-size: 12px; font-weight: 600; } + #ws-notice p { margin: 0 0 6px; color: var(--dim); } + #ws-notice ul { margin: 0 0 8px; padding-left: 18px; } + #ws-notice code { font-family: var(--mono); font-size: 11px; color: var(--ink); overflow-wrap: anywhere; } + .ws-notice-row { display: flex; gap: 6px; justify-content: flex-end; margin-top: 10px; } .keys kbd { font-family: var(--mono); font-size: 10px; background: #23272f; border: 1px solid var(--line); border-bottom-width: 2px; border-radius: 3px; padding: 0 4px; color: var(--ink); @@ -225,11 +291,16 @@
+