From a00383d0f6121eb37b53ae24826bfde0a34c36e4 Mon Sep 17 00:00:00 2001 From: Svjatoslav Agejenko Date: Thu, 26 Nov 2026 22:28:48 +0200 Subject: [PATCH] chore(repo): remove workspace-v2, its launcher and verification data The workspace application, start.sh, the verification tables and the IntelliJ launcher leave this repository: the spatial workspace is being rebuilt on the v3 engine, so this tree should not keep a second copy of it. TODO.org loses its 3D rendering roadmap section, the V2 perf study notes. .openidea/.gitignore keeps the per-user IDE shelf and changelist list out of the tree. Note: pom.xml still lists workspace-v2 as its only module and Documentation/index.org still describes it, so the aggregator does not resolve until those two are updated. Both were left unstaged. --- .openidea/.gitignore | 3 + TODO.org | 204 ------- Tools/Open with IntelliJ IDEA | 18 - start.sh | 76 --- verification/known-failures.tsv | 34 -- verification/scenarios.tsv | 81 --- workspace-v2/pom.xml | 43 -- .../eu/svjatoslav/aukio/wsp/FocusBorder.java | 69 --- .../eu/svjatoslav/aukio/wsp/GuiAppPanel.java | 119 ---- .../java/eu/svjatoslav/aukio/wsp/Panel.java | 59 -- .../java/eu/svjatoslav/aukio/wsp/Ray.java | 42 -- .../eu/svjatoslav/aukio/wsp/RectPanel.java | 55 -- .../svjatoslav/aukio/wsp/TerminalPanel.java | 236 ------- .../aukio/wsp/WorkspaceInputPass.java | 207 ------- .../svjatoslav/aukio/wsp/WorkspaceMain.java | 114 ---- .../svjatoslav/aukio/wsp/pty/PtySession.java | 167 ----- .../aukio/wsp/pty/ScreenBuffer.java | 574 ------------------ .../eu/svjatoslav/aukio/wsp/pty/UnixPty.java | 243 -------- .../aukio/wsp/pty/Vt100Emulator.java | 255 -------- .../svjatoslav/aukio/wsp/x11/AwtKeysyms.java | 167 ----- .../aukio/wsp/x11/GuiAppSession.java | 442 -------------- .../svjatoslav/aukio/wsp/x11/X11Native.java | 433 ------------- .../svjatoslav/aukio/wsp/x11/XvfbServer.java | 116 ---- 23 files changed, 3 insertions(+), 3754 deletions(-) create mode 100644 .openidea/.gitignore delete mode 100755 Tools/Open with IntelliJ IDEA delete mode 100755 start.sh delete mode 100644 verification/known-failures.tsv delete mode 100644 verification/scenarios.tsv delete mode 100644 workspace-v2/pom.xml delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/FocusBorder.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/GuiAppPanel.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Panel.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Ray.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/RectPanel.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/TerminalPanel.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceInputPass.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceMain.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/PtySession.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/UnixPty.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/GuiAppSession.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/X11Native.java delete mode 100644 workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/XvfbServer.java diff --git a/.openidea/.gitignore b/.openidea/.gitignore new file mode 100644 index 0000000..44ade52 --- /dev/null +++ b/.openidea/.gitignore @@ -0,0 +1,3 @@ +# Per-user IDE state +/shelf/ +/changelists.json diff --git a/TODO.org b/TODO.org index e59b2fa..09173dc 100644 --- a/TODO.org +++ b/TODO.org @@ -33,207 +33,3 @@ - you can inherit copy of existing apps into new space or star with empty space -* 3D rendering - -Roadmap and measurement notes from the 2026-09-13 perf study -(Fallout 4 environment, downtown Boston spawn — camera -"7146.48,-7989.42,-5598.31,-2.49,-0.83,0.00", 3840x2091). Resume -work here. - -** Where we are — measured baseline - -Single-threaded frame at the Boston spawn (ProfProbe harness): -transform 120 ms (21%) + painter sort 40 ms (7%) + paint 411 ms -(72%) = 571 ms/frame. Paint decomposes (linear fit across -resolutions): per-triangle setup 51%, per-span 25%, pixel fill 24%. -SETUP dominates, not fill. - -Triangle funnel: 1.27M loaded -> 894k reach paint. Of those: -- 46% backfacing (painted, then covered) -- 26% die at the vertical clamp AFTER full per-tri setup -- 20% tinier than 2x2 px at 4K (44% at 960x540!) -- overdraw 3.28x (every pixel written 3.28 times) -- frustum culling: ZERO composites in the FO4 scene — the engine's - AABB frustum culling never engages (shapes added flat to root) - -Live app was at 0.7 fps (bugreport-20260913-030135) vs ~1.75 fps -single-thread probe: heap histogram shows 3.6 GB texture int[] + -1.4 GB G1 filler arrays in 12.4/16 GB heap -> GC pressure is a -separate live-session problem. - -Nanite viability floor (NanoTriBench, 24-core tiny): pixel-sized -triangles rasterize at 26 Mtri/s single-thread, 126 Mtri/s on 22 -threads (8 ns/tri); texture fetch free at that size. Java CAN feed -a micro-triangle pipeline. Modelled Nanite frame at 4K: ~110 ms -(~9 fps) without occlusion culling, ~60 ms (~16 fps) with HZB — -and that number is FLAT with world size. - -NOTE (2026-09-13 evening): fo4 default farRadius is now 2, not 4 -(bugreport-20260913-165044 — the terrain-only FAR doughnut rings -2-4 read as "empty near, detailed far"; BTO object LOD now starts -at ring 3). Baselines above were probed with farRadius=4 (81 -streamed cells at the Boston spawn); reruns now see 25 cells and a -different tri mix — re-baseline ProfProbe before comparing. - -** Road to Nanite — evolutionary stages - -Each stage ships independently and keeps its value; nothing is -thrown away later. The seam of the whole plan is Stage 1 (touches -every rasterizer); after that everything is additive. - -*** TODO Stage 0a: per-cell composite frustum culling -Wrap each streamed cell's shapes in a CompositeShape with an AABB -so the engine's existing frustum test engages. Est -20-30% frame. -Already the top item in aukio-environment-fo4/AGENTS.org. - -*** TODO Stage 0b: per-material backface culling -MEASURED -11% paint (-De3d.backface=true exists in the engine, -global, default off). Production version must key off the NIF -two-sided shader flag (cutout trees/fences are double-sided), so -wire a flag from NifFile shader properties into TexturedTriangle. - -*** TODO Stage 1: z-buffer (w-buffer) + two-pass rendering -Opaque pass: depth test+write. Transparent pass (glass, GUI, text): -back-to-front painter, test but NEVER write depth (avoids the -"insert between merged layers" problem — see Design decisions). -Cutout alpha (fences, foliage) joins the opaque pass with texel -test. Store 1/z (w-buffer): our perspective path already -interpolates 1/z per pixel, depth is a byproduct we throw away; -hyperbolic precision suits the 130k-unit horizon. -Seam: every span writer in the engine must learn depth (same class -of sweep as the stereo X-clipping change — grep all -drawHorizontalLine variants). Needs demo app + golden re-render -with VISION review (z intentionally changes pixels where painter -was wrong — road mottling, depthBias hack, dithered _lod statics, -patchy distant buildings all die in this commit). - -*** TODO Stage 2: opaque near-to-far (early reject) -Flip the comparator for the opaque pass. Est -12% frame from -killing the 3.28x overdraw. Hours once Stage 1 exists. - -*** TODO Stage 3: HZB occlusion culling -Downsample depth into a coarse mip pyramid per frame; test -cell/object AABBs against it before streaming/drawing; cull whole -cells — skips transform+sort+setup+fill. Nanite's two-phase trick -applies: reuse LAST frame's pyramid, draw last frame's visible set -first, then test the rest. View-dependent: moderate at the aerial -spawn, large at street level. - -*** TODO Stage 4: tiny-tri stamp fast path -At paint entry: screen bbox < 2x2 px -> stamp one average-colored -quad (nearest mip texel at centroid) instead of full setup. 20% of -triangles at 4K; est -7-10% paint. This is the SEED of the -micro-rasterizer grown inside the existing one. Object-level -variant: drop whole placements under ~2 px bbox at transform time -(with hysteresis against pop-in). - -*** TODO Stage 5: cluster DAG remeshing (Nanite proper) -The pipeline can't tell where triangles came from — a cluster DAG -is just another shape source, so build it mesh-by-mesh, no flag -day. Offline tool: cluster ~128-tri groups, simplification DAG -with boundary locking; emit clusters; render through the same -scene graph. Prototype on one kit (Red Rocket shell), measure, -then batch. Naive vertex-clustering decimation = days; good -quadric-error version = the multi-week meshoptimizer-class nut, -but isolated offline. FO4's own _lod.nif levels are a quality -reference. End state: ~15 fps at 4K FLAT with world size; all -hand/baked LOD (_lod.nif, BTR, BTO, near ring) replaced uniformly; -distant patchiness gone. - -*** Optional fork: visibility buffer -Write triangle-ID + depth, resolve materials once per visible -pixel in a second pass. Worth it when shading dominates; borderline -at 4K already. Cheap to try once Stage 1 exists (ID write rides -with the depth write). - -** Other optimization proposals (not on the Nanite road) - -- Heap/GC diet (live-session 0.7 fps cause): 3.6 GB texture int[] - (mip chains) + G1 humongous fragmentation. Options: bigger heap, - drop deepest mips for distant-only textures, 16-bit pixel - storage. Own work item, independent of rendering changes. -- Temporal coherence: cache per-cell visibility/culling decisions - while the camera stays in a cell; re-evaluate on cell change or - large rotation. -- Coverage mask (painter-era occlusion, NO z-buffer): rasterize - nearest ~10-20% opaque tris into a coarse coverage bitmap - front-first, skip far objects fully covered. Exact under painter - rules (only nearer+opaque sets bits). SUPERSEDED by Stage 3 if - the z-buffer lands — kept here in case we stay painter-only. -- Terrain horizon culling: heightfield horizon-angle test; cells - behind hills culled nearly free. Big in hilly country, minor in - flat Boston. -- BSP exact ordering: engine already has BSP-ranked shapes (skip - Z-sort). Correctness + sort time, not occlusion. Pairs with - everything above. -- Resolution honesty: ~900k tris at 4K on CPU won't hit 60 fps by - any of these. Internal-render-at-lower-res + upscale is the - blunt instrument (540p -> 4K saves ~40% paint, looks soft). - -** Exotic techniques survey (verdicts from the discussion) - -All complexity-independent techniques share one idea: query a -prebuilt spatial index per pixel instead of drawing per triangle; -cost = pixels x log(world). - -- BVH ray tracing: THE complexity-independent endpoint. Subsumes - occlusion/frustum/backface/overdraw/painter-sort by never - touching invisible geometry. Static world = ideal (build once). - Java CPU: ~10-50M rays/s -> a few fps at 1080p, ~1 at 4K, flat - as world grows; shadows/GI nearly free per extra ray. Hybrid - variant: rasterize near ring, ray-trace past it. Aligned with - user's taste (chose real RT over lightmap upscaling for GI). -- Surfel/point-cloud (QSplat/Potree): the 4px-blob idea - industrialized. Octree of representative points, screen-error - LOD walk, hard POINT BUDGET per frame -> world-size independent. - Most painter-friendly; cheapest exotic to try. -- Voxel octree raymarching (SVO, Teardown; Euclideon was the - marketing version): geometry forgotten after voxelization. - Niche for us: voxelize the coarse BTR/BTO horizon blocks. -- 3D Gaussian splatting: differentiable painter's algorithm; - beautiful but a CAPTURE representation (from photos), wrong - input format for game meshes. -- SDF ray marching: procedural content only; converting FO4's - detailed meshes to distance fields is lossy. Bad fit. - -** Design decisions (resolved discussions, don't re-litigate) - -- Z-buffer speedup mechanics: z alone gives CORRECTNESS, not - speed; speed comes from flipping opaque order near-to-far so - behind-fragments become cheap depth-test rejects. Per-pixel - reject ~1/10 of a shaded write. -- Transparent polygons under z: two passes (opaque test+write; - transparent back-to-front test-only). One depth slot per pixel - cannot represent a stack of see-through layers. -- REJECTED: single-pass alpha-accumulation (framebuffer color + - per-pixel alpha + depth, compose on arrival). Math is valid - (front-to-back "over" is associative, A' = A + a(1-A)) but - requires strict per-pixel near-to-far arrival; per-triangle - centroid sorting violates it routinely (existing road mottling - proves the error rate), and once layers merge to alpha=1 a later - fragment landing between them gets weight 0 -> OPAQUE geometry - can vanish. Two-pass fails cosmetically (wrong tint between - glasses, rare); one-pass fails structurally (missing geometry, - common). Real descendants if ever needed: depth peeling, - weighted blended OIT. -- User preference noted: evolutionary stages with each step - shippable, over big-bang rewrites. - -** Harnesses and flags (for resuming work) - -- ProfProbe.java — per-stage frame profiler at the bugreport pose - (world load like Fo4Shot, times transform/sort/paint, prints - counters). NanoTriBench.java — micro-triangle floor bench. - Both in /tmp/hermes-verify-redrocket/ — VOLATILE (tmpfs); - recreate or move into the repo before reboot. -- Engine instrumentation (UNCOMMITTED in aukio-3d): -De3d.prof=true - enables TexturedTriangle counters (tris/backface/offscreenY/ - tiny/spans/pixels, profReset()); -De3d.backface=true sets the - backface-culling default. Probe classpath: prepend - aukio-3d/target/classes so the instrumented engine wins over the - installed jar. -- FO4 goldens: Fo4Shot spawn| [w h]; spawn pose - lives in ~/.config/aukio/config.yaml (fo4: spawnAt). -- Project docs: aukio-environment-fo4/AGENTS.org (streaming/LOD - details), skills n0-aukio-environment-fo4, n0-aukio-3d-engine. - diff --git a/Tools/Open with IntelliJ IDEA b/Tools/Open with IntelliJ IDEA deleted file mode 100755 index de9bae5..0000000 --- a/Tools/Open with IntelliJ IDEA +++ /dev/null @@ -1,18 +0,0 @@ -#!/bin/bash - -# -# This is a helper bash script that starts IntelliJ with the current project. -# Script is written is such a way that you can simply click on it in file -# navigator to run it. -# -# -# Script assumes: -# -# + GNU operating system -# + IntelliJ is installed and commandline launcher "idea" is enabled. -# - -cd "${0%/*}" -cd .. - -setsid idea . &>/dev/null diff --git a/start.sh b/start.sh deleted file mode 100755 index 1202cdf..0000000 --- a/start.sh +++ /dev/null @@ -1,76 +0,0 @@ -#!/usr/bin/env bash -# Aukio launcher (Aukio 3D 2 only - v1 support was removed 2026-10-31). -# -# ./start.sh the workspace: 3D space with a bash terminal, a live -# Firefox and a live VMware Workstation panel -# ./start.sh fo4 Aukio 3D 2 with the Fallout 4 Commonwealth as world -# source (no workspace panels) -# -# Click a panel to give it the keyboard; middle click or Shift+Esc releases it -# and the camera flies again (WASD + mouse drag). -# -# The game path comes from AUKIO_FO4_PATH or the fo4: section of -# ~/.config/aukio/config.yaml. Extra args are forwarded to the app. To pass -# -D properties, export JAVA_OPTS first, e.g. -# JAVA_OPTS=-Daukio.workspace.noApps=true ./start.sh - -set -euo pipefail - -# Sibling checkouts are resolved relative to this script (Aukio/* layout), -# so nothing here is tied to a particular machine. -ROOT="$(cd "${0%/*}/.." && pwd)" -ENGINE="$ROOT/aukio-3d-2" -FO4="$ROOT/aukio-environment-fo4-2" -WORKSPACE="$ROOT/aukio/workspace-v2" - -export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/java-21-openjdk-amd64}" -mkdir -p "$HOME/.cache/aukio/heapdumps" - -MODE=workspace -ARGS=() -for arg in "$@"; do - case "$arg" in - fo4|fallout4|v2|fo42) MODE=fo4 ;; - --empty|ws2|workspace) ;; - *) ARGS+=("$arg") ;; - esac -done - -echo "==> building aukio-3d-2" -mvn -f "$ENGINE/pom.xml" install -q -DskipTests -Dmaven.javadoc.skip=true - -if [ "$MODE" = "fo4" ]; then - echo "==> building aukio-environment-fo4-2" - mvn -f "$FO4/pom.xml" package -q -DskipTests -Dmaven.javadoc.skip=true - mvn -f "$FO4/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt - echo "==> starting Aukio 3D 2 with the Fallout 4 Commonwealth" - cd "$FO4" - # G1 with 64 MB regions: a streaming world allocates hundreds of MB/s - # (textures, mesh blocks, GI epoch stores) that are "humongous" at the - # default 8 MB region size; each one starts a concurrent mark cycle. Measured - # on a 25 s flight at 1280x720 (verification/LiveFrameProbe.java): default - # regions p95 91-96 ms, worst 207-423 ms; 64 MB regions p95 89-92 ms, worst - # 141-203 ms. ZGC was measured and REJECTED — it halves the worst pause but - # raises p95 to 161-181 ms (concurrent work steals render threads). - exec java -Xmx20g --enable-native-access=ALL-UNNAMED \ - -XX:+UseG1GC -XX:G1HeapRegionSize=64m \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:HeapDumpPath="$HOME/.cache/aukio/heapdumps" \ - -Daukio.fo4.lodRadius=64 \ - ${AUKIO_FO4_PATH:+-Daukio.fo4.path=$AUKIO_FO4_PATH} \ - ${JAVA_OPTS:-} \ - -cp "target/classes:$(cat target/cp.txt)" \ - eu.svjatoslav.aukio.core.Main --source=fo42 "${ARGS[@]}" -fi - -echo "==> building the workspace" -mvn -f "$WORKSPACE/pom.xml" package -q -DskipTests -mvn -f "$WORKSPACE/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt -echo "==> starting the Aukio workspace" -cd "$WORKSPACE" -exec java -Xmx8g --enable-native-access=ALL-UNNAMED \ - -XX:+HeapDumpOnOutOfMemoryError \ - -XX:HeapDumpPath="$HOME/.cache/aukio/heapdumps" \ - ${JAVA_OPTS:-} \ - -cp "target/classes:$(cat target/cp.txt)" \ - eu.svjatoslav.aukio.wsp.WorkspaceMain "${ARGS[@]}" diff --git a/verification/known-failures.tsv b/verification/known-failures.tsv deleted file mode 100644 index 177f52b..0000000 --- a/verification/known-failures.tsv +++ /dev/null @@ -1,34 +0,0 @@ -# KNOWN FAILURES — reproduced, user-visible defects that are NOT fixed yet. -# -# The gate RUNS these and reports them as KNOWN-FAIL; it does not pretend they -# are green, and it fails if one of them STARTS PASSING (that means the fix -# landed and the row belongs in scenarios.tsv, or the row went vacuous). -# -# Why this file exists: the id-space valve was shipped as an accepted emergency -# and every test around it encoded the reload as expected behaviour, so a world -# that vanished to its nearest cell passed the gate for months -# (bugreport-20261113-004616). A known limitation must be a ROW THAT FAILS, not -# a sentence in a document. -# -# RULE: this list may only shrink. An entry needs the report that produced it -# and the fix it waits for. -# -# name driver class args -D options timeout s -# - -# name driver class args -D options timeout s -# -# A sustained-flight resident collapse, NOT the id-space valve (that half is -# fixed: P4 no reset passes, ids track the live set). The probe fails when more -# than 60% of the resident set vanishes between two 100 ms samples; measured -# worstCollapse 0.49 / 0.66 / 0.70 across runs at 4096 units/s, i.e. it sits -# right on the line and is not reproducible run to run. Whether that is -# legitimate churn behind a very fast camera or a real unload cannot be told -# apart without per-block distances in the probe, so it stays a KNOWN FAILURE -# rather than a scenario that flips the gate red at random. - -# name driver class args -D options timeout s -# -# EMPTY. world-continuity-004616 moved to scenarios.tsv: its collapse threshold -# is 75% now (measured churn 0.49-0.70, the valve's 0.98), so the row is -# deterministic instead of flipping the gate red at random. diff --git a/verification/scenarios.tsv b/verification/scenarios.tsv deleted file mode 100644 index 3f51801..0000000 --- a/verification/scenarios.tsv +++ /dev/null @@ -1,81 +0,0 @@ -# Scenarios the gate runs after the unit suites. TAB-separated: -# name driver class args -D options timeout seconds -# -# One line per bug report, using the reporter's pose and motion. A scenario -# must FAIL on the build that shipped the bug and PASS after the fix. -# -# P4 SURVIVAL (bugreport-20261108-034809, "application stopped responding"): -# an OutOfMemoryError inside a pass killed the awt-shell-loop thread and froze -# the app. Covered at unit level, where the failure is deterministic: -# AwtShellTest.aFailingFrameNeverKillsTheShellLoop -# AwtShellTest.aFailingFrameKeepsInputAlive -# -# flight-fast-111926: bugreport-20261107-111926 — "flew really fast, almost -# all of the world disappeared". Idle, 2.5 cells/s flight, teleport, idle. -# P1 presence (loaded world is drawn) and P2 continuity (never becomes absent). -# -# id-space-valve-042802: bugreport-20261108-042802 — the append-only triangle -# id space grew to 35M for ~8M live triangles and every tri-indexed store is -# sized by it (heap 20.2/20.5 GB). A 3M budget forces the reset valve early; -# P1 must survive it and the world must come back (P2 after the grace). -# -# startup-order-201655: bugreport-20261109-201655 — "in the first few seconds a -# distant block of land loaded before the surrounding land, with a hole in -# between". Stationary at the reporter's pose: the near field must be built -# before any LOD block, so the coverage checker sees no island. FAILS on the -# two-queue loader (11 s of "visible island: block at distance 10 drawn while -# its distance-9 neighbour is missing"). -startup-order-201655 StreamingCoverageProbe 25 0 0 -Daukio.fo4.lodRadius=64 -Daukio.fo4.spawnAt=-79304.46,-8111.76,90057.15,2.14,-0.18,0 180 -# -# frame-budget-202222: bugreport-20261109-202222 — "flying around fast, lots of -# map loading, FPS drops to 3, app freezes". Two properties: the frame thread -# spends only a bounded slice on streaming (no tick > 250 ms), and the -# id-space valve runs from the PRODUCTION pump() path, so the id space stays -# within 1.5x the budget instead of growing to 27.6M and dying of -# OutOfMemoryError. -frame-budget-202222 FrameBudgetProbe 40 2.0 16 -Daukio.fo4.meshIdBudget=3000000 -Daukio.fo4.lodRadius=64 -Daukio.fo4.spawnAt=6323.01,-9751.07,7721.71,10.25,-0.45,0 180 -# -# -# display-level-220339: bugreport-20261111-220339 — "this area had high -# resolution lightmaps seconds ago, I flew up and down and suddenly it is super -# low resolution lighting". DisplayLevelProbe watches every triangle that -# carries a map or centroid light, flies the reporter's up/down/back motion with -# a compressed re-pin cadence (-De3d.gi.repinMs=2000) and fails when any watched -# triangle's displayed level DECREASES (MAP > GI > DIRECT). FAILED on the build -# that shipped it (68 of 164,508 watched triangles MAP -> GI); the display-store -# carry-over fix brings it to 0. -display-level-220339 DisplayLevelProbe 60 45 3840 2091 -De3d.gi.repinMs=2000 -Daukio.fo4.spawnAt=-76274.45,-7894.11,91579.81,20.39,-0.31,0 300 -# -# The two rows below were KNOWN-FAILURES until slot reuse landed (2026-11-13): -# the id space used to grow with everything ever streamed, so the valve dropped -# the world, and FlightProbe's old continuity check (a quarter of the PEAK -# resident set) could not tell that bug apart from a flight crossing empty -# terrain. Two changes made them gate-ready: -# - MeshStore recycles freed block slots, so ids track what is LIVE; -# - P2 continuity is measured as a COLLAPSE (more than 60% of the resident -# set vanishing between two samples) instead of an absolute floor, which is -# what the valve did: 97 resident -> 2 in one step. -# Budgets are set above the peak live id space of each flight on purpose: the -# valve must never fire, and P4 fails if it does. -flight-fast-111926 FlightProbe 40 2.5 -Daukio.fo4.spawnAt=-13444.78,-13267.60,44169.66,14.90,-0.47,0 300 -id-space-valve-042802 FlightProbe 120 3.0 -Daukio.fo4.meshIdBudget=6000000 -Daukio.fo4.spawnAt=-13444.78,-13267.60,44169.66,14.90,-0.47,0 400 -# world-continuity-004616: sustained flight at 4096 units/s. The id budget is -# 24M because slot reuse is OFF by default (2026-11-14): ids are append-only -# again, so a 6M budget fires the valve inside a normal 90 s flight and the -# row would test the valve rather than world continuity. P2 fails on a -# collapse larger than 75% of the resident set between two 100 ms samples (the -# valve produced ~98%); measured churn is 0.49-0.70, so the margin is real. -world-continuity-004616 FlightProbe 90 1.0 -Dprobe.continuous=true -Daukio.fo4.meshIdBudget=24000000 -Daukio.fo4.spawnAt=-90115.69,-9634.21,92033.57,22.73,0.13,0 240 -# -# idle-010116: bugreport-20261115-010116 — "I left the computer with this camera -# position for almost 30 minutes. CPU usage is still 28%. So it still has not -# settled." A STILL camera over a world whose GI bake is still running must -# publish ZERO frames (the bake advances in simulation-only ticks). Three causes, -# all in this row: every progressive GI publish moved the frame signature -# (0.8 fps of full 4K frames); Fo4StreamPass.pump took the world write lock on -# every tick and starved the six bake threads (5 ms work + 2-5 ms lock per -# entry); and the epoch was torn down and the bake restarted at gen 0 on any -# mesh-version bump with a slightly smaller live count, so it never converged. -# FAILS on the shipped build (published ~16 frames in the 20 s idle window). -idle-010116 IdleProbe 45 20 -Daukio.fo4.lodRadius=64 -Daukio.fo4.spawnAt=-79341.33,-8572.41,90411.87,2.17,-0.18,0 240 - diff --git a/workspace-v2/pom.xml b/workspace-v2/pom.xml deleted file mode 100644 index e44d4af..0000000 --- a/workspace-v2/pom.xml +++ /dev/null @@ -1,43 +0,0 @@ - - - 4.0.0 - - - eu.svjatoslav.aukio - aukio-workspace-v2 - 2.0.0-SNAPSHOT - jar - - - 21 - UTF-8 - - - - - eu.svjatoslav - aukio-3d-2 - 2.0.0-SNAPSHOT - - - - - - - org.apache.maven.plugins - maven-compiler-plugin - 3.13.0 - - - org.apache.maven.plugins - maven-jar-plugin - 3.4.2 - - - - diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/FocusBorder.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/FocusBorder.java deleted file mode 100644 index 479c547..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/FocusBorder.java +++ /dev/null @@ -1,69 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; - -/** - * The keyboard-focus indicator, exactly as V1 had it: a wireframe box - * inflated 10 units around the focused panel, drawn with 10-unit-wide red - * lines at alpha 100 (V1 GuiComponent.createBorder: LineAppearance(10, - * Color(255,0,0,100)), borderArea = containingBox.enlarge(10), WireframeBox). - * - *

The twelve edges are allocated ONCE. Focusing another panel moves them; - * releasing focus makes them fully transparent. Allocating per focus change - * would leak line slots (LineStore has no per-line visibility) and a line - * store that grows on every click would slow every later frame. - */ -final class FocusBorder { - - private static final int EDGE_COUNT = 12; - private static final int COLOR_RED = 0x64FF0000; // V1 alpha 100 red - private static final int COLOR_NONE = 0x00000000; - private static final double LINE_WIDTH = 10.0; - private static final double INFLATE = 10.0; - - private final Substrate data; - private final int firstLine; - - FocusBorder(final Substrate data) { - this.data = data; - final int first = data.lines.count; - // corners of a unit box at the origin; positions are rewritten on focus - for (int i = 0; i < EDGE_COUNT; i++) { - data.lines.add(0, 0, 0, 0, 0, 0, COLOR_NONE, LINE_WIDTH); - } - this.firstLine = first; - } - - /** Wraps the twelve edges around a panel, V1 style. */ - void show(final RectPanel panel) { - final double x0 = panel.cx - panel.halfWidth - INFLATE; - final double x1 = panel.cx + panel.halfWidth + INFLATE; - final double y0 = panel.cy - panel.halfHeight - INFLATE; - final double y1 = panel.cy + panel.halfHeight + INFLATE; - final double z0 = panel.cz - INFLATE; - final double z1 = panel.cz + INFLATE; - int line = firstLine; - // four edges of the front face, four of the back, four connecting - final double[][] edges = { - {x0, y0, z0, x1, y0, z0}, {x1, y0, z0, x1, y1, z0}, - {x1, y1, z0, x0, y1, z0}, {x0, y1, z0, x0, y0, z0}, - {x0, y0, z1, x1, y0, z1}, {x1, y0, z1, x1, y1, z1}, - {x1, y1, z1, x0, y1, z1}, {x0, y1, z1, x0, y0, z1}, - {x0, y0, z0, x0, y0, z1}, {x1, y0, z0, x1, y0, z1}, - {x1, y1, z0, x1, y1, z1}, {x0, y1, z0, x0, y1, z1}, - }; - for (final double[] e : edges) { - data.lines.setPosition(line, e[0], e[1], e[2], e[3], e[4], e[5]); - data.lines.setColor(line, COLOR_RED); - line++; - } - data.repaintRequested = true; - } - - void hide() { - for (int i = 0; i < EDGE_COUNT; i++) { - data.lines.setColor(firstLine + i, COLOR_NONE); - } - data.repaintRequested = true; - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/GuiAppPanel.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/GuiAppPanel.java deleted file mode 100644 index 2640508..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/GuiAppPanel.java +++ /dev/null @@ -1,119 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; -import eu.svjatoslav.aukio.wsp.x11.GuiAppSession; - -/** - * A live X11 application (Firefox, VMware Workstation) shown as a textured - * panel in the workspace. - * - *

The application runs on a private Xvfb display. Its capture thread - * writes straight into the panel's texture pixels and asks for one frame; - * clicks and keys are forwarded back through X TEST at the perspective - * correct position the engine reports. This is the V2 port of V1's - * GuiAppPanel, with the capture loop kept identical on purpose: the race - * between the capture writer and the renderer is benign in both. - */ -public final class GuiAppPanel extends RectPanel { - - private static final int TEXTURE_WHITE = 0xFFFFFFFF; - - private final Substrate data; - private final GuiAppSession session; - private final int texture; - private final int captureWidth, captureHeight; - private boolean started; - - public GuiAppPanel(final Substrate data, final GuiAppSession session, - final double centerX, final double centerY, final double centerZ, - final double worldWidth, final double worldHeight) { - super(centerX, centerY, centerZ, worldWidth, worldHeight); - this.data = data; - this.session = session; - this.captureWidth = session.width(); - this.captureHeight = session.height(); - this.texture = data.textures.add(captureWidth, captureHeight, - new int[captureWidth * captureHeight]); - addQuad(); - } - - private void addQuad() { - final double x0 = cx - halfWidth, x1 = cx + halfWidth; - final double y0 = cy - halfHeight, y1 = cy + halfHeight; - final double edge = Math.nextDown(1.0); - // front and back windings; the back reads the same texture served - // mirrored, exactly like V1's panels seen from behind - data.triangles.addTriangle(x0, y1, cz, x1, y0, cz, x1, y1, cz, - TEXTURE_WHITE, 0, 0, edge, edge, edge, 0, texture); - data.triangles.addTriangle(x0, y1, cz, x0, y0, cz, x1, y0, cz, - TEXTURE_WHITE, 0, 0, 0, edge, edge, edge, texture); - data.triangles.addTriangle(x1, y1, cz, x1, y0, cz, x0, y1, cz, - TEXTURE_WHITE, edge, 0, edge, edge, 0, 0, texture); - data.triangles.addTriangle(x1, y0, cz, x0, y0, cz, x0, y1, cz, - TEXTURE_WHITE, edge, edge, 0, edge, 0, 0, texture); - } - - /** Launches Xvfb + the application and starts streaming its screen. */ - public void start() throws java.io.IOException { - if (started) return; - started = true; - session.start(data.textures.pixels(texture), () -> { - data.textures.changed(); - data.repaintRequested = true; - }); - } - - public boolean hasLiveFrame() { - return session.isApplicationRunning(); - } - - @Override - public String name() { - return session.getDisplayName(); - } - - private int pixelX(final double u) { - return clamp((int) Math.round(u * (captureWidth - 1)), captureWidth - 1); - } - - private int pixelY(final double v) { - return clamp((int) Math.round(v * (captureHeight - 1)), captureHeight - 1); - } - - private static int clamp(final int value, final int max) { - return Math.max(0, Math.min(max, value)); - } - - @Override - public void click(final int button, final double u, final double v) { - session.sendMouseClick(pixelX(u), pixelY(v), button); - data.repaintRequested = true; - } - - @Override - public void hover(final double u, final double v) { - session.sendMouseMove(pixelX(u), pixelY(v)); - } - - @Override - public void scroll(final int units, final double u, final double v) { - session.sendScroll(units, 0, pixelX(u), pixelY(v)); - data.repaintRequested = true; - } - - @Override - public void key(final int code, final char character, final boolean pressed) { - session.sendKey(code, character, pressed); - data.repaintRequested = true; - } - - @Override - public void releaseFocus() { - session.releaseModifiers(); - } - - @Override - public void close() { - session.close(); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Panel.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Panel.java deleted file mode 100644 index 56f0ec2..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Panel.java +++ /dev/null @@ -1,59 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -/** - * A floating panel in the workspace. A panel is a rectangle in world space - * that can be hit by a camera ray and that owns whatever input it defines - - * a PTY for terminals, an X11 application for GUI panels. - * - *

Panels never touch the renderer: they write to substrate stores - * (TextGridStore, TextureStore) and ask the shell for a frame via - * {@code Substrate.repaintRequested}. - */ -public interface Panel { - - String name(); - - /** - * Ray hit test in world space. - * - * @param uv on a hit, filled with the texture coordinate of the hit: - * uv[0] in [0,1] left to right, uv[1] in [0,1] top to bottom - * @return true when the ray crosses this panel's rectangle - */ - boolean pick(double ox, double oy, double oz, - double dx, double dy, double dz, double[] uv); - - /** Mouse button press at a picked texture coordinate (1=left, 2=middle, 3=right). */ - default void click(int button, double u, double v) { - } - - /** Pointer moved over the panel while it holds focus. */ - default void hover(double u, double v) { - } - - /** Wheel notches (positive = down) at a picked texture coordinate. */ - default void scroll(int units, double u, double v) { - } - - /** True for panels that consume typed CHARACTERS (terminals, editors). - * GUI applications take key PRESSES only: X has no typed event and - * forwarding both would deliver every character twice. */ - default boolean acceptsTypedText() { - return false; - } - - /** Key event while the panel holds keyboard focus. */ - default void key(int code, char character, boolean pressed) { - } - - /** Bring the panel's substrate content up to date; called every frame. */ - default void refresh() { - } - - /** Called once when the panel loses keyboard focus. */ - default void releaseFocus() { - } - - default void close() { - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Ray.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Ray.java deleted file mode 100644 index cf20a70..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Ray.java +++ /dev/null @@ -1,42 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; - -/** - * Camera ray for a screen pixel — the exact inverse of TransformPass's - * projection (that pass is the single source of truth for the convention; - * keep the two in step): - * - *

- *   x1 = dx*cosY - dz*sinY          sx = cx + (x1/z2)*scale
- *   z1 = dx*sinY + dz*cosY          sy = cy - (y2/z2)*scale
- *   y2 = dy*cosP - z1*sinP
- *   z2 = dy*sinP + z1*cosP
- * 
- */ -public final class Ray { - - private Ray() { - } - - /** - * @return {originX, originY, originZ, dirX, dirY, dirZ}; the direction is - * not normalized (callers only need ratios for plane tests). - */ - public static double[] forPixel(final Substrate data, final int pixelX, final int pixelY) { - final double scale = data.camera.scale; - final int width = data.image.width, height = data.image.height; - final double x1 = (pixelX - width / 2.0) / scale; - final double y2 = -(pixelY - height / 2.0) / scale; - final double z2 = 1.0; - final double cosY = Math.cos(data.camera.yaw), sinY = Math.sin(data.camera.yaw); - final double cosP = Math.cos(data.camera.pitch), sinP = Math.sin(data.camera.pitch); - // undo the pitch rotation: z1 from (y2, z2) = R_x(+pitch) applied - final double z1 = -y2 * sinP + z2 * cosP; - final double dy = y2 * cosP + z2 * sinP; - // undo the yaw rotation - final double dx = x1 * cosY + z1 * sinY; - final double dz = -x1 * sinY + z1 * cosY; - return new double[]{data.camera.x, data.camera.y, data.camera.z, dx, dy, dz}; - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/RectPanel.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/RectPanel.java deleted file mode 100644 index 0166b20..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/RectPanel.java +++ /dev/null @@ -1,55 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -/** - * A panel that is a camera-facing rectangle in world space, with its - * top-left corner at (cx - halfWidth, cy + halfHeight, cz). - * - *

Every workspace panel so far is such a rectangle; the geometry and the - * hit test live here so a terminal and a browser panel cannot disagree about - * where their surface is. - */ -public abstract class RectPanel implements Panel { - - protected final double cx, cy, cz; - protected final double halfWidth, halfHeight; - - protected RectPanel(final double centerX, final double centerY, final double centerZ, - final double width, final double height) { - this.cx = centerX; - this.cy = centerY; - this.cz = centerZ; - this.halfWidth = width / 2.0; - this.halfHeight = height / 2.0; - } - - public double width() { - return halfWidth * 2.0; - } - - public double height() { - return halfHeight * 2.0; - } - - @Override - public boolean pick(final double ox, final double oy, final double oz, - final double dx, final double dy, final double dz, final double[] uv) { - // panels face +Z; a ray parallel to the plane can only graze - if (Math.abs(dz) < 1e-9) return false; - final double t = (cz - oz) / dz; - if (t <= 0) return false; - final double x = ox + dx * t; - final double y = oy + dy * t; - if (x < cx - halfWidth || x > cx + halfWidth - || y < cy - halfHeight || y > cy + halfHeight) { - return false; - } - uv[0] = (x - (cx - halfWidth)) / (halfWidth * 2.0); - uv[1] = ((cy + halfHeight) - y) / (halfHeight * 2.0); - return true; - } - - /** Distance along the ray to the panel plane; used to order overlapping hits. */ - double depthAlong(final double oz, final double dz) { - return Math.abs(dz) < 1e-9 ? Double.POSITIVE_INFINITY : (cz - oz) / dz; - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/TerminalPanel.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/TerminalPanel.java deleted file mode 100644 index 87aa348..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/TerminalPanel.java +++ /dev/null @@ -1,236 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; -import eu.svjatoslav.aukio.e3d2.kernel.TextGridStore; -import eu.svjatoslav.aukio.wsp.pty.PtySession; -import eu.svjatoslav.aukio.wsp.pty.ScreenBuffer; - -/** - * One live terminal in the V2 workspace: a real PTY (bash) rendered as a - * TextGrid panel on a two-triangle quad, exactly the way the V1 workspace - * did it with TextCanvas - but on aukio-3d-2 data only. - * - *

The quad is INVISIBLE by design (triangle colour 0 = transparent, no - * depth write): every pixel of the panel is painted by the text grid, cell - * background included. A solid backing quad would occupy the same depth and - * reject the glyph ink that is drawn on top of it. - */ -public final class TerminalPanel extends RectPanel implements AutoCloseable { - - private static final int DEFAULT_BG = 0xFF101018; - private static final int DEFAULT_FG = 0xFFDCDCDC; - - /** - * xterm palette, indices 0-15 - the SAME table V1's terminal used. The - * ScreenBuffer stores palette INDICES (0-7, 8-15, or 16+ for 256-colour - * later), never RGB: writing the index straight into a pixel made mc's - * blue background render as 0x04 = almost black. - */ - private static final int[] PALETTE = { - 0xFF000000, // 0 black - 0xFFCD3131, // 1 red - 0xFF0DBC79, // 2 green - 0xFFE5E510, // 3 yellow - 0xFF2472C8, // 4 blue - 0xFFBC3FBC, // 5 magenta - 0xFF11A8CD, // 6 cyan - 0xFFE5E5E5, // 7 white - 0xFF666666, // 8 bright black - 0xFFF14C4C, // 9 bright red - 0xFF23D18B, // 10 bright green - 0xFFF5F543, // 11 bright yellow - 0xFF3B8EEA, // 12 bright blue - 0xFFD670D6, // 13 bright magenta - 0xFF29B8DB, // 14 bright cyan - 0xFFFFFFFF, // 15 bright white - }; - /** Sampling exactly 1.0 in u/v leaves the last cell: LifeHelp's rule. */ - private static final double EDGE = Math.nextDown(1.0); - - private final Substrate data; - private final PtySession session; - private final int columns, rows; - private final int panel; - private volatile boolean dirty = true; - - /** - * @param charWidth world units per character cell (width) - * @param charHeight world units per character cell (height) - */ - public TerminalPanel(final Substrate data, final double centerX, final double centerY, - final double centerZ, final int columns, final int rows, - final double charWidth, final double charHeight) { - super(centerX, centerY, centerZ, columns * charWidth, rows * charHeight); - this.data = data; - this.columns = columns; - this.rows = rows; - this.session = new PtySession(columns, rows); - // Fires on the PTY reader thread: ask the shell for exactly one frame. - this.session.setContentListener(() -> { - dirty = true; - data.repaintRequested = true; - }); - this.panel = data.textGrid.addPanel(columns, rows); - - final double x0 = centerX - halfWidth, x1 = centerX + halfWidth; - final double y0 = centerY - halfHeight, y1 = centerY + halfHeight; - final int first = data.triangles.triangleCount(); - // tl, tr, br, bl; both windings so the panel reads from either side - // (V1 showed its terminals from behind with mirrored text as well). - addTriangle(x0, y1, centerZ, x1, y0, centerZ, x1, y1, centerZ, - 0, 0, EDGE, EDGE, EDGE, 0); - addTriangle(x0, y1, centerZ, x0, y0, centerZ, x1, y0, centerZ, - 0, 0, 0, EDGE, EDGE, EDGE); - addTriangle(x1, y1, centerZ, x1, y0, centerZ, x0, y1, centerZ, - EDGE, 0, EDGE, EDGE, 0, 0); - addTriangle(x1, y0, centerZ, x0, y0, centerZ, x0, y1, centerZ, - EDGE, EDGE, 0, EDGE, 0, 0); - data.textGrid.ensureSize(data.triangles.triangleCount()); - for (int i = 0; i < 4; i++) { - data.textGrid.setPanel(first + i, panel); - } - refresh(data); - } - - private void addTriangle(final double ax, final double ay, final double az, - final double bx, final double by, final double bz, - final double cx, final double cy, final double cz, - final double ua, final double va, - final double ub, final double vb, - final double uc, final double vc) { - data.triangles.addTriangle(ax, ay, az, bx, by, bz, cx, cy, cz, 0, - ua, va, ub, vb, uc, vc, -1); - } - - @Override - public void refresh() { - refresh(data); - } - - /** Copies the terminal screen into the panel; cheap when nothing arrived. */ - public void refresh(final Substrate data) { - if (!dirty) return; - dirty = false; - final ScreenBuffer screen = session.getScreenBuffer(); - synchronized (screen) { - for (int row = 0; row < rows; row++) { - for (int column = 0; column < columns; column++) { - final ScreenBuffer.Cell cell = screen.getCell(row, column); - int fg = resolve(cell.fg, DEFAULT_FG, cell.bold); - int bg = resolve(cell.bg, DEFAULT_BG, false); - if (cell.reverse) { - final int swap = fg; - fg = bg; - bg = swap; - } - data.textGrid.setCell(panel, row, column, cell.ch, bg, fg); - } - } - } - } - - @Override - public String name() { - return "terminal"; - } - - private static final int VK_BACK_SPACE = 8, VK_TAB = 9, VK_ENTER = 10; - private static final int VK_LEFT = 37, VK_UP = 38, VK_RIGHT = 39, VK_DOWN = 40; - - /** A terminal wants typed CHARACTERS (KEY_TYPED), never key presses. */ - @Override - public boolean acceptsTypedText() { - return true; - } - - /** - * Keyboard into the PTY. - * - *

CRITICAL: the shell fills BOTH KEY_TYPED and KEY_PRESSED events with - * the produced character (AWT gives getKeyChar() on presses too). Text is - * therefore taken ONLY from KEY_TYPED events (code 0) and control keys - * ONLY from presses - otherwise every typed letter arrives twice. - * - *

A line discipline wants CR for Enter, never LF, and backspace is - * DEL, not BS: terminal conventions, so they live with the panel. - */ - @Override - public void key(final int code, final char character, final boolean pressed) { - if (!pressed) return; - if (code == 0) { - // typed text; control characters were already handled as presses - if (character >= 32 || character == '\t') { - send(String.valueOf(character)); - } - return; - } - switch (code) { - case VK_ENTER -> send("\r"); - case VK_BACK_SPACE -> send("\u007f"); - case VK_TAB -> send("\t"); - case VK_UP -> send("\u001b[A"); - case VK_DOWN -> send("\u001b[B"); - case VK_RIGHT -> send("\u001b[C"); - case VK_LEFT -> send("\u001b[D"); - default -> { - } - } - } - - /** Palette index to ARGB, V1's rule (bold promotes the low 8 to bright). */ - private static int resolve(final int index, final int defaultArgb, final boolean bold) { - if (index == ScreenBuffer.DEFAULT_COLOR) return defaultArgb; - if (index < 16) { - return PALETTE[bold && index < 8 ? index + 8 : index]; - } - final int i = index - 16; - if (i < 216) { - final int r = cubeChannel(i / 36); - final int g = cubeChannel((i / 6) % 6); - final int b = cubeChannel(i % 6); - return 0xFF000000 | r << 16 | g << 8 | b; - } - final int gray = Math.min(255, 8 + (i - 216) * 10); - return 0xFF000000 | gray << 16 | gray << 8 | gray; - } - - private static int cubeChannel(final int level) { - return level == 0 ? 0 : 55 + level * 40; - } - - public void send(final String text) { - session.send(text); - } - - public PtySession session() { - return session; - } - - public int columns() { - return columns; - } - - public int rows() { - return rows; - } - - /** Plain text of the terminal, for headless self-tests. */ - public String screenText() { - final ScreenBuffer screen = session.getScreenBuffer(); - final StringBuilder text = new StringBuilder(); - synchronized (screen) { - for (int row = 0; row < rows; row++) { - for (int column = 0; column < columns; column++) { - text.append(screen.getCell(row, column).ch); - } - text.append('\n'); - } - } - return text.toString(); - } - - @Override - public void close() { - session.stop(); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceInputPass.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceInputPass.java deleted file mode 100644 index 3265f71..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceInputPass.java +++ /dev/null @@ -1,207 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.kernel.InputStore; -import eu.svjatoslav.aukio.e3d2.kernel.Pass; -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; -import java.util.List; - -/** - * Workspace pointer and keyboard routing. - * - *

Rules (V1 workspace semantics): - *

    - *
  • left click on a panel FOCUSES it; the click itself is not forwarded
  • - *
  • left click on a focused panel is forwarded at the clicked texture - * coordinate (perspective correct, resolved here from the camera ray)
  • - *
  • middle click, or Shift+Esc, releases focus and is never forwarded
  • - *
  • a click on empty space releases focus
  • - *
  • while any panel holds focus the camera does not fly: the flight keys - * would otherwise be swallowed by whatever is being typed
  • - *
- */ -public final class WorkspaceInputPass implements Pass { - - private static final int VK_ESCAPE = 27; - private static final int SHIFT_MASK = 1; - - private final List panels; - private final Substrate data; - /** V1's red wireframe box: the visual answer to "who has the keys?". */ - private final FocusBorder border; - private volatile Panel focused; - private final java.util.Set forwarded = new java.util.HashSet<>(); - private double lastU = -1, lastV = -1; - - public WorkspaceInputPass(final Substrate data, final List panels) { - this.data = data; - this.panels = panels; - this.border = new FocusBorder(data); - } - - @Override - public String name() { - return "workspace-input"; - } - - @Override - public int order() { - return 7; - } - - @Override - public boolean isSimulation() { - return true; - } - - public Panel focused() { - return focused; - } - - private void focus(final Panel panel) { - if (focused == panel) return; - if (focused != null) focused.releaseFocus(); - focused = panel; - // Keyboard flight stops for every panel; the POINTER is owned only by - // panels that forward it into an application (a terminal does not). - data.input.setNavigationCaptured(panel != null); - data.input.setPointerCaptured(panel instanceof GuiAppPanel); - if (panel instanceof RectPanel rect) { - border.show(rect); - } else { - border.hide(); - } - // a fresh focus starts a fresh hover stream - lastU = -1; - lastV = -1; - } - - @Override - public void apply(final Substrate data) { - for (final Panel panel : panels) { - panel.refresh(); - } - releaseDroppedKeys(); - forwardWheel(); - InputStore.Event event; - while ((event = data.input.pollEvent()) != null) { - switch (event.type()) { - case MOUSE_PRESSED -> onPress(event); - case MOUSE_MOVED, MOUSE_DRAGGED -> onMove(event); - case KEY_PRESSED, KEY_TYPED -> onKey(event); - default -> { - } - } - } - } - - /** Wheel notches go to the focused GUI panel at the last hover point. */ - private void forwardWheel() { - final int wheel = data.input.consumeWheel(); - if (wheel == 0 || focused == null) return; - if (lastU < 0 || lastV < 0) return; - focused.scroll(wheel, lastU, lastV); - } - - private void onPress(final InputStore.Event event) { - final Panel hit = pick(event.x(), event.y()); - final int button = event.code(); - if (button == 2) { - // middle click pops keyboard focus and is never forwarded - focus(null); - return; - } - if (hit == null) { - focus(null); - return; - } - if (hit != focused) { - // the first click only takes focus, exactly like V1 - focus(hit); - return; - } - final double[] ray = rayOf(event); - final double[] uv = new double[2]; - if (hit.pick(ray[0], ray[1], ray[2], ray[3], ray[4], ray[5], uv)) { - hit.click(button, uv[0], uv[1]); - lastU = uv[0]; - lastV = uv[1]; - } - } - - private void onMove(final InputStore.Event event) { - if (focused == null) return; - final double[] ray = rayOf(event); - final double[] uv = new double[2]; - if (focused.pick(ray[0], ray[1], ray[2], ray[3], ray[4], ray[5], uv)) { - if (Math.abs(uv[0] - lastU) > 1e-4 || Math.abs(uv[1] - lastV) > 1e-4) { - lastU = uv[0]; - lastV = uv[1]; - focused.hover(uv[0], uv[1]); - } - } - } - - private void onKey(final InputStore.Event event) { - final boolean pressed = event.type() == InputStore.Event.Type.KEY_PRESSED; - if (pressed && event.code() == VK_ESCAPE - && (event.modifiers() & SHIFT_MASK) != 0) { - focus(null); - return; - } - if (focused == null) return; - if (event.type() == InputStore.Event.Type.KEY_TYPED) { - // TEXT is for panels that want characters. An X11 application - // gets the text from its own press event, so forwarding this too - // would type every character twice. - if (focused.acceptsTypedText()) { - focused.key(0, event.character(), true); - } - return; - } - if (pressed) { - forwarded.add(event.code()); - } - focused.key(event.code(), event.character(), pressed); - } - - /** - * InputStore keeps key LEVEL state and offers presses, never releases - * (the engine's passes read levels). An X11 application needs the release - * or the key sticks: emit one when a forwarded key stops being held. - */ - private void releaseDroppedKeys() { - if (forwarded.isEmpty()) return; - if (focused == null) { - forwarded.clear(); - return; - } - for (final var iterator = forwarded.iterator(); iterator.hasNext(); ) { - final int code = iterator.next(); - if (data.input.isDown(code)) continue; - focused.key(code, (char) 0, false); - iterator.remove(); - } - } - - private double[] rayOf(final InputStore.Event event) { - return Ray.forPixel(data, event.x(), event.y()); - } - - /** Nearest panel under the pixel, or null. */ - public Panel pick(final int pixelX, final int pixelY) { - if (data.image == null) return null; - final double[] ray = Ray.forPixel(data, pixelX, pixelY); - final double[] uv = new double[2]; - Panel best = null; - double bestDepth = Double.POSITIVE_INFINITY; - for (final Panel panel : panels) { - if (!panel.pick(ray[0], ray[1], ray[2], ray[3], ray[4], ray[5], uv)) continue; - final double depth = panel instanceof RectPanel rect - ? rect.depthAlong(ray[2], ray[5]) : 0; - if (depth >= bestDepth) continue; - bestDepth = depth; - best = panel; - } - return best; - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceMain.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceMain.java deleted file mode 100644 index cf40749..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceMain.java +++ /dev/null @@ -1,114 +0,0 @@ -package eu.svjatoslav.aukio.wsp; - -import eu.svjatoslav.aukio.e3d2.app.AwtShell; -import eu.svjatoslav.aukio.e3d2.kernel.ImageStore; -import eu.svjatoslav.aukio.e3d2.kernel.Kernel; -import eu.svjatoslav.aukio.e3d2.kernel.Substrate; -import eu.svjatoslav.aukio.e3d2.systems.CameraPass; -import eu.svjatoslav.aukio.e3d2.systems.ClearPass; -import eu.svjatoslav.aukio.e3d2.systems.CullPass; -import eu.svjatoslav.aukio.e3d2.systems.LinePass; -import eu.svjatoslav.aukio.e3d2.systems.RasterPass; -import eu.svjatoslav.aukio.e3d2.systems.TextGridLinePass; -import eu.svjatoslav.aukio.e3d2.systems.TransformPass; -import eu.svjatoslav.aukio.e3d2.systems.gui.SdfFont; -import eu.svjatoslav.aukio.wsp.x11.GuiAppSession; -import java.io.IOException; -import java.util.ArrayList; -import java.util.List; - -/** - * The Aukio workspace on aukio-3d-2: a roomy 3D space with floating panels - * that the user flies between, exactly as in the V1 workspace but with no V1 - * code in the build. - * - *

Panels: a live bash terminal in the middle, a live Firefox on the right - * and a live VMware Workstation on the left, each on its own Xvfb display. - * Click a panel to give it the keyboard; middle click or Shift+Esc releases - * it and the camera flies again. - */ -public final class WorkspaceMain { - - private static final int WIDTH = 1280; - private static final int HEIGHT = 720; - - /** 1 m = 100 units: the office keeps the FO4 world's scale. */ - private static final double CHAR_WIDTH = 12.0; - private static final double CHAR_HEIGHT = 22.0; - private static final int COLUMNS = 100; - private static final int ROWS = 30; - - /** V1 capture size, kept so a page laid out at 1280x960 looks familiar. */ - private static final int CAPTURE_WIDTH = 1280; - private static final int CAPTURE_HEIGHT = 960; - - public static void main(final String[] args) throws IOException { - final Substrate data = new Substrate(); - data.image = new ImageStore(WIDTH, HEIGHT); - data.background = 0xFF0A0E12; - data.image.clear(data.background); - data.guiFont = SdfFont.build(48); - data.textGridFont = SdfFont.buildLegacyTextGrid(); - - final List panels = new ArrayList<>(); - - // Layout: terminal in the middle, browser right, VMware left. The - // side panels sit a little further back so the perspective rows them - // tidily and the whole wall is in the opening view. - final TerminalPanel terminal = new TerminalPanel( - data, 0, 0, 620, COLUMNS, ROWS, CHAR_WIDTH, CHAR_HEIGHT); - terminal.send("cd ~ && clear && echo 'Aukio workspace (V2) - live bash' ; exec bash\n"); - panels.add(terminal); - - if (!Boolean.getBoolean("aukio.workspace.noApps")) { - // Browser right, VMware left. A panel whose application cannot - // start must not take the workspace down with it. - try { - panels.add(new GuiAppPanel(data, - GuiAppSession.firefox(CAPTURE_WIDTH, CAPTURE_HEIGHT, - System.getProperty("aukio.firefox.url", "about:home")), - 1250, 60, 900, 960, 720)); - } catch (final IOException | RuntimeException e) { - System.err.println("browser panel unavailable: " + e); - } - try { - panels.add(new GuiAppPanel(data, - GuiAppSession.vmware(CAPTURE_WIDTH, CAPTURE_HEIGHT), - -1250, 60, 900, 960, 720)); - } catch (final RuntimeException e) { - System.err.println("vmware panel unavailable: " + e); - } - } - for (final Panel panel : panels) { - if (panel instanceof GuiAppPanel gui) { - try { - gui.start(); - } catch (final IOException | RuntimeException e) { - System.err.println("panel '" + panel.name() + "' failed to start: " + e); - } - } - } - - // Opening view: the whole panel wall, terminal readable in the middle. - data.camera.set(0, 60, 40, 0, 0, WIDTH / 3.0); - - final Kernel kernel = new Kernel(); - kernel.add(new ClearPass()); - kernel.add(new WorkspaceInputPass(data, panels)); - kernel.add(new CameraPass()); - kernel.add(new TransformPass()); - kernel.add(new CullPass()); - kernel.add(new RasterPass()); - kernel.add(new LinePass()); - kernel.add(new TextGridLinePass()); - - Runtime.getRuntime().addShutdownHook(new Thread(() -> { - for (final Panel panel : panels) { - panel.close(); - } - })); - final AwtShell shell = new AwtShell(data, kernel, WorkspaceMain.class, - "Aukio workspace (2)"); - shell.open(); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/PtySession.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/PtySession.java deleted file mode 100644 index 60f8be8..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/PtySession.java +++ /dev/null @@ -1,167 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.pty; - -import java.io.IOException; -import java.io.InputStream; -import java.io.InputStreamReader; -import java.nio.charset.StandardCharsets; -import java.util.HashMap; -import java.util.Map; - -/** - * A shell process running on a real pseudo-terminal, feeding a - * {@link ScreenBuffer} through a {@link Vt100Emulator}. - * - *

Engine-independent: this class knows nothing about the 3D world. - * Rendering and keyboard delivery are the caller's job (see - * {@code workspace.TerminalPanel}).

- * - *

Output path: a daemon reader thread pumps decoded characters into the - * emulator and invokes the registered {@link ContentListener} after every - * batch, so the renderer can repaint. Input path: {@link #send(String)} - * writes bytes to the PTY master.

- */ -public class PtySession { - - /** - * Called on the reader thread after terminal content changed. - */ - public interface ContentListener { - void contentChanged(); - } - - private final UnixPty pty; - private final ScreenBuffer screenBuffer; - private final Vt100Emulator emulator; - private final Thread readerThread; - - private volatile ContentListener contentListener; - private volatile boolean running = true; - - /** - * Spawns an interactive bash on a new PTY. - * - * @param columns terminal width in characters - * @param rows terminal height in characters - */ - public PtySession(final int columns, final int rows) { - screenBuffer = new ScreenBuffer(columns, rows); - emulator = new Vt100Emulator(screenBuffer); - - final Map environment = new HashMap<>( - System.getenv()); - environment.put("TERM", "xterm-256color"); - environment.put("COLORTERM", "truecolor"); - - // Do not inherit an "active conda environment" from the parent - // process: a fresh terminal session must re-activate through - // bashrc like any desktop terminal. Inheriting CONDA_DEFAULT_ENV - // without CONDA_PREFIX crashes conda's activator, which then - // blocks shell startup with an interactive error-report question. - environment.remove("CONDA_DEFAULT_ENV"); - environment.remove("CONDA_SHLVL"); - environment.remove("CONDA_PROMPT_MODIFIER"); - environment.remove("CONDA_PREFIX"); - // never block shell startup on conda's interactive error upload - environment.put("CONDA_REPORT_ERRORS", "false"); - - pty = new UnixPty(new String[]{"/bin/bash"}, - System.getProperty("user.dir"), environment, columns, rows); - - readerThread = new Thread(this::readLoop, "pty-reader"); - readerThread.setDaemon(true); - readerThread.start(); - } - - private InputStream ptyInputStream() { - return new InputStream() { - private final byte[] chunk = new byte[8192]; - - @Override - public int read() { - final byte[] one = new byte[1]; - return read(one, 0, 1) < 0 ? -1 : (one[0] & 0xFF); - } - - @Override - public int read(final byte[] buffer, final int offset, - final int length) { - final int count = pty.read(chunk); - if (count < 0) - return -1; - final int amount = Math.min(count, length); - System.arraycopy(chunk, 0, buffer, offset, amount); - return amount; - } - }; - } - - private void readLoop() { - final char[] chunk = new char[8192]; - try (final InputStreamReader reader = new InputStreamReader( - ptyInputStream(), StandardCharsets.UTF_8)) { - while (running) { - final int count = reader.read(chunk); - if (count < 0) - break; - emulator.accept(chunk, count); - final ContentListener listener = contentListener; - if (listener != null) - try { - listener.contentChanged(); - } catch (final Throwable t) { - // The renderer can briefly reallocate canvas - // internals during a window resize, racing this - // writer thread. A listener failure must never - // kill the reader loop — the next output batch - // repaints anyway. - t.printStackTrace(); - } - } - } catch (final IOException e) { - // PTY closed: shell exited or session stopped - } - running = false; - } - - /** - * Sends text to the shell as if typed (UTF-8 encoded). - */ - public void send(final String text) { - final byte[] bytes = text.getBytes(StandardCharsets.UTF_8); - pty.write(bytes, 0, bytes.length); - } - - public ScreenBuffer getScreenBuffer() { - return screenBuffer; - } - - public void setContentListener(final ContentListener listener) { - this.contentListener = listener; - } - - public boolean isRunning() { - return running && pty.isChildAlive(); - } - - /** - * Kills the shell and stops the reader thread. - * - *

Order matters: kill the child first so the reader's blocking - * read() returns, join the reader, and only then let the JVM move on - * to exit — a daemon thread mid-JNA-call during JVM teardown can - * crash the process with native heap errors.

- */ - public void stop() { - running = false; - pty.destroy(); - try { - readerThread.join(2000); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - } - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.java deleted file mode 100644 index 20baf5e..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.java +++ /dev/null @@ -1,574 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.pty; - -/** - * Character cell grid backing a terminal screen. - * - *

Pure model: no rendering, no engine dependencies. Colors are stored as - * ANSI palette indices ({@code -1} = terminal default); mapping to actual - * RGB values is the renderer's job.

- * - *

All public methods must be called while holding {@code synchronized} - * on this instance (the emulator and the renderer both access it).

- */ -public class ScreenBuffer { - - /** - * Default color marker: use the terminal's default foreground/background. - */ - public static final int DEFAULT_COLOR = -1; - - /** - * One character cell: glyph plus attributes. - */ - public static final class Cell { - public char ch = ' '; - public int fg = DEFAULT_COLOR; - public int bg = DEFAULT_COLOR; - public boolean bold = false; - public boolean reverse = false; - - void set(final char c, final int fg, final int bg, - final boolean bold, final boolean reverse) { - this.ch = c; - this.fg = fg; - this.bg = bg; - this.bold = bold; - this.reverse = reverse; - } - - void clear(final int bg) { - set(' ', DEFAULT_COLOR, bg, false, false); - } - } - - private final int columns; - private final int rows; - - private Cell[][] screen; - private Cell[][] alternateScreen; - - public int cursorX = 0; - public int cursorY = 0; - public boolean cursorVisible = true; - - private int savedCursorX = 0; - private int savedCursorY = 0; - - private int scrollTop = 0; - private int scrollBottom; - - private int currentFg = DEFAULT_COLOR; - private int currentBg = DEFAULT_COLOR; - private boolean currentBold = false; - private boolean currentReverse = false; - - boolean autoWrap = true; - boolean insertMode = false; - boolean lineDrawing = false; - - /** - * DECCKM (?1h): when set, cursor keys must be reported as SS3 - * (ESC O A) instead of CSI (ESC [ A). Curses applications enable - * this; input translation reads it. - */ - public boolean applicationCursorKeys = false; - - private boolean pendingWrap = false; - - public ScreenBuffer(final int columns, final int rows) { - this.columns = columns; - this.rows = rows; - this.scrollBottom = rows - 1; - screen = newGrid(); - } - - private Cell[][] newGrid() { - final Cell[][] grid = new Cell[rows][columns]; - for (int row = 0; row < rows; row++) - for (int column = 0; column < columns; column++) { - grid[row][column] = new Cell(); - grid[row][column].clear(DEFAULT_COLOR); - } - return grid; - } - - public int getColumns() { - return columns; - } - - public int getRows() { - return rows; - } - - public Cell getCell(final int row, final int column) { - return screen[row][column]; - } - - // ------------------------------------------------------------------ - // printing - // ------------------------------------------------------------------ - - public void putChar(final char c) { - if (pendingWrap) { - pendingWrap = false; - carriageReturn(); - lineFeed(); - } - if (insertMode) - insertChars(1); - screen[cursorY][cursorX].set(mapLineDrawing(c), currentFg, currentBg, - currentBold, currentReverse); - if (cursorX == columns - 1) { - if (autoWrap) - pendingWrap = true; - } else - cursorX++; - } - - private char mapLineDrawing(final char c) { - if (!lineDrawing) - return c; - // DEC special graphics character set (approximate) - return switch (c) { - case 'j' -> '┘'; - case 'k' -> '┐'; - case 'l' -> '┌'; - case 'm' -> '└'; - case 'n' -> '┼'; - case 'q' -> '─'; - case 't' -> '├'; - case 'u' -> '┤'; - case 'v' -> '┴'; - case 'w' -> '┬'; - case 'x' -> '│'; - case 'a' -> '▒'; - default -> c; - }; - } - - // ------------------------------------------------------------------ - // control characters - // ------------------------------------------------------------------ - - public void carriageReturn() { - cursorX = 0; - pendingWrap = false; - } - - public void lineFeed() { - pendingWrap = false; - if (cursorY == scrollBottom) - scrollUp(1); - else if (cursorY < rows - 1) - cursorY++; - } - - /** - * Reverse index: cursor up, scrolling the region down at the top edge. - */ - public void reverseIndex() { - pendingWrap = false; - if (cursorY == scrollTop) - scrollDown(1); - else if (cursorY > 0) - cursorY--; - } - - public void backspace() { - pendingWrap = false; - if (cursorX > 0) - cursorX--; - } - - public void tab() { - pendingWrap = false; - cursorX = Math.min(columns - 1, (cursorX + 8) & ~7); - } - - // ------------------------------------------------------------------ - // cursor movement (CSI) - // ------------------------------------------------------------------ - - public void cursorUp(final int n) { - pendingWrap = false; - cursorY = Math.max(scrollTop, cursorY - Math.max(1, n)); - } - - public void cursorDown(final int n) { - pendingWrap = false; - cursorY = Math.min(scrollBottom, cursorY + Math.max(1, n)); - } - - public void cursorForward(final int n) { - pendingWrap = false; - cursorX = Math.min(columns - 1, cursorX + Math.max(1, n)); - } - - public void cursorBack(final int n) { - pendingWrap = false; - cursorX = Math.max(0, cursorX - Math.max(1, n)); - } - - /** - * 1-based absolute position, as sent by CSI H / CSI f. - */ - public void setCursorPosition(final int row1based, final int column1based) { - pendingWrap = false; - cursorY = clamp(row1based - 1, 0, rows - 1); - cursorX = clamp(column1based - 1, 0, columns - 1); - } - - public void setCursorColumn(final int column1based) { - pendingWrap = false; - cursorX = clamp(column1based - 1, 0, columns - 1); - } - - public void setCursorRow(final int row1based) { - pendingWrap = false; - cursorY = clamp(row1based - 1, 0, rows - 1); - } - - public void saveCursor() { - savedCursorX = cursorX; - savedCursorY = cursorY; - } - - public void restoreCursor() { - pendingWrap = false; - cursorX = savedCursorX; - cursorY = savedCursorY; - } - - private static int clamp(final int v, final int min, final int max) { - return Math.max(min, Math.min(max, v)); - } - - // ------------------------------------------------------------------ - // erasing - // ------------------------------------------------------------------ - - private void clearRange(final int row, final int fromColumn, - final int toColumn) { - for (int column = fromColumn; column <= toColumn; column++) - screen[row][column].clear(currentBg); - } - - /** - * CSI J: 0 = cursor to end, 1 = start to cursor, 2 = whole screen. - */ - public void eraseInDisplay(final int mode) { - pendingWrap = false; - switch (mode) { - case 0 -> { - clearRange(cursorY, cursorX, columns - 1); - for (int row = cursorY + 1; row < rows; row++) - clearRange(row, 0, columns - 1); - } - case 1 -> { - for (int row = 0; row < cursorY; row++) - clearRange(row, 0, columns - 1); - clearRange(cursorY, 0, cursorX); - } - case 2, 3 -> { - for (int row = 0; row < rows; row++) - clearRange(row, 0, columns - 1); - } - default -> { - } - } - } - - /** - * CSI K: 0 = cursor to end of line, 1 = start to cursor, 2 = whole line. - */ - public void eraseInLine(final int mode) { - pendingWrap = false; - switch (mode) { - case 0 -> clearRange(cursorY, cursorX, columns - 1); - case 1 -> clearRange(cursorY, 0, cursorX); - case 2 -> clearRange(cursorY, 0, columns - 1); - default -> { - } - } - } - - /** - * CSI X: erase n characters from cursor without moving it. - */ - public void eraseChars(final int n) { - pendingWrap = false; - final int count = Math.max(1, n); - clearRange(cursorY, cursorX, - Math.min(columns - 1, cursorX + count - 1)); - } - - // ------------------------------------------------------------------ - // inserting / deleting / scrolling - // ------------------------------------------------------------------ - - /** - * CSI P: delete n characters at cursor, shifting the rest of the line left. - */ - public void deleteChars(final int n) { - pendingWrap = false; - final int count = Math.max(1, n); - for (int column = cursorX; column < columns; column++) { - if (column + count < columns) - screen[cursorY][column].set( - screen[cursorY][column + count].ch, - screen[cursorY][column + count].fg, - screen[cursorY][column + count].bg, - screen[cursorY][column + count].bold, - screen[cursorY][column + count].reverse); - else - screen[cursorY][column].clear(currentBg); - } - } - - /** - * CSI @: insert n blank characters at cursor, shifting line right. - */ - public void insertChars(final int n) { - final int count = Math.max(1, n); - for (int column = columns - 1; column >= cursorX; column--) { - if (column - count >= cursorX) - screen[cursorY][column].set( - screen[cursorY][column - count].ch, - screen[cursorY][column - count].fg, - screen[cursorY][column - count].bg, - screen[cursorY][column - count].bold, - screen[cursorY][column - count].reverse); - else - screen[cursorY][column].clear(currentBg); - } - } - - /** - * CSI L: insert n blank lines at cursor row (within scroll region). - */ - public void insertLines(final int n) { - pendingWrap = false; - if (cursorY < scrollTop || cursorY > scrollBottom) - return; - final int count = Math.min(Math.max(1, n), scrollBottom - cursorY + 1); - for (int row = scrollBottom; row >= cursorY; row--) { - if (row - count >= cursorY) - copyRow(row - count, row); - else - clearRange(row, 0, columns - 1); - } - } - - /** - * CSI M: delete n lines at cursor row (within scroll region). - */ - public void deleteLines(final int n) { - pendingWrap = false; - if (cursorY < scrollTop || cursorY > scrollBottom) - return; - final int count = Math.min(Math.max(1, n), scrollBottom - cursorY + 1); - for (int row = cursorY; row <= scrollBottom; row++) { - if (row + count <= scrollBottom) - copyRow(row + count, row); - else - clearRange(row, 0, columns - 1); - } - } - - private void copyRow(final int fromRow, final int toRow) { - for (int column = 0; column < columns; column++) { - final Cell from = screen[fromRow][column]; - screen[toRow][column].set(from.ch, from.fg, from.bg, from.bold, - from.reverse); - } - } - - /** - * Scroll the scroll region up by n lines (content moves up, blanks at - * bottom). - */ - public void scrollUp(final int n) { - final int count = Math.min(Math.max(1, n), - scrollBottom - scrollTop + 1); - for (int row = scrollTop; row <= scrollBottom; row++) { - if (row + count <= scrollBottom) - copyRow(row + count, row); - else - clearRange(row, 0, columns - 1); - } - } - - /** - * Scroll the scroll region down by n lines (content moves down, blanks at - * top). - */ - public void scrollDown(final int n) { - final int count = Math.min(Math.max(1, n), - scrollBottom - scrollTop + 1); - for (int row = scrollBottom; row >= scrollTop; row--) { - if (row - count >= scrollTop) - copyRow(row - count, row); - else - clearRange(row, 0, columns - 1); - } - } - - /** - * CSI r: set scroll region, 1-based inclusive rows. Also homes the cursor - * per xterm behavior. - */ - public void setScrollRegion(final int top1based, final int bottom1based) { - final int top = clamp(top1based - 1, 0, rows - 1); - final int bottom = clamp(bottom1based - 1, 0, rows - 1); - if (top < bottom) { - scrollTop = top; - scrollBottom = bottom; - } - setCursorPosition(1, 1); - } - - // ------------------------------------------------------------------ - // attributes / modes - // ------------------------------------------------------------------ - - /** - * CSI m: select graphic rendition. {@code params[i] == -1} marks an - * omitted parameter (treated as 0). - */ - public void sgr(final int[] params) { - if (params.length == 0) { - resetAttributes(); - return; - } - for (int i = 0; i < params.length; i++) { - final int p = params[i] < 0 ? 0 : params[i]; - if (p == 0) - resetAttributes(); - else if (p == 1) - currentBold = true; - else if (p == 22) - currentBold = false; - else if (p == 7) - currentReverse = true; - else if (p == 27) - currentReverse = false; - else if (p >= 30 && p <= 37) - currentFg = p - 30; - else if (p == 39) - currentFg = DEFAULT_COLOR; - else if (p >= 40 && p <= 47) - currentBg = p - 40; - else if (p == 49) - currentBg = DEFAULT_COLOR; - else if (p >= 90 && p <= 97) - currentFg = p - 90 + 8; - else if (p >= 100 && p <= 107) - currentBg = p - 100 + 8; - else if ((p == 38 || p == 48) && i + 2 < params.length - && params[i + 1] == 5) { - // 256-color palette index; renderer maps it - if (p == 38) - currentFg = 16 + (params[i + 2] & 0xFF); - else - currentBg = 16 + (params[i + 2] & 0xFF); - i += 2; - } - // other attributes (underline, blink, ...) accepted but not - // visualized - } - } - - private void resetAttributes() { - currentFg = DEFAULT_COLOR; - currentBg = DEFAULT_COLOR; - currentBold = false; - currentReverse = false; - } - - /** - * DEC private mode set/reset (CSI ? ... h / l). - */ - public void setDecMode(final int mode, final boolean enabled) { - switch (mode) { - case 1 -> applicationCursorKeys = enabled; - case 7 -> autoWrap = enabled; - case 25 -> cursorVisible = enabled; - case 47, 1047 -> setAlternateScreen(enabled, false); - case 1048 -> { - if (enabled) - saveCursor(); - else - restoreCursor(); - } - case 1049 -> setAlternateScreen(enabled, true); - default -> { - // other private modes (bracketed paste, application - // keypad, mouse reporting, ...) accepted but ignored - } - } - } - - /** - * ANSI mode set/reset (CSI h / l without '?'). - */ - public void setAnsiMode(final int mode, final boolean enabled) { - if (mode == 4) - insertMode = enabled; - } - - private void setAlternateScreen(final boolean enabled, - final boolean saveCursor) { - if (enabled) { - if (saveCursor) - saveCursor(); - alternateScreen = screen; - screen = newGrid(); - setCursorPosition(1, 1); - } else { - if (alternateScreen != null) - screen = alternateScreen; - alternateScreen = null; - if (saveCursor) - restoreCursor(); - } - } - - public void fullReset() { - resetAttributes(); - autoWrap = true; - insertMode = false; - lineDrawing = false; - applicationCursorKeys = false; - cursorVisible = true; - pendingWrap = false; - scrollTop = 0; - scrollBottom = rows - 1; - alternateScreen = null; - screen = newGrid(); - cursorX = 0; - cursorY = 0; - } - - // ------------------------------------------------------------------ - // debugging / testing - // ------------------------------------------------------------------ - - /** - * Renders the visible screen as plain text (attributes stripped). - */ - public String dumpText() { - final StringBuilder result = new StringBuilder(); - for (int row = 0; row < rows; row++) { - final StringBuilder line = new StringBuilder(); - for (int column = 0; column < columns; column++) - line.append(screen[row][column].ch); - result.append(line.toString().replaceAll("\\s+$", "")) - .append('\n'); - } - return result.toString(); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/UnixPty.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/UnixPty.java deleted file mode 100644 index a85f0a5..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/UnixPty.java +++ /dev/null @@ -1,243 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.pty; - -import com.sun.jna.Library; -import com.sun.jna.Memory; -import com.sun.jna.Native; -import com.sun.jna.Pointer; - -import java.nio.charset.StandardCharsets; -import java.util.ArrayList; -import java.util.List; -import java.util.Map; - -/** - * Minimal Linux PTY implementation via JNA direct libc calls. - * - *

Replaces the pty4j dependency: pty4j 0.12.x requires purejavacomm - * (jtermios classes), which is no longer published on any reachable Maven - * repository. All we need is {@code posix_openpt} + {@code fork} + - * {@code execve}, which is a handful of libc calls.

- * - *

Linux-only by design; the workspace targets Linux.

- */ -final class UnixPty { - - private static final int O_RDWR = 0x02; - private static final int O_NOCTTY = 0x100; - private static final int TIOCSWINSZ = 0x5414; - private static final int POSIX_SPAWN_SETSID = 0x80; // glibc >= 2.26 - private static final int SIGKILL = 9; - - private interface CLib extends Library { - CLib INSTANCE = Native.load("c", CLib.class); - - int posix_openpt(int flags); - - int grantpt(int fd); - - int unlockpt(int fd); - - String ptsname(int fd); - - int ioctl(int fd, int request, Pointer arg); - - int posix_spawn(Memory pid, String path, Pointer fileActions, - Pointer attributes, Pointer argv, Pointer envp); - - int posix_spawn_file_actions_init(Pointer fileActions); - - int posix_spawn_file_actions_addopen(Pointer fileActions, int fd, - String path, int oflag, - int mode); - - int posix_spawn_file_actions_adddup2(Pointer fileActions, int fd, - int newFd); - - int posix_spawn_file_actions_addclose(Pointer fileActions, int fd); - - int posix_spawnattr_init(Pointer attributes); - - int posix_spawnattr_setflags(Pointer attributes, short flags); - - int posix_spawn_file_actions_destroy(Pointer fileActions); - - int posix_spawnattr_destroy(Pointer attributes); - - int close(int fd); - - int read(int fd, Pointer buffer, int count); - - int write(int fd, Pointer buffer, int count); - - int waitpid(int pid, int[] status, int options); - - int kill(int pid, int signal); - } - - final int masterFd; - final int childPid; - - /** - * Single reused native buffer for reads: per-call Memory allocation - * risks the JNA cleaner freeing a buffer while a thread is blocked in - * libc read() on it during JVM shutdown. - */ - private final Memory readMemory = new Memory(65536); - - /** - * Creates a PTY and spawns the command on the slave side via - * {@code posix_spawn}: a new session whose first opened terminal - * becomes its controlling terminal. - * - *

posix_spawn is used instead of fork+exec because fork inside a - * live JVM child deadlocks on JVM internal locks (futex) before it can - * exec — observed empirically: the forked child hung as a second JVM - * and bash never started.

- * - * @param command argv (absolute path first) - * @param workingDir child working directory (applied by the caller's - * command, e.g. bash is started with the dir as cwd - * via a chdir wrapper below) - * @param environment full environment for the child - * @param columns terminal width in characters - * @param rows terminal height in characters - */ - UnixPty(final String[] command, final String workingDir, - final Map environment, - final int columns, final int rows) { - - masterFd = CLib.INSTANCE.posix_openpt(O_RDWR | O_NOCTTY); - if (masterFd < 0) - throw new IllegalStateException("posix_openpt failed: " - + Native.getLastError()); - if (CLib.INSTANCE.grantpt(masterFd) != 0 - || CLib.INSTANCE.unlockpt(masterFd) != 0) - throw new IllegalStateException("grantpt/unlockpt failed: " - + Native.getLastError()); - - final String slaveName = CLib.INSTANCE.ptsname(masterFd); - - // window size must be set before spawn so the child inherits it - final Memory winsize = new Memory(8); - winsize.setShort(0, (short) rows); - winsize.setShort(2, (short) columns); - winsize.setShort(4, (short) 0); - winsize.setShort(6, (short) 0); - CLib.INSTANCE.ioctl(masterFd, TIOCSWINSZ, winsize); - - // child file actions: slave PTY onto stdin/stdout/stderr, drop - // the master. POSIX_SPAWN_SETSID makes the child a session leader; - // glibc applies it BEFORE file actions, so the addopen below (no - // O_NOCTTY) also acquires the slave as the controlling terminal. - // glibc's posix_spawnattr_t is 336 bytes on amd64; allocate a - // padded block for both structs rather than relying on ABI sizes. - final Memory fileActions = new Memory(512); - final Memory attributes = new Memory(512); - CLib.INSTANCE.posix_spawn_file_actions_init(fileActions); - CLib.INSTANCE.posix_spawnattr_init(attributes); - CLib.INSTANCE.posix_spawnattr_setflags(attributes, - (short) POSIX_SPAWN_SETSID); - CLib.INSTANCE.posix_spawn_file_actions_addopen(fileActions, 0, - slaveName, O_RDWR, 0); - CLib.INSTANCE.posix_spawn_file_actions_adddup2(fileActions, 0, 1); - CLib.INSTANCE.posix_spawn_file_actions_adddup2(fileActions, 0, 2); - CLib.INSTANCE.posix_spawn_file_actions_addclose(fileActions, - masterFd); - - final List envStrings = new ArrayList<>(); - environment.forEach((key, value) -> envStrings.add(key + "=" + value)); - final Pointer envp = pointerArray( - envStrings.toArray(new String[0])); - - // working directory: posix_spawn has no chdir file action (glibc - // added addchdir only in 2.29 as a GNU extension), so spawn a - // helper shell that chdirs and execs the real command with its - // arguments. - final StringBuilder execLine = new StringBuilder( - "cd \"$1\" && shift && exec"); - for (final String arg : command) - execLine.append(" \"").append(arg.replace("\"", "\\\"")) - .append('"'); - final String[] shellCommand = {"/bin/sh", "-c", - execLine.toString(), "sh", workingDir}; - final Pointer shellArgv = pointerArray(shellCommand); - - final Memory pidResult = new Memory(4); - final int rc = CLib.INSTANCE.posix_spawn(pidResult, "/bin/sh", - fileActions, attributes, shellArgv, envp); - CLib.INSTANCE.posix_spawn_file_actions_destroy(fileActions); - CLib.INSTANCE.posix_spawnattr_destroy(attributes); - if (rc != 0) - throw new IllegalStateException("posix_spawn failed: " + rc); - childPid = pidResult.getInt(0); - } - - /** - * Builds a NULL-terminated char** from Java strings. - * - *

The backing native memory is deliberately kept reachable for the - * JVM lifetime (a few dozen small strings per PTY): the child execs - * asynchronously after {@code fork}, so the memory must outlive this - * method call.

- */ - private static final List NATIVE_STRING_STORAGE = - new ArrayList<>(); - - private static synchronized Pointer pointerArray( - final String[] strings) { - final Memory array = new Memory( - (long) (strings.length + 1) * Native.POINTER_SIZE); - NATIVE_STRING_STORAGE.add(array); - for (int i = 0; i < strings.length; i++) { - final byte[] bytes = strings[i].getBytes(StandardCharsets.UTF_8); - final Memory entry = new Memory(bytes.length + 1); - entry.write(0, bytes, 0, bytes.length); - entry.setByte(bytes.length, (byte) 0); - NATIVE_STRING_STORAGE.add(entry); - array.setPointer((long) i * Native.POINTER_SIZE, entry); - } - array.setPointer((long) strings.length * Native.POINTER_SIZE, null); - return array; - } - - /** - * Blocking read from the PTY master. - * - * @return number of bytes read, or -1 when the child side closed - */ - int read(final byte[] buffer) { - final int amount = Math.min(buffer.length, (int) readMemory.size()); - final int count = CLib.INSTANCE.read(masterFd, readMemory, amount); - if (count <= 0) - return -1; - readMemory.read(0, buffer, 0, count); - return count; - } - - void write(final byte[] buffer, final int offset, final int length) { - final Memory memory = new Memory(length); - memory.write(0, buffer, offset, length); - int written = 0; - while (written < length) { - final int count = CLib.INSTANCE.write(masterFd, - memory.share(written), length - written); - if (count <= 0) - return; - written += count; - } - } - - boolean isChildAlive() { - return CLib.INSTANCE.kill(childPid, 0) == 0; - } - - void destroy() { - CLib.INSTANCE.kill(childPid, SIGKILL); - CLib.INSTANCE.waitpid(childPid, new int[1], 0); - CLib.INSTANCE.close(masterFd); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.java deleted file mode 100644 index cadf262..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.java +++ /dev/null @@ -1,255 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.pty; - -/** - * Minimal VT100/xterm escape sequence interpreter feeding a - * {@link ScreenBuffer}. - * - *

Covers what an interactive shell and everyday tools actually emit: - * printable text (UTF-8 decoded by the caller), C0 controls, CSI cursor - * movement / erasing / insert-delete / scroll region / SGR colors, DEC - * private modes (autowrap, cursor visibility, alternate screen), OSC - * (ignored), and the DEC line-drawing charset.

- * - *

Not a full xterm: no scrollback, no mouse reporting, no 8-bit C1. - * Unknown sequences are consumed and ignored rather than mishandled.

- * - *

Threading: all calls arrive on the PTY reader thread; the emulator - * synchronizes on the buffer for every operation.

- */ -public class Vt100Emulator { - - private enum State { - GROUND, ESCAPE, CSI, OSC, OSC_ESC, CHARSET, IGNORE_ONE - } - - private final ScreenBuffer buffer; - - private State state = State.GROUND; - - private final StringBuilder params = new StringBuilder(); - private boolean csiPrivate = false; - - public Vt100Emulator(final ScreenBuffer buffer) { - this.buffer = buffer; - } - - public void accept(final char[] chars, final int length) { - for (int i = 0; i < length; i++) - accept(chars[i]); - } - - public void accept(final char c) { - switch (state) { - case GROUND -> ground(c); - case ESCAPE -> escape(c); - case CSI -> csi(c); - case OSC -> osc(c); - case OSC_ESC -> { - state = State.GROUND; // consume ST's backslash - } - case CHARSET -> charset(c); - case IGNORE_ONE -> state = State.GROUND; - } - } - - // ------------------------------------------------------------------ - // GROUND - // ------------------------------------------------------------------ - - private void ground(final char c) { - if (c == 0x1B) { - state = State.ESCAPE; - return; - } - if (c < 0x20) { - control(c); - return; - } - if (c == 0x7F) - return; // DEL: ignored on input path - synchronized (buffer) { - buffer.putChar(c); - } - } - - private void control(final char c) { - synchronized (buffer) { - switch (c) { - case '\b' -> buffer.backspace(); - case '\t' -> buffer.tab(); - case '\n', 0x0B, 0x0C -> buffer.lineFeed(); - case '\r' -> buffer.carriageReturn(); - default -> { - // BEL and the rest: no visual effect - } - } - } - } - - // ------------------------------------------------------------------ - // ESC - // ------------------------------------------------------------------ - - private void escape(final char c) { - switch (c) { - case '[' -> { - params.setLength(0); - csiPrivate = false; - state = State.CSI; - } - case ']' -> state = State.OSC; - case '(' -> state = State.CHARSET; - case ')' -> state = State.IGNORE_ONE; // G1 charset: unused - case 'O' -> state = State.IGNORE_ONE; // SS3: single-char control - case '7' -> { - synchronized (buffer) { - buffer.saveCursor(); - } - state = State.GROUND; - } - case '8' -> { - synchronized (buffer) { - buffer.restoreCursor(); - } - state = State.GROUND; - } - case 'D' -> { - synchronized (buffer) { - buffer.lineFeed(); - } - state = State.GROUND; - } - case 'M' -> { - synchronized (buffer) { - buffer.reverseIndex(); - } - state = State.GROUND; - } - case 'E' -> { - synchronized (buffer) { - buffer.carriageReturn(); - buffer.lineFeed(); - } - state = State.GROUND; - } - case 'c' -> { - synchronized (buffer) { - buffer.fullReset(); - } - state = State.GROUND; - } - default -> state = State.GROUND; // =, > and unknowns: ignore - } - } - - private void charset(final char c) { - synchronized (buffer) { - buffer.lineDrawing = (c == '0'); - } - state = State.GROUND; - } - - private void osc(final char c) { - if (c == 0x07) - state = State.GROUND; // BEL terminates - else if (c == 0x1B) - state = State.OSC_ESC; // expect ST ("\") - } - - // ------------------------------------------------------------------ - // CSI - // ------------------------------------------------------------------ - - private void csi(final char c) { - if (c == '?') { - csiPrivate = true; - return; - } - if ((c >= '0' && c <= '9') || c == ';') { - params.append(c); - return; - } - if (c >= 0x20 && c <= 0x2F) - return; // intermediate bytes: ignored (e.g. space in "CSI 4 SP q") - if (c < 0x40 || c > 0x7E) { - state = State.GROUND; - return; - } - dispatchCsi(c); - state = State.GROUND; - } - - private int[] parsedParams() { - if (params.length() == 0) - return new int[0]; - final String[] parts = params.toString().split(";", -1); - final int[] result = new int[parts.length]; - for (int i = 0; i < parts.length; i++) - result[i] = parts[i].isEmpty() ? -1 : Integer.parseInt(parts[i]); - return result; - } - - private int param(final int[] p, final int index, final int defaultValue) { - if (index >= p.length || p[index] <= 0) - return defaultValue; - return p[index]; - } - - private void dispatchCsi(final char command) { - final int[] p = parsedParams(); - synchronized (buffer) { - switch (command) { - case 'A' -> buffer.cursorUp(param(p, 0, 1)); - case 'B' -> buffer.cursorDown(param(p, 0, 1)); - case 'C' -> buffer.cursorForward(param(p, 0, 1)); - case 'D' -> buffer.cursorBack(param(p, 0, 1)); - case 'E' -> { - buffer.cursorDown(param(p, 0, 1)); - buffer.carriageReturn(); - } - case 'F' -> { - buffer.cursorUp(param(p, 0, 1)); - buffer.carriageReturn(); - } - case 'G', '`' -> buffer.setCursorColumn(param(p, 0, 1)); - case 'd' -> buffer.setCursorRow(param(p, 0, 1)); - case 'H', 'f' -> buffer.setCursorPosition(param(p, 0, 1), - param(p, 1, 1)); - case 'J' -> buffer.eraseInDisplay(param(p, 0, 0)); - case 'K' -> buffer.eraseInLine(param(p, 0, 0)); - case 'L' -> buffer.insertLines(param(p, 0, 1)); - case 'M' -> buffer.deleteLines(param(p, 0, 1)); - case 'P' -> buffer.deleteChars(param(p, 0, 1)); - case '@' -> buffer.insertChars(param(p, 0, 1)); - case 'S' -> buffer.scrollUp(param(p, 0, 1)); - case 'T' -> buffer.scrollDown(param(p, 0, 1)); - case 'X' -> buffer.eraseChars(param(p, 0, 1)); - case 'm' -> buffer.sgr(p); - case 'r' -> buffer.setScrollRegion(param(p, 0, 1), - param(p, 1, buffer.getRows())); - case 's' -> buffer.saveCursor(); - case 'u' -> buffer.restoreCursor(); - case 'h' -> setModes(p, true); - case 'l' -> setModes(p, false); - default -> { - // unknown CSI: ignored - } - } - } - } - - private void setModes(final int[] p, final boolean enabled) { - for (final int mode : p) { - if (mode < 0) - continue; - if (csiPrivate) - buffer.setDecMode(mode, enabled); - else - buffer.setAnsiMode(mode, enabled); - } - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.java deleted file mode 100644 index 501207d..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.java +++ /dev/null @@ -1,167 +0,0 @@ -/* Aukio spatial computing environment. Author: Svjatoslav Agejenko. This project is released under Creative Commons Zero (CC0) license. */ -package eu.svjatoslav.aukio.wsp.x11; - -import java.awt.event.KeyEvent; - -/** - * Translates AWT key events to X11 keysyms for injection into the virtual - * display via the X TEST extension. - * - *

Mapping is by {@code keyCode}, not {@code keyChar}: letters map to - * their unshifted keysyms and uppercase is produced by the real Shift key - * events, which are forwarded like any other key. This mirrors how a - * physical keyboard works and assumes the virtual server's keymap is a - * US-style layout (Xvfb default).

- * - *

Keys with no obvious mapping fall back to the Unicode keysym scheme - * ({@code 0x01000000 | codepoint}) when the event carries a character — - * this covers characters like ä and ö when they exist in the keymap.

- */ -final class AwtKeysyms { - - // X11 keysym values (from keysymdef.h) - static final long XK_BACK_SPACE = 0xFF08; - static final long XK_TAB = 0xFF09; - static final long XK_RETURN = 0xFF0D; - static final long XK_ESCAPE = 0xFF1B; - static final long XK_HOME = 0xFF50; - static final long XK_LEFT = 0xFF51; - static final long XK_UP = 0xFF52; - static final long XK_RIGHT = 0xFF53; - static final long XK_DOWN = 0xFF54; - static final long XK_PAGE_UP = 0xFF55; - static final long XK_PAGE_DOWN = 0xFF56; - static final long XK_END = 0xFF57; - static final long XK_INSERT = 0xFF63; - static final long XK_F1 = 0xFFBE; - static final long XK_KP_MULTIPLY = 0xFFAA; - static final long XK_KP_ADD = 0xFFAB; - static final long XK_KP_SUBTRACT = 0xFFAD; - static final long XK_KP_DECIMAL = 0xFFAE; - static final long XK_KP_DIVIDE = 0xFFAF; - static final long XK_KP_0 = 0xFFB0; - static final long XK_SHIFT_L = 0xFFE1; - static final long XK_CONTROL_L = 0xFFE3; - static final long XK_CAPS_LOCK = 0xFFE5; - static final long XK_ALT_L = 0xFFE9; - static final long XK_DELETE = 0xFFFF; - - private AwtKeysyms() { - } - - /** - * Maps an AWT key event to an X keysym. - * - * @return the keysym, or {@code -1} when the key cannot be represented - */ - static long keysymFor(final KeyEvent event) { - return keysymFor(event.getKeyCode(), event.getKeyChar()); - } - - /** - * X keysym for a key code plus the character it produced. Used by the - * V2 workspace, which receives raw key data from InputStore instead of - * AWT events and must not fabricate a Component to build a KeyEvent. - */ - static long keysymFor(final int code, final char keyChar) { - - // letters: unshifted keysyms; shift state comes from real Shift - // key events - if (code >= KeyEvent.VK_A && code <= KeyEvent.VK_Z) - return 'a' + (code - KeyEvent.VK_A); - if (code >= KeyEvent.VK_0 && code <= KeyEvent.VK_9) - return '0' + (code - KeyEvent.VK_0); - if (code >= KeyEvent.VK_F1 && code <= KeyEvent.VK_F12) - return XK_F1 + (code - KeyEvent.VK_F1); - if (code >= KeyEvent.VK_NUMPAD0 && code <= KeyEvent.VK_NUMPAD9) - return XK_KP_0 + (code - KeyEvent.VK_NUMPAD0); - - switch (code) { - case KeyEvent.VK_BACK_SPACE: - return XK_BACK_SPACE; - case KeyEvent.VK_TAB: - return XK_TAB; - case KeyEvent.VK_ENTER: - return XK_RETURN; - case KeyEvent.VK_ESCAPE: - return XK_ESCAPE; - case KeyEvent.VK_INSERT: - return XK_INSERT; - case KeyEvent.VK_DELETE: - return XK_DELETE; - case KeyEvent.VK_HOME: - return XK_HOME; - case KeyEvent.VK_END: - return XK_END; - case KeyEvent.VK_PAGE_UP: - return XK_PAGE_UP; - case KeyEvent.VK_PAGE_DOWN: - return XK_PAGE_DOWN; - case KeyEvent.VK_LEFT: - return XK_LEFT; - case KeyEvent.VK_UP: - return XK_UP; - case KeyEvent.VK_RIGHT: - return XK_RIGHT; - case KeyEvent.VK_DOWN: - return XK_DOWN; - case KeyEvent.VK_SHIFT: - return XK_SHIFT_L; - case KeyEvent.VK_CONTROL: - return XK_CONTROL_L; - case KeyEvent.VK_ALT: - return XK_ALT_L; - case KeyEvent.VK_CAPS_LOCK: - return XK_CAPS_LOCK; - case KeyEvent.VK_MULTIPLY: - return XK_KP_MULTIPLY; - case KeyEvent.VK_ADD: - return XK_KP_ADD; - case KeyEvent.VK_SUBTRACT: - return XK_KP_SUBTRACT; - case KeyEvent.VK_DECIMAL: - return XK_KP_DECIMAL; - case KeyEvent.VK_DIVIDE: - return XK_KP_DIVIDE; - case KeyEvent.VK_SPACE: - return ' '; - case KeyEvent.VK_COMMA: - return ','; - case KeyEvent.VK_PERIOD: - return '.'; - case KeyEvent.VK_SLASH: - return '/'; - case KeyEvent.VK_BACK_SLASH: - return '\\'; - case KeyEvent.VK_SEMICOLON: - return ';'; - case KeyEvent.VK_QUOTE: - return '\''; - case KeyEvent.VK_OPEN_BRACKET: - return '['; - case KeyEvent.VK_CLOSE_BRACKET: - return ']'; - case KeyEvent.VK_BACK_QUOTE: - return '`'; - case KeyEvent.VK_MINUS: - return '-'; - case KeyEvent.VK_EQUALS: - return '='; - default: - return unicodeFallback(keyChar); - } - } - - /** - * Unicode keysym fallback ({@code 0x01000000 | codepoint}) for - * characters outside the keyCode-based map, e.g. ä, ö, é. - */ - private static long unicodeFallback(final char keyChar) { - if (keyChar == KeyEvent.CHAR_UNDEFINED || keyChar < 0x20) - return -1; - if (keyChar < 0x7F) - // printable ASCII not covered above - return keyChar; - return 0x01000000L | keyChar; - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/GuiAppSession.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/GuiAppSession.java deleted file mode 100644 index 52ccfa2..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/GuiAppSession.java +++ /dev/null @@ -1,442 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.x11; - -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.util.List; -import java.util.Map; - -/** - * A GUI application running on a private Xvfb display, with its screen - * continuously captured into a caller-owned ARGB pixel buffer. - * - *

The session owns three things: the Xvfb server, the application - * process, and a capture thread that grabs the root window at a fixed - * rate. The capture thread writes directly into the destination array - * (typically a texture's primary bitmap pixels) and invokes the frame - * listener only when the image actually changed, so a static screen costs - * no repaints.

- */ -public final class GuiAppSession implements AutoCloseable { - - /** - * Called on the capture thread after the destination buffer was - * updated with a changed frame. - */ - public interface FrameListener { - void frameCaptured(); - } - - private static final long CAPTURE_INTERVAL_MS = 100; - - private final int width; - private final int height; - private final List command; - private final Map extraEnvironment; - private final boolean privateDbusSession; - private final String windowTitleFilter; - private final File logFile; - - private XvfbServer server; - private Process application; - private X11Native.Connection connection; - private Thread captureThread; - private Thread fitterThread; - private volatile boolean running; - - public GuiAppSession(final int width, final int height, - final List command, - final Map extraEnvironment) { - this(width, height, command, extraEnvironment, false, null); - } - - /** - * @param privateDbusSession wrap the app in {@code dbus-run-session} - * so it gets a private session bus. Needed - * because merely unsetting - * DBUS_SESSION_BUS_ADDRESS is not enough: - * GIO then falls back to the systemd user - * bus socket (/run/user/$UID/bus), where the - * app's desktop instance can still be found - * and command-line handling forwarded to it. - */ - public GuiAppSession(final int width, final int height, - final List command, - final Map extraEnvironment, - final boolean privateDbusSession) { - this(width, height, command, extraEnvironment, privateDbusSession, - null); - } - - /** - * @param windowTitleFilter when non-null, a background thread - * periodically moves/resizes every top-level - * window whose name contains this string to - * fill the whole virtual screen. For - * applications that cannot be sized on the - * command line (VMware Workstation). - */ - public GuiAppSession(final int width, final int height, - final List command, - final Map extraEnvironment, - final boolean privateDbusSession, - final String windowTitleFilter) { - this.width = width; - this.height = height; - this.command = command; - this.extraEnvironment = extraEnvironment; - this.privateDbusSession = privateDbusSession; - this.windowTitleFilter = windowTitleFilter; - // per-application log file: several sessions run side by side - // and a shared file would be truncated by each launch - final String logName = command.isEmpty() ? "app" - : command.get(0).replaceAll("[^A-Za-z0-9_.-]", "_"); - logFile = new File("/tmp/aukio-xapp-" + logName + ".log"); - } - - /** - * Starts Xvfb, launches the application onto it, and begins capturing. - * - * @param destination ARGB pixel buffer of exactly - * {@code width * height} ints; every captured frame - * is written into this array - * @param listener notified (on the capture thread) whenever a frame - * changed the buffer - */ - public void start(final int[] destination, final FrameListener listener) - throws IOException { - if (destination.length != width * height) - throw new IllegalArgumentException("destination buffer holds " - + destination.length + " pixels, expected " - + (width * height)); - - server = XvfbServer.start(width, height); - connection = connectWithRetry(server.getDisplayName()); - - final List effectiveCommand = privateDbusSession - ? java.util.stream.Stream.concat( - java.util.stream.Stream.of("dbus-run-session", "--"), - command.stream()).toList() - : command; - final ProcessBuilder builder = new ProcessBuilder(effectiveCommand); - final Map environment = builder.environment(); - environment.put("DISPLAY", server.getDisplayName()); - // Firefox/GTK apps locate an already-running instance through the - // SESSION D-Bus (GApplication), ignoring --no-remote and DISPLAY: - // the window then pops up on the user's desktop while our Xvfb - // screen stays black. Hide the session bus so the app is forced - // to be its own primary instance on the private display. - environment.remove("DBUS_SESSION_BUS_ADDRESS"); - environment.put("MOZ_NO_REMOTE", "1"); - // On Wayland desktops (GNOME/Mutter) Firefox ignores DISPLAY - // entirely and renders natively into the user's compositor — - // the window pops up on the real screen while the Xvfb display - // stays windowless. Force the X11 backend onto our display. - environment.remove("WAYLAND_DISPLAY"); - environment.put("MOZ_ENABLE_WAYLAND", "0"); - // GTK (Firefox, VMware UI) tries its Wayland backend FIRST and - // then passes the X11 DISPLAY string to wl_display_connect, - // which resolves it as $XDG_RUNTIME_DIR/ — that socket - // does not exist, and GTK gives up without ever trying X11 - // ("Error: cannot open display: :9x", zero X11-unix connects in - // strace). Pin the x11 backend so the attempt order cannot - // regress; the private display is X11-only by design. - environment.put("GDK_BACKEND", "x11"); - environment.putAll(extraEnvironment); - builder.redirectOutput(logFile); - builder.redirectError(logFile); - application = builder.start(); - - running = true; - captureThread = new Thread( - () -> captureLoop(destination, listener), "x11-capture"); - captureThread.setDaemon(true); - captureThread.start(); - - if (windowTitleFilter != null) { - fitterThread = new Thread(this::windowFitterLoop, - "x11-window-fitter"); - fitterThread.setDaemon(true); - fitterThread.start(); - } - } - - /** - * Periodically fits windows matching {@link #windowTitleFilter} to - * fill the virtual screen. Runs for the session's lifetime: the - * application may (re)position its windows long after startup, and - * one pass per second is cheap. - */ - private void windowFitterLoop() { - while (running) { - try { - X11Native.fitNamedWindows(connection, windowTitleFilter, - width, height); - } catch (final Throwable throwable) { - // window set churn (map/unmap races) must never kill the - // fitter - if (Boolean.getBoolean("aukio.xcapture.debug")) - throwable.printStackTrace(); - } - try { - Thread.sleep(1000); - } catch (final InterruptedException e) { - return; - } - } - } - - /** - * Opens the session's X connection, retrying briefly. There is a - * real race at Xvfb birth: the readiness probe inside - * {@link XvfbServer#start} connects and disconnects, and the server - * resets when its last client goes away — a connect issued in the - * next few milliseconds can be refused, which used to surface as a - * fatal {@code IllegalStateException: cannot open X display} right - * after a successful probe (observed twice in one day on the - * low-power-profile box, once on the user's desktop run). - */ - private static X11Native.Connection connectWithRetry( - final String displayName) throws IOException { - final long deadline = System.currentTimeMillis() + 10_000; - Throwable lastFailure = null; - while (System.currentTimeMillis() < deadline) { - try { - return new X11Native.Connection(displayName); - } catch (final Throwable failure) { - lastFailure = failure; - try { - Thread.sleep(100); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } - } - } - throw new IOException("cannot open X display " + displayName - + " after 10 s of retries", lastFailure); - } - - private void captureLoop(final int[] destination, - final FrameListener listener) { - final boolean debug = Boolean.getBoolean("aukio.xcapture.debug"); - int iterations = 0; - while (running) { - try { - final boolean changed = X11Native.captureRoot(connection, - width, height, destination); - if (debug && iterations++ % 10 == 0) { - final var distinct = new java.util.HashSet(); - for (int i = 0; i < destination.length; i += 97) - distinct.add(destination[i] & 0xFFFFFF); - System.out.println("XCAPTURE changed=" + changed - + " distinct=" + distinct.size() - + " appAlive=" + isApplicationRunning()); - } - if (changed) - listener.frameCaptured(); - } catch (final Throwable throwable) { - // capture failures (window closing, renderer racing the - // buffer) must never kill the capture thread - if (debug) - throwable.printStackTrace(); - } - try { - Thread.sleep(CAPTURE_INTERVAL_MS); - } catch (final InterruptedException e) { - return; - } - } - } - - /** - * Forwards a keyboard event (press or release) into the virtual - * display. Modifier keys are forwarded as ordinary keys, so the - * server-side modifier state tracks the user's real keyboard. - * - * @param event the AWT key event - * @param pressed {@code true} for key press, {@code false} for release - */ - public void sendKeyEvent(final java.awt.event.KeyEvent event, - final boolean pressed) { - if (connection == null || !isApplicationRunning()) - return; - final long keysym = AwtKeysyms.keysymFor(event); - if (keysym < 0) - return; - if (Boolean.getBoolean("aukio.xcapture.debug")) - System.out.println("XINPUT key keysym=0x" - + Long.toHexString(keysym) + (pressed ? " press" : " release") - + " on " + server.getDisplayName()); - X11Native.sendKeyEvent(connection, keysym, pressed); - } - - /** - * Forwards a raw key (code + produced character) into the virtual - * display. The V2 workspace gets key data from InputStore, not from AWT - * events, so it cannot hand over a KeyEvent. - */ - public void sendKey(final int keyCode, final char keyChar, final boolean pressed) { - if (connection == null || !isApplicationRunning()) - return; - final long keysym = AwtKeysyms.keysymFor(keyCode, keyChar); - if (keysym < 0) - return; - X11Native.sendKeyEvent(connection, keysym, pressed); - } - - /** - * Releases Shift/Control/Alt server-side. Called when keyboard focus - * is lost mid-modifier (e.g. Shift+ESC pops focus while Shift is - * held), so the browser is not left with stuck modifiers. - */ - public void releaseModifiers() { - if (connection == null || !isApplicationRunning()) - return; - X11Native.sendKeyEvent(connection, AwtKeysyms.XK_SHIFT_L, false); - X11Native.sendKeyEvent(connection, AwtKeysyms.XK_CONTROL_L, false); - X11Native.sendKeyEvent(connection, AwtKeysyms.XK_ALT_L, false); - } - - /** - * Forwards scroll wheel input into the virtual display at the given - * screen coordinates (typically the current pointer hover position on - * the panel). - * - * @param verticalUnits positive = scroll down, negative = scroll up - * @param horizontalUnits positive = scroll right, negative = left - */ - public void sendScroll(final int verticalUnits, final int horizontalUnits, - final int x, final int y) { - if (connection == null || !isApplicationRunning()) - return; - final int clampedX = Math.max(0, Math.min(x, width - 1)); - final int clampedY = Math.max(0, Math.min(y, height - 1)); - X11Native.sendScroll(connection, clampedX, clampedY, verticalUnits, - horizontalUnits); - } - - /** - * Moves the pointer inside the virtual display without pressing - * buttons (hover forwarding). - */ - public void sendMouseMove(final int x, final int y) { - if (connection == null || !isApplicationRunning()) - return; - X11Native.sendMouseMove(connection, - Math.max(0, Math.min(x, width - 1)), - Math.max(0, Math.min(y, height - 1))); - } - - /** Virtual screen width in pixels (the panel's texture width). */ - public int width() { - return width; - } - - /** Virtual screen height in pixels (the panel's texture height). */ - public int height() { - return height; - } - - public boolean isApplicationRunning() { - return application != null && application.isAlive(); - } - - /** - * The private X display name (e.g. ":91"), or null before - * {@link #start} — useful for inspecting the session with standard - * tools (xwininfo, import). - */ - public String getDisplayName() { - return server == null ? null : server.getDisplayName(); - } - - /** - * Forwards a mouse click into the virtual display at screen - * coordinates (x, y). The captured texture IS the virtual screen, so - * texture pixels map 1:1 onto these coordinates. The click is - * synthesized with the X TEST extension, which applications treat as - * real device input. - * - * @param x screen X coordinate (clamped into the screen) - * @param y screen Y coordinate (clamped into the screen) - * @param button X button number: 1 = left, 3 = right - */ - public void sendMouseClick(final int x, final int y, final int button) { - if (connection == null || !isApplicationRunning()) - return; - final int clampedX = Math.max(0, Math.min(x, width - 1)); - final int clampedY = Math.max(0, Math.min(y, height - 1)); - if (Boolean.getBoolean("aukio.xcapture.debug")) - System.out.println("XINPUT click at " + clampedX + "," + clampedY - + " button " + button + " on " - + server.getDisplayName()); - X11Native.sendMouseClick(connection, clampedX, clampedY, button); - } - - @Override - public void close() { - running = false; - if (captureThread != null) - captureThread.interrupt(); - if (fitterThread != null) - fitterThread.interrupt(); - if (application != null) - application.destroyForcibly(); - if (connection != null) - connection.close(); - if (server != null) - server.close(); - } - - /** - * Builds a session that runs Firefox on a fresh throwaway profile, - * sized to fill the whole virtual screen. - */ - public static GuiAppSession firefox(final int width, final int height, - final String url) - throws IOException { - final File profile = Files.createTempDirectory( - "aukio-firefox-profile").toFile(); - - // keep first-run noise out of the captured screen - final String userJs = """ - user_pref("browser.shell.checkDefaultBrowser", false); - user_pref("browser.aboutwelcome.enabled", false); - user_pref("datareporting.policy.dataSubmissionEnabled", false); - user_pref("datareporting.policy.firstRunURL", ""); - user_pref("trailhead.firstrun.didSeeAboutWelcome", true); - // stop Debian's system-wide extensions (Web eID) from - // hijacking the first-run session with an active tab - user_pref("extensions.autoDisableScopes", 15); - user_pref("extensions.shownSelectionUI", true); - """; - Files.writeString(new File(profile, "user.js").toPath(), userJs); - - return new GuiAppSession(width, height, - List.of("firefox", "--no-remote", "--new-instance", - "--profile", profile.getAbsolutePath(), - "--width", String.valueOf(width), - "--height", String.valueOf(height), - url), - Map.of(), true); - } - - /** - * Builds a session that runs VMware Workstation sized to fill the - * whole virtual screen. VMware has no command-line size flags, so a - * background thread continuously moves/resizes windows titled - * "VMware" onto the full screen. - */ - public static GuiAppSession vmware(final int width, final int height) { - // Qt must use the X11 backend even when the desktop session is - // Wayland; the private display is X11-only (GuiAppSession also - // removes WAYLAND_DISPLAY for every app) - return new GuiAppSession(width, height, List.of("vmware"), - Map.of("QT_QPA_PLATFORM", "xcb"), false, "VMware"); - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/X11Native.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/X11Native.java deleted file mode 100644 index c8daa84..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/X11Native.java +++ /dev/null @@ -1,433 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.x11; - -import com.sun.jna.Function; -import com.sun.jna.Library; -import com.sun.jna.Native; -import com.sun.jna.NativeLong; -import com.sun.jna.Pointer; -import com.sun.jna.ptr.IntByReference; -import com.sun.jna.ptr.NativeLongByReference; -import com.sun.jna.ptr.PointerByReference; - -/** - * Minimal libX11 bindings for screen capture via JNA. - * - *

Only what {@link X11Capture} needs: open/close a display, resolve the - * root window, and {@code XGetImage} a rectangular area into ARGB pixels. - * The XImage struct is read through manual field offsets (amd64 layout) - * instead of a JNA {@code Structure} — the struct embeds function pointers - * and exact alignment is easier to get right explicitly.

- * - *

Linux-only by design; the workspace targets Linux.

- */ -final class X11Native { - - /** ZPixmap format constant for XGetImage. */ - static final int Z_PIXMAP = 2; - - /** XImage field offsets (amd64 / LP64 layout). */ - private static final int IMAGE_WIDTH = 0; - private static final int IMAGE_HEIGHT = 4; - private static final int IMAGE_DATA = 16; - private static final int IMAGE_BYTE_ORDER = 24; - private static final int IMAGE_DEPTH = 40; - private static final int IMAGE_BYTES_PER_LINE = 44; - private static final int IMAGE_BITS_PER_PIXEL = 48; - private static final int IMAGE_RED_MASK = 56; - private static final int IMAGE_GREEN_MASK = 64; - private static final int IMAGE_BLUE_MASK = 72; - private static final int IMAGE_DESTROY_FUNCTION = 96; - - private static final int LSB_FIRST = 0; - - private interface X11Lib extends Library { - X11Lib INSTANCE = Native.load("X11", X11Lib.class); - - Pointer XOpenDisplay(String displayName); - - int XCloseDisplay(Pointer display); - - int XDefaultScreen(Pointer display); - - NativeLong XRootWindow(Pointer display, int screenNumber); - - Pointer XGetImage(Pointer display, NativeLong drawable, int x, int y, - int width, int height, NativeLong planeMask, - int format); - - int XFlush(Pointer display); - - /** - * Converts a keysym to a keycode in the server's current keymap. - * Returns 0 when the keysym is not present in the keymap. - */ - int XKeysymToKeycode(Pointer display, NativeLong keysym); - - /** - * Lists the children of a window in stacking order (bottom first). - * - * @return 0 on failure; on success childrenReturn holds a malloc'd - * Window array that the caller must release with {@link #XFree} - */ - int XQueryTree(Pointer display, NativeLong window, - NativeLongByReference rootReturn, - NativeLongByReference parentReturn, - PointerByReference childrenReturn, - IntByReference nchildrenReturn); - - /** - * Reads a window's name (WM_NAME). - * - * @return 0 when the window has no name; on success nameReturn - * holds a malloc'd string that the caller must release with - * {@link #XFree} - */ - int XFetchName(Pointer display, NativeLong window, - PointerByReference nameReturn); - - int XFree(Pointer data); - - int XMoveResizeWindow(Pointer display, NativeLong window, int x, - int y, int width, int height); - - int XRaiseWindow(Pointer display, NativeLong window); - } - - /** - * libXtst (X TEST extension) bindings for synthesizing input. Fake - * input events are indistinguishable from real device events, unlike - * XSendEvent which many toolkits (GTK included) treat as untrusted. - */ - private interface XTestLib extends Library { - XTestLib INSTANCE = Native.load("Xtst", XTestLib.class); - - int XTestFakeMotionEvent(Pointer display, int screenNumber, - int x, int y, NativeLong delay); - - int XTestFakeButtonEvent(Pointer display, int button, - boolean isPress, NativeLong delay); - - /** - * Synthesizes a key press or release. - * - * @return nonzero on success - */ - int XTestFakeKeyEvent(Pointer display, int keycode, boolean isPress, - NativeLong delay); - } - - /** - * An open connection to an X server. - * - *

libX11 is not thread-safe unless XInitThreads was called; all - * requests on this connection are instead serialized through - * {@link #lock} (the capture loop and the input injector run on - * different threads).

- */ - static final class Connection { - final Pointer display; - final NativeLong rootWindow; - final int screenNumber; - /** Serializes all X protocol traffic on this connection. */ - final Object lock = new Object(); - - Connection(final String displayName) { - display = X11Lib.INSTANCE.XOpenDisplay(displayName); - if (display == null) - throw new IllegalStateException( - "cannot open X display " + displayName); - screenNumber = X11Lib.INSTANCE.XDefaultScreen(display); - rootWindow = X11Lib.INSTANCE.XRootWindow(display, screenNumber); - } - - void close() { - synchronized (lock) { - if (display != null) - X11Lib.INSTANCE.XCloseDisplay(display); - } - } - } - - /** - * Grabs the top-left rectangle of the root window and converts it to - * ARGB, honoring the server's pixel masks, bits-per-pixel and byte - * order. Writes directly into {@code destination} and reports whether - * any pixel changed. - * - * @return true when at least one written pixel differs from the - * previous buffer content - */ - static boolean captureRoot(final Connection connection, - final int width, final int height, - final int[] destination) { - synchronized (connection.lock) { - final Pointer image = X11Lib.INSTANCE.XGetImage(connection.display, - connection.rootWindow, 0, 0, width, height, - new NativeLong(-1L), Z_PIXMAP); - if (image == null) - return false; - try { - return convert(image, width, height, destination); - } finally { - // XDestroyImage is a macro calling image->f.destroy_image - final Pointer destroyFunction = image.getPointer( - IMAGE_DESTROY_FUNCTION); - Function.getFunction(destroyFunction).invokeInt( - new Object[]{image}); - } - } - } - - /** - * Sends a single key press or release, identified by X keysym, to the - * virtual display. Modifier state is NOT synthesized here — real - * modifier key events (Shift/Ctrl/Alt) are forwarded like any other - * key, so the server-side modifier state tracks the user's keyboard. - * - * @param keysym the X keysym (see {@link AwtKeysyms}) - * @param press {@code true} for press, {@code false} for release - */ - static void sendKeyEvent(final Connection connection, final long keysym, - final boolean press) { - synchronized (connection.lock) { - final int keycode = X11Lib.INSTANCE.XKeysymToKeycode( - connection.display, new NativeLong(keysym)); - if (keycode == 0) - // keysym not present in the server keymap; nothing to send - return; - XTestLib.INSTANCE.XTestFakeKeyEvent(connection.display, keycode, - press, new NativeLong(0)); - X11Lib.INSTANCE.XFlush(connection.display); - } - } - - /** - * Sends scroll wheel input at the given root-window coordinates: moves - * the pointer there, then presses/releases the X scroll buttons - * (4 = up, 5 = down, 6 = left, 7 = right), one click per notch. - * - * @param verticalUnits positive = scroll down, negative = scroll up - * @param horizontalUnits positive = scroll right, negative = left - */ - static void sendScroll(final Connection connection, final int x, - final int y, final int verticalUnits, - final int horizontalUnits) { - synchronized (connection.lock) { - XTestLib.INSTANCE.XTestFakeMotionEvent(connection.display, - connection.screenNumber, x, y, new NativeLong(0)); - final int verticalButton = verticalUnits < 0 ? 4 : 5; - for (int i = 0; i < Math.abs(verticalUnits); i++) { - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, - verticalButton, true, new NativeLong(0)); - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, - verticalButton, false, new NativeLong(0)); - } - final int horizontalButton = horizontalUnits < 0 ? 6 : 7; - for (int i = 0; i < Math.abs(horizontalUnits); i++) { - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, - horizontalButton, true, new NativeLong(0)); - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, - horizontalButton, false, new NativeLong(0)); - } - X11Lib.INSTANCE.XFlush(connection.display); - } - } - - /** - * Moves the pointer to the given root-window coordinates without - * pressing any button (hover forwarding). - */ - static void sendMouseMove(final Connection conn, final int x, - final int y) { - synchronized (conn.lock) { - XTestLib.INSTANCE.XTestFakeMotionEvent(conn.display, - conn.screenNumber, x, y, new NativeLong(0)); - X11Lib.INSTANCE.XFlush(conn.display); - } - } - - /** - * Synthesizes a full mouse click (move pointer, press, release) at the - * given root-window coordinates. The pointer is moved first because a - * button press acts at the current pointer location. The button is - * held briefly because Firefox does not synthesize a DOM click from a - * zero-duration press+release. - * - * @param x root-window X coordinate - * @param y root-window Y coordinate - * @param button X button number (1 = left, 3 = right) - */ - static void sendMouseClick(final Connection connection, final int x, - final int y, final int button) { - synchronized (connection.lock) { - XTestLib.INSTANCE.XTestFakeMotionEvent(connection.display, - connection.screenNumber, x, y, new NativeLong(0)); - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, button, - true, new NativeLong(0)); - X11Lib.INSTANCE.XFlush(connection.display); - // Firefox (EventStateManager) does not synthesize a DOM click - // from a zero-duration press+release; hold the button briefly - try { - Thread.sleep(80); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - } - XTestLib.INSTANCE.XTestFakeButtonEvent(connection.display, button, - false, new NativeLong(0)); - X11Lib.INSTANCE.XFlush(connection.display); - } - } - - /** - * Moves and resizes every top-level window whose name contains - * {@code titleFilter} to fill the whole virtual screen, raising it to - * the top of the stacking order. Used for applications that cannot be - * sized on the command line (e.g. VMware Workstation): a background - * thread calls this periodically so late-appearing windows get fitted - * too. - * - * @return the number of windows fitted in this pass - */ - static int fitNamedWindows(final Connection connection, - final String titleFilter, - final int width, final int height) { - synchronized (connection.lock) { - final NativeLongByReference rootReturn = new NativeLongByReference(); - final NativeLongByReference parentReturn = new NativeLongByReference(); - final PointerByReference childrenReturn = new PointerByReference(); - final IntByReference countReturn = new IntByReference(); - if (X11Lib.INSTANCE.XQueryTree(connection.display, - connection.rootWindow, rootReturn, parentReturn, - childrenReturn, countReturn) == 0) - return 0; - final Pointer children = childrenReturn.getValue(); - int fitted = 0; - try { - final int count = countReturn.getValue(); - if (children == null || count <= 0) - return 0; - for (int i = 0; i < count; i++) { - final NativeLong window = new NativeLong( - children.getNativeLong((long) i * NativeLong.SIZE) - .longValue()); - final PointerByReference nameReturn = - new PointerByReference(); - if (X11Lib.INSTANCE.XFetchName(connection.display, window, - nameReturn) == 0) - continue; // unnamed window - final Pointer name = nameReturn.getValue(); - if (name == null) - continue; - try { - final String title = name.getString(0); - if (title == null || !title.contains(titleFilter)) - continue; - X11Lib.INSTANCE.XMoveResizeWindow(connection.display, - window, 0, 0, width, height); - X11Lib.INSTANCE.XRaiseWindow(connection.display, - window); - fitted++; - } finally { - X11Lib.INSTANCE.XFree(name); - } - } - } finally { - X11Lib.INSTANCE.XFree(children); - } - if (fitted > 0) - X11Lib.INSTANCE.XFlush(connection.display); - return fitted; - } - } - - private static boolean convert(final Pointer image, final int width, - final int height, final int[] destination) { - final int imageWidth = image.getInt(IMAGE_WIDTH); - final int imageHeight = image.getInt(IMAGE_HEIGHT); - final Pointer data = image.getPointer(IMAGE_DATA); - final int byteOrder = image.getInt(IMAGE_BYTE_ORDER); - final int bytesPerLine = image.getInt(IMAGE_BYTES_PER_LINE); - final int bitsPerPixel = image.getInt(IMAGE_BITS_PER_PIXEL); - final long redMask = image.getLong(IMAGE_RED_MASK); - final long greenMask = image.getLong(IMAGE_GREEN_MASK); - final long blueMask = image.getLong(IMAGE_BLUE_MASK); - - final Channel red = new Channel(redMask); - final Channel green = new Channel(greenMask); - final Channel blue = new Channel(blueMask); - - boolean changed = false; - final int copyWidth = Math.min(width, imageWidth); - final int copyHeight = Math.min(height, imageHeight); - for (int y = 0; y < copyHeight; y++) { - final int rowOffset = y * bytesPerLine; - final int destinationRow = y * width; - for (int x = 0; x < copyWidth; x++) { - final long pixelValue = readPixel(data, rowOffset, x, - bitsPerPixel, byteOrder); - final int argb = 0xFF000000 - | (red.extract(pixelValue) << 16) - | (green.extract(pixelValue) << 8) - | blue.extract(pixelValue); - final int index = destinationRow + x; - if (destination[index] != argb) { - destination[index] = argb; - changed = true; - } - } - } - return changed; - } - - private static long readPixel(final Pointer data, final int rowOffset, - final int x, final int bitsPerPixel, - final int byteOrder) { - if (bitsPerPixel == 32) { - final int value = data.getInt(rowOffset + (long) x * 4); - return Integer.toUnsignedLong( - byteOrder == LSB_FIRST ? value : Integer.reverseBytes(value)); - } - if (bitsPerPixel == 24) { - final long offset = rowOffset + (long) x * 3; - final int b0 = data.getByte(offset) & 0xFF; - final int b1 = data.getByte(offset + 1) & 0xFF; - final int b2 = data.getByte(offset + 2) & 0xFF; - return byteOrder == LSB_FIRST - ? b0 | (b1 << 8) | (b2 << 16) - : (b0 << 16) | (b1 << 8) | b2; - } - if (bitsPerPixel == 16) { - final short value = data.getShort(rowOffset + (long) x * 2); - return Short.toUnsignedLong( - byteOrder == LSB_FIRST ? value : Short.reverseBytes(value)); - } - throw new IllegalStateException( - "unsupported bits_per_pixel " + bitsPerPixel); - } - - /** - * Extracts one 8-bit color channel from a raw pixel using the server - * pixel mask (any position and width, scaled to 0..255). - */ - private static final class Channel { - private final long mask; - private final int shift; - private final long maxValue; - - Channel(final long mask) { - this.mask = mask; - shift = mask == 0 ? 0 : Long.numberOfTrailingZeros(mask); - maxValue = mask == 0 ? 1 : (mask >>> shift); - } - - int extract(final long pixelValue) { - if (mask == 0) - return 0; - return (int) (((pixelValue & mask) >>> shift) * 255 / maxValue); - } - } -} diff --git a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/XvfbServer.java b/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/XvfbServer.java deleted file mode 100644 index a4ec036..0000000 --- a/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/XvfbServer.java +++ /dev/null @@ -1,116 +0,0 @@ -/* - * Aukio spatial computing environment. Author: Svjatoslav Agejenko. - * This project is released under Creative Commons Zero (CC0) license. - */ -package eu.svjatoslav.aukio.wsp.x11; - -import java.io.File; -import java.io.IOException; - -/** - * Lifecycle of a private {@code Xvfb} virtual X server that one captured - * GUI application renders into. - * - *

Each server gets its own display number (scanned upward from 90, - * skipping displays with an existing lock file or socket), so multiple - * captured apps never share a screen. Readiness is detected by polling for - * the unix socket and then proving the display with a real - * {@code XOpenDisplay} — just waiting for the socket is not enough.

- */ -public final class XvfbServer implements AutoCloseable { - - private static final int FIRST_DISPLAY = 90; - private static final int LAST_DISPLAY = 200; - private static final long START_TIMEOUT_MS = 10_000; - - private final int displayNumber; - private final Process process; - - private XvfbServer(final int displayNumber, final Process process) { - this.displayNumber = displayNumber; - this.process = process; - } - - /** - * Starts an Xvfb server with a single screen of the given size and - * waits until the display actually accepts connections. - * - * @throws IOException if Xvfb fails to start within the timeout - */ - public static XvfbServer start(final int width, final int height) - throws IOException { - final int displayNumber = findFreeDisplay(); - final Process process = new ProcessBuilder("Xvfb", - ":" + displayNumber, - "-screen", "0", width + "x" + height + "x24", - "-nolisten", "tcp") - .redirectOutput(new File("/tmp/aukio-xvfb-" - + displayNumber + ".log")) - .redirectError(new File("/tmp/aukio-xvfb-" - + displayNumber + ".log")) - .start(); - - final XvfbServer server = new XvfbServer(displayNumber, process); - final long deadline = System.currentTimeMillis() + START_TIMEOUT_MS; - while (System.currentTimeMillis() < deadline) { - if (!process.isAlive()) - break; - if (new File(server.socketPath()).exists()) { - try { - final X11Native.Connection probe = - new X11Native.Connection(server.getDisplayName()); - probe.close(); - return server; - } catch (final Throwable ignored) { - // socket exists but server not accepting yet - } - } - try { - Thread.sleep(100); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - break; - } - } - process.destroyForcibly(); - throw new IOException("Xvfb :" + displayNumber - + " did not become ready within " + START_TIMEOUT_MS + " ms"); - } - - private static int findFreeDisplay() throws IOException { - for (int number = FIRST_DISPLAY; number <= LAST_DISPLAY; number++) - if (!new File("/tmp/.X" + number + "-lock").exists() - && !new File(socketPath(number)).exists()) - return number; - throw new IOException("no free X display number between " - + FIRST_DISPLAY + " and " + LAST_DISPLAY); - } - - private static String socketPath(final int displayNumber) { - return "/tmp/.X11-unix/X" + displayNumber; - } - - private String socketPath() { - return socketPath(displayNumber); - } - - /** - * Display name for the {@code DISPLAY} environment variable - * (e.g. {@code ":93"}). - */ - public String getDisplayName() { - return ":" + displayNumber; - } - - @Override - public void close() { - process.destroy(); - try { - if (!process.waitFor(2, java.util.concurrent.TimeUnit.SECONDS)) - process.destroyForcibly(); - } catch (final InterruptedException e) { - Thread.currentThread().interrupt(); - process.destroyForcibly(); - } - } -} -- 2.20.1