public static final int TERMINAL_GRID_COLUMNS = 4;
public static final int TERMINAL_GRID_ROWS = 4;
+ /** The whole workspace floats this far ABOVE the world origin. The engine
+ * is -Y-up, so height = -APP_ALTITUDE. Without it a loaded environment's
+ * terrain and buildings swallow the panels (bugreport-20261031-202627:
+ * "raise all apps, otherwise they are stuck inside buildings"). 6000
+ * units = 60 m in FO4 scale, above the downtown roofline. */
+ public static final double APP_ALTITUDE = Double.parseDouble(
+ System.getProperty("aukio.workspace.altitude", "20000"));
+
private final ViewFrame viewFrame;
private final List<TerminalPanel> terminalPanels = new ArrayList<>();
private FirefoxPanel firefoxPanel;
final ViewPanel viewPanel = viewFrame.getViewPanel();
final ShapeCollection scene = viewPanel.getRootShapeCollection();
- viewPanel.getCamera().getTransform().set(150, -120, -350, 0,
- -0.12, 0);
+ viewPanel.getCamera().getTransform().set(150,
+ -120 - APP_ALTITUDE, -350, 0, -0.12, 0);
addGrid(scene);
addTextEditor(viewPanel, scene);
}
private void addGrid(final ShapeCollection scene) {
- final Transform transform = Transform.fromAngles(0, 100, 0, 0,
- Math.PI / 2, 0);
+ final Transform transform = Transform.fromAngles(0,
+ 100 - APP_ALTITUDE, 0, 0, Math.PI / 2, 0);
final Rectangle rectangle = new Rectangle(2000);
final LineAppearance appearance = new LineAppearance(10,
hex("00b3ad"));
private void addTextEditor(final ViewPanel viewPanel,
final ShapeCollection scene) {
final TextEditComponent editor = new TextEditComponent(
- new Transform(point(-700, 0, 300)), viewPanel,
+ new Transform(point(-700, 0 - APP_ALTITUDE, 300)), viewPanel,
new Point2D(400, 240), new LookAndFeel());
editor.setText("Aukio workspace\n\n"
+ "Click a panel to focus it.\n"
TERMINAL_ROWS);
final TerminalPanel terminalPanel = new TerminalPanel(
new Transform(point(100 + (x * 900),
- -100 - (y * 600), 300)), viewPanel,
+ -100 - (y * 600) - APP_ALTITUDE, 300)), viewPanel,
new Point2D(
TERMINAL_COLUMNS * TextCanvas.FONT_CHAR_WIDTH,
TERMINAL_ROWS * TextCanvas.FONT_CHAR_HEIGHT),
*/
private void addFirefox(final ViewPanel viewPanel,
final ShapeCollection scene) throws IOException {
- firefoxPanel = new FirefoxPanel(new Transform(point(-700, -450, 300)),
+ firefoxPanel = new FirefoxPanel(
+ new Transform(point(-700, -450 - APP_ALTITUDE, 300)),
viewPanel, new Point2D(640, 480));
firefoxPanel.start();
scene.addShape(firefoxPanel);
*/
private void addVmware(final ViewPanel viewPanel,
final ShapeCollection scene) throws IOException {
- vmwarePanel = new VmwarePanel(new Transform(point(-700, -1050, 300)),
+ vmwarePanel = new VmwarePanel(
+ new Transform(point(-700, -1050 - APP_ALTITUDE, 300)),
viewPanel, new Point2D(640, 480));
vmwarePanel.start();
scene.addShape(vmwarePanel);
#!/usr/bin/env bash
-# Start the Fallout 4 Commonwealth app on Aukio 3D 2.
+# Aukio launcher.
#
-# Builds the V2 engine and the standalone FO4-2 consumer in dependency
-# order, then launches the Aukio 3D host (eu.svjatoslav.aukio.core.Main) with
-# the Commonwealth as its world source (--source=fo42). The host owns the
-# loop; the environment is a library it opens by name.
+# ./start.sh the workspace app: 3D space with its panels, terminals
+# and apps; no world environment
+# ./start.sh fo4 the same workspace PLUS the Fallout 4 environment
+# (V1 engine + V1 loader, the reference implementation)
+# ./start.sh v2 the V2 host: Aukio 3D 2 + the Commonwealth as its
+# world source (no workspace panels)
+# ./start.sh ws2 the NEW workspace on Aukio 3D 2 (port in progress:
+# live bash terminal; V1 panels not yet available)
+#
+# The workspace app is this repository (eu.svjatoslav.aukio:aukio) and hosts
+# environments through the EnvironmentProvider SPI; "fo4" selects the provider
+# with --env=fallout4 and puts aukio-environment-fo4 on the classpath.
#
# The game path comes from AUKIO_FO4_PATH or the fo4: section of
-# ~/.config/aukio/config.yaml. Extra args are forwarded to the host.
+# ~/.config/aukio/config.yaml. Extra args are forwarded to the app.
# To pass -D properties, edit JAVA_OPTS below or export them first.
set -euo pipefail
-# Sibling checkouts are resolved relative to this script (Aukio/*
-# layout), so nothing here is tied to a particular machine.
+# 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"
+FO4V2="$ROOT/aukio-environment-fo4-2"
+FO4V1="$ROOT/aukio-environment-fo4"
+WORKSPACE="$ROOT/aukio"
-echo "==> building aukio-3d-2"
-mvn -f "$ENGINE/pom.xml" install -q -DskipTests -Dmaven.javadoc.skip=true
+# The workspace app is a Java 21 build and its javadoc plugin needs JAVA_HOME.
+export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/java-21-openjdk-amd64}"
-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
+MODE=workspace
+ARGS=()
+for arg in "$@"; do
+ case "$arg" in
+ fo4|fallout4) MODE=fo4 ;;
+ v2|fo42) MODE=v2 ;;
+ ws2) MODE=ws2 ;;
+ --empty) MODE=workspace ;;
+ *) ARGS+=("$arg") ;;
+ esac
+done
-echo "==> starting Aukio 3D 2 with Fallout 4"
-cd "$FO4"
mkdir -p "$HOME/.cache/aukio/heapdumps"
-exec java -Xmx20g --enable-native-access=ALL-UNNAMED \
+
+if [ "$MODE" = "v2" ]; then
+ echo "==> building aukio-3d-2"
+ mvn -f "$ENGINE/pom.xml" install -q -DskipTests -Dmaven.javadoc.skip=true
+ echo "==> building aukio-environment-fo4-2"
+ mvn -f "$FO4V2/pom.xml" package -q -DskipTests -Dmaven.javadoc.skip=true
+ mvn -f "$FO4V2/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt
+ echo "==> starting Aukio 3D 2 with Fallout 4 (V2 host)"
+ cd "$FO4V2"
+ exec java -Xmx20g --enable-native-access=ALL-UNNAMED \
+ -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
+
+if [ "$MODE" = "ws2" ]; then
+ WS2="$ROOT/aukio/workspace-v2"
+ echo "==> building aukio-3d-2"
+ mvn -f "$ENGINE/pom.xml" install -q -DskipTests -Dmaven.javadoc.skip=true
+ echo "==> building the V2 workspace"
+ mvn -f "$WS2/pom.xml" package -q -DskipTests
+ mvn -f "$WS2/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt
+ echo "==> starting the Aukio workspace on Aukio 3D 2"
+ cd "$WS2"
+ 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[@]}"
+fi
+
+echo "==> building the Aukio workspace app"
+mvn -f "$WORKSPACE/pom.xml" package -q -DskipTests -Dmaven.javadoc.skip=true
+mvn -f "$WORKSPACE/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt
+
+EXTRA_CP=""
+ENV_ARGS=()
+if [ "$MODE" = "fo4" ]; then
+ echo "==> building aukio-environment-fo4 (V1 loader)"
+ mvn -f "$FO4V1/pom.xml" package -q -DskipTests -Dmaven.javadoc.skip=true
+ mvn -f "$FO4V1/pom.xml" dependency:build-classpath -q -Dmdep.outputFile=target/cp.txt
+ EXTRA_CP="$FO4V1/target/classes:$(cat "$FO4V1/target/cp.txt"):"
+ ENV_ARGS=("--env=fallout4")
+ echo "==> starting the workspace with the Fallout 4 environment"
+ cd "$WORKSPACE"
+ exec java -Xmx20g --enable-native-access=ALL-UNNAMED \
+ -XX:+HeapDumpOnOutOfMemoryError \
+ -XX:HeapDumpPath="$HOME/.cache/aukio/heapdumps" \
+ ${AUKIO_FO4_PATH:+-Daukio.fo4.path=$AUKIO_FO4_PATH} \
+ ${JAVA_OPTS:-} \
+ -cp "target/classes:${EXTRA_CP}$(cat target/cp.txt)" \
+ eu.svjatoslav.aukio.core.Main "${ENV_ARGS[@]}" "${ARGS[@]}"
+fi
+
+echo "==> starting the workspace"
+cd "$WORKSPACE"
+exec java -Xmx8g --enable-native-access=ALL-UNNAMED \
-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 "$@"
+ eu.svjatoslav.aukio.core.Main "${ARGS[@]}"
--- /dev/null
+<?xml version="1.0" encoding="UTF-8"?>
+<project xmlns="http://maven.apache.org/POM/4.0.0"
+ xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+
+ <!-- The Aukio workspace on aukio-3d-2. It deliberately has NO dependency on
+ aukio-3d (V1) or on the V1 workspace app: the port's whole point is to
+ retire V1, so anything needed from it is copied here and the V1 copy
+ dies with V1. -->
+ <groupId>eu.svjatoslav.aukio</groupId>
+ <artifactId>aukio-workspace-v2</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ <packaging>jar</packaging>
+
+ <properties>
+ <maven.compiler.release>21</maven.compiler.release>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ </properties>
+
+ <dependencies>
+ <dependency>
+ <groupId>eu.svjatoslav</groupId>
+ <artifactId>aukio-3d-2</artifactId>
+ <version>2.0.0-SNAPSHOT</version>
+ </dependency>
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.13.0</version>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>3.4.2</version>
+ </plugin>
+ </plugins>
+ </build>
+</project>
--- /dev/null
+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.
+ *
+ * <p>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();
+ }
+}
--- /dev/null
+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.
+ *
+ * <p>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) {
+ }
+
+ /** 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() {
+ }
+}
--- /dev/null
+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):
+ *
+ * <pre>
+ * 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
+ * </pre>
+ */
+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};
+ }
+}
--- /dev/null
+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).
+ *
+ * <p>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;
+ }
+}
--- /dev/null
+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.
+ *
+ * <p>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 = 0xFF0E1216;
+ private static final int DEFAULT_FG = 0xFFC8D0D8;
+ /** 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 = cell.fg == ScreenBuffer.DEFAULT_COLOR
+ ? DEFAULT_FG : 0xFF000000 | (cell.fg & 0xFFFFFF);
+ int bg = cell.bg == ScreenBuffer.DEFAULT_COLOR
+ ? DEFAULT_BG : 0xFF000000 | (cell.bg & 0xFFFFFF);
+ 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;
+
+ /**
+ * Keyboard into the PTY. A line discipline wants CR for Enter, never LF,
+ * and backspace is DEL, not BS - both are terminal conventions, not
+ * engine ones, so they live with the panel.
+ */
+ @Override
+ public void key(final int code, final char character, final boolean pressed) {
+ if (!pressed) return;
+ if (character == '\n' || character == '\r') {
+ send("\r");
+ } else if (character >= 32 || character == '\t' || character == '\b'
+ || character == 127) {
+ send(String.valueOf(character));
+ } else {
+ 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 -> {
+ }
+ }
+ }
+ }
+
+ 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();
+ }
+}
--- /dev/null
+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.
+ *
+ * <p>Rules (V1 workspace semantics):
+ * <ul>
+ * <li>left click on a panel FOCUSES it; the click itself is not forwarded</li>
+ * <li>left click on a focused panel is forwarded at the clicked texture
+ * coordinate (perspective correct, resolved here from the camera ray)</li>
+ * <li>middle click, or Shift+Esc, releases focus and is never forwarded</li>
+ * <li>a click on empty space releases focus</li>
+ * <li>while any panel holds focus the camera does not fly: the flight keys
+ * would otherwise be swallowed by whatever is being typed</li>
+ * </ul>
+ */
+public final class WorkspaceInputPass implements Pass {
+
+ private static final int VK_ESCAPE = 27;
+ private static final int SHIFT_MASK = 1;
+
+ private final List<Panel> panels;
+ private final Substrate data;
+ private volatile Panel focused;
+ private final java.util.Set<Integer> forwarded = new java.util.HashSet<>();
+ private double lastU = -1, lastV = -1;
+
+ public WorkspaceInputPass(final Substrate data, final List<Panel> panels) {
+ this.data = data;
+ this.panels = panels;
+ }
+
+ @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 GuiAppPanel) {
+ 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) {
+ // a typed character is TEXT, not a press: it carries no key code
+ // and must reach the panel even though the key is still held
+ 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;
+ }
+}
--- /dev/null
+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.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.
+ *
+ * <p>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<Panel> 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);
+ }
+ }
+ }
+
+ data.camera.set(0, 60, -300, 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 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();
+ }
+}
--- /dev/null
+/*
+ * 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}.
+ *
+ * <p>Engine-independent: this class knows nothing about the 3D world.
+ * Rendering and keyboard delivery are the caller's job (see
+ * {@code workspace.TerminalPanel}).</p>
+ *
+ * <p>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.</p>
+ */
+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<String, String> 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.
+ *
+ * <p>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.</p>
+ */
+ public void stop() {
+ running = false;
+ pty.destroy();
+ try {
+ readerThread.join(2000);
+ } catch (final InterruptedException e) {
+ Thread.currentThread().interrupt();
+ }
+ }
+}
--- /dev/null
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ *
+ * <p>All public methods must be called while holding {@code synchronized}
+ * on this instance (the emulator and the renderer both access it).</p>
+ */
+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();
+ }
+}
--- /dev/null
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ *
+ * <p>Linux-only by design; the workspace targets Linux.</p>
+ */
+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.
+ *
+ * <p>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.</p>
+ *
+ * @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<String, String> 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<String> 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.
+ *
+ * <p>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.</p>
+ */
+ private static final List<Memory> 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);
+ }
+}
--- /dev/null
+/*
+ * 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}.
+ *
+ * <p>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.</p>
+ *
+ * <p>Not a full xterm: no scrollback, no mouse reporting, no 8-bit C1.
+ * Unknown sequences are consumed and ignored rather than mishandled.</p>
+ *
+ * <p>Threading: all calls arrive on the PTY reader thread; the emulator
+ * synchronizes on the buffer for every operation.</p>
+ */
+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);
+ }
+ }
+}
--- /dev/null
+/* 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.
+ *
+ * <p>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).</p>
+ *
+ * <p>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.</p>
+ */
+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;
+ }
+}
--- /dev/null
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ */
+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<String> command;
+ private final Map<String, String> 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<String> command,
+ final Map<String, String> 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<String> command,
+ final Map<String, String> 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<String> command,
+ final Map<String, String> 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<String> 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<String, String> 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/<display> — 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<Integer>();
+ 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");
+ }
+}
--- /dev/null
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ *
+ * <p>Linux-only by design; the workspace targets Linux.</p>
+ */
+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.
+ *
+ * <p>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).</p>
+ */
+ 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);
+ }
+ }
+}
--- /dev/null
+/*
+ * 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.
+ *
+ * <p>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.</p>
+ */
+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();
+ }
+ }
+}
--- /dev/null
+/home/n0/.m2/repository/eu/svjatoslav/aukio-3d-2/2.0.0-SNAPSHOT/aukio-3d-2-2.0.0-SNAPSHOT.jar:/home/n0/.m2/repository/net/java/dev/jna/jna/5.14.0/jna-5.14.0.jar
\ No newline at end of file
--- /dev/null
+artifactId=aukio-workspace-v2
+groupId=eu.svjatoslav.aukio
+version=2.0.0-SNAPSHOT
--- /dev/null
+eu/svjatoslav/aukio/wsp/x11/X11Native$Channel.class
+eu/svjatoslav/aukio/wsp/pty/PtySession.class
+eu/svjatoslav/aukio/wsp/GuiAppPanel.class
+eu/svjatoslav/aukio/wsp/pty/PtySession$ContentListener.class
+eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.class
+eu/svjatoslav/aukio/wsp/x11/GuiAppSession$FrameListener.class
+eu/svjatoslav/aukio/wsp/pty/Vt100Emulator$State.class
+eu/svjatoslav/aukio/wsp/pty/UnixPty$CLib.class
+eu/svjatoslav/aukio/wsp/pty/UnixPty.class
+eu/svjatoslav/aukio/wsp/WorkspaceInputPass.class
+eu/svjatoslav/aukio/wsp/Panel.class
+eu/svjatoslav/aukio/wsp/x11/X11Native$Connection.class
+eu/svjatoslav/aukio/wsp/Ray.class
+eu/svjatoslav/aukio/wsp/pty/ScreenBuffer$Cell.class
+eu/svjatoslav/aukio/wsp/x11/XvfbServer.class
+eu/svjatoslav/aukio/wsp/x11/X11Native$X11Lib.class
+eu/svjatoslav/aukio/wsp/pty/PtySession$1.class
+eu/svjatoslav/aukio/wsp/TerminalPanel.class
+eu/svjatoslav/aukio/wsp/WorkspaceMain.class
+eu/svjatoslav/aukio/wsp/x11/X11Native$XTestLib.class
+eu/svjatoslav/aukio/wsp/x11/X11Native.class
+eu/svjatoslav/aukio/wsp/x11/GuiAppSession.class
+eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.class
+eu/svjatoslav/aukio/wsp/RectPanel.class
+eu/svjatoslav/aukio/wsp/WorkspaceInputPass$1.class
+eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.class
--- /dev/null
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/GuiAppPanel.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Panel.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/Ray.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/RectPanel.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/TerminalPanel.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceInputPass.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/WorkspaceMain.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/PtySession.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/ScreenBuffer.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/UnixPty.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/pty/Vt100Emulator.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/AwtKeysyms.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/GuiAppSession.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/X11Native.java
+/home/n0/workspace/Aukio/aukio/workspace-v2/src/main/java/eu/svjatoslav/aukio/wsp/x11/XvfbServer.java