Archive incari-client (client, 26.3, clean)

This commit is contained in:
2026-11-28 00:54:38 -06:00
parent 7a6174687f
commit 12838e838c
2383 changed files with 280266 additions and 0 deletions
@@ -0,0 +1,59 @@
package incari.platform.web;
/**
* The canvas's size as the game sees it.
*
* @param width the CSS width: the window's width in screen coordinates, which mouse positions
* are relative to
* @param pixelWidth the backing store's width in device pixels: the framebuffer
* @param density device pixels per CSS pixel ({@code devicePixelRatio}), which browser zoom
* changes too
*/
record CanvasSize(int width, int height, int pixelWidth, int pixelHeight, double density) {
/**
* The size from one measurement of the page.
*
* @param cssWidth the CSS content width, possibly fractional
* @param deviceWidth the exact device-pixel width where the browser reports one
* ({@code devicePixelContentBoxSize}), else 0 to derive it from the CSS size and density
* @param previous the size measured before: kept when the page reports an empty canvas (it
* was hidden or isn't laid out), and its exact pixel size kept when a measurement without
* one agrees with it
*/
static CanvasSize measure(
double cssWidth,
double cssHeight,
double deviceWidth,
double deviceHeight,
double density,
CanvasSize previous) {
if (!(cssWidth > 0 && cssHeight > 0)) {
return previous;
}
double scale = density > 0 ? density : 1;
int width = Math.max(1, (int) Math.round(cssWidth));
int height = Math.max(1, (int) Math.round(cssHeight));
int pixelWidth;
int pixelHeight;
if (deviceWidth > 0 && deviceHeight > 0) {
pixelWidth = (int) Math.round(deviceWidth);
pixelHeight = (int) Math.round(deviceHeight);
} else if (width == previous.width && height == previous.height && scale == previous.density) {
// A window resize or density check that found nothing new: keep the exact size the
// ResizeObserver reported, rather than a rounded guess that can be off by a pixel.
pixelWidth = previous.pixelWidth;
pixelHeight = previous.pixelHeight;
} else {
pixelWidth = (int) Math.round(cssWidth * scale);
pixelHeight = (int) Math.round(cssHeight * scale);
}
return new CanvasSize(width, height, Math.max(1, pixelWidth), Math.max(1, pixelHeight), scale);
}
/** The size to start from before the page has measured the canvas. */
static CanvasSize initial(double cssWidth, double cssHeight, double density) {
CanvasSize unknown = new CanvasSize(1, 1, 1, 1, density > 0 ? density : 1);
return measure(cssWidth, cssHeight, 0, 0, density, unknown);
}
}
@@ -0,0 +1,264 @@
package incari.platform.web;
import incari.platform.api.window.DisplayMode;
import incari.platform.api.window.IconImage;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.SystemBehavior;
import incari.platform.api.window.SystemCursor;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSObject;
/**
* The page's canvas as the game's window. Screen coordinates are CSS pixels, with the canvas's
* top left as the origin; the framebuffer is the canvas's backing store, CSS size times the device
* pixel ratio. The size, cursor and Pointer Lock state live in the {@link DomEventQueue}, which
* sees the page's events; this class answers from it and forwards the game's requests to the page.
*/
final class CanvasWindow implements PlatformWindow, DomEventQueue.Surface {
/** A constant, non-zero handle: the game only compares handles to tell windows apart. */
static final long HANDLE = 1L;
private final JSObject canvas;
private @Nullable DomEventQueue events;
/** The game holds the mouse ({@link #setRelativeMouseMode}). */
private boolean mouseHeld;
/** The player is in a world ({@link #setLeaveWarning}). */
private boolean inWorld;
/** Whether the page's leave guard is on now, so it's set only when it changes. */
private boolean guarded;
CanvasWindow(JSObject canvas) {
this.canvas = canvas;
}
/** Connects the queue; done once, right after both exist (each needs the other). */
void connect(DomEventQueue queue) {
this.events = queue;
}
JSObject canvas() {
return canvas;
}
private DomEventQueue events() {
DomEventQueue queue = events;
if (queue == null) {
throw new IllegalStateException("The canvas window isn't connected to its events yet");
}
return queue;
}
// --- What the queue asks of the page ---
@Override
public void setBackingSize(int pixelWidth, int pixelHeight) {
Dom.setCanvasSize(canvas, pixelWidth, pixelHeight);
}
@Override
public void setPointerLock(boolean locked) {
Dom.setPointerLock(canvas, locked);
}
@Override
public long nativeHandle() {
return HANDLE;
}
@Override
public int x() {
return 0;
}
@Override
public int y() {
return 0;
}
@Override
public int width() {
return events().size().width();
}
@Override
public int height() {
return events().size().height();
}
@Override
public int framebufferWidth() {
return events().size().pixelWidth();
}
@Override
public int framebufferHeight() {
return events().size().pixelHeight();
}
@Override
public int unusedWidth() {
return 0;
}
@Override
public float pixelDensity() {
return (float) events().size().density();
}
@Override
public int displayId() {
return WebDisplays.SCREEN;
}
/** The tab keeps the page's own title, "Incari Client", whatever the game names its window. */
@Override
public void setTitle(String title) {}
@Override
public void setIcon(List<IconImage> sizes) {
// The page's favicon belongs to the host page, not the game.
}
@Override
public void setMaximumSize(int maxWidth, int maxHeight) {
// The page decides the canvas size.
}
@Override
public boolean setWindowed(int newX, int newY, int newWidth, int newHeight) {
if (isFullscreen()) {
events().fullscreenRequested(false);
Dom.requestFullscreen(canvas, false);
}
// The page decides the canvas's size, not the game: report the size it has, which the
// game then takes as its window size.
events().forceSizeReport();
return true;
}
@Override
public boolean setFullscreen(@Nullable DisplayMode exclusiveMode) {
if (isFullscreen()) {
return true;
}
if (!Dom.canEnterFullscreen()) {
// Refusing now, rather than letting the page refuse later, lets the game turn its
// fullscreen option back off instead of asking again every frame.
return false;
}
// A page can't change the display mode; fullscreen is always "borderless".
events().fullscreenRequested(true);
Dom.requestFullscreen(canvas, true);
return true;
}
/**
* Whether the canvas is fullscreen, or about to be: the page answers a request only later,
* and the game checks right after asking.
*/
@Override
public boolean isFullscreen() {
Boolean pending = events().pendingFullscreen();
return pending != null ? pending : Dom.isFullscreen();
}
@Override
public boolean isExclusiveFullscreen() {
return false;
}
@Override
public void setSystemBehavior(SystemBehavior behavior, boolean enabled) {
// Desktop behaviors; nothing to do in a page.
}
@Override
public @Nullable DisplayMode currentDisplayMode() {
return WebDisplays.screenMode();
}
@Override
public void setRelativeMouseMode(boolean enabled) {
events().setRelativeMouseMode(enabled);
// The game holds the mouse while the player plays: that's when closing the tab by
// accident loses the most.
mouseHeld = enabled;
updateLeaveGuard();
}
/**
* In a world, closing the tab loses what wasn't saved (an inventory or chat open doesn't pause
* singleplayer, so doesn't save it), and Ctrl+W, sprinting forward, is the browser's close-tab
* shortcut outside fullscreen: the page asks first.
*/
@Override
public void setLeaveWarning(boolean warn) {
inWorld = warn;
updateLeaveGuard();
}
private void updateLeaveGuard() {
boolean guard = mouseHeld || inWorld;
if (guard != guarded) {
guarded = guard;
Dom.setLeaveGuard(canvas, guard);
}
}
@Override
public void warpMouse(double x, double y) {
// Pages can't move the cursor.
}
@Override
public CursorPosition cursorPosition() {
// Where the mouse last moved over the page. A page can't see the cursor outside itself.
return new CursorPosition(events().cursorX(), events().cursorY());
}
@Override
public void setCursor(SystemCursor cursor) {
Dom.setCursor(
canvas,
switch (cursor) {
case DEFAULT, ARROW -> "default";
case TEXT -> "text";
case CROSSHAIR -> "crosshair";
case POINTING_HAND -> "pointer";
case RESIZE_NS -> "ns-resize";
case RESIZE_EW -> "ew-resize";
case RESIZE_ALL -> "move";
case NOT_ALLOWED -> "not-allowed";
});
}
/**
* Typed text comes from key events; input methods, dead keys and touchscreen keyboards need a
* text element with the focus, which the page's text input element is while this is on.
*/
@Override
public void startTextInput() {
events().setTextInput(true);
Dom.setTextInput(canvas, true);
}
@Override
public void stopTextInput() {
events().setTextInput(false);
Dom.setTextInput(canvas, false);
}
@Override
public void setTextInputArea(int areaX, int areaY, int areaWidth, int areaHeight) {
// Window coordinates are the canvas's CSS pixels already.
Dom.setTextInputArea(canvas, areaX, areaY, areaWidth, areaHeight);
}
@Override
public void setQuitShortcutEnabled(boolean enabled) {}
@Override
public void close() {}
}
@@ -0,0 +1,914 @@
package incari.platform.web;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Every JavaScript snippet the web platform calls (through TeaVM's interop), in one file so the
* browser surface is easy to audit.
*
* <p>Runs on the page's only thread. Nothing here blocks except {@link #nextAnimationFrameOrMessage}, which
* suspends the calling coroutine and lets the page run.
*/
final class Dom {
/** Frames the frame monitor keeps: about four and a half minutes at 60 frames a second. */
static final int FRAME_ROWS = 16384;
/** Numbers per frame in the frame monitor's table ({@link #installFrameMonitor}). */
static final int FRAME_COLUMNS = 16;
private Dom() {}
// --- Time and frames -------------------------------------------------------------------
@JSBody(script = "return performance.now();")
static native double nowMillis();
/**
* Suspends until the browser's next animation frame (where the page draws and handles input),
* or until a WebSocket message arrives first ({@code window.__incariNetWake}, below).
*
* @return true for the frame; false for a message, and the frame is still to come: the next
* call waits for that same frame
*/
@Async
static native Boolean nextAnimationFrameOrMessage();
private static void nextAnimationFrameOrMessage(AsyncCallback<Boolean> callback) {
waitForFrame(frame -> callback.complete(frame));
}
@JSFunctor
interface FrameCallback extends JSObject {
void run();
}
/** Called with true for the animation frame, false for a WebSocket message that came first. */
@JSFunctor
interface FrameOrMessageCallback extends JSObject {
void run(boolean frame);
}
/**
* Calls back on the next animation frame, or after a quarter second if none comes: hidden tabs
* get no animation frames, and the game would stop. A hidden page's own timers are held to a
* wake-up a second, then a minute, too few to answer a server's keep-alives, so while hidden the
* quarter second is timed by the page's worker timer ({@code window.incariTimer}, app-web's
* {@code wakeups.ts}) where there is one.
*
* <p>A WebSocket message that comes first calls back with false instead ({@code
* window.__incariNetWake}); the frame stays requested, and a frame that came while nobody waited
* is answered at once.
*/
@JSBody(
params = "callback",
script = "var w = window.__incariFrameWait;"
+ "if (!w) { w = window.__incariFrameWait = { pending: false, fired: false, waiter: null };"
// The render thread hands the message to its connection's thread and waits
// again; that thread (and what it wakes in turn) then runs at once, not on a
// timer the browser runs late in play (incariRunWoken, app-web's wakeups.ts).
+ " window.__incariNetWake = function() { var c = w.waiter; if (!c) return; w.waiter = null;"
+ " var run = window.incariRunWoken; if (run) run(function() { c(false); }); else c(false); }; }"
+ "function frame(c) { var frames = window.__incariFrames; if (frames) frames.begin();"
+ " c(true); if (frames) frames.returned(); }"
+ "if (w.fired) { w.fired = false; Promise.resolve().then(function() { frame(callback); }); return; }"
+ "w.waiter = callback;"
+ "if (w.pending) return;"
+ "w.pending = true; var done = false, cancel = null;"
+ "function run() { if (done) return; done = true; if (cancel) cancel(); w.pending = false;"
+ " var c = w.waiter; w.waiter = null; if (c) frame(c); else w.fired = true; }"
+ "requestAnimationFrame(run); var fb = window.incariFallback, tm = fb ? 0 : setTimeout(run, 250);"
+ "cancel = fb ? fb(run, 250) : function() { clearTimeout(tm); };")
private static native void waitForFrame(FrameOrMessageCallback callback);
/**
* Installs the frame monitor, {@code window.__incariFrames}: how long each game frame takes
* (animation frame to {@link #frameEnded}), and whether the render thread suspended mid-frame.
* That's a blocking wait (a lock, a {@code join}, a {@code sleep}); it should only suspend
* between frames (the threading audit, ADR 0015). The frame runs inside the animation frame
* callback, so a callback that returns before the frame ends means the thread waited.
*
* <p>Every {@code wait} in the web build goes through web-classlib's {@code Waits}, which adds
* the render thread's waits to its frame's {@code waitMillis}. A frame that waited 50 ms or more
* in all counts in {@code waitStalls}, the threading audit's gate. Frames that waited, and
* frames over 50 ms (waiting or not), are counted with the longest of each; checks read these.
*
* <p>It also keeps the last {@value #FRAME_ROWS} frames for the benchmark runner, as rows of
* {@value #FRAME_COLUMNS} numbers:
*
* <ol>
* <li>when the frame ended, the time since the previous one ended, how long it took from its
* animation frame, and whether it waited;
* <li>the game's measurements ({@link #frameSample}): tick, extract, render and GPU
* milliseconds, draw calls, terrain draw calls and sections, the mesh queue, and the
* module's linear memory in megabytes;
* <li>the page's heap in megabytes;
* <li>the background pool's milliseconds since the previous frame ({@link IdleSlots}), and its
* latest run past a slot's deadline (for finding stutters).
* </ol>
*
* <p>{@code rows(from)} returns the kept rows from frame {@code from} on, flat; {@code count} is
* the next row's number. {@code marks} holds start-up's marks ({@link #mark}) in milliseconds
* since navigation start. Heap drops over a megabyte between frames count as garbage collections
* ({@code collections}), exact only with Chrome's {@code --enable-precise-memory-info}, which
* the runner turns on.
*/
@JSBody(
script = "window.incariFallback = function(run, delay) { var t = window.incariTimer;"
+ " if (document.hidden && t) { var id = t.set(run, delay); return function() { t.clear(id); }; }"
+ " var timer = setTimeout(run, delay); return function() { clearTimeout(timer); }; };"
+ "var f = { start: 0, ended: true, waited: false, frames: 0, waiting: 0, slow: 0, slowWaiting: 0,"
+ " worst: 0, worstWaiting: 0, waitMillis: 0, waitStalls: 0, worstWait: 0, last: null,"
+ " columns: " + FRAME_COLUMNS + ", capacity: " + FRAME_ROWS + ", count: 0, lastEnd: 0,"
+ " sample: null, marks: {}, heap: 0, collections: 0, idle: 0, late: 0 };"
+ "f.table = new Float64Array(f.capacity * f.columns);"
+ "f.begin = function() { f.start = performance.now(); f.ended = false; f.waited = false; f.waitMillis = 0; };"
+ "f.returned = function() { if (f.ended) return; f.waited = true;"
+ " var slots = window.__incariIdleSlots || []; for (var i = 0; i < slots.length; i++) slots[i].schedule(); };"
+ "f.heapMegabytes = function() { var m = performance.memory; return m ? m.usedJSHeapSize / 1048576 : NaN; };"
+ "f.record = function(now, took) { var heap = f.heapMegabytes();"
+ " if (heap < f.heap - 1) f.collections++; f.heap = heap;"
+ " var row = (f.count % f.capacity) * f.columns, t = f.table, s = f.sample;"
+ " t[row] = now; t[row + 1] = f.lastEnd ? now - f.lastEnd : NaN; t[row + 2] = took; t[row + 3] = f.waited ? 1 : 0;"
+ " for (var i = 0; i < 8; i++) t[row + 4 + i] = s ? s[i] : NaN;"
+ " t[row + 12] = heap; t[row + 13] = s ? s[8] : NaN; t[row + 14] = f.idle; t[row + 15] = f.late;"
+ " f.idle = 0; f.late = 0; f.sample = null; f.lastEnd = now; f.count++; };"
+ "f.rows = function(from) { var first = Math.max(from, f.count - f.capacity, 0), out = [];"
+ " for (var n = first; n < f.count; n++) { var row = (n % f.capacity) * f.columns;"
+ " for (var i = 0; i < f.columns; i++) out.push(f.table[row + i]); } return out; };"
+ "f.end = function() { f.ended = true; f.frames++; var now = performance.now();"
+ " if (!f.start) { f.record(now, NaN); return 0; }"
+ " f.record(now, now - f.start);"
+ " if (f.waited) f.waiting++;"
+ " if (f.waitMillis > f.worstWait) f.worstWait = f.waitMillis;"
+ " if (f.waitMillis >= 50) f.waitStalls++;"
+ " var took = now - f.start; f.start = 0; if (took <= 50) return 0;"
+ " f.slow++; f.worst = Math.max(f.worst, took);"
+ " if (f.waited) { f.slowWaiting++; f.worstWaiting = Math.max(f.worstWaiting, took); }"
+ " f.last = { took: took, waited: f.waited }; return f.waited ? -took : took; };"
+ "window.__incariFrames = f;")
static native void installFrameMonitor();
/**
* Marks the end of the game's frame, just before it waits for the next one. Returns 0 for a
* frame of 50 ms or less, else its length, negative if the render thread waited in it.
*/
@JSBody(script = "var f = window.__incariFrames; return f ? f.end() : 0;")
static native double frameEnded();
/** Marks an animation frame the game skips (a frame limit) as between frames, not part of one. */
@JSBody(script = "var f = window.__incariFrames; if (f) { f.ended = true; f.start = 0; f.waited = false; }")
static native void frameSkipped();
/** Tells the host page's loader (app-web's {@code boot.ts}) that the game has drawn its first frame. */
@JSBody(
script =
"var loader = window.incariLoader; if (loader) loader.done();"
+ "var f = window.__incariFrames; if (f && !f.marks.firstFrame) f.marks.firstFrame = performance.now();")
static native void loaderDone();
/**
* The game's measurements of the frame about to end, for the frame monitor's table.
* Numbers only: the monitor copies them into its row when the frame ends.
*/
@JSBody(
params = {
"tick",
"extract",
"render",
"gpu",
"draws",
"terrainDraws",
"terrainSections",
"meshQueue",
"linear"
},
script = "var f = window.__incariFrames;"
+ "if (f) f.sample = [tick, extract, render, gpu, draws, terrainDraws, terrainSections, meshQueue,"
+ " linear / 1048576];")
static native void frameSample(
double tick,
double extract,
double render,
double gpu,
int draws,
int terrainDraws,
int terrainSections,
int meshQueue,
double linear);
/** Records a start-up mark's time the first time it's reached ({@code marks}). */
@JSBody(
params = "name",
script = "var f = window.__incariFrames; if (f && !(name in f.marks)) f.marks[name] = performance.now();")
static native void mark(String name);
/** The page's JavaScript heap in bytes, or -1 where the browser doesn't say (only Chrome does). */
@JSBody(script = "var m = performance.memory; return m ? m.usedJSHeapSize : -1;")
static native double heapUsed();
/** The most the page's JavaScript heap may grow to, or -1 where the browser doesn't say. */
@JSBody(script = "var m = performance.memory; return m ? m.jsHeapSizeLimit : -1;")
static native double heapLimit();
/** The size of the {@code ArrayBuffer} under {@code view}: for a direct buffer's view, the module's linear memory. */
@JSBody(params = "view", script = "return view.buffer.byteLength;")
static native double backingBytes(Int8Array view);
/** Garbage collections the frame monitor has seen as drops in the heap. */
@JSBody(script = "var f = window.__incariFrames; return f ? f.collections : -1;")
static native double collections();
/** Frames over 50 ms since the page started, and those of them in which the render thread waited. */
@JSBody(
script =
"var f = window.__incariFrames; return f ? f.waiting + ' waited (' + f.waitStalls + ' for 50 ms or more, longest '"
+ " + Math.round(f.worstWait) + ' ms); ' + f.slow + ' over 50 ms (' + f.slowWaiting"
+ " + ' waiting, longest ' + Math.round(f.worstWaiting) + ' ms), longest ' + Math.round(f.worst) + ' ms' : '';")
static native String frameStats();
/**
* The background pool's slots ({@link IdleTimeExecutor}): after an animation frame, once the
* game's frame (which runs inside its own animation frame callback) is done and the page has
* drawn it, until shortly before the next frame is due.
*
* <p>The slot starts from a message posted in the animation frame callback, not the callback
* itself: callbacks run before the page draws, so work there would hold the frame back. A slot
* ends 2 ms before the next frame is due (the display's interval, measured) and lasts at least
* 4 ms, so the pool moves even when the game's frames run long.
*
* <p>A render thread suspended mid-frame may be waiting for a task here (a {@code join}), so
* once it has waited 8 ms, slots come without a frame, 4 ms at a time, until its frame ends: the
* wait lasts about as long as the work, not until the next frame. Short waits (a sound handed to
* the sound thread) end first and never start a task. In a hidden tab a slot comes after a
* quarter second at the latest, as the game's frames do.
*/
static final class IdleSlots implements IdleTimeExecutor.Slots {
private final JSObject slot = createIdleSlot();
@Override
public void arm() {
armIdleSlot(slot);
}
@Override
public double await() {
awaitIdleSlot(slot);
return idleSlotDeadline(slot);
}
@Override
public double now() {
return nowMillis();
}
@Override
public void worked(double millis, double pastDeadline) {
poolWorked(millis, pastDeadline);
}
}
/**
* The least time a background-pool slot gets while the pool has work, in milliseconds (ADR 0035):
* the time before the next frame, but never less than this.
*/
@JSBody(params = "millis", script = "window.__incariPoolFloor = millis;")
static native void setPoolFloor(double millis);
/** The frame table's pool columns: the pool's work since the last frame, and its worst lateness. */
@JSBody(
params = {"millis", "late"},
script = "var f = window.__incariFrames; if (f) { f.idle += millis; f.late = Math.max(f.late, late); }")
private static native void poolWorked(double millis, double late);
@JSBody(
script =
"var s = { callback: null, armed: false, scheduled: false, urgentPosted: false, urgentFiring: false, helped: false,"
+ " frame: 0,"
+ " previous: 0, interval: 1000 / 60, deadline: 0 };"
// The render thread suspended mid-frame (the frame monitor saw it): it may be
// waiting for a task here, so the pool runs soon, a few milliseconds at a time.
+ "function blocked() { var f = window.__incariFrames; return !!f && !f.ended && f.waited; }"
+ "var channel = new MessageChannel();"
+ "channel.port1.onmessage = function() { var urgent = s.urgentFiring; s.urgentFiring = false;"
// A slot that falls while the render thread is suspended mid-frame takes the
// delayed path below: the render thread may be about to resume, and a task
// started now would keep it waiting for as long as the task runs.
+ " if (!urgent && blocked()) { s.scheduled = false; s.schedule(); return; }"
+ " s.urgentPosted = false; var callback = s.callback;"
+ " if (!callback) return; s.callback = null; s.scheduled = false; s.armed = false;"
+ " var now = performance.now();"
// Until shortly before the next frame; a slot that starts late (after a long
// frame) still gets a moment, and its first task or part runs whatever the time.
// While work is queued, a slot is at least the pool's floor (ADR 0035): a frame
// that overran its interval would otherwise leave the pool 1 ms, and terrain
// after a teleport took minutes on a slow device.
+ " s.deadline = blocked() ? now + 4"
+ " : Math.max(s.frame + s.interval - 2, now + (window.__incariPoolFloor || 1)); callback(); };"
+ "s.schedule = function() { if (!s.armed || !s.callback) return;"
// Not at once: most waits (a sound handed to the sound thread) end within a
// couple of timer turns, and a task started meanwhile would hold the render
// thread for as long as it runs. A timer, so a render thread just woken (by a
// timer too, queued earlier) always runs first.
+ " if (blocked()) { if (!s.urgentPosted) { s.urgentPosted = true; var first = !s.helped; s.helped = true;"
+ " setTimeout(function() { if (blocked()) { s.urgentFiring = true; channel.port2.postMessage(0); }"
+ " else { s.urgentPosted = false; s.schedule(); } },"
+ " first ? 8 : 1); } return; }"
+ " s.helped = false;"
+ " if (s.scheduled) return; s.scheduled = true;"
+ " var done = false, cancel = null;"
+ " function run(time) { if (done) return; done = true; if (cancel) cancel();"
+ " if (typeof time === 'number') {"
// The display's interval, from the steps between animation frames. Only a step
// near one interval counts: the pool asks for a slot only when it has work, so
// it often skips frames, and a two-frame step taken as the interval would let
// each slot run into the next frame's time (and the frames it delays then
// stretch the steps further). A faster display is learned from its shorter steps.
+ " var step = time - s.previous; if (s.previous && step > 4 && step < s.interval * 1.4)"
+ " s.interval += (step - s.interval) * 0.1;"
+ " s.previous = time; s.frame = time; } else { s.frame = performance.now(); }"
+ " channel.port2.postMessage(0); }"
+ " requestAnimationFrame(run); var fb = window.incariFallback, tm = fb ? 0 : setTimeout(run, 250);"
+ " cancel = fb ? fb(run, 250) : function() { clearTimeout(tm); }; };"
+ "(window.__incariIdleSlots = window.__incariIdleSlots || []).push(s);"
+ "return s;")
private static native JSObject createIdleSlot();
@JSBody(params = "slot", script = "slot.armed = true; slot.schedule();")
private static native void armIdleSlot(JSObject slot);
@JSBody(params = "slot", script = "return slot.deadline;")
private static native double idleSlotDeadline(JSObject slot);
/** Suspends the calling coroutine until the slot's next start (see {@link IdleSlots}). */
@Async
private static native Void awaitIdleSlot(JSObject slot);
private static void awaitIdleSlot(JSObject slot, AsyncCallback<Void> callback) {
setIdleSlotCallback(slot, () -> callback.complete(null));
}
@JSBody(
params = {"slot", "callback"},
script = "slot.callback = callback; slot.schedule();")
private static native void setIdleSlotCallback(JSObject slot, FrameCallback callback);
// --- Screen and canvas ------------------------------------------------------------------
@JSBody(script = "return window.devicePixelRatio || 1;")
static native double devicePixelRatio();
@JSBody(script = "return screen.width;")
static native int screenWidth();
@JSBody(script = "return screen.height;")
static native int screenHeight();
/** The game's canvas: the page's element with this id, created full-window if it's missing. */
@JSBody(
params = "id",
script = "var c = document.getElementById(id);"
+ "if (!c) { c = document.createElement('canvas'); c.id = id;"
+ " c.style.width = '100vw'; c.style.height = '100vh'; c.style.display = 'block';"
+ " document.body.style.margin = '0'; document.body.appendChild(c); }"
+ "c.tabIndex = 0; return c;")
static native JSObject canvas(String id);
/**
* The canvas's CSS width, or the window's while the canvas isn't laid out yet (it's then
* 0 wide). The page must size the canvas with CSS: its backing store is set to the CSS size
* times the density, and a canvas without a CSS size would grow with it.
*/
@JSBody(params = "canvas", script = "return canvas.clientWidth || window.innerWidth;")
static native int cssWidth(JSObject canvas);
@JSBody(params = "canvas", script = "return canvas.clientHeight || window.innerHeight;")
static native int cssHeight(JSObject canvas);
/** The single HTML file plays from the disk; otherwise the page's build says JSPI or not. */
@JSBody(
script = "if (location.protocol === 'file:') return 'html';"
+ "var build = window.incariBuild && window.incariBuild.program;"
+ "return build && build.jspi ? 'fast' : 'compatible';")
static native String buildKind();
@JSBody(
params = {"canvas", "width", "height"},
script = "if (canvas.width !== width) canvas.width = width;"
+ "if (canvas.height !== height) canvas.height = height;")
static native void setCanvasSize(JSObject canvas, int width, int height);
@JSBody(
params = {"canvas", "cursor"},
script = "canvas.style.cursor = cursor;")
static native void setCursor(JSObject canvas, String cursor);
@JSBody(script = "return !!document.fullscreenElement;")
static native boolean isFullscreen();
/**
* Whether a fullscreen request would be granted now: the page allows fullscreen and the player
* just pressed a key or clicked. Browsers without the User Activation API are assumed to allow
* it.
*/
@JSBody(
script = "return !!document.fullscreenEnabled"
+ " && (!navigator.userActivation || navigator.userActivation.isActive);")
static native boolean canEnterFullscreen();
/**
* Enters or leaves fullscreen. The answer comes as a "fullscreen" event: from the page's
* fullscreenchange, or from here when the request is refused.
*/
@JSBody(
params = {"canvas", "enter"},
script = "function refused() { var s = canvas.__incariSink;"
+ " if (s) s('fullscreen', '', '', document.fullscreenElement ? 1 : 0, 0, 0, 0, 0, 0); }"
+ "try { var p = null;"
+ " if (enter) { if (canvas.requestFullscreen) p = canvas.requestFullscreen(); }"
+ " else if (document.fullscreenElement) { p = document.exitFullscreen(); }"
+ " if (p && p.catch) p.catch(refused); else if (!p) refused(); } catch (e) { refused(); }")
static native void requestFullscreen(JSObject canvas, boolean enter);
/**
* Pointer Lock with unadjusted movement where offered: raw mouse, no OS acceleration. Browsers
* that don't offer it refuse the option, and get a plain request.
*/
@JSBody(
params = {"canvas", "lock"},
script =
"function ignore() {}"
+ "try { if (lock) { var p = canvas.requestPointerLock({ unadjustedMovement: true });"
+ " if (p && p.catch) p.catch(function(err) { if (err && err.name === 'NotSupportedError') {"
+ " var q = canvas.requestPointerLock(); if (q && q.catch) q.catch(ignore); } }); }"
+ " else if (document.pointerLockElement === canvas) { document.exitPointerLock(); } } catch (e) {}")
static native void setPointerLock(JSObject canvas, boolean lock);
/**
* Whether the browser runs on macOS, where keys pressed while Command is held never report
* their release.
*/
@JSBody(
script =
"var p = (navigator.userAgentData && navigator.userAgentData.platform) || navigator.platform || '';"
+ "return /^mac/i.test(p);")
static native boolean isMac();
/**
* Whether F then a digit types a function key ({@code DomEventQueue}): on ChromeOS, whose
* keyboards have no function row the game can use, and nowhere else, where it would hold back
* F (swap hands) until it's released. {@code ?fchord=on} or {@code off} in the page's address
* overrides it.
*/
@JSBody(
script = "var q = null; try { q = new URLSearchParams(location.search).get('fchord'); } catch (e) {}"
+ "if (q === 'on') return true; if (q === 'off') return false;"
+ "var p = (navigator.userAgentData && navigator.userAgentData.platform) || '';"
+ "return /^chrome ?os$/i.test(p) || /\\bCrOS\\b/.test(navigator.userAgent || '');")
static native boolean functionKeyChords();
// --- Shell -------------------------------------------------------------------------------
@JSBody(params = "url", script = "window.open(url, '_blank', 'noopener');")
static native void openUrl(String url);
/**
* Puts text on the clipboard without waiting: the async Clipboard API, or where it's missing
* (pages served over plain http from another machine) or refuses, a copy command. Both need
* the page focused and a recent key press or click, which the game's copy shortcuts give.
*/
@JSBody(
params = "text",
script = "function viaCopyEvent() { function onCopy(e) { e.clipboardData.setData('text/plain', text);"
+ " e.preventDefault(); }"
+ " document.addEventListener('copy', onCopy, true);"
+ " try { document.execCommand('copy'); } catch (e) {}"
+ " document.removeEventListener('copy', onCopy, true); }"
+ "if (navigator.clipboard && navigator.clipboard.writeText) {"
+ " navigator.clipboard.writeText(text).catch(viaCopyEvent); } else { viaCopyEvent(); }")
static native void writeClipboard(String text);
/**
* Puts a PNG on the clipboard without waiting, through the async Clipboard API.
*
* @return false where the browser has no image clipboard (no {@code ClipboardItem})
*/
@JSBody(
params = "data",
script = "if (!navigator.clipboard || !navigator.clipboard.write || typeof ClipboardItem === 'undefined') {"
+ " return false; }"
+ "var blob = new Blob([data], {type: 'image/png'});"
+ "navigator.clipboard.write([new ClipboardItem({'image/png': blob})]).catch(function(e) {"
+ " console.warn('[Incari] Couldn\\'t copy the image: ' + e); });"
+ "return true;")
static native boolean writeClipboardImage(Int8Array data);
@JSBody(params = "message", script = "window.alert(message);")
static native void alert(String message);
@JSBody(params = "message", script = "return window.confirm(message);")
static native boolean confirm(String message);
@JSBody(params = "message", script = "console.log(message);")
static native void consoleLog(String message);
@JSBody(params = "message", script = "console.warn(message);")
static native void consoleWarn(String message);
@JSBody(params = "message", script = "console.error(message);")
static native void consoleError(String message);
@JSBody(script = "return navigator.userAgent;")
static native String userAgent();
// --- Events --------------------------------------------------------------------------------
/**
* Decides, while a key event is being dispatched, whether the page cancels its default action
* ({@link DomEventQueue#consumesKey}). The one call from a DOM listener into Java: it must be a
* pure function of its arguments. TeaVM compiles any Java that can reach a suspension point (in
* this program, most collection and {@code Object} methods) as a coroutine, and a coroutine
* can't start from a JavaScript callback, where there's no Java thread to suspend.
*/
@JSFunctor
interface KeyPolicy extends JSObject {
boolean consumes(String code, String key, int flags);
}
/*
* Events wait in a JavaScript array on the canvas, nine slots each, until the game's next poll
* reads them on its own thread ({@link WebPlatform#pollEvents}): see KeyPolicy for why the
* listeners don't call Java. The slots, which {@link DomEventQueue#event} reads:
* type, text, key, a, b, c, d, e, flags
* "keydown", "keyup": text {@code code}, key {@code key}, a repeat, b composing (1/0)
* "move": a, b the position in CSS pixels from the canvas's top left (may be outside it);
* c, d {@code movementX/Y}
* "down", "up": a the DOM button (0 left, 1 middle, 2 right, 3 back, 4 forward)
* "wheel": a, b {@code deltaX/Y}; c {@code deltaMode}; d, e the legacy {@code wheelDeltaX/Y},
* 0 where missing
* "resize": a, b the CSS content size; c, d the device-pixel size, 0 where the browser can't
* tell; e {@code devicePixelRatio}
* "focus", "blur", "enter" (the cursor entered or left the page), "visibility" (a 1 if hidden),
* "fullscreen" (a 1 if fullscreen), "lock" (a 1 if the canvas holds Pointer Lock),
* "lockerror", "paste" (text the pasted text)
* "compose": text an input method's uncommitted composition ("" when it ends), a the cursor
* in it, b the length of the selection in it (listenTextInput)
* "commit": text committed text that came without a key event (listenTextInput)
* "keymap": text the keyboard layout, a "<code> <character>" line per key (watchLayout)
* "drop": a the id of the files in canvas.__incariDrops (listenDrops); WebPlatform copies
* them into the file system and hands the queue their paths, a line each, as text
* flags: the modifier flags of key, mouse and wheel events (DomEventQueue.DOM_*).
*/
/** Slots per queued event. */
static final int EVENT_SLOTS = 9;
@JSBody(params = "canvas", script = "var q = canvas.__incariEvents; return q ? q.length : 0;")
static native int queuedSlots(JSObject canvas);
@JSBody(
params = {"canvas", "index"},
script = "return String(canvas.__incariEvents[index]);")
static native String queuedString(JSObject canvas, int index);
@JSBody(
params = {"canvas", "index"},
script = "return +canvas.__incariEvents[index];")
static native double queuedNumber(JSObject canvas, int index);
@JSBody(params = "canvas", script = "var q = canvas.__incariEvents; if (q) q.length = 0;")
static native void clearQueued(JSObject canvas);
/**
* Installs the page listeners once. Keys, mouse motion and releases are listened for on the
* window, so a drag that leaves the canvas keeps reporting and always gets its release; presses
* and the wheel only on the canvas.
*/
@JSBody(
params = {"canvas", "policy"},
script = "var queue = []; var pressed = 0; canvas.__incariEvents = queue;\n"
// Queues an event and says whether to cancel its default action: keys by the
// policy, presses on the canvas and their releases, and the wheel.
+ "function sink(type, text, key, a, b, c, d, e, f) {"
+ " queue.push(type, text, key, a, b, c, d, e, f);"
+ " switch (type) {"
+ " case 'keydown': case 'keyup': return !b && policy(text, key, f);"
+ " case 'down': if (a >= 0 && a < 30) { pressed |= 1 << a; return true; } return false;"
+ " case 'up': var bit = 1 << a; var was = (pressed & bit) !== 0; pressed &= ~bit; return was;"
+ " case 'wheel': return true;"
+ " } return false; }\n"
+ "canvas.__incariSink = sink;\n"
// The page may be closed with no game frame to come: what must happen then
// (singleplayer's server saving) is registered in window.__incariOnLeave by the
// channels (JsChannel) and run straight from these listeners, at most once a second.
+ "var lastLeave = 0;"
+ "function leaving() { var now = Date.now(); if (now - lastLeave < 1000) return; lastLeave = now;"
+ " var hooks = window.__incariOnLeave || [];"
+ " for (var i = 0; i < hooks.length; i++) { try { hooks[i](); } catch (err) {} } }\n"
+ "function flags(e) { var m = e.getModifierState ? function(k) { return e.getModifierState(k); }"
+ " : function() { return false; };"
+ " return (e.shiftKey ? 1 : 0) | (e.ctrlKey ? 2 : 0) | (e.altKey ? 4 : 0) | (e.metaKey ? 8 : 0)"
+ " | (m('CapsLock') ? 16 : 0) | (m('NumLock') ? 32 : 0) | (m('AltGraph') ? 64 : 0); }\n"
// Keys are the game's while the game has focus: the canvas, its text input
// element, or nothing in particular (the body). Whatever else the host page
// shows beside the game (a text field, a button) keeps its keys, and their
// default actions.
+ "function forPage(e) { var t = e.target; return !!t && t !== canvas && t !== canvas.__incariText"
+ " && t !== document.body && t !== document.documentElement && t !== document && t !== window; }\n"
+ "function key(type, e) { if (forPage(e)) return;"
+ " if (sink(type, e.code || '', e.key || '', e.repeat ? 1 : 0,"
+ " (e.isComposing || e.keyCode === 229) ? 1 : 0, 0, 0, 0, flags(e))) e.preventDefault(); }\n"
+ "window.addEventListener('keydown', function(e) { key('keydown', e); });\n"
+ "window.addEventListener('keyup', function(e) { key('keyup', e); });\n"
// Relative to the canvas's content box. Under Pointer Lock the position holds
// still and only movementX/Y count.
+ "window.addEventListener('mousemove', function(e) { var r = canvas.getBoundingClientRect();"
+ " sink('move', '', '', e.clientX - r.left - canvas.clientLeft, e.clientY - r.top - canvas.clientTop,"
+ " e.movementX || 0, e.movementY || 0, 0, flags(e)); });\n"
// A click focuses the game: its text input element while a text field wants
// typing (setTextInput), else the canvas. The press itself is cancelled below,
// which would otherwise have moved the focus.
+ "canvas.addEventListener('mousedown', function(e) {"
+ " var text = canvas.__incariTextOn && canvas.__incariText;"
+ " (text || canvas).focus({ preventScroll: true });"
+ " if (sink('down', '', '', e.button, 0, 0, 0, 0, flags(e))) e.preventDefault(); });\n"
+ "window.addEventListener('mouseup', function(e) {"
+ " if (sink('up', '', '', e.button, 0, 0, 0, 0, flags(e))) e.preventDefault(); });\n"
+ "canvas.addEventListener('wheel', function(e) {"
+ " if (sink('wheel', '', '', e.deltaX, e.deltaY, e.deltaMode, e.wheelDeltaX || 0, e.wheelDeltaY || 0,"
+ " flags(e))) e.preventDefault(); }, { passive: false });\n"
+ "canvas.addEventListener('contextmenu', function(e) { e.preventDefault(); });\n"
+ "document.documentElement.addEventListener('mouseenter', function() {"
+ " sink('enter', '', '', 0, 0, 0, 0, 0, 0); });\n"
+ "document.documentElement.addEventListener('mouseleave', function() {"
+ " sink('enter', '', '', 0, 0, 0, 0, 0, 0); });\n"
+ "window.addEventListener('focus', function() { sink('focus', '', '', 0, 0, 0, 0, 0, 0); });\n"
+ "window.addEventListener('blur', function() { sink('blur', '', '', 0, 0, 0, 0, 0, 0); });\n"
// Hiding the tab counts as losing focus (DomEventQueue); showing it again gives
// focus back only if the page has it, which no focus event may announce.
+ "document.addEventListener('visibilitychange', function() {"
+ " if (document.hidden) leaving();"
+ " sink('visibility', '', '', document.hidden ? 1 : 0, 0, 0, 0, 0, 0);"
+ " if (!document.hidden && document.hasFocus && document.hasFocus())"
+ " sink('focus', '', '', 0, 0, 0, 0, 0, 0); });\n"
// Sizes: a ResizeObserver sees every change of the canvas's box, from window
// resizes, fullscreen, page layout and zoom, and, where the browser has
// device-pixel-content-box, the exact device-pixel size (so moving to a denser
// display counts too). A media query on the density and the window's resize
// cover browsers without it.
+ "function measure() { var d = window.devicePixelRatio || 1;"
+ " sink('resize', '', '', canvas.clientWidth, canvas.clientHeight, 0, 0, d, 0); }\n"
+ "if (window.ResizeObserver) {"
+ " var observer = new ResizeObserver(function(entries) { var en = entries[entries.length - 1];"
+ " var box = en.contentBoxSize && en.contentBoxSize[0];"
+ " var dev = en.devicePixelContentBoxSize && en.devicePixelContentBoxSize[0];"
+ " sink('resize', '', '', box ? box.inlineSize : en.contentRect.width,"
+ " box ? box.blockSize : en.contentRect.height, dev ? dev.inlineSize : 0, dev ? dev.blockSize : 0,"
+ " window.devicePixelRatio || 1, 0); });"
+ " try { observer.observe(canvas, { box: 'device-pixel-content-box' }); }"
+ " catch (err) { observer.observe(canvas); } }\n"
+ "function watchDensity() { if (!window.matchMedia) return;"
+ " var query = window.matchMedia('(resolution: ' + (window.devicePixelRatio || 1) + 'dppx)');"
+ " var changed = function() { query.removeEventListener('change', changed); measure(); watchDensity(); };"
+ " query.addEventListener('change', changed); }\n"
+ "watchDensity();\n"
+ "window.addEventListener('resize', measure);\n"
// In fullscreen the page can have the shortcuts browsers otherwise keep
// (Keyboard Lock, Chromium only): Ctrl+W, Ctrl+T, Ctrl+N and Ctrl+Q are
// sprinting while walking, chatting or dropping a stack, and Ctrl+1-9 are the
// hotbar while sprinting. Escape too, so it pauses the game instead of leaving
// fullscreen; holding it still leaves. Tab isn't locked, so Alt+Tab still
// switches windows.
+ "var locked = ['Escape', 'KeyW', 'KeyT', 'KeyN', 'KeyQ'];"
+ "for (var digit = 1; digit <= 9; digit++) locked.push('Digit' + digit);\n"
+ "document.addEventListener('fullscreenchange', function() {"
+ " var kb = navigator.keyboard;"
+ " if (kb && kb.lock) { if (document.fullscreenElement === canvas) {"
+ " var p = kb.lock(locked); if (p && p.catch) p.catch(function() {}); } else { kb.unlock(); } }"
+ " sink('fullscreen', '', '', document.fullscreenElement ? 1 : 0, 0, 0, 0, 0, 0); });\n"
// The clipboard's text comes with the paste event Ctrl+V fires, before the game
// handles the key (DomEventQueue). Cancelled on the game's own elements, so it
// isn't also pasted into the text input element.
+ "document.addEventListener('paste', function(e) {"
+ " var t = e.clipboardData ? e.clipboardData.getData('text') : '';"
+ " if (e.target === canvas || e.target === canvas.__incariText) e.preventDefault();"
+ " sink('paste', t || '', '', 0, 0, 0, 0, 0, 0); });\n"
// Closing the tab by accident while playing (Ctrl+W is sprint and walk) asks
// first. Only while the game holds the mouse (setLeaveGuard): a browser asks
// only after the player has used the page anyway.
+ "window.addEventListener('beforeunload', function(e) { leaving();"
+ " if (canvas.__incariGuard) { e.preventDefault(); e.returnValue = ''; } });\n"
+ "window.addEventListener('pagehide', function() { leaving(); });\n"
+ "document.addEventListener('pointerlockchange', function() {"
+ " sink('lock', '', '', document.pointerLockElement === canvas ? 1 : 0, 0, 0, 0, 0, 0); });\n"
+ "document.addEventListener('pointerlockerror', function() {"
+ " sink('lockerror', '', '', 0, 0, 0, 0, 0, 0); });\n"
// The state the page starts in, which no event will announce.
+ "if (document.hasFocus && !document.hasFocus()) sink('blur', '', '', 0, 0, 0, 0, 0, 0);\n"
+ "if (document.hidden) sink('visibility', '', '', 1, 0, 0, 0, 0, 0);")
static native void listen(JSObject canvas, KeyPolicy policy);
/**
* Whether a page unload asks the player first (the "leave site?" dialog): on while the game
* holds the mouse, so a stray Ctrl+W doesn't close a game in progress.
*/
@JSBody(
params = {"canvas", "guard"},
script = "canvas.__incariGuard = guard;")
static native void setLeaveGuard(JSObject canvas, boolean guard);
// --- Text input ------------------------------------------------------------------------------
/**
* Adds the game's text input element: an invisible textarea beside the canvas that has the
* focus while a text field wants typing. A canvas can't host an input method (Chinese,
* Japanese, Korean), a dead key's composition or a touchscreen's keyboard; a text element can.
* Plain typing still comes from key events, which are cancelled, so they never reach the
* textarea; only what an input method composes does, and is reported from its events.
* Installed once, after {@link #listen}.
*/
@JSBody(
params = "canvas",
script = "var sink = canvas.__incariSink;"
+ "var text = document.createElement('textarea');"
+ "text.id = canvas.id + '-text';"
+ "text.setAttribute('aria-label', 'Game text input');"
+ "text.setAttribute('autocomplete', 'off'); text.setAttribute('autocorrect', 'off');"
+ "text.setAttribute('autocapitalize', 'off'); text.spellcheck = false; text.tabIndex = -1;"
// Invisible, out of the way of the mouse, and fixed, so focusing it never
// scrolls the page. setTextInputArea moves it over the text field, where an
// input method places its candidate list.
+ "text.style.cssText = 'position:fixed;left:0;top:0;width:1px;height:1px;opacity:0;"
+ "padding:0;border:0;margin:0;outline:none;resize:none;overflow:hidden;white-space:pre;"
+ "pointer-events:none;caret-color:transparent;z-index:-1;';"
+ "(canvas.parentNode || document.body).insertBefore(text, canvas.nextSibling);"
+ "canvas.__incariText = text;\n"
+ "function compose() { var start = text.selectionStart || 0;"
+ " sink('compose', text.value, '', start, (text.selectionEnd || start) - start, 0, 0, 0, 0); }\n"
+ "text.addEventListener('input', function(e) {"
+ " if (e.isComposing) { compose(); return; }"
// After compositionend some browsers report the commit again as an input.
+ " if (e.inputType === 'insertFromComposition' || e.inputType === 'deleteCompositionText') return;"
+ " if (text.value) sink('commit', text.value, '', 0, 0, 0, 0, 0, 0);"
+ " text.value = ''; });\n"
+ "text.addEventListener('compositionend', function(e) {"
+ " sink('commit', e.data || '', '', 0, 0, 0, 0, 0, 0); text.value = ''; });")
static native void listenTextInput(JSObject canvas);
/**
* Turns the text input element on or off. On, it takes the focus if the game has it; off, the
* focus goes back to the canvas, which ends any composition.
*/
@JSBody(
params = {"canvas", "on"},
script = "canvas.__incariTextOn = on; var text = canvas.__incariText; if (!text) return;"
+ "var active = document.activeElement;"
+ "if (on) { if (!active || active === canvas || active === document.body"
+ " || active === document.documentElement) text.focus({ preventScroll: true }); }"
+ "else { if (active === text) { text.blur(); canvas.focus({ preventScroll: true }); }"
+ " text.value = ''; }")
static native void setTextInput(JSObject canvas, boolean on);
/** Moves the text input element over the text being edited, in CSS pixels from the canvas. */
@JSBody(
params = {"canvas", "x", "y", "width", "height"},
script = "var text = canvas.__incariText; if (!text) return;"
+ "var r = canvas.getBoundingClientRect(); var s = text.style;"
+ "s.left = (r.left + x) + 'px'; s.top = (r.top + y) + 'px';"
+ "s.width = Math.max(1, width) + 'px'; s.height = Math.max(1, height) + 'px';"
+ "s.fontSize = Math.max(1, height) + 'px';")
static native void setTextInputArea(JSObject canvas, int x, int y, int width, int height);
// --- Keyboard layout ------------------------------------------------------------------------
/**
* Reads the player's keyboard layout with the Keyboard Map API (Chromium) now and whenever the
* page regains focus, and queues a "keymap" event when it differs from the last one. Browsers
* without the API report nothing, and the queue learns key names from typing instead.
*/
@JSBody(
params = "canvas",
script = "var sink = canvas.__incariSink; var last = null;"
+ "function read() { var kb = navigator.keyboard; if (!kb || !kb.getLayoutMap) return;"
// Refused in frames without permission, and while the page is hidden.
+ " kb.getLayoutMap().then(function(map) { var lines = [];"
+ " map.forEach(function(character, code) { lines.push(code + ' ' + character); });"
+ " var entries = lines.sort().join('\\n');"
+ " if (entries !== last) { last = entries; sink('keymap', entries, '', 0, 0, 0, 0, 0, 0); }"
+ " }, function() {}); }\n"
+ "read(); window.addEventListener('focus', read);")
static native void watchLayout(JSObject canvas);
// --- Dropped files ---------------------------------------------------------------------------
/**
* Takes files and folders dropped anywhere on the page (so the browser doesn't navigate away to
* show them): reads them all, folders recursively, keeps them in {@code canvas.__incariDrops}
* under a new id as a flat array (relative path, then an {@code Int8Array}, or null for a
* folder), and queues a "drop" event with the id. Reading is asynchronous: the event comes
* once every file is in memory.
*/
@JSBody(
params = "canvas",
script = "var sink = canvas.__incariSink; var next = 1; canvas.__incariDrops = {};\n"
+ "function hasFiles(e) { var types = e.dataTransfer && e.dataTransfer.types;"
+ " if (!types) return false;"
+ " for (var i = 0; i < types.length; i++) if (types[i] === 'Files') return true; return false; }\n"
+ "window.addEventListener('dragover', function(e) {"
+ " if (hasFiles(e)) { e.preventDefault(); e.dataTransfer.dropEffect = 'copy'; } });\n"
+ "window.addEventListener('drop', function(e) { if (!hasFiles(e)) return; e.preventDefault();"
+ " var out = [], jobs = [];"
+ " function readFile(file, path) { return file.arrayBuffer().then("
+ " function(b) { out.push(path, new Int8Array(b)); }, function() {}); }"
+ " function walk(entry, path) {"
+ " if (entry.isFile) return new Promise(function(done) {"
+ " entry.file(function(f) { readFile(f, path).then(done); }, function() { done(); }); });"
+ " out.push(path, null); var reader = entry.createReader(), children = [];"
+ " return new Promise(function(done) { function finish() { Promise.all(children).then(done); }"
// readEntries hands out a folder's entries in batches, until an empty one.
// (No immediately invoked function here: TeaVM's printer drops its parentheses.)
+ " function more() { reader.readEntries(function(batch) { if (!batch.length) { finish(); return; }"
+ " for (var j = 0; j < batch.length; j++) children.push(walk(batch[j], path + '/' + batch[j].name));"
+ " more(); }, finish); }"
+ " more(); }); }"
// Entries must be taken while the drop is dispatched: the data is gone after.
+ " var items = e.dataTransfer.items;"
+ " if (items && items.length && items[0].webkitGetAsEntry) {"
+ " for (var i = 0; i < items.length; i++) { if (items[i].kind !== 'file') continue;"
+ " var entry = items[i].webkitGetAsEntry();"
+ " if (entry) { jobs.push(walk(entry, entry.name)); continue; }"
+ " var f = items[i].getAsFile(); if (f) jobs.push(readFile(f, f.name)); } }"
+ " else { var files = e.dataTransfer.files;"
+ " for (var k = 0; k < files.length; k++) jobs.push(readFile(files[k], files[k].name)); }"
+ " Promise.all(jobs).then(function() { canvas.__incariAddDrop(out); }); });\n"
// Also for files the player picks (chooseFiles): they reach the game as a drop.
+ "canvas.__incariAddDrop = function(out) { if (!out.length) return; var id = next++;"
+ " canvas.__incariDrops[id] = out; sink('drop', '', '', id, 0, 0, 0, 0, 0); };")
static native void listenDrops(JSObject canvas);
/**
* Opens the browser's file picker; the files the player picks arrive as a "drop" event, as if
* dropped on the page (listenDrops must have run). The game asks for it on a click, and a
* page may only open a picker while the player's click or key press is recent (a few
* seconds): it's still recent when the game handles the click, a frame later.
*/
@JSBody(
params = "canvas",
script = "var input = canvas.__incariPicker;\n"
+ "if (!input) { input = document.createElement('input'); input.type = 'file'; input.multiple = true;"
+ " input.id = canvas.id + '-files'; input.style.display = 'none';"
+ " document.body.appendChild(input); canvas.__incariPicker = input;\n"
+ " input.addEventListener('change', function() { var files = input.files, out = [], jobs = [];"
+ " function read(file) { return file.arrayBuffer().then("
+ " function(b) { out.push(file.name, new Int8Array(b)); }, function() {}); }"
+ " for (var i = 0; i < files.length; i++) jobs.push(read(files[i]));"
+ " input.value = '';"
+ " Promise.all(jobs).then(function() { canvas.__incariAddDrop(out); }); }); }\n"
+ "input.click();")
static native void chooseFiles(JSObject canvas);
/** Hands the player a file to save, as a download (a page can't show them its files otherwise). */
@JSBody(
params = {"name", "data", "type"},
script = "var url = URL.createObjectURL(new Blob([data], {type: type}));"
+ "var a = document.createElement('a'); a.href = url; a.download = name; a.style.display = 'none';"
+ "document.body.appendChild(a); a.click(); a.remove();"
// The download has its own copy by the time it starts; a minute is plenty.
+ "setTimeout(function() { URL.revokeObjectURL(url); }, 60000);")
static native void download(String name, Int8Array data, String type);
/** How many entries (files and folders) the drop with this id holds. */
@JSBody(
params = {"canvas", "id"},
script = "var d = canvas.__incariDrops[id]; return d ? d.length / 2 : 0;")
static native int droppedCount(JSObject canvas, int id);
/** An entry's path relative to the drop, with "/" between folders. */
@JSBody(
params = {"canvas", "id", "index"},
script = "return String(canvas.__incariDrops[id][2 * index]);")
static native String droppedPath(JSObject canvas, int id, int index);
@JSBody(
params = {"canvas", "id", "index"},
script = "return !canvas.__incariDrops[id][2 * index + 1];")
static native boolean droppedIsFolder(JSObject canvas, int id, int index);
/** A file entry's contents (not a folder's: {@link #droppedIsFolder}). */
@JSBody(
params = {"canvas", "id", "index"},
script = "return canvas.__incariDrops[id][2 * index + 1];")
static native Int8Array droppedBytes(JSObject canvas, int id, int index);
/** Lets the page free a drop's contents once they're copied. */
@JSBody(
params = {"canvas", "id"},
script = "delete canvas.__incariDrops[id];")
static native void forgetDropped(JSObject canvas, int id);
}
@@ -0,0 +1,337 @@
package incari.platform.web;
import incari.platform.api.input.Scancodes;
import org.jspecify.annotations.Nullable;
/**
* Maps the browser's keys to the platform's. {@code KeyboardEvent.code} names the physical key,
* the same on every layout, and becomes a scancode: a USB HID usage id (HID usage tables,
* keyboard page 0x07), so {@code "KeyQ"} is the key right of Tab whatever it types.
* {@code KeyboardEvent.key} is what the key means in the player's layout, and becomes an SDL3
* keycode, the "shortcut key" the game's text fields read (Ctrl+V is keycode {@code 'v'}).
*/
final class DomKeys {
/** SDL's keycode flag for keys that type nothing: the scancode with this bit set. */
static final int NON_PRINTABLE = 1 << 30;
/** HID usage 0x9C, Keyboard Clear: what the keypad's 5 means with Num Lock off. */
private static final int CLEAR = 156;
/** HID usage 0x49: the first of the navigation block, which runs from Insert to the arrows. */
private static final int INSERT = 73;
private DomKeys() {}
/**
* The scancode for a {@code KeyboardEvent.code}, or {@link Scancodes#UNKNOWN}. Every code in
* the UI Events code tables that SDL3 has a scancode for is mapped; the rest (Fn, the launch
* keys, legacy codes like Hyper) stay unknown, as they are to SDL.
*/
static int scancode(String code) {
if (code.length() == 4 && code.startsWith("Key")) {
char letter = code.charAt(3);
if (letter >= 'A' && letter <= 'Z') {
return Scancodes.A + (letter - 'A');
}
}
if (code.length() == 6 && code.startsWith("Digit")) {
int digit = digit(code.charAt(5));
if (digit >= 0) {
return digit == 0 ? Scancodes.DIGIT_0 : Scancodes.DIGIT_1 + digit - 1;
}
}
if (code.length() == 7 && code.startsWith("Numpad")) {
int digit = digit(code.charAt(6));
if (digit >= 0) {
// HID puts the keypad's 1-9 at 0x59-0x61 and its 0 after them, at 0x62.
return digit == 0 ? 98 : 89 + digit - 1;
}
}
if (code.length() >= 2 && code.length() <= 3 && code.charAt(0) == 'F') {
int number = parsePositive(code.substring(1));
if (number >= 1 && number <= 12) {
return Scancodes.F1 + number - 1;
}
if (number >= 13 && number <= 24) {
// F13-F24 are a separate run, 0x68-0x73.
return 104 + number - 13;
}
}
return switch (code) {
case "Enter" -> Scancodes.RETURN;
case "Escape" -> Scancodes.ESCAPE;
case "Backspace" -> Scancodes.BACKSPACE;
case "Tab" -> Scancodes.TAB;
case "Space" -> Scancodes.SPACE;
case "Minus" -> 45;
case "Equal" -> 46;
case "BracketLeft" -> 47;
case "BracketRight" -> 48;
// Also the ISO key left of Enter (HID's "Non-US #"): browsers name both "Backslash".
case "Backslash" -> 49;
case "Semicolon" -> 51;
case "Quote" -> 52;
case "Backquote" -> 53;
case "Comma" -> 54;
case "Period" -> 55;
case "Slash" -> 56;
case "CapsLock" -> 57;
case "PrintScreen" -> 70;
case "ScrollLock" -> 71;
case "Pause" -> 72;
case "Insert" -> 73;
case "Home" -> 74;
case "PageUp" -> 75;
case "Delete" -> 76;
case "End" -> 77;
case "PageDown" -> 78;
case "ArrowRight" -> Scancodes.RIGHT;
case "ArrowLeft" -> Scancodes.LEFT;
case "ArrowDown" -> Scancodes.DOWN;
case "ArrowUp" -> Scancodes.UP;
case "NumLock" -> 83;
case "NumpadDivide" -> 84;
case "NumpadMultiply" -> 85;
case "NumpadSubtract" -> 86;
case "NumpadAdd" -> 87;
case "NumpadEnter" -> 88;
case "NumpadDecimal" -> 99;
// The ISO key right of the left Shift.
case "IntlBackslash" -> 100;
case "ContextMenu" -> 101;
case "Power" -> 102;
case "NumpadEqual" -> 103;
case "Open" -> 116;
case "Help" -> 117;
case "Select" -> 119;
case "Again" -> 121;
case "Undo" -> 122;
case "Cut" -> 123;
case "Copy" -> 124;
case "Paste" -> 125;
case "Find" -> 126;
// Older Firefox used the shorter names.
case "AudioVolumeMute", "VolumeMute" -> 127;
case "AudioVolumeUp", "VolumeUp" -> 128;
case "AudioVolumeDown", "VolumeDown" -> 129;
case "NumpadComma" -> 133;
case "IntlRo" -> 135;
case "KanaMode" -> 136;
case "IntlYen" -> 137;
case "Convert" -> 138;
case "NonConvert" -> 139;
case "Lang1" -> 144;
case "Lang2" -> 145;
case "Lang3" -> 146;
case "Lang4" -> 147;
case "Lang5" -> 148;
// The legacy names of Lang3 and Lang4.
case "Katakana" -> 146;
case "Hiragana" -> 147;
case "NumpadParenLeft" -> 182;
case "NumpadParenRight" -> 183;
case "NumpadBackspace" -> 187;
// Phone keypads' "#" and "*".
case "NumpadHash" -> 204;
case "NumpadStar" -> 85;
case "NumpadMemoryStore" -> 208;
case "NumpadMemoryRecall" -> 209;
case "NumpadMemoryClear" -> 210;
case "NumpadMemoryAdd" -> 211;
case "NumpadMemorySubtract" -> 212;
case "NumpadClear" -> 216;
case "NumpadClearEntry" -> 217;
// Media and browser keys: HID's consumer page, which SDL3 numbers from 258 on. They have
// no HID keyboard usage, so SDL3's own values are the scancodes.
case "Sleep" -> 258;
case "WakeUp" -> 259;
case "MediaPlay" -> 262;
case "MediaPause" -> 263;
case "MediaRecord" -> 264;
case "MediaFastForward" -> 265;
case "MediaRewind" -> 266;
case "MediaTrackNext" -> 267;
case "MediaTrackPrevious" -> 268;
case "MediaStop" -> 269;
case "Eject" -> 270;
case "MediaPlayPause" -> 271;
case "MediaSelect", "LaunchMediaPlayer" -> 272;
case "BrowserSearch" -> 280;
case "BrowserHome" -> 281;
case "BrowserBack" -> 282;
case "BrowserForward" -> 283;
case "BrowserStop" -> 284;
case "BrowserRefresh" -> 285;
case "BrowserFavorites" -> 286;
case "ControlLeft" -> Scancodes.LEFT_CTRL;
case "ShiftLeft" -> Scancodes.LEFT_SHIFT;
case "AltLeft" -> Scancodes.LEFT_ALT;
// "OSLeft"/"OSRight": Firefox before version 118.
case "MetaLeft", "OSLeft" -> Scancodes.LEFT_SUPER;
case "ControlRight" -> Scancodes.RIGHT_CTRL;
case "ShiftRight" -> Scancodes.RIGHT_SHIFT;
case "AltRight" -> Scancodes.RIGHT_ALT;
case "MetaRight", "OSRight" -> Scancodes.RIGHT_SUPER;
default -> Scancodes.UNKNOWN;
};
}
/**
* SDL3's keycode for a key event: the character the key types in the player's layout without
* Shift or AltGr, or the scancode with {@link #NON_PRINTABLE} for keys that type nothing.
*
* <p>The browser's {@code key} already includes Shift and AltGr ("!" for Shift+1, "@" for
* AltGr+Q on a German keyboard), while SDL's keycode doesn't. So the unmodified character is
* remembered per key in {@code learned} whenever the key is pressed without them, and used
* when it's pressed with them; until then a US layout's character stands in. Like SDL3's
* default keycode options, digit keys always give digits (French keyboards type "&" there
* unshifted) and letter keys on non-Latin layouts give the US letter, so Ctrl+C works on a
* Russian keyboard.
*
* @param code {@code KeyboardEvent.code}
* @param scancode {@link #scancode} of {@code code}
* @param key {@code KeyboardEvent.key}
* @param levelShifted whether Shift, AltGr or Alt changed what {@code key} says
* @param learned the unmodified character seen for each scancode, 0 if none yet; updated here
*/
static int keyCode(String code, int scancode, String key, boolean levelShifted, int[] learned) {
int character = singleCodePoint(key);
if (code.startsWith("Numpad")) {
// The keypad has keycodes of its own, even for the keys that type digits. With Num
// Lock off the browser reports what the key does instead ("End" for 1), as SDL does.
// Enter stays the keypad's own Enter.
int navigation = "Clear".equals(key) ? CLEAR : scancode(key);
if (navigation == CLEAR || (navigation >= INSERT && navigation <= Scancodes.UP)) {
return namedKeyCode(key, navigation);
}
return scancode | NON_PRINTABLE;
}
if (character < 0 || isControl(character)) {
return namedKeyCode(key, scancode);
}
if (scancode >= Scancodes.DIGIT_1 && scancode <= Scancodes.DIGIT_0) {
return scancode == Scancodes.DIGIT_0 ? '0' : '1' + scancode - Scancodes.DIGIT_1;
}
int lower = Character.toLowerCase(character);
if (scancode >= Scancodes.A && scancode <= Scancodes.Z) {
int usLetter = 'a' + scancode - Scancodes.A;
if (Character.isLetter(lower)) {
// Caps Lock and Shift only change the case of a letter.
return isLatin(lower) ? lower : usLetter;
}
if (!levelShifted) {
// A letter key that types a symbol: a layout like Dvorak's.
remember(learned, scancode, lower);
return lower;
}
return fallback(learned, scancode, usLetter);
}
if (!levelShifted) {
remember(learned, scancode, lower);
return lower;
}
return fallback(learned, scancode, usCharacter(scancode, lower));
}
/** The keycode for a key the browser names by a word, like "Enter" or "ArrowUp". */
private static int namedKeyCode(String key, int scancode) {
return switch (key) {
case "Enter" -> '\r';
case "Escape" -> 0x1B;
case "Backspace" -> '\b';
case "Tab" -> '\t';
case "Delete" -> 0x7F;
default -> scancode | NON_PRINTABLE;
};
}
/**
* What a key types on a US keyboard, unshifted, as its label: for the letter, digit and
* punctuation keys, whose names depend on the layout; null for the rest.
*/
static @Nullable String usName(int scancode) {
int character;
if (scancode >= Scancodes.A && scancode <= Scancodes.Z) {
character = 'a' + scancode - Scancodes.A;
} else if (scancode >= Scancodes.DIGIT_1 && scancode <= Scancodes.DIGIT_0) {
character = scancode == Scancodes.DIGIT_0 ? '0' : '1' + scancode - Scancodes.DIGIT_1;
} else if (scancode >= 45 && scancode <= 56 && scancode != 50) {
character = usCharacter(scancode, 0);
} else {
return null;
}
return String.valueOf((char) character);
}
/** What an unshifted US layout types on the keys whose character a layout can change. */
private static int usCharacter(int scancode, int otherwise) {
return switch (scancode) {
case Scancodes.SPACE -> ' ';
case 45 -> '-';
case 46 -> '=';
case 47 -> '[';
case 48 -> ']';
case 49 -> '\\';
case 51 -> ';';
case 52 -> '\'';
case 53 -> '`';
case 54 -> ',';
case 55 -> '.';
case 56 -> '/';
default -> otherwise;
};
}
private static void remember(int[] learned, int scancode, int character) {
if (scancode > 0 && scancode < learned.length) {
learned[scancode] = character;
}
}
private static int fallback(int[] learned, int scancode, int otherwise) {
if (scancode > 0 && scancode < learned.length && learned[scancode] != 0) {
return learned[scancode];
}
return otherwise;
}
/** The one code point {@code text} holds, or -1 if it holds none or several. */
static int singleCodePoint(String text) {
if (text.length() == 1) {
return text.charAt(0);
}
if (text.length() == 2 && Character.isSurrogatePair(text.charAt(0), text.charAt(1))) {
return text.codePointAt(0);
}
return -1;
}
private static boolean isControl(int character) {
return character < 0x20 || (character >= 0x7F && character < 0xA0);
}
/**
* Latin letters: Basic Latin through Latin Extended-B, and Latin Extended Additional. Enough
* to tell a Latin layout (AZERTY, QWERTZ, Nordic) from a Cyrillic, Greek or Thai one.
*/
private static boolean isLatin(int letter) {
return letter < 0x250 || (letter >= 0x1E00 && letter < 0x1F00);
}
private static int digit(char c) {
return c >= '0' && c <= '9' ? c - '0' : -1;
}
private static int parsePositive(String digits) {
int value = 0;
for (int i = 0; i < digits.length(); i++) {
int d = digit(digits.charAt(i));
if (d < 0) {
return -1;
}
value = value * 10 + d;
}
return digits.isEmpty() ? -1 : value;
}
}
@@ -0,0 +1,126 @@
package incari.platform.web;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* Files dropped on the page, copied into the page's file system so the game can open them by path,
* as it opens files dropped on a desktop window (the resource and data pack screens copy them into
* their folders). A page gets the files' contents, never a path on the player's disk.
*
* <p>Each drop goes into a folder of its own under the root, and only the latest drop is kept:
* the root is scratch space that storage never keeps (ADR 0011), the files take memory, and the
* game copies what it wants (a pack into its resource pack folder, which is kept) while it handles
* the drop.
*/
final class DroppedFiles {
/** One drop's entries, as the page read them. */
interface Source {
int count();
/** The entry's path relative to the drop, "/" between folders; the first part is what was dropped. */
String path(int index);
boolean isFolder(int index);
byte[] bytes(int index);
}
private final File root;
private @Nullable File latest;
DroppedFiles(File root) {
this.root = root;
}
/**
* Copies a drop into the file system.
*
* @param id the drop's id, unique within the page's life
* @return the paths of the dropped files and folders themselves (not their contents), in the
* order they were dropped
*/
List<String> store(int id, Source source) throws IOException {
File previous = latest;
if (previous != null) {
deleteRecursively(previous);
}
File directory = new File(root, Integer.toString(id));
latest = directory;
Set<String> dropped = new LinkedHashSet<>();
for (int i = 0; i < source.count(); i++) {
String relative = safePath(source.path(i));
if (relative == null) {
continue;
}
File file = new File(directory, relative);
if (source.isFolder(i)) {
makeDirectory(file);
} else {
File parent = file.getParentFile();
if (parent != null) {
makeDirectory(parent);
}
try (OutputStream out = new FileOutputStream(file)) {
out.write(source.bytes(i));
}
}
int slash = relative.indexOf('/');
dropped.add(new File(directory, slash < 0 ? relative : relative.substring(0, slash)).getPath());
}
return new ArrayList<>(dropped);
}
/**
* A dropped entry's path made safe to put under the drop's folder: no empty, "." or ".." parts
* (a page mustn't be able to write outside it), and no characters file systems reject. Null if
* nothing is left.
*/
static @Nullable String safePath(String path) {
StringBuilder safe = new StringBuilder(path.length());
int start = 0;
while (start <= path.length()) {
int end = path.indexOf('/', start);
if (end < 0) {
end = path.length();
}
String part = path.substring(start, end);
if (!part.isEmpty() && !part.equals(".") && !part.equals("..")) {
if (safe.length() > 0) {
safe.append('/');
}
for (int i = 0; i < part.length(); i++) {
char c = part.charAt(i);
safe.append(c < 0x20 || c == 0x7F || "\\:*?\"<>|".indexOf(c) >= 0 ? '_' : c);
}
}
start = end + 1;
}
return safe.length() == 0 ? null : safe.toString();
}
private static void makeDirectory(File directory) throws IOException {
if (!directory.isDirectory() && !directory.mkdirs()) {
throw new IOException("Can't create " + directory);
}
}
private static void deleteRecursively(File file) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
deleteRecursively(child);
}
}
// Best effort: a file left behind costs memory, nothing else.
file.delete();
}
}
@@ -0,0 +1,66 @@
package incari.platform.web;
import incari.platform.api.storage.PlatformStorage;
import incari.platform.web.storage.WebFileSystem;
import java.io.IOException;
import java.io.UncheckedIOException;
import org.jspecify.annotations.Nullable;
/**
* The platform's storage in the browser: where the game's folders are (the entry point's
* choice), and the page's file system for handing a world to a copy of the game in a worker and
* back (ADR 0039).
*/
final class FileStorage implements PlatformStorage {
private final PlatformStorage folders;
private final WebFileSystem files;
FileStorage(PlatformStorage folders, WebFileSystem files) {
this.folders = folders;
this.files = files;
}
@Override
public String gameDirectory() {
return folders.gameDirectory();
}
@Override
public String assetsDirectory() {
return folders.assetsDirectory();
}
@Override
public @Nullable String assetIndex() {
return folders.assetIndex();
}
@Override
public byte[] handOver(String directory) {
try {
return files.handOver(directory);
} catch (IOException e) {
throw new UncheckedIOException("Couldn't hand over " + directory, e);
}
}
@Override
public void takeOver(byte[] bundle) {
try {
files.takeOver(bundle);
} catch (IOException e) {
throw new UncheckedIOException("Couldn't take back the files a worker had", e);
}
}
@Override
public byte @Nullable [] takeChanges() {
return files.takeChanges();
}
@Override
public void storeChanges(byte[] changes) {
files.storeChanges(changes);
}
}
@@ -0,0 +1,486 @@
package incari.platform.web;
import java.util.ArrayDeque;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.AbstractExecutorService;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.function.Consumer;
import java.util.function.Supplier;
import org.jspecify.annotations.Nullable;
/**
* The game's background pool in the page: coroutines that run the pool's tasks in the time left
* over after each frame, never inside one.
*
* <p>The page has one thread, so a task run where it's submitted lands mid-frame, and a burst
* stalls the frame: turning the camera schedules a mesh for every section coming into view, and
* the section dispatcher resubmits itself after each, so one frame would compile the whole backlog
* (hundreds of milliseconds). Here a task only queues. Once the game's frame has run and the page
* has drawn it, a runner runs queued tasks until shortly before the next frame is due, then waits
* for the next slot ({@link Slots}). A burst spreads over as many frames as it takes.
*
* <p>A task runs to its end once started: a slot can run over by one task. A thread that waits on
* a task still queued here (a {@code join} on the render thread) waits for the next slot, which
* comes whether or not the game draws, so nothing deadlocks.
*
* <p>One runner works at a time (it holds the pool). A task that waits for work done elsewhere (a
* Web Worker's mesh) steps aside ({@link #awaitOutside}): another runner carries on with the queue
* in the same slot, and the waiting task takes the pool back in a later slot. So several meshes are
* in flight at once, and everything still runs between frames.
*
* <p>A task that blocks in any other wait (a {@code join} on another pool task, a lock held by the
* integrated server) gives the pool up for good ({@link #beforeWait}): what it waits for may be
* queued behind it, and would never run while it held the pool (world generation's structure
* placement joins work it queued itself). Another runner takes the queue; the waiting task goes on
* when woken, outside the slots, and its runner then queues for the pool like any other.
*
* <p>Everything here runs on the page's one thread; the monitor only orders the runners, which are
* coroutines that suspend in {@link Slots#await}, in a monitor wait, or in an outside wait.
*/
final class IdleTimeExecutor extends AbstractExecutorService {
/** When the runners may run: the page's frames ({@link Dom}), or a test's. */
interface Slots {
/** Asks for the next slot: work is queued. Never suspends; asking twice asks once. */
void arm();
/**
* Suspends until the next slot once one is asked for ({@link #arm}), before or during the
* wait.
*
* @return when the slot ends, on {@link #now}'s clock
*/
double await();
/** The page's clock, in milliseconds. */
double now();
/**
* A stretch of the pool's work just ended (a task, or a part of one before it paused or
* waited outside): how long it ran, and how far past its slot's deadline it ended (negative
* if in time). For the frame table's pool columns; wherever the page resumed the work from.
*/
default void worked(double millis, double pastDeadline) {}
}
/**
* The most runners, not counting those that gave the pool up ({@link #beforeWait}). Runners are
* cheap coroutines, but the meshes they wait on aren't.
*/
private static final int MAX_RUNNERS = 16;
/** The pool the current thread is a runner of, for {@link #awaitOutside}. */
private static final ThreadLocal<@Nullable IdleTimeExecutor> CURRENT = new ThreadLocal<>();
/** The current thread's runner, if it is one. */
private static final ThreadLocal<@Nullable Runner> RUNNER = new ThreadLocal<>();
/** A runner's own state. */
private static final class Runner {
/** Its task gave the pool up to wait ({@link #beforeWait}); it finishes outside the slots. */
boolean gaveUp;
}
/** Every pool made, for {@link #queuedEverywhere}: a few, made at start-up and kept. */
private static final List<IdleTimeExecutor> POOLS = new ArrayList<>();
private final ArrayDeque<Runnable> queue = new ArrayDeque<>();
private final Slots slots;
private final Consumer<Runnable> startRunner;
private int runners;
/** Runners parked, waiting for work or for the pool. */
private int parked;
/** Runners in an outside wait ({@link #stepAside}), not yet back. */
private int outside;
/** Tasks back from an outside wait, waiting to take the pool back. */
private int rejoining;
/** Runners whose task gave the pool up to wait ({@link #beforeWait}), not back in their loop. */
private int waiting;
/** The runner holding the pool, or null. */
private @Nullable Runner holder;
/** When the current slot ends. */
private double deadline = Double.NEGATIVE_INFINITY;
/** A slot just began: its first task runs even if the slot is already over. */
private boolean freshSlot;
/** When the pool's current stretch of work began, for {@link Slots#worked}. */
private double stretchStart;
private boolean shutdown;
private boolean terminated;
/**
* @param startRunner starts {@code work} on a thread of its own: the first time a task comes,
* and whenever a task steps aside with work still queued and no runner free
*/
IdleTimeExecutor(Slots slots, Consumer<Runnable> startRunner) {
this.slots = slots;
this.startRunner = startRunner;
synchronized (POOLS) {
POOLS.add(this);
}
}
/** How many tasks wait for a slot in all the pools of this program. */
static int queuedEverywhere() {
int total = 0;
synchronized (POOLS) {
for (IdleTimeExecutor pool : POOLS) {
total += pool.queued();
}
}
return total;
}
/** The executor the page's game uses: its runners are daemon threads named {@code threadName}-n. */
static IdleTimeExecutor forPage(String threadName) {
int[] count = {0};
return new IdleTimeExecutor(new Dom.IdleSlots(), work -> {
Thread thread = new Thread(work, threadName + "-" + ++count[0]);
thread.setDaemon(true);
thread.start();
});
}
/**
* The executor in a copy of the game in a worker (ADR 0039): slots are turns of the worker's
* event loop ({@link WorkerSlots}), as it has no frames. Its runners are daemon threads named
* {@code threadName}-n.
*/
static IdleTimeExecutor forWorker(String threadName) {
int[] count = {0};
return new IdleTimeExecutor(new WorkerSlots(), work -> {
Thread thread = new Thread(work, threadName + "-" + ++count[0]);
thread.setDaemon(true);
thread.start();
});
}
/**
* Waits for something done outside the page's thread, from a task of the pool this thread runs:
* the pool goes on with other tasks meanwhile, and this task goes on in a later slot. Anywhere
* else, it just waits.
*/
static <T> T awaitOutside(Supplier<T> wait) {
IdleTimeExecutor pool = CURRENT.get();
return pool == null ? wait.get() : pool.stepAside(wait);
}
/**
* From a task of the pool this thread runs: if the slot is over, waits for the next one, keeping
* the pool, and goes on there. A long task (a section's snapshot) calls it between its parts so
* it never runs far past its slot. Anywhere else it returns at once.
*/
static void pauseIfLate() {
IdleTimeExecutor pool = CURRENT.get();
if (pool != null) {
pool.pauseIfLateHere();
}
}
/**
* Called just before any wait on a thread of the page (web-classlib's {@code Waits}, wired by
* the entry point). A runner holding the pool gives it up, for good: see the class comment.
* Anywhere else, and in the pool's own waits, it does nothing.
*/
static void beforeWait() {
IdleTimeExecutor pool = CURRENT.get();
Runner runner = RUNNER.get();
if (pool != null && runner != null) {
pool.giveUp(runner);
}
}
private void giveUp(Runner runner) {
synchronized (this) {
if (holder != runner) {
return;
}
holder = null;
runner.gaveUp = true;
waiting++;
if (!queue.isEmpty() && parked == 0 && runners - outside - waiting == 0) {
startRunnerLocked();
}
notifyAll();
}
endStretch();
}
/** Whether the current thread is the runner holding the pool. */
private synchronized boolean holdsPool() {
Runner runner = RUNNER.get();
return runner != null && holder == runner;
}
private void pauseIfLateHere() {
if (!holdsPool()) {
// Its task gave the pool up to wait: it has no slot to pause in.
return;
}
if (slots.now() >= deadline) {
endStretch();
slots.arm();
deadline = slots.await();
freshSlot = false;
stretchStart = slots.now();
}
}
private void endStretch() {
double now = slots.now();
slots.worked(now - stretchStart, now - deadline);
stretchStart = now;
}
@Override
public void execute(Runnable task) {
Objects.requireNonNull(task, "task");
synchronized (this) {
if (shutdown) {
throw new RejectedExecutionException("The background pool is shut down");
}
queue.add(task);
if (runners == 0) {
startRunnerLocked();
} else if (parked > 0) {
notifyAll();
} else if (outside + waiting == runners && runners - waiting < MAX_RUNNERS) {
// Every runner is waiting (a mesh in a worker, or a task that gave the pool up):
// one more takes the queue, rather than the task waiting for an answer.
startRunnerLocked();
}
}
slots.arm();
}
private void startRunnerLocked() {
runners++;
startRunner.accept(this::work);
}
/** A runner's loop: take the pool when there's work and it's free, run slots, give it back. */
private void work() {
CURRENT.set(this);
Runner me = new Runner();
RUNNER.set(me);
while (true) {
synchronized (this) {
parked++;
boolean interrupted = false;
while (!(shutdown && queue.isEmpty()) && (holder != null || queue.isEmpty() || rejoining > 0)) {
try {
wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
if (interrupted) {
Thread.currentThread().interrupt();
}
parked--;
if (shutdown && queue.isEmpty()) {
runners--;
if (runners == 0) {
terminated = true;
}
notifyAll();
return;
}
holder = me;
}
stretchStart = slots.now();
try {
runSlots(me);
} finally {
synchronized (this) {
if (holder == me) {
holder = null;
}
if (me.gaveUp) {
me.gaveUp = false;
waiting--;
}
notifyAll();
}
}
}
}
/**
* Runs queued tasks in slots while this runner holds the pool, until the queue is empty or a
* task back from an outside wait wants the pool, or a task gave it up to wait.
*/
private void runSlots(Runner me) {
while (true) {
Runnable task;
synchronized (this) {
if (queue.isEmpty() || rejoining > 0) {
return;
}
}
if (!freshSlot && slots.now() >= deadline) {
slots.arm();
deadline = slots.await();
freshSlot = true;
stretchStart = slots.now();
continue;
}
synchronized (this) {
task = queue.poll();
}
if (task != null) {
freshSlot = false;
run(task);
if (me.gaveUp) {
// It finished outside the slots; the runner queues for the pool again.
return;
}
endStretch();
}
}
}
/** Gives the pool up for {@code wait}, then takes it back, in a slot. */
private <T> T stepAside(Supplier<T> wait) {
if (!holdsPool()) {
// Its task already gave the pool up to wait: nothing to step aside from.
return wait.get();
}
endStretch();
Runner me;
synchronized (this) {
me = Objects.requireNonNull(holder);
holder = null;
outside++;
if (!queue.isEmpty()) {
if (parked > 0) {
notifyAll();
} else if (runners - waiting < MAX_RUNNERS) {
startRunnerLocked();
}
}
}
try {
return wait.get();
} finally {
synchronized (this) {
outside--;
rejoining++;
boolean interrupted = false;
while (holder != null) {
try {
wait();
} catch (InterruptedException e) {
interrupted = true;
}
}
rejoining--;
if (interrupted) {
Thread.currentThread().interrupt();
}
holder = me;
}
stretchStart = slots.now();
pauseIfLateHere();
}
}
/**
* Runs queued tasks, oldest first, until {@code deadline} has passed or none are left; tasks
* queued meanwhile count. At least one runs if any are queued, so the pool always moves. (The
* tests' way of running a slot; the runners run the same way through {@link #runSlots}.)
*
* @return how many ran
*/
int runUntil(double deadline) {
int ran = 0;
Runnable task;
while ((task = poll()) != null) {
run(task);
ran++;
if (slots.now() >= deadline) {
break;
}
}
return ran;
}
private synchronized @Nullable Runnable poll() {
return queue.poll();
}
/** Runs one task; what it throws goes where an uncaught exception in a pool thread would. */
private static void run(Runnable task) {
try {
task.run();
} catch (RuntimeException | Error e) {
Thread thread = Thread.currentThread();
Thread.UncaughtExceptionHandler handler = thread.getUncaughtExceptionHandler();
if (handler == null) {
handler = Thread.getDefaultUncaughtExceptionHandler();
}
if (handler != null) {
handler.uncaughtException(thread, e);
} else {
e.printStackTrace();
}
}
}
/** How many tasks wait for a slot. */
synchronized int queued() {
return queue.size();
}
/** How many runners have been started. */
synchronized int runners() {
return runners;
}
@Override
public void shutdown() {
synchronized (this) {
shutdown = true;
if (runners == 0) {
terminated = true;
return;
}
notifyAll();
}
// Wakes the runners to finish the queue and stop.
slots.arm();
}
@Override
public List<Runnable> shutdownNow() {
shutdown();
synchronized (this) {
List<Runnable> dropped = List.copyOf(queue);
queue.clear();
notifyAll();
return dropped;
}
}
@Override
public synchronized boolean isShutdown() {
return shutdown;
}
@Override
public synchronized boolean isTerminated() {
return terminated;
}
/**
* Says whether the pool has finished, without waiting: a wait here would hold the page's only
* thread, and the page never shuts down in an orderly way (the tab just closes).
*/
@Override
public synchronized boolean awaitTermination(long timeout, TimeUnit unit) {
return terminated;
}
}
@@ -0,0 +1,172 @@
package incari.platform.web;
import incari.platform.api.threads.PlatformChannel;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* A {@link PlatformChannel} over a JavaScript object with four calls, the same at both ends: the
* page's side of a game worker ({@link #startWorker}) and the worker's side of its page
* ({@link #parent}, offered by app-web's {@code game-worker.ts}). {@code send} hands a buffer over,
* {@code take} gives the next message if there is one, {@code next} a promise of it (null once the
* channel ends), {@code close} ends it. A message only queues on the JavaScript side; a Java thread
* waiting in {@link #receive} is resumed with it (ADR 0039).
*/
final class JsChannel implements PlatformChannel {
private final JSObject channel;
private JsChannel(JSObject channel) {
this.channel = channel;
}
/**
* Starts the game's program again in a module worker ({@code game-worker.js}), in the build the
* page loaded, and returns the channel to it; null if the page doesn't know its build (an
* experiment's page) or has no workers. In a game worker, a worker of its own, in its build.
*/
static @Nullable JsChannel startWorker(String role) {
JSObject channel = createWorker(role);
return channel == null ? null : new JsChannel(channel);
}
/** In a game worker, the channel to the page that started it; null elsewhere. */
static @Nullable JsChannel parent() {
JSObject channel = parentObject();
return channel == null ? null : new JsChannel(channel);
}
@Override
public void send(int kind, byte[] bytes, int offset, int length) {
byte[] part =
offset == 0 && length == bytes.length ? bytes : Arrays.copyOfRange(bytes, offset, offset + length);
sendBuffer(channel, kind, Int8Array.copyFromJavaArray(part).getBuffer());
}
@Override
public @Nullable Message receive() {
return message(next(channel));
}
@Override
public @Nullable Message poll() {
return message(take(channel));
}
@Override
public void close() {
closeChannel(channel);
}
@Override
public void sendWhenLeaving(int kind) {
sendOnLeave(channel, kind);
}
/** Registers the channel's leave message with the page's listeners ({@code Dom.listen}). */
@JSBody(
params = {"channel", "kind"},
script = "if (channel.onLeave) channel.onLeave(kind);")
private static native void sendOnLeave(JSObject channel, int kind);
private static @Nullable Message message(@Nullable JSObject envelope) {
if (envelope == null) {
return null;
}
return new Message(kindOf(envelope), new Int8Array(dataOf(envelope)).copyToJavaArray());
}
@Async
private static native @Nullable JSObject next(JSObject channel);
private static void next(JSObject channel, AsyncCallback<@Nullable JSObject> callback) {
whenNext(channel, callback::complete);
}
@JSFunctor
interface Received extends JSObject {
void received(@Nullable JSObject envelope);
}
@JSBody(
params = {"channel", "callback"},
script = "channel.next().then(function(envelope) { callback(envelope); });")
private static native void whenNext(JSObject channel, Received callback);
@JSBody(params = "channel", script = "return channel.take();")
private static native @Nullable JSObject take(JSObject channel);
@JSBody(
params = {"channel", "kind", "data"},
script = "channel.send(kind, data);")
private static native void sendBuffer(JSObject channel, int kind, ArrayBuffer data);
@JSBody(params = "channel", script = "channel.close();")
private static native void closeChannel(JSObject channel);
@JSBody(params = "envelope", script = "return envelope.kind;")
private static native int kindOf(JSObject envelope);
@JSBody(params = "envelope", script = "return envelope.data;")
private static native ArrayBuffer dataOf(JSObject envelope);
@JSBody(script = "return self.__incariParent || null;")
private static native @Nullable JSObject parentObject();
/**
* The page's side: a module worker running {@code game-worker.js} beside the page's scripts,
* started with the build {@code boot.ts} recorded.
*/
@JSBody(
params = "role",
script = "if (typeof window === 'undefined') {"
// A game worker's own workers (ADR 0042), through its game-worker.ts.
+ " return self.__incariStartWorker ? self.__incariStartWorker(role) : null; }"
+ "var build = window.incariBuild && window.incariBuild.program;"
+ "if (!build || typeof Worker === 'undefined') return null;"
+ "var queue = [], waiting = null, ended = false;"
+ "function push(envelope) { if (ended) return; if (envelope === null) ended = true;"
+ " if (waiting) { var resolve = waiting; waiting = null; resolve(envelope); }"
+ " else queue.push(envelope); }"
// The single-file page's folder where it has one: its own URL may have none (offline.ts).
+ "var base = window.incariFiles ? window.incariFiles.base : document.baseURI;"
+ "var worker = new Worker(new URL('game-worker.js', base),"
+ " {type: 'module', name: 'incari-' + role});"
+ "worker.onmessage = function(event) { var d = event.data;"
+ " if (d.kind === -1) { push(null); return; }"
+ " push({kind: d.kind, data: d.data}); };"
+ "worker.onerror = function(event) {"
+ " console.error('[Incari] The ' + role + ' worker failed: ' + (event.message || event)); push(null); };"
// A port of the storage worker's own (ADR 0041): the worker's file changes go
// straight to it, not through the page.
+ "var storage = window.incariStorage && window.incariStorage.connect"
+ " ? window.incariStorage.connect() : null;"
+ "worker.postMessage({start: {runtime: new URL(build.runtime, base).href,"
+ " module: new URL(build.module, base).href, jspi: build.jspi, role: role,"
+ " query: location.search}, storage: storage}, storage ? [storage] : []);"
+ "var leave = null;"
+ "function unhook() { var hooks = window.__incariOnLeave;"
+ " if (leave && hooks) { var at = hooks.indexOf(leave); if (at >= 0) hooks.splice(at, 1); } leave = null; }"
+ "return {"
+ " send: function(kind, data) { worker.postMessage({kind: kind, data: data}, [data]); },"
+ " take: function() { var head = queue[0]; if (head === undefined || head === null) return null;"
+ " queue.shift(); return head; },"
+ " next: function() { if (queue.length > 0) return Promise.resolve(queue.shift());"
+ " return new Promise(function(resolve) { waiting = resolve; }); },"
// Posted from the page's own listener: the worker runs on while the page is
// hidden, or shows its leave dialog, and gets the message even if no game frame
// ever comes again.
+ " onLeave: function(kind) { unhook(); if (ended) return;"
+ " leave = function() { if (!ended) worker.postMessage({kind: kind, data: new ArrayBuffer(0)}); };"
+ " (window.__incariOnLeave = window.__incariOnLeave || []).push(leave); },"
+ " close: function() { unhook(); worker.postMessage({kind: -1, data: new ArrayBuffer(0)});"
+ " setTimeout(function() { worker.terminate(); }, 5000); push(null); } };")
private static native @Nullable JSObject createWorker(String role);
}
@@ -0,0 +1,38 @@
package incari.platform.web;
import incari.platform.api.window.DisplayInfo;
import incari.platform.api.window.DisplayMode;
import incari.platform.api.window.PlatformDisplays;
import java.util.List;
import org.jspecify.annotations.Nullable;
/** The screen the page is on: the only display a page can see. */
final class WebDisplays implements PlatformDisplays {
static final int SCREEN = 1;
static DisplayMode screenMode() {
// Pages can't read the refresh rate; 60 Hz is what almost every Chromebook runs at.
return new DisplayMode(Dom.screenWidth(), Dom.screenHeight(), 8, 8, 8, 60.0F);
}
@Override
public List<DisplayInfo> all() {
DisplayInfo screen = get(SCREEN);
return screen == null ? List.of() : List.of(screen);
}
@Override
public @Nullable DisplayInfo get(int id) {
if (id != SCREEN) {
return null;
}
DisplayMode mode = screenMode();
return new DisplayInfo(SCREEN, "Screen", 0, 0, mode.width(), mode.height(), mode, List.of());
}
@Override
public int primaryId() {
return SCREEN;
}
}
@@ -0,0 +1,70 @@
package incari.platform.web;
import java.io.IOException;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* HTTP GETs through the browser's {@code fetch}, for {@link WebSocketNetwork#fetch}. The calling
* thread suspends until the reply is in; other threads, and frames, carry on meanwhile.
*/
final class WebFetch {
private WebFetch() {}
/**
* The body of {@code url}, at most {@code maxBytes}. Suspends the calling thread; never call it
* on the render thread.
*/
static byte[] get(String url, int maxBytes) throws IOException {
JSObject reply = request(url, maxBytes);
String error = error(reply);
if (error != null) {
throw new IOException(error);
}
return new Int8Array(data(reply)).copyToJavaArray();
}
@Async
private static native JSObject request(String url, int maxBytes);
private static void request(String url, int maxBytes, AsyncCallback<JSObject> callback) {
start(url, maxBytes, callback::complete);
}
@JSFunctor
interface Done extends JSObject {
void done(JSObject reply);
}
/**
* Starts the fetch; {@code done} hears {@code {data}} or {@code {error}}, never both. A body
* the server says is too big is refused before it's read. A refused cross-origin fetch fails
* with no reason the page may see, so the error names the likely one.
*/
@JSBody(
params = {"url", "maxBytes", "done"},
script =
"var tooBig = function(n) { return new Error('the file is ' + n + ' bytes, over the limit of ' + maxBytes); };"
+ "fetch(url, {credentials: 'omit'}).then(function(r) {"
+ " if (!r.ok) throw new Error('HTTP ' + r.status);"
+ " var length = Number(r.headers.get('Content-Length'));"
+ " if (length > maxBytes) { if (r.body) r.body.cancel(); throw tooBig(length); }"
+ " return r.arrayBuffer(); },"
+ " function(e) { throw new Error(e + ' (offline, or the host doesn\\'t let web pages download it)'); })"
+ ".then(function(b) { if (b.byteLength > maxBytes) throw tooBig(b.byteLength); done({data: b}); })"
+ ".catch(function(e) { done({error: 'Couldn\\'t fetch ' + url + ': ' + (e && e.message || e)}); });")
private static native void start(String url, int maxBytes, Done done);
@JSBody(params = "reply", script = "return reply.error ? String(reply.error) : null;")
private static native @Nullable String error(JSObject reply);
@JSBody(params = "reply", script = "return reply.data;")
private static native ArrayBuffer data(JSObject reply);
}
@@ -0,0 +1,529 @@
package incari.platform.web;
import incari.platform.api.AppInfo;
import incari.platform.api.NativeSurfaceFactory;
import incari.platform.api.Platform;
import incari.platform.api.PlatformNotice;
import incari.platform.api.PlatformRecorder;
import incari.platform.api.PlatformShell;
import incari.platform.api.audio.PlatformAudio;
import incari.platform.api.fonts.PlatformFonts;
import incari.platform.api.input.PlatformInput;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.profile.PlatformProfiling;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.storage.PlatformStorage;
import incari.platform.api.threads.PlatformChannel;
import incari.platform.api.threads.PlatformThreads;
import incari.platform.api.threads.WorkerPool;
import incari.platform.api.window.PlatformDisplays;
import incari.platform.api.window.PlatformEventListener;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.WindowSpec;
import incari.platform.web.audio.WebAudio;
import incari.platform.web.fonts.CanvasFonts;
import incari.platform.web.rtc.WebRtc;
import incari.platform.web.storage.WebFileSystem;
import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.nio.file.Files;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.ExecutorService;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* The platform in a browser tab, over TeaVM's JavaScript interop: a canvas window with keyboard
* (layout-aware key names, input methods), mouse (Pointer Lock), fullscreen, the clipboard, file
* drops, links and dialogs; WebSocket connections to servers; the file system over OPFS,
* file downloads and the file picker; Web Audio.
*
* <p>Everything runs on the page's one thread. The game's loop yields to the page every frame
* ({@link #endFrame}); that's when DOM events are queued, to be delivered on the next poll.
*/
public final class WebPlatform implements Platform {
/** The id of the host page's canvas; created full-window if the page has none. */
public static final String CANVAS_ID = "incari-canvas";
/** Where files dropped on the page are copied for the game to open ({@link DroppedFiles}). */
public static final String DROP_DIRECTORY = "/incari/dropped";
private static final double HEARTBEAT_MILLIS = 5000;
private final PlatformFonts fonts = new CanvasFonts();
private final PlatformStorage storage;
private final WebFileSystem files;
private final WebDisplays displays = new WebDisplays();
private final WebAudio audio = new WebAudio();
private final DroppedFiles drops = new DroppedFiles(new File(DROP_DIRECTORY));
private final WebSocketNetwork network = new WebSocketNetwork();
private final WebRtc rtc = new WebRtc();
private final WebProfiling profiling = new WebProfiling();
/**
* Java threads are coroutines on the page's one thread, so extra pool threads would only add
* switching; the background pool runs in the time the game's frames leave over
* ({@link IdleTimeExecutor}).
*/
private final PlatformThreads threads = new PlatformThreads() {
@Override
public int backgroundThreads(int suggested) {
return 0;
}
@Override
public ExecutorService backgroundExecutor(String name) {
return IdleTimeExecutor.forPage("Worker-" + name);
}
@Override
public void pauseIfLate() {
IdleTimeExecutor.pauseIfLate();
}
@Override
public boolean oneThread() {
return true;
}
@Override
public int backgroundQueued() {
return IdleTimeExecutor.queuedEverywhere();
}
@Override
public @Nullable WorkerPool workers(String program) {
return pools.computeIfAbsent(program, name -> Optional.ofNullable(WebWorkerPool.start(name)))
.orElse(null);
}
@Override
public @Nullable PlatformChannel startGameWorker(String role) {
return JsChannel.startWorker(role);
}
};
/** Each program's workers, started the first time they're asked for. */
private final Map<String, Optional<WorkerPool>> pools = new HashMap<>();
private @Nullable CanvasWindow window;
private @Nullable DomEventQueue events;
/**
* Animation frames come every display interval, give or take; a frame that would be this early
* for the limit still counts, so a 60 fps limit on a 60 Hz display doesn't skip every other one.
*/
private static final double FRAME_LIMIT_SLACK_MILLIS = 4;
private long frames;
private double frameStart = Double.NEGATIVE_INFINITY;
private double frameInterval;
private double lastHeartbeat = Double.NaN;
/**
* The least time the background pool gets in a frame while it has work, in milliseconds
* (ADR 0035). Its slots end shortly before the next frame is due, so without this a slow frame
* left it 1 ms, part of one section's snapshot.
*/
public static void setPoolFloor(double millis) {
Dom.setPoolFloor(Math.max(1.0, millis));
}
/**
* To run just before every wait off the render thread: a background pool task that blocks gives
* the pool up, so the work it waits for can run (the entry point wires it to web-classlib's
* {@code Waits}).
*/
public static void beforeWait() {
IdleTimeExecutor.beforeWait();
}
/**
* The platform for this page.
*
* @param files the page's file system, already installed ({@link WebFileSystem#install}); the
* platform sends its changes to storage once a frame
*/
public WebPlatform(PlatformStorage storage, WebFileSystem files) {
this.storage = new FileStorage(storage, files);
this.files = files;
}
@Override
public String description() {
return "Browser (" + Dom.userAgent() + ")";
}
@Override
public String buildKind() {
return Dom.buildKind();
}
private final WebRecorder recorder = new WebRecorder();
@Override
public PlatformRecorder recorder() {
return recorder;
}
@Override
public void initialize(AppInfo app) {
Dom.installFrameMonitor();
CanvasWindow canvasWindow = new CanvasWindow(Dom.canvas(CANVAS_ID));
JSObject canvas = canvasWindow.canvas();
CanvasSize size = CanvasSize.initial(Dom.cssWidth(canvas), Dom.cssHeight(canvas), Dom.devicePixelRatio());
DomEventQueue queue = new DomEventQueue(canvasWindow, size, Dom.isMac(), Dom.functionKeyChords());
canvasWindow.connect(queue);
Dom.listen(canvas, DomEventQueue::consumesKey);
Dom.listenTextInput(canvas);
Dom.watchLayout(canvas);
Dom.listenDrops(canvas);
window = canvasWindow;
events = queue;
}
@Override
public void shutdown() {}
@Override
public long nanoTime() {
return (long) (Dom.nowMillis() * 1_000_000.0);
}
@Override
public PlatformDisplays displays() {
return displays;
}
@Override
public PlatformWindow createWindow(WindowSpec spec, NativeSurfaceFactory surface) {
CanvasWindow canvasWindow = requireInitialized(window);
// The canvas is the surface; backends that need a native window get the constant handle.
surface.create(spec.title(), spec.width(), spec.height(), 0L);
canvasWindow.setTitle(spec.title());
return canvasWindow;
}
@Override
public void pollEvents(PlatformEventListener listener) {
DomEventQueue queue = requireInitialized(events);
takeQueued(queue);
queue.drainTo(listener);
PlatformNotice notice;
while ((notice = files.takeNotice()) != null) {
listener.notice(notice);
}
// Network callbacks queue in the page like input does; the game's thread delivers them.
deliverNetwork();
}
/** Hands what the page's sockets and data channels queued to their listeners. The game's thread. */
private void deliverNetwork() {
network.deliver();
rtc.deliver();
}
/**
* Waits for the next animation frame. A WebSocket message that comes first is delivered at
* once, so the network's thread decodes it in the wait instead of after the next frame's packet
* handling; then the wait goes on for the same frame.
*/
private void waitForFrame() {
while (!Dom.nextAnimationFrameOrMessage()) {
deliverNetwork();
}
}
/** Moves the events the page queued since the last poll into {@code queue}, on the game's thread. */
private void takeQueued(DomEventQueue queue) {
JSObject canvas = requireInitialized(window).canvas();
int slots = Dom.queuedSlots(canvas);
for (int i = 0; i + Dom.EVENT_SLOTS <= slots; i += Dom.EVENT_SLOTS) {
String type = Dom.queuedString(canvas, i);
if (type.equals("drop")) {
queue.event(type, storeDrop(canvas, (int) Dom.queuedNumber(canvas, i + 3)), "", 0, 0, 0, 0, 0, 0);
continue;
}
queue.event(
type,
Dom.queuedString(canvas, i + 1),
Dom.queuedString(canvas, i + 2),
Dom.queuedNumber(canvas, i + 3),
Dom.queuedNumber(canvas, i + 4),
Dom.queuedNumber(canvas, i + 5),
Dom.queuedNumber(canvas, i + 6),
Dom.queuedNumber(canvas, i + 7),
(int) Dom.queuedNumber(canvas, i + 8));
}
Dom.clearQueued(canvas);
}
/**
* Copies the files of a drop from the page into the file system, and frees the page's copy.
*
* @return the dropped paths, one per line, as the queue's "drop" event takes them; empty if
* they couldn't be stored (logged)
*/
private String storeDrop(JSObject canvas, int id) {
try {
List<String> paths = drops.store(id, new DroppedFiles.Source() {
@Override
public int count() {
return Dom.droppedCount(canvas, id);
}
@Override
public String path(int index) {
return Dom.droppedPath(canvas, id, index);
}
@Override
public boolean isFolder(int index) {
return Dom.droppedIsFolder(canvas, id, index);
}
@Override
public byte[] bytes(int index) {
return Dom.droppedBytes(canvas, id, index).copyToJavaArray();
}
});
return String.join("\n", paths);
} catch (IOException e) {
Dom.consoleError("[Incari] Couldn't store the dropped files: " + e);
return "";
} finally {
Dom.forgetDropped(canvas, id);
}
}
@Override
public void endFrame() {
// What the game wrote this frame goes to storage now, while the page draws: a save point
// (options, the server list, a world) is durable a frame after the game reaches it.
files.flush();
if (frames == 0 && Double.isNaN(lastHeartbeat)) {
// The first frame is drawn: the host page's loading screen can go.
Dom.loaderDone();
}
double stall = Dom.frameEnded();
if (stall < 0) {
// The render thread waited mid-frame; a wait of 50 ms or more prints where it was.
Dom.consoleWarn("[Incari] Stall: a " + Math.round(-stall) + " ms frame in which the render thread waited");
}
// What the servers sent during the frame goes to its connections now: the network's thread
// decodes it while the page waits, and the game handles it as the next frame starts. Handed
// over only at the next frame's pollEvents, it was decoded after that frame's packet
// handling, a whole frame later.
deliverNetwork();
// The page's only chance to run: input, drawing, timers, network callbacks. Under a frame
// limit, as many animation frames as it takes: the page keeps drawing and handling input,
// the game waits between its frames rather than inside one.
waitForFrame();
while (frameInterval > 0 && Dom.nowMillis() - frameStart < frameInterval - FRAME_LIMIT_SLACK_MILLIS) {
// A skipped animation frame is between the game's frames, not a wait inside one.
Dom.frameSkipped();
waitForFrame();
}
frameStart = Dom.nowMillis();
frameInterval = 0;
heartbeat();
}
@Override
public boolean limitFrameRate(int framesPerSecond) {
// For the frame about to end; the game asks again every frame it wants limited.
frameInterval = framesPerSecond > 0 ? 1000.0 / framesPerSecond : 0;
return true;
}
/** Logs the loop's progress every few seconds: the first sign in the console that the game runs. */
private void heartbeat() {
frames++;
double now = Dom.nowMillis();
if (Double.isNaN(lastHeartbeat)) {
lastHeartbeat = now;
} else if (now - lastHeartbeat >= HEARTBEAT_MILLIS) {
Dom.consoleLog("[Incari] Main loop running: " + frames + " frames, "
+ Math.round(frames * 1000.0 / (now - lastHeartbeat)) + " per second; " + Dom.frameStats());
frames = 0;
lastHeartbeat = now;
}
}
@Override
public void flushInputEvents() {
DomEventQueue queue = requireInitialized(events);
// Take what the page queued first: flushing keeps releases, which must not be lost.
takeQueued(queue);
queue.flushInput();
}
@Override
public PlatformInput input() {
DomEventQueue queue = requireInitialized(events);
return new PlatformInput() {
@Override
public boolean isKeyDown(int scancode) {
return queue.isKeyDown(scancode);
}
@Override
public int modifiers() {
return queue.modifiers();
}
@Override
public @Nullable String keyName(int scancode) {
return queue.keyName(scancode);
}
};
}
@Override
public PlatformShell shell() {
return new PlatformShell() {
@Override
public @Nullable String clipboardText() {
return events == null ? "" : events.lastPaste();
}
@Override
public boolean setClipboardText(String text) {
// Asynchronous: the browser answers later, so this can't say whether it worked.
// The game never waits on it (must not block: coroutines).
if (events != null) {
events.copied(text);
}
Dom.writeClipboard(text);
return true;
}
@Override
public boolean setClipboardImage(byte[] png) {
// Asynchronous, as text is: the browser may still refuse (no focus, no permission).
return Dom.writeClipboardImage(Int8Array.copyFromJavaArray(png));
}
@Override
public void open(URI uri) {
Dom.openUrl(uri.toString());
}
@Override
public void openPath(String path) {
File file = new File(path);
if (file.isDirectory()) {
// A page can't show a folder; the picker lets the player add files to it,
// which the game takes as a drop (the pack screens copy them in).
CanvasWindow canvasWindow = window;
if (canvasWindow != null) {
Dom.chooseFiles(canvasWindow.canvas());
}
} else if (file.isFile()) {
try {
byte[] bytes = Files.readAllBytes(file.toPath());
Dom.download(file.getName(), Int8Array.copyFromJavaArray(bytes), mediaType(file.getName()));
} catch (IOException e) {
Dom.consoleError("[Incari] Couldn't read " + path + " to download it: " + e);
}
} else {
Dom.consoleWarn("[Incari] Nothing to open at " + path);
}
}
@Override
public boolean showsFolders() {
return false;
}
@Override
public void download(String fileName, byte[] bytes) {
Dom.download(fileName, Int8Array.copyFromJavaArray(bytes), mediaType(fileName));
}
@Override
public boolean showErrorDialog(String title, String message, boolean askToContinue) {
if (askToContinue) {
return Dom.confirm(title + "\n\n" + message);
}
Dom.alert(title + "\n\n" + message);
return false;
}
};
}
@Override
public PlatformAudio audio() {
return audio;
}
@Override
public PlatformNetwork network() {
return network;
}
@Override
public PlatformRtc rtc() {
return rtc;
}
@Override
public void crashNatively() {
throw new InternalError("Debug crash requested; a page can't crash natively");
}
@Override
public PlatformStorage storage() {
return storage;
}
@Override
public PlatformThreads threads() {
return threads;
}
@Override
public PlatformProfiling profiling() {
return profiling;
}
@Override
public PlatformFonts fonts() {
return fonts;
}
/** The media type a download of {@code name} is offered as. */
static String mediaType(String name) {
String lower = name.toLowerCase(Locale.ROOT);
if (lower.endsWith(".png")) {
return "image/png";
} else if (lower.endsWith(".zip")) {
return "application/zip";
} else if (lower.endsWith(".json") || lower.endsWith(".mcmeta")) {
return "application/json";
} else if (lower.endsWith(".txt") || lower.endsWith(".log")) {
return "text/plain";
}
return "application/octet-stream";
}
/** Logs to the browser console; the entry point wires the game's logging here. */
public static void log(String level, String message) {
switch (level) {
case "ERROR" -> Dom.consoleError(message);
case "WARN" -> Dom.consoleWarn(message);
default -> Dom.consoleLog(message);
}
}
private static <T> T requireInitialized(@Nullable T part) {
if (part == null) {
throw new IllegalStateException("The web platform isn't initialized yet");
}
return part;
}
}
@@ -0,0 +1,62 @@
package incari.platform.web;
import incari.platform.api.profile.FrameSample;
import incari.platform.api.profile.MemoryUsage;
import incari.platform.api.profile.PlatformProfiling;
import java.nio.ByteBuffer;
import org.teavm.jso.JSBody;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Profiling in the page (ADR 0021): frames go into the frame monitor's table
* ({@code window.__incariFrames}), where the benchmark runner reads them; memory is the page's
* JavaScript heap (Chrome's {@code performance.memory}, which WebAssembly GC objects count in) and
* the module's linear memory, where the game's off-heap buffers are (ADR 0008). The runner asks the
* game for things through the monitor's {@code requests} ({@link #takeRequest}).
*/
final class WebProfiling implements PlatformProfiling {
/** A direct buffer, so its view's {@code ArrayBuffer} is the module's linear memory. */
private final ByteBuffer probe = ByteBuffer.allocateDirect(8);
@Override
public MemoryUsage memory() {
return new MemoryUsage((long) Dom.heapUsed(), (long) Dom.heapLimit(), linearBytes(), (long) Dom.collections());
}
/** The module's linear memory. It only grows, and growing detaches older views, so a fresh view each time. */
private long linearBytes() {
return (long) Dom.backingBytes(Int8Array.fromJavaBuffer(probe));
}
@Override
public void frameProfiled(FrameSample sample) {
Dom.frameSample(
sample.tickMillis(),
sample.extractMillis(),
sample.renderMillis(),
sample.gpuMillis(),
sample.drawCalls(),
sample.terrainDrawCalls(),
sample.terrainSections(),
sample.meshQueue(),
(double) linearBytes());
}
@Override
public void mark(String name) {
Dom.mark(name);
}
@Override
public boolean takeRequest(String name) {
return takePageRequest(name);
}
/** A request the benchmark runner left in the frame monitor's {@code requests}, taken once. */
@JSBody(
params = "name",
script = "var f = window.__incariFrames, r = f && f.requests;"
+ "if (!r || !r[name]) return false; delete r[name]; return true;")
private static native boolean takePageRequest(String name);
}
@@ -0,0 +1,134 @@
package incari.platform.web;
import incari.platform.api.PlatformRecorder;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
/**
* Screen recording in the page (ADR 0062), as Eaglercraft's browser builds record: the canvas as a
* video track ({@code captureStream}), the game's sound from the audio device's master gain (ADR
* 0013) through a gain of its own, and the microphone if asked, mixed into one stream that a
* {@code MediaRecorder} encodes (the browser's own encoder, off the page's thread; MP4 where Chrome
* records it, else WebM). On stop the video downloads.
*
* <p>The recorded chunks stay in the tab's memory until then: about 19 MB a minute at the default
* 2.5 Mbit/s, which the settings screen says.
*/
final class WebRecorder implements PlatformRecorder {
@Override
public boolean supported() {
return available();
}
@Override
public void start(Options options, String fileName) {
if (state() != State.IDLE) {
return;
}
start(
WebPlatform.CANVAS_ID,
options.framesPerSecond(),
options.videoKilobits(),
options.gameVolume(),
options.microphone(),
options.microphoneVolume(),
fileName);
}
@Override
public void stop() {
stopRecording();
}
@Override
public State state() {
return switch (stateName()) {
case "starting" -> State.STARTING;
case "recording" -> State.RECORDING;
default -> State.IDLE;
};
}
@Override
public @Nullable String error() {
return errorText();
}
@Override
public long elapsedMillis() {
return (long) elapsed();
}
@JSBody(
script = "return typeof MediaRecorder !== 'undefined' && typeof HTMLCanvasElement !== 'undefined'"
+ " && typeof HTMLCanvasElement.prototype.captureStream === 'function';")
private static native boolean available();
@JSBody(
params = {"canvasId", "fps", "kbps", "gameVolume", "mic", "micVolume", "fileName"},
script = "var r = globalThis.incariRecorder = {state: 'starting', error: null, chunks: [], started: 0};"
+ "try {"
+ " var canvas = document.getElementById(canvasId);"
+ " var video = canvas.captureStream(fps);"
+ " var tracks = video.getVideoTracks().slice(); r.video = video;"
+ " var a = globalThis.incariAudio, dest = null;"
+ " if (a && a.master) { r.ctx = a.master.context; dest = r.ctx.createMediaStreamDestination();"
+ " r.game = r.ctx.createGain(); r.game.gain.value = gameVolume;"
+ " a.master.connect(r.game); r.game.connect(dest); r.master = a.master; }"
+ " function cleanup() {"
+ " try { if (r.master && r.game) r.master.disconnect(r.game); } catch (e) {}"
+ " if (r.mic) r.mic.getTracks().forEach(function (t) { t.stop(); });"
+ " r.video.getTracks().forEach(function (t) { t.stop(); }); }"
+ " function begin(micStream) {"
+ " if (r.state !== 'starting') { if (micStream) micStream.getTracks().forEach(function (t) { t.stop(); });"
+ " cleanup(); return; }"
+ " if (micStream && dest) { r.mic = micStream; var source = r.ctx.createMediaStreamSource(micStream);"
+ " var level = r.ctx.createGain(); level.gain.value = micVolume; source.connect(level); level.connect(dest); }"
+ " if (dest) dest.stream.getAudioTracks().forEach(function (t) { tracks.push(t); });"
+ " var types = ['video/mp4;codecs=avc1.42E01E,mp4a.40.2', 'video/webm;codecs=vp9,opus',"
+ " 'video/webm;codecs=vp8,opus', 'video/webm'];"
+ " var type = ''; for (var i = 0; i < types.length; i++)"
+ " if (MediaRecorder.isTypeSupported(types[i])) { type = types[i]; break; }"
+ " var ext = type.indexOf('mp4') >= 0 ? 'mp4' : 'webm';"
+ " var rec = new MediaRecorder(new MediaStream(tracks), type"
+ " ? {mimeType: type, videoBitsPerSecond: kbps * 1000, audioBitsPerSecond: 128000}"
+ " : {videoBitsPerSecond: kbps * 1000});"
+ " rec.ondataavailable = function (e) { if (e.data && e.data.size > 0) r.chunks.push(e.data); };"
+ " rec.onerror = function (e) { r.error = 'The browser stopped the recording'"
+ " + (e && e.error && e.error.message ? ': ' + e.error.message : ''); };"
+ " rec.onstop = function () { cleanup();"
+ " if (r.chunks.length > 0) { var blob = new Blob(r.chunks, {type: type || 'video/webm'});"
+ " var url = URL.createObjectURL(blob); var link = document.createElement('a');"
+ " link.href = url; link.download = fileName + '.' + ext; document.body.appendChild(link);"
+ " link.click(); link.remove(); setTimeout(function () { URL.revokeObjectURL(url); }, 60000); }"
+ " r.chunks = []; r.state = 'idle'; };"
+ " rec.start(1000); r.rec = rec; r.started = performance.now(); r.state = 'recording'; }"
+ " if (mic && navigator.mediaDevices && navigator.mediaDevices.getUserMedia)"
+ " navigator.mediaDevices.getUserMedia({audio: true}).then(begin, function () {"
+ " r.error = 'No microphone (not allowed, or none): recording without it'; begin(null); });"
+ " else begin(null);"
+ "} catch (e) { r.state = 'idle'; r.error = 'Couldn\\'t record: ' + (e && e.message ? e.message : e);"
+ " try { if (r.master && r.game) r.master.disconnect(r.game); } catch (e2) {}"
+ " if (r.video) r.video.getTracks().forEach(function (t) { t.stop(); }); }")
private static native void start(
String canvasId, int fps, int kbps, float gameVolume, boolean mic, float micVolume, String fileName);
@JSBody(
script =
"var r = globalThis.incariRecorder; if (!r) return;"
+ " if (r.state === 'starting') { r.state = 'idle'; return; }"
+ " if (r.state === 'recording' && r.rec && r.rec.state !== 'inactive') { r.state = 'stopping'; r.rec.stop(); }")
private static native void stopRecording();
@JSBody(script = "var r = globalThis.incariRecorder; return r ? r.state : 'idle';")
private static native String stateName();
@JSBody(script = "var r = globalThis.incariRecorder; return r && r.error ? r.error : null;")
private static native @Nullable String errorText();
@JSBody(
script = "var r = globalThis.incariRecorder;"
+ " return r && r.state === 'recording' ? performance.now() - r.started : 0;")
private static native double elapsed();
}
@@ -0,0 +1,380 @@
package incari.platform.web;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Server connections in the browser: WebSockets only, since a page can't open a TCP socket. HTTP
* GETs go through {@code fetch} ({@link WebFetch}).
*
* <p>The browser's socket callbacks never call Java: they queue what happened in a JavaScript
* array on the socket, and {@link #deliver} (called by the platform on the game's thread) hands it
* to the listeners. TeaVM compiles most of this program as coroutines, and a coroutine can't start
* from a JavaScript callback. The platform delivers as each frame starts and ends, and when a
* message ends the render thread's wait between frames, so the network's thread decodes it before
* the next frame's packet handling.
*/
final class WebSocketNetwork implements PlatformNetwork {
/** Connections with events still to deliver; the game's thread only. */
private final List<Socket> sockets = new ArrayList<>();
@Override
public boolean canAcceptConnections() {
return false;
}
@Override
public boolean canOpenSockets() {
return false;
}
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
Socket socket = new Socket(host + ":" + port, listener, null);
socket.failLater("Browsers can only join WebSocket servers. Use an address starting with ws:// or wss://");
sockets.add(socket);
return socket;
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
JSObject handle;
try {
handle = open(url);
} catch (RuntimeException e) {
// The constructor throws on a URL it won't open (a bad port, ws:// from an https page).
Socket socket = new Socket(url, listener, null);
socket.failLater("The browser refused to open " + url + ": " + e.getMessage());
sockets.add(socket);
return socket;
}
Socket socket = new Socket(url, listener, handle);
sockets.add(socket);
return socket;
}
@Override
public byte[] fetch(String url, int maxBytes) throws IOException {
return WebFetch.get(url, maxBytes);
}
/** Delivers every queued socket event to its listener. The game's thread, once per frame. */
void deliver() {
if (sockets.isEmpty()) {
return;
}
// A listener may open another socket while this runs; that one waits for the next frame.
List<Socket> current = new ArrayList<>(sockets);
for (Socket socket : current) {
socket.deliver();
if (socket.finished) {
sockets.remove(socket);
}
}
}
/** One connection, and the events its browser socket queued since the last delivery. */
private static final class Socket implements NetConnection {
private final String description;
private final NetConnection.Listener listener;
private final @Nullable JSObject handle;
private @Nullable String pendingFailure;
private boolean open;
private boolean closedByUs;
private boolean finished;
// For details(), the game's thread only.
/** The longest a browser event waited in the queue before the game read it, in ms. */
private double longestQueueWait;
private int closeCode = -1;
private String closeReason = "";
/** Bytes the browser still held unsent when the socket closed; -1 if it didn't close itself. */
private double unsentAtClose = -1;
private boolean onlineAtClose = true;
Socket(String description, NetConnection.Listener listener, @Nullable JSObject handle) {
this.description = description;
this.listener = listener;
this.handle = handle;
}
void failLater(String reason) {
pendingFailure = reason;
}
@Override
public void send(ByteBuffer data) {
JSObject socket = handle;
if (socket == null || closedByUs || finished) {
return;
}
// The channel hands over a buffer that is exactly its array: copied to the page once.
byte[] bytes;
if (data.hasArray()
&& data.arrayOffset() + data.position() == 0
&& data.remaining() == data.array().length) {
bytes = data.array();
data.position(data.limit());
} else {
bytes = new byte[data.remaining()];
data.get(bytes);
}
// Sent at once if open; queued by the page until the socket opens otherwise.
WebSocketNetwork.send(socket, Int8Array.copyFromJavaArray(bytes));
}
@Override
public void sendText(String text) {
JSObject socket = handle;
if (socket == null || closedByUs || finished) {
return;
}
WebSocketNetwork.sendText(socket, text);
}
@Override
public void close() {
if (closedByUs || finished) {
return;
}
closedByUs = true;
open = false;
JSObject socket = handle;
if (socket != null) {
WebSocketNetwork.close(socket);
}
// Reported at the next delivery, in order after anything already queued.
}
@Override
public boolean isOpen() {
return open;
}
@Override
public String remoteDescription() {
return description;
}
void deliver() {
if (finished) {
return;
}
String failure = pendingFailure;
if (failure != null) {
finish(new IOException(failure));
return;
}
JSObject socket = handle;
if (socket == null) {
return;
}
int count = queued(socket);
double now = now();
for (int i = 0; i < count && !finished; i++) {
longestQueueWait = Math.max(longestQueueWait, now - queuedTime(socket, i));
switch (queuedType(socket, i)) {
case "open" -> {
if (!closedByUs) {
open = true;
listener.connected();
}
}
case "message" -> {
if (!closedByUs) {
byte[] message = new Int8Array(queuedData(socket, i)).copyToJavaArray();
listener.received(ByteBuffer.wrap(message));
}
}
case "text" -> {
if (!closedByUs) {
listener.receivedText(queuedText(socket, i));
}
}
case "close" -> {
int code = queuedCode(socket, i);
String reason = queuedReason(socket, i);
closeCode = code;
closeReason = reason;
unsentAtClose = queuedUnsent(socket, i);
onlineAtClose = queuedOnline(socket, i);
boolean clean = code == 1000 || code == 1001 || closedByUs;
finish(
clean
? null
: new IOException("Connection to " + description + " closed (" + code
+ (reason.isEmpty() ? "" : ": " + reason) + ")"));
}
default -> {
// "error" always comes with a "close", which reports it.
}
}
}
// Listeners may suspend (coroutines), letting the page queue more meanwhile: drop only
// what was delivered.
dropQueued(socket, count);
if (closedByUs && !finished) {
finish(null);
}
}
@Override
public Map<String, String> details() {
Map<String, String> details = new LinkedHashMap<>();
if (closeCode >= 0) {
details.put(
"Close code",
closeCode(closeCode) + (closeReason.isEmpty() ? "" : ", \"" + closeReason + "\""));
details.put("Unsent at close", Math.round(unsentAtClose) + " B");
details.put("Browser online", onlineAtClose ? "Yes" : "No, it had lost the network");
} else if (closedByUs) {
details.put("Close code", "Closed by this game");
}
if (handle != null) {
details.put("Longest game stall", Math.round(longestQueueWait) + " ms");
}
return details;
}
private void finish(@Nullable Throwable cause) {
finished = true;
open = false;
listener.closed(cause);
}
}
/** A WebSocket close code with what it means. */
static String closeCode(int code) {
String meaning =
switch (code) {
case 1000 -> "normal close";
case 1001 -> "server going away or page leaving";
case 1002 -> "protocol error";
case 1003 -> "unsupported data";
case 1005 -> "no code given";
case 1006 -> "dropped with no close message";
case 1007 -> "invalid text";
case 1008 -> "policy violation";
case 1009 -> "message too big";
case 1011 -> "server error";
case 1012 -> "server restarting";
case 1013 -> "try again later";
case 1015 -> "TLS failed";
default -> "";
};
return code + (meaning.isEmpty() ? "" : " (" + meaning + ")");
}
// --- The page side ---------------------------------------------------------------------
/*
* Each socket keeps a queue of what happened, as arrays: ["open"], ["message", ArrayBuffer],
* ["text", string] (Eagler's query answers), ["close", code, reason, unsent bytes, online],
* ["error"]. __incariTimes holds when each entry was queued (performance.now()), for details().
*/
@JSBody(
params = "url",
script = "var ws = new WebSocket(url); ws.binaryType = 'arraybuffer'; var q = []; ws.__incariQueue = q;"
+ "var t = []; ws.__incariTimes = t;"
// Ends the render thread's wait between frames, so the message is delivered now.
+ "function add(e) { q.push(e); t.push(performance.now());"
+ " var wake = window.__incariNetWake; if (wake) wake(); }"
+ "ws.onopen = function() { add(['open']); };"
+ "ws.onmessage = function(e) {"
+ " add(typeof e.data === 'string' ? ['text', e.data] : ['message', e.data]); };"
+ "ws.onerror = function() { add(['error']); };"
+ "ws.onclose = function(e) { add(['close', e.code, e.reason || '', ws.bufferedAmount,"
+ " typeof navigator === 'undefined' || navigator.onLine !== false]); };"
+ "return ws;")
private static native JSObject open(String url);
@JSBody(
params = {"ws", "data"},
script = "if (ws.readyState === 1) ws.send(data);"
+ " else if (ws.readyState === 0) { var p = ws.__incariPending;"
+ " if (!p) { p = ws.__incariPending = [];"
+ " ws.addEventListener('open', function() { for (var i = 0; i < p.length; i++) ws.send(p[i]);"
+ " p.length = 0; }); }"
+ " p.push(data); }")
private static native void send(JSObject ws, Int8Array data);
// The same queueing as send: a text message is one more entry in the pending list.
@JSBody(
params = {"ws", "text"},
script = "if (ws.readyState === 1) ws.send(text);"
+ " else if (ws.readyState === 0) { var p = ws.__incariPending;"
+ " if (!p) { p = ws.__incariPending = [];"
+ " ws.addEventListener('open', function() { for (var i = 0; i < p.length; i++) ws.send(p[i]);"
+ " p.length = 0; }); }"
+ " p.push(text); }")
private static native void sendText(JSObject ws, String text);
@JSBody(params = "ws", script = "try { ws.close(1000); } catch (e) {}")
private static native void close(JSObject ws);
@JSBody(params = "ws", script = "return ws.__incariQueue.length;")
private static native int queued(JSObject ws);
@JSBody(
params = {"ws", "index"},
script = "return ws.__incariQueue[index][0];")
private static native String queuedType(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return ws.__incariQueue[index][1];")
private static native ArrayBuffer queuedData(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return String(ws.__incariQueue[index][1]);")
private static native String queuedText(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return ws.__incariQueue[index][1] | 0;")
private static native int queuedCode(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return String(ws.__incariQueue[index][2]);")
private static native String queuedReason(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return ws.__incariTimes[index];")
private static native double queuedTime(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return +ws.__incariQueue[index][3] || 0;")
private static native double queuedUnsent(JSObject ws, int index);
@JSBody(
params = {"ws", "index"},
script = "return ws.__incariQueue[index][4] !== false;")
private static native boolean queuedOnline(JSObject ws, int index);
@JSBody(script = "return performance.now();")
private static native double now();
@JSBody(
params = {"ws", "count"},
script = "ws.__incariQueue.splice(0, count); ws.__incariTimes.splice(0, count);")
private static native void dropQueued(JSObject ws, int count);
}
@@ -0,0 +1,343 @@
package incari.platform.web;
import incari.platform.api.threads.WorkerException;
import incari.platform.api.threads.WorkerJob;
import incari.platform.api.threads.WorkerPool;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.util.ArrayDeque;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Web Workers running a program of the build's beside the game (ADR 0023): each loads the
* program's own WebAssembly module ({@code <program>.wasm}, TeaVM's loader beside it) through a
* small bootstrap script ({@code src/main/js/program-worker.js}) and answers the messages the game
* sends it.
*
* <p>Messages are copied out of the game's linear memory as they're sent: into a slot of a
* {@code SharedArrayBuffer} where the page is cross-origin isolated, else into an
* {@code ArrayBuffer} handed over to the worker. Answers come back in an {@code ArrayBuffer} of
* their own and are copied into a direct buffer (linear memory) when their job is awaited. A job
* awaited from the background pool steps aside for the wait ({@link IdleTimeExecutor#awaitOutside}),
* so the pool keeps other jobs going.
*
* <p>Everything here runs on the page's one thread.
*/
final class WebWorkerPool implements WorkerPool {
/** Bytes per slot of the shared message buffer; a longer message is handed over instead. */
private static final int SLOT_BYTES = 64 * 1024;
private static final int SLOTS = 32;
private final JSObject pool;
private final int size;
private final ArrayDeque<ByteBuffer> replyBuffers = new ArrayDeque<>();
/**
* Messages are copied here and replies land here, each read through a view kept from one job to
* the next (ADR 0027): a JavaScript object handed to Java is wrapped and kept in the runtime's
* weak map, and two views a job, hundreds a second while terrain loads, made major collections
* pause walking that map. Made again only when replaced or detached by growing memory.
*/
private ByteBuffer staging = ByteBuffer.allocateDirect(64 * 1024);
private @Nullable Int8Array stagingView;
private ByteBuffer replyStaging = ByteBuffer.allocateDirect(256 * 1024);
private @Nullable Int8Array replyView;
private int inFlight;
private WebWorkerPool(JSObject pool, int size) {
this.pool = pool;
this.size = size;
}
/**
* Starts the workers for {@code program}, or returns null if the page can't: no Workers, or no
* program by that name in the build.
*/
static @Nullable WebWorkerPool start(String program) {
if (!hasWorkers()) {
return null;
}
String runtime = programUrl(program, "runtime", program + ".wasm-runtime.js");
String module = programUrl(program, "module", program + ".wasm");
int count = Math.max(1, Math.min(4, hardwareConcurrency() - 1));
JSObject pool = createPool(ProgramWorkerSource.SCRIPT, program, count, runtime, module, SLOT_BYTES, SLOTS);
return new WebWorkerPool(pool, count);
}
@Override
public int size() {
return size;
}
@Override
public void broadcast(ByteBuffer message) {
int length = stage(message);
if (!broadcast(pool, stagingView(false), length)) {
broadcast(pool, stagingView(true), length);
}
}
@Override
public WorkerJob submit(ByteBuffer message) {
int length = stage(message);
int id = submit(pool, stagingView(false), length);
if (id < 0) {
id = submit(pool, stagingView(true), length);
}
inFlight++;
return new Job(id);
}
@Override
public int inFlight() {
return inFlight;
}
/** Copies the message's remaining bytes to the start of {@link #staging}; their count. */
private int stage(ByteBuffer message) {
int length = message.remaining();
if (staging.capacity() < length) {
staging = ByteBuffer.allocateDirect(Math.max(length, staging.capacity() * 2));
stagingView = null;
}
staging.put(0, message, message.position(), length);
return length;
}
private Int8Array stagingView(boolean remake) {
Int8Array view = stagingView;
if (view == null || remake) {
view = Int8Array.fromJavaBuffer(staging);
stagingView = view;
}
return view;
}
/** The reply buffer's kept view, the buffer grown to {@code length} first. */
private Int8Array replyView(int length, boolean remake) {
if (replyStaging.capacity() < length) {
replyStaging = ByteBuffer.allocateDirect(Math.max(length, replyStaging.capacity() * 2));
replyView = null;
}
Int8Array view = replyView;
if (view == null || remake) {
view = Int8Array.fromJavaBuffer(replyStaging);
replyView = view;
}
return view;
}
private final class Job implements WorkerJob {
private final int id;
private @Nullable ByteBuffer reply;
/** The direct buffer holding the reply, returned to the pool on release. */
private @Nullable ByteBuffer held;
private boolean awaited;
private boolean released;
Job(int id) {
this.id = id;
}
@Override
public ByteBuffer await() {
if (released) {
throw new IllegalStateException("The job was released");
}
ByteBuffer answer = reply;
if (answer == null) {
answer = receive();
}
return answer.duplicate().order(ByteOrder.LITTLE_ENDIAN);
}
private ByteBuffer receive() {
if (!hasReply(pool, id)) {
IdleTimeExecutor.awaitOutside(() -> {
awaitReply(pool, id);
return null;
});
}
awaited = true;
inFlight--;
int length = replyLength(pool, id);
if (length < 0) {
String error = replyError(pool, id);
forget(pool, id);
throw new WorkerException(error);
}
ByteBuffer buffer = replyBuffers.poll();
if (buffer == null || buffer.capacity() < length) {
buffer = ByteBuffer.allocateDirect(Math.max(length, 256 * 1024));
}
if (!copyReply(pool, id, replyView(length, false))) {
copyReply(pool, id, replyView(length, true));
}
buffer.put(0, replyStaging, 0, length);
forget(pool, id);
held = buffer;
ByteBuffer answer = buffer.slice(0, length).order(ByteOrder.LITTLE_ENDIAN);
reply = answer;
return answer;
}
@Override
public boolean done() {
return reply != null || hasReply(pool, id);
}
@Override
public void release() {
if (released) {
return;
}
released = true;
reply = null;
ByteBuffer buffer = held;
held = null;
if (buffer != null) {
replyBuffers.push(buffer);
} else if (!awaited) {
// Never awaited: the answer is dropped when it comes.
inFlight--;
discardWhenAnswered(pool, id);
}
}
}
// ---- The page's side, in JavaScript -----------------------------------------------------
@JSBody(script = "return typeof Worker === 'function';")
private static native boolean hasWorkers();
@JSBody(script = "return (navigator.hardwareConcurrency | 0) || 2;")
private static native int hardwareConcurrency();
/** The program's file URL from the build manifest, or the development build's default name. */
@JSBody(
params = {"program", "part", "fallback"},
script = "var build = window.incariBuild; var programs = build && build.programs;"
+ " var entry = programs && programs[program];"
// The single-file page's own URL may have no folder (offline.ts).
+ " var base = window.incariFiles ? window.incariFiles.base : location.href;"
+ " return new URL((entry && entry[part]) || fallback, base).href;")
private static native String programUrl(String program, String part, String fallback);
@JSBody(
params = {"source", "program", "count", "runtime", "module", "slotBytes", "slots"},
script = "var url = URL.createObjectURL(new Blob([source], {type: 'text/javascript'}));"
+ "var pool = {workers: [], inFlight: [], replies: new Map(), waiters: new Map(),"
+ " discard: new Set(), slotOf: new Map(), freeSlots: [], sab: null, slotBytes: slotBytes,"
+ " nextId: 1, failed: null};"
// Messages go through shared memory where the page is cross-origin isolated.
+ "if (self.crossOriginIsolated && typeof SharedArrayBuffer === 'function') {"
+ " pool.sab = new SharedArrayBuffer(slotBytes * slots);"
+ " for (var s = 0; s < slots; s++) pool.freeSlots.push(s); }"
+ "var answered = function(id, data) {"
+ " if (pool.slotOf.has(id)) { pool.freeSlots.push(pool.slotOf.get(id)); pool.slotOf.delete(id); }"
+ " if (pool.discard.delete(id)) return;"
+ " pool.replies.set(id, data);"
+ " var waiter = pool.waiters.get(id); if (waiter) { pool.waiters.delete(id); waiter(); } };"
+ "pool.fail = function(reason) { if (pool.failed) return; pool.failed = reason;"
+ " console.error('[Incari] ' + program + ' workers failed: ' + reason);"
+ " var ids = Array.from(pool.waiters.keys()); ids.forEach(function(id) { answered(id, {id: id, error: reason}); }); };"
// A function expression called in the loop: TeaVM's minifier drops the parentheses
// around an immediately called one, which then reads as a declaration.
+ "var startWorker = function(index) {"
+ " var worker = new Worker(url, {name: 'incari-' + program + '-' + index});"
+ " worker.onmessage = function(event) { var data = event.data;"
+ " if (data.kind === 'ready') return;"
+ " if (data.kind === 'failed') { pool.fail(data.error); return; }"
+ " pool.inFlight[index]--; answered(data.id, data); };"
+ " worker.onerror = function(event) { pool.fail('worker ' + index + ': ' + (event.message || 'error')); };"
+ " worker.postMessage({kind: 'start', runtime: runtime, module: module});"
+ " pool.workers.push(worker); pool.inFlight.push(0); };"
+ "for (var i = 0; i < count; i++) startWorker(i);"
+ "self.__incariWorkerPools = self.__incariWorkerPools || {};"
+ "self.__incariWorkerPools[program] = pool;"
+ "return pool;")
private static native JSObject createPool(
String source, String program, int count, String runtime, String module, int slotBytes, int slots);
@JSBody(
params = {"pool", "staging", "length"},
script = "if (staging.byteLength === 0) return -1; var view = staging.subarray(0, length);"
+ "var id = pool.nextId++; if (pool.failed) { pool.replies.set(id, {id: id, error: pool.failed}); return id; }"
+ "var best = 0; for (var i = 1; i < pool.workers.length; i++) if (pool.inFlight[i] < pool.inFlight[best]) best = i;"
+ "pool.inFlight[best]++;"
+ "if (pool.sab && view.length <= pool.slotBytes && pool.freeSlots.length) {"
+ " var slot = pool.freeSlots.pop(); pool.slotOf.set(id, slot);"
+ " new Int8Array(pool.sab, slot * pool.slotBytes, view.length).set(view);"
+ " pool.workers[best].postMessage({id: id, buffer: pool.sab, offset: slot * pool.slotBytes, length: view.length});"
+ "} else { var copy = view.slice();"
+ " pool.workers[best].postMessage({id: id, buffer: copy.buffer, offset: 0, length: view.length}, [copy.buffer]); }"
+ "return id;")
private static native int submit(JSObject pool, Int8Array staging, int length);
@JSBody(
params = {"pool", "staging", "length"},
script = "if (staging.byteLength === 0) return false; var view = staging.subarray(0, length);"
+ "pool.workers.forEach(function(worker) { var copy = view.slice();"
+ " worker.postMessage({id: -1, buffer: copy.buffer, offset: 0, length: view.length}, [copy.buffer]); });"
+ "return true;")
private static native boolean broadcast(JSObject pool, Int8Array staging, int length);
@JSBody(
params = {"pool", "id"},
script = "return pool.replies.has(id);")
private static native boolean hasReply(JSObject pool, int id);
@JSBody(
params = {"pool", "id"},
script = "var data = pool.replies.get(id); return data && data.reply ? data.reply.byteLength : -1;")
private static native int replyLength(JSObject pool, int id);
@JSBody(
params = {"pool", "id"},
script = "var data = pool.replies.get(id); return data ? String(data.error) : 'no answer';")
private static native String replyError(JSObject pool, int id);
@JSBody(
params = {"pool", "id", "view"},
script = "if (view.byteLength === 0) return false;"
+ "view.set(new Int8Array(pool.replies.get(id).reply)); return true;")
private static native boolean copyReply(JSObject pool, int id, Int8Array view);
@JSBody(
params = {"pool", "id"},
script = "pool.replies.delete(id);")
private static native void forget(JSObject pool, int id);
@JSBody(
params = {"pool", "id"},
script = "if (!pool.replies.delete(id)) pool.discard.add(id);")
private static native void discardWhenAnswered(JSObject pool, int id);
/** Suspends the calling coroutine until the job's answer is in. */
@Async
private static native Void awaitReply(JSObject pool, int id);
private static void awaitReply(JSObject pool, int id, AsyncCallback<Void> callback) {
onReply(pool, id, () -> callback.complete(null));
}
@JSFunctor
interface Answered extends JSObject {
void answered();
}
@JSBody(
params = {"pool", "id", "callback"},
script = "if (pool.replies.has(id)) { callback(); } else { pool.waiters.set(id, callback); }")
private static native void onReply(JSObject pool, int id, Answered callback);
}
@@ -0,0 +1,240 @@
package incari.platform.web;
import incari.platform.api.AppInfo;
import incari.platform.api.NativeSurfaceFactory;
import incari.platform.api.Platform;
import incari.platform.api.PlatformShell;
import incari.platform.api.audio.PlatformAudio;
import incari.platform.api.input.PlatformInput;
import incari.platform.api.net.NetConnection;
import incari.platform.api.net.PlatformNetwork;
import incari.platform.api.profile.PlatformProfiling;
import incari.platform.api.storage.PlatformStorage;
import incari.platform.api.threads.PlatformChannel;
import incari.platform.api.threads.PlatformThreads;
import incari.platform.api.window.PlatformDisplays;
import incari.platform.api.window.PlatformEventListener;
import incari.platform.api.window.PlatformWindow;
import incari.platform.api.window.WindowSpec;
import incari.platform.web.storage.WebFileSystem;
import java.net.URI;
import java.util.concurrent.ExecutorService;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
/**
* The platform in a copy of the game started in a worker (ADR 0039): singleplayer's server, which
* needs threads, files and its page, and none of a window, sound or the network. The background
* pool runs in slots a message loop hands out, as there are no frames here; the server's own thread
* runs whenever the pool's tasks wait or a slot ends. Files are the worker's own tree, its changes
* going to the page ({@link WebFileSystem#installDetached}).
*/
public final class WorkerPlatform implements Platform {
private final PlatformStorage storage;
private final WebFileSystem files;
private final @Nullable PlatformChannel parent = JsChannel.parent();
private final WorkerProfiling profiling = new WorkerProfiling();
private final PlatformThreads threads = new PlatformThreads() {
@Override
public int backgroundThreads(int suggested) {
return 0;
}
@Override
public ExecutorService backgroundExecutor(String name) {
return IdleTimeExecutor.forWorker("Worker-" + name);
}
@Override
public void pauseIfLate() {
IdleTimeExecutor.pauseIfLate();
}
@Override
public boolean oneThread() {
return true;
}
@Override
public int backgroundQueued() {
return IdleTimeExecutor.queuedEverywhere();
}
@Override
public @Nullable PlatformChannel parentChannel() {
return parent;
}
@Override
public @Nullable PlatformChannel startGameWorker(String role) {
return JsChannel.startWorker(role);
}
};
/**
* @param folders where the game's folders are (the same as the page's)
* @param files the worker's own file system
*/
public WorkerPlatform(PlatformStorage folders, WebFileSystem files) {
this.storage = new FileStorage(folders, files);
this.files = files;
}
/**
* Reads a zip the page's storage keeps (the client jar) straight from the origin's private file
* system, where the storage worker put it; else fetches it from {@code url}, as the page did
* the first time. Suspends until it's read.
*
* @param cachePath where the storage worker keeps it, from the private file system's root
*/
@Async
public static native ArrayBuffer cachedZip(String cachePath, String url);
private static void cachedZip(String cachePath, String url, AsyncCallback<ArrayBuffer> callback) {
readCachedZip(cachePath, url, buffer -> callback.complete(buffer));
}
@JSFunctor
interface BufferRead extends JSObject {
void read(ArrayBuffer buffer);
}
@JSBody(
params = {"cachePath", "url", "done"},
script = "function fetchIt() { return fetch(url).then(function(r) {"
+ " if (!r.ok) throw new Error(url + ': ' + r.status); return r.arrayBuffer(); }); }"
+ "var read = navigator.storage && navigator.storage.getDirectory"
+ " ? navigator.storage.getDirectory().then(function(dir) {"
+ " var parts = cachePath.split('/').filter(function(p) { return p; });"
+ " var file = parts.pop(); var step = Promise.resolve(dir);"
+ " parts.forEach(function(p) { step = step.then(function(d) { return d.getDirectoryHandle(p); }); });"
+ " return step.then(function(d) { return d.getFileHandle(file); })"
+ " .then(function(h) { return h.getFile(); }).then(function(f) { return f.arrayBuffer(); }); })"
+ " : Promise.reject(new Error('no private file system'));"
+ "read.catch(fetchIt).then(done, function(error) {"
+ " console.error('[Incari] Worker: no ' + url + ': ' + error); done(new ArrayBuffer(0)); });")
private static native void readCachedZip(String cachePath, String url, BufferRead done);
@Override
public String description() {
return "Browser worker";
}
@Override
public PlatformProfiling profiling() {
return profiling;
}
@Override
public void initialize(AppInfo app) {}
@Override
public void shutdown() {
files.flush();
}
@Override
public long nanoTime() {
return (long) (Dom.nowMillis() * 1_000_000.0);
}
@Override
public PlatformDisplays displays() {
throw new UnsupportedOperationException("A worker has no displays");
}
@Override
public PlatformWindow createWindow(WindowSpec spec, NativeSurfaceFactory surface) {
throw new UnsupportedOperationException("A worker has no window");
}
@Override
public void pollEvents(PlatformEventListener listener) {}
@Override
public void endFrame() {}
@Override
public void flushInputEvents() {}
@Override
public PlatformInput input() {
throw new UnsupportedOperationException("A worker has no input");
}
@Override
public PlatformShell shell() {
return new PlatformShell() {
@Override
public String clipboardText() {
return "";
}
@Override
public boolean setClipboardText(String text) {
return false;
}
@Override
public void open(URI uri) {}
@Override
public boolean showErrorDialog(String title, String message, boolean askToContinue) {
Dom.consoleError("[Incari] " + title + ": " + message);
return false;
}
};
}
@Override
public PlatformAudio audio() {
throw new UnsupportedOperationException("A worker has no sound");
}
@Override
public PlatformNetwork network() {
return new PlatformNetwork() {
@Override
public NetConnection connect(String host, int port, NetConnection.Listener listener) {
throw new UnsupportedOperationException("A worker's copy of the game connects nowhere");
}
@Override
public NetConnection openWebSocket(String url, NetConnection.Listener listener) {
throw new UnsupportedOperationException("A worker's copy of the game connects nowhere");
}
@Override
public boolean canAcceptConnections() {
return false;
}
@Override
public boolean canOpenSockets() {
return false;
}
};
}
@Override
public void crashNatively() {
throw new InternalError("Debug crash requested; a worker can't crash natively");
}
@Override
public PlatformStorage storage() {
return storage;
}
@Override
public PlatformThreads threads() {
return threads;
}
}
@@ -0,0 +1,58 @@
package incari.platform.web;
import incari.platform.api.profile.FrameSample;
import incari.platform.api.profile.MemoryUsage;
import incari.platform.api.profile.PlatformProfiling;
import org.teavm.jso.JSBody;
/**
* Profiling in a copy of the game in a worker (ADR 0039): no frames, but singleplayer's server
* ticks here, and each tick goes into {@code self.__incariServer}, where the singleplayer benchmark
* reads it through the worker's DevTools target. It keeps the last {@value #ROWS} ticks as rows of
* {@value #COLUMNS} numbers: when the tick ended (the worker's {@code performance.now()}), how long
* it took in milliseconds, whether the server was paused, and the overworld's loaded chunks;
* {@code rows(from)} and {@code count} as the page's frame monitor has them.
*/
final class WorkerProfiling implements PlatformProfiling {
static final int ROWS = 16384;
static final int COLUMNS = 4;
WorkerProfiling() {
install();
}
@JSBody(
script = "var s = { columns: " + COLUMNS + ", capacity: " + ROWS + ", count: 0 };"
+ "s.table = new Float64Array(s.capacity * s.columns);"
+ "s.rows = function(from) { var first = Math.max(from, s.count - s.capacity, 0), out = [];"
+ " for (var n = first; n < s.count; n++) { var row = (n % s.capacity) * s.columns;"
+ " for (var i = 0; i < s.columns; i++) out.push(s.table[row + i]); } return out; };"
+ "self.__incariServer = s;")
private static native void install();
@Override
public MemoryUsage memory() {
// A worker has no performance.memory; the runner reads its heap over DevTools.
return MemoryUsage.UNKNOWN;
}
@Override
public void frameProfiled(FrameSample sample) {}
@Override
public void mark(String name) {}
@Override
public void serverTickProfiled(double millis, boolean paused, int loadedChunks) {
record(millis, paused ? 1 : 0, loadedChunks);
}
@JSBody(
params = {"millis", "paused", "chunks"},
script = "var s = self.__incariServer; if (!s) return;"
+ "var row = (s.count % s.capacity) * s.columns, t = s.table;"
+ "t[row] = performance.now(); t[row + 1] = millis; t[row + 2] = paused; t[row + 3] = chunks;"
+ "s.count++;")
private static native void record(double millis, int paused, int chunks);
}
@@ -0,0 +1,54 @@
package incari.platform.web;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
/**
* The background pool's slots in a worker's copy of the game (ADR 0039): a worker has no frames to
* fit between, so a slot is the next turn of its event loop, a few milliseconds long. Ending each
* slot hands the worker's thread back to its event loop, where the server's own thread (waiting
* for its next tick, or for the pool's work) and the page's messages get their turns.
*/
final class WorkerSlots implements IdleTimeExecutor.Slots {
/** How long the pool runs before the worker's other work gets a turn. */
private static final double SLOT_MILLIS = 8;
@Override
public void arm() {}
@Override
public double await() {
nextTurn();
return Dom.nowMillis() + SLOT_MILLIS;
}
@Override
public double now() {
return Dom.nowMillis();
}
/** Suspends until the event loop's next turn: a message posted to itself, not a clamped timer. */
@Async
private static native Void nextTurn();
private static void nextTurn(AsyncCallback<Void> callback) {
post(() -> callback.complete(null));
}
@JSFunctor
interface Turn extends JSObject {
void run();
}
@JSBody(
params = "turn",
script = "var c = self.__incariTurns; if (!c) { c = new MessageChannel(); c.waiting = [];"
+ " c.port1.onmessage = function() { var t = c.waiting.shift(); if (t) t(); };"
+ " self.__incariTurns = c; }"
+ "c.waiting.push(turn); c.port2.postMessage(0);")
private static native void post(Turn turn);
}
@@ -0,0 +1,290 @@
package incari.platform.web.audio;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Every JavaScript snippet the Web Audio platform runs, in one place.
*
* <p>The graph: each source (a "voice") feeds a 2-channel gain node that up-mixes mono to both
* sides, a splitter, one gain per ear (the {@link Spatializer}'s gains), and a merger into the
* device's master gain, then the page's output. With HRTF ("Directional Audio") a mono voice goes
* through a Web Audio HRTF panner instead of the ear gains' panning. Sounds are buffer sources
* (one-shot nodes, restarted at an offset to resume) or, for streams, a media element that
* decodes as it plays.
*
* <p>Callbacks here (a node's end, a media element's events, the unlock gesture) never call Java:
* they set flags on the voice that the sound thread reads, as the input platform's listeners queue
* events (ADR 0010). The one exception is the decoder's promise, which completes an
* {@code AsyncCallback}.
*
* <p>{@code globalThis.incariAudio} holds the context, the master gain, the playing streams' media
* elements and counters, for the browser checks and for debugging from the console.
*/
final class AudioJs {
private AudioJs() {}
// --- The context, and the unlock prompt ------------------------------------------------------
/** The page's audio context, or null if the browser has none (or refused to make one). */
@JSBody(
script = "var C = window.AudioContext || window.webkitAudioContext; if (!C) return null;"
+ " var ctx; try { ctx = new C({ latencyHint: 'interactive' }); } catch (e) { return null; }"
+ " var a = globalThis.incariAudio || (globalThis.incariAudio = {});"
+ " a.context = ctx; a.buffersStarted = 0; a.streamsStarted = 0; a.voices = 0; a.pending = [];"
+ " a.streams = [];"
+ " a.unlockRequested = false; return ctx;")
static native @Nullable JSObject createContext();
@JSBody(params = "ctx", script = "return ctx.currentTime;")
static native double time(JSObject ctx);
@JSBody(params = "ctx", script = "return ctx.sampleRate;")
static native int sampleRate(JSObject ctx);
@JSBody(params = "ctx", script = "return ctx.state === 'closed';")
static native boolean closed(JSObject ctx);
/**
* Whether a sound started now will be heard soon: the context runs, or a gesture has asked it
* to. Before the first gesture it might not run for minutes, and short sounds are dropped then
* rather than all heard at once when it does.
*/
@JSBody(params = "ctx", script = "return ctx.state === 'running' || globalThis.incariAudio.unlockRequested;")
static native boolean startsSoon(JSObject ctx);
/**
* Browsers start an audio context suspended until the page gets a click or a key press. This
* shows a small prompt until then, resumes the context on the first gesture anywhere on the
* page, and starts the streams that were waiting for it.
*/
@JSBody(
params = "ctx",
script = "var a = globalThis.incariAudio; var events = ['pointerdown', 'mousedown', 'keydown', 'touchend'];"
+ " var prompt = null;"
+ " function startPending() { var p = a.pending; a.pending = [];"
+ " for (var i = 0; i < p.length; i++) incariPlayMedia(p[i]); }"
+ " function done() { if (ctx.state !== 'running') return;"
+ " if (prompt) { prompt.remove(); prompt = null; }"
+ " for (var i = 0; i < events.length; i++) window.removeEventListener(events[i], gesture, true);"
+ " a.unlocked = true; startPending(); }"
+ " function gesture() { a.unlockRequested = true; ctx.resume().then(done, function() {}); }"
+ " ctx.addEventListener('statechange', done);"
+ " if (ctx.state === 'running') { a.unlocked = true; return; }"
+ " a.unlocked = false;"
+ " prompt = document.createElement('div'); prompt.id = 'incari-audio-unlock';"
+ " prompt.textContent = 'Click or press a key to turn on sound';"
+ " prompt.style.cssText = 'position:fixed;right:12px;bottom:12px;padding:6px 12px;"
+ "border-radius:14px;background:rgba(0,0,0,0.6);color:#eee;font:13px system-ui,sans-serif;"
+ "pointer-events:none;z-index:2147483647;user-select:none';"
+ " document.body.appendChild(prompt);"
+ " for (var i = 0; i < events.length; i++) window.addEventListener(events[i], gesture, true);")
static native void installUnlock(JSObject ctx);
/**
* Defines the page-wide helper the unlock and the voices share to start a media element, once:
* a stream asked to play while the context is suspended waits for it to run, and one the
* browser still refuses waits for the next gesture.
*/
@JSBody(
script = "if (globalThis.incariPlayMedia) return;"
+ " function incariPlayMediaImpl(v) { var m = v.media; if (!m || !m.want) return;"
+ " var a = globalThis.incariAudio;"
+ " if (v.ctx.state !== 'running') { if (a.pending.indexOf(v) < 0) a.pending.push(v); return; }"
+ " a.streamsStarted++;"
+ " m.el.play().catch(function(e) {"
+ " if (e && e.name === 'NotAllowedError') {"
+ " function retry() { window.removeEventListener('pointerdown', retry, true);"
+ " window.removeEventListener('keydown', retry, true); incariPlayMediaImpl(v); }"
+ " window.addEventListener('pointerdown', retry, true); window.addEventListener('keydown', retry, true);"
+ " } else if (e && e.name !== 'AbortError') { m.ended = true; } }); }"
+ " globalThis.incariPlayMedia = incariPlayMediaImpl;")
static native void defineHelpers();
// --- The device --------------------------------------------------------------------------
/** The device's master gain, into the page's output. */
@JSBody(
params = {"ctx", "hrtf"},
script = "var m = ctx.createGain(); m.connect(ctx.destination); globalThis.incariAudio.master = m;"
+ " return { ctx: ctx, master: m, hrtf: hrtf };")
static native JSObject createBus(JSObject ctx, boolean hrtf);
@JSBody(params = "bus", script = "bus.master.disconnect();")
static native void closeBus(JSObject bus);
// --- Voices ------------------------------------------------------------------------------
@JSBody(
params = "bus",
script = "var ctx = bus.ctx;"
+ " var v = { bus: bus, ctx: ctx, input: ctx.createGain(), split: ctx.createChannelSplitter(2),"
+ " l: ctx.createGain(), r: ctx.createGain(), merge: ctx.createChannelMerger(2), panner: null,"
+ " nodes: [], gen: 0, ended: false, media: null, routed: false };"
+ " v.input.channelCount = 2; v.input.channelCountMode = 'explicit';"
+ " v.input.channelInterpretation = 'speakers';"
+ " v.split.connect(v.l, 0); v.split.connect(v.r, 1);"
+ " v.l.connect(v.merge, 0, 0); v.r.connect(v.merge, 0, 1); v.merge.connect(bus.master);"
+ " globalThis.incariAudio.voices++; return v;")
static native JSObject createVoice(JSObject bus);
/**
* Connects the voice's input for {@code stereo} or mono content: straight to the ear gains, or
* for mono with HRTF on, through an HRTF panner (with no distance model of its own).
*/
@JSBody(
params = {"v", "stereo"},
script = "if (v.routed) { v.input.disconnect(); if (v.panner) { v.panner.disconnect(); v.panner = null; } }"
+ " if (v.bus.hrtf && !stereo) { v.input.channelCount = 1; var p = v.ctx.createPanner();"
+ " p.panningModel = 'HRTF'; p.distanceModel = 'linear'; p.rolloffFactor = 0;"
+ " p.positionZ.value = -1; v.input.connect(p); p.connect(v.split); v.panner = p;"
+ " } else { v.input.channelCount = 2; v.input.connect(v.split); }"
+ " v.routed = true;")
static native void route(JSObject v, boolean stereo);
/**
* Sets the ear gains: at once before the voice plays, otherwise smoothly (a 5 ms time
* constant), so a moving source doesn't click.
*/
@JSBody(
params = {"v", "left", "right", "immediate"},
script = "var t = v.ctx.currentTime; var ps = [v.l.gain, v.r.gain]; var xs = [left, right];"
+ " for (var i = 0; i < 2; i++) { if (immediate) { ps[i].cancelScheduledValues(0); ps[i].value = xs[i]; }"
+ " else ps[i].setTargetAtTime(xs[i], t, 0.005); }")
static native void setGains(JSObject v, double left, double right, boolean immediate);
@JSBody(
params = {"v", "x", "y", "z"},
script =
"var p = v.panner; if (p) { p.positionX.value = x; p.positionY.value = y; p.positionZ.value = z; }")
static native void setPannerPosition(JSObject v, double x, double y, double z);
/** Starts {@code buffer} at context time {@code when} (0: now), {@code offset} seconds in. */
@JSBody(
params = {"v", "buffer", "when", "offset", "rate", "loop"},
script = "var n = v.ctx.createBufferSource(); n.buffer = buffer; n.loop = loop;"
+ " n.playbackRate.value = rate; n.connect(v.input); var gen = v.gen;"
+ " n.onended = function() { var i = v.nodes.indexOf(n); if (i >= 0) v.nodes.splice(i, 1);"
+ " if (gen === v.gen && v.nodes.length === 0) v.ended = true; };"
+ " v.ended = false; v.nodes.push(n); n.start(when, offset);"
+ " globalThis.incariAudio.buffersStarted++;")
static native void startBuffer(JSObject v, JSObject buffer, double when, double offset, double rate, boolean loop);
/** Stops every buffer the voice started; they don't count as having ended. */
@JSBody(
params = "v",
script = "v.gen++; var ns = v.nodes; v.nodes = []; v.ended = false;"
+ " for (var i = 0; i < ns.length; i++) { ns[i].onended = null;"
+ " try { ns[i].stop(); } catch (e) {} ns[i].disconnect(); }")
static native void stopBuffers(JSObject v);
/** Whether the buffers the voice last started have all played to their end. */
@JSBody(params = "v", script = "return v.ended;")
static native boolean buffersEnded(JSObject v);
@JSBody(
params = {"v", "rate"},
script = "for (var i = 0; i < v.nodes.length; i++) v.nodes[i].playbackRate.value = rate;"
+ " if (v.media) v.media.el.playbackRate = rate;")
static native void setRate(JSObject v, double rate);
@JSBody(
params = {"v", "loop"},
script = "for (var i = 0; i < v.nodes.length; i++) v.nodes[i].loop = loop;"
+ " if (v.media) v.media.el.loop = loop;")
static native void setLoop(JSObject v, boolean loop);
/**
* Attaches a whole Ogg Vorbis file as a media element the browser decodes as it plays, rather
* than decoding a whole track of music into memory up front.
*/
@JSBody(
params = {"v", "bytes", "loop", "rate"},
script =
"var url = URL.createObjectURL(new Blob([bytes], { type: 'audio/ogg' }));"
+ " var el = new Audio(); el.preload = 'auto'; el.loop = loop; el.preservesPitch = false;"
+ " el.src = url; el.playbackRate = rate;"
+ " var node = v.ctx.createMediaElementSource(el); node.connect(v.input);"
+ " var m = { el: el, node: node, url: url, ended: false, want: false }; v.media = m;"
+ " globalThis.incariAudio.streams.push(el);"
+ " el.addEventListener('ended', function() { m.ended = true; });"
+ " el.addEventListener('error', function() { m.ended = true;"
+ " console.warn('[Incari] A sound stream failed: ' + (el.error ? el.error.message || el.error.code : '')); });")
static native void attachMedia(JSObject v, Int8Array bytes, boolean loop, double rate);
@JSBody(params = "v", script = "if (v.media) { v.media.want = true; incariPlayMedia(v); }")
static native void playMedia(JSObject v);
@JSBody(
params = {"v", "rewind"},
script = "var m = v.media; if (!m) return; m.want = false; m.el.pause();"
+ " var p = globalThis.incariAudio.pending; var i = p.indexOf(v); if (i >= 0) p.splice(i, 1);"
+ " if (rewind) { m.el.currentTime = 0; m.ended = false; }")
static native void pauseMedia(JSObject v, boolean rewind);
@JSBody(params = "v", script = "return !!(v.media && v.media.ended);")
static native boolean mediaEnded(JSObject v);
/** Stops everything and takes the voice out of the graph for good. */
@JSBody(
params = "v",
script = "v.gen++; var ns = v.nodes; v.nodes = [];"
+ " for (var i = 0; i < ns.length; i++) { ns[i].onended = null; try { ns[i].stop(); } catch (e) {}"
+ " ns[i].disconnect(); }"
+ " var a = globalThis.incariAudio; var m = v.media;"
+ " if (m) { m.want = false; m.el.pause(); m.el.removeAttribute('src'); m.el.load();"
+ " URL.revokeObjectURL(m.url); m.node.disconnect(); v.media = null;"
+ " var i = a.pending.indexOf(v); if (i >= 0) a.pending.splice(i, 1);"
+ " var j = a.streams.indexOf(m.el); if (j >= 0) a.streams.splice(j, 1); }"
+ " v.input.disconnect(); if (v.panner) v.panner.disconnect(); v.split.disconnect();"
+ " v.l.disconnect(); v.r.disconnect(); v.merge.disconnect(); a.voices--;")
static native void closeVoice(JSObject v);
// --- Buffers -----------------------------------------------------------------------------
/** Interleaved little-endian PCM (8-bit unsigned or 16-bit signed) into a Web Audio buffer. */
@JSBody(
params = {"ctx", "bytes", "rate", "channels", "bits"},
script = "var frames = Math.floor(bytes.length / (channels * bits / 8));"
+ " var b = ctx.createBuffer(channels, Math.max(frames, 1), rate);"
+ " var d = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);"
+ " for (var c = 0; c < channels; c++) { var out = b.getChannelData(c);"
+ " for (var i = 0; i < frames; i++) { var k = i * channels + c;"
+ " out[i] = bits === 16 ? d.getInt16(k * 2, true) / 32768 : (d.getUint8(k) - 128) / 128; } }"
+ " return b;")
static native JSObject pcmBuffer(JSObject ctx, Int8Array bytes, int rate, int channels, int bits);
@JSBody(params = "buffer", script = "return buffer.sampleRate;")
static native int bufferRate(JSObject buffer);
@JSBody(params = "buffer", script = "return buffer.numberOfChannels;")
static native int bufferChannels(JSObject buffer);
@JSBody(params = "buffer", script = "return buffer.length;")
static native int bufferFrames(JSObject buffer);
/** A decoded file, or a message saying why it couldn't be. */
@JSFunctor
interface Decoded extends JSObject {
void decoded(JSObject buffer);
}
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
/**
* Decodes a whole file with the browser's decoder, which runs off the page's thread (Chromium
* and Firefox decode on a thread of their own) and resamples to the context's rate.
*/
@JSBody(
params = {"ctx", "bytes", "done", "failed"},
script = "ctx.decodeAudioData(bytes.buffer).then(function(b) { done(b); },"
+ " function(e) { failed(String(e && e.message ? e.message : e)); });")
static native void decode(JSObject ctx, Int8Array bytes, Decoded done, Failed failed);
}
@@ -0,0 +1,58 @@
package incari.platform.web.audio;
import org.jspecify.annotations.Nullable;
/**
* Reads the channel count and sample rate from an Ogg Vorbis file's identification header, which
* is the first packet of the first page. A stream played by a media element is positioned (mono)
* or not (stereo) from the moment it's attached, before the browser has read any of it.
*/
final class OggVorbisInfo {
/** "OggS", version, header type, granule position, serial, sequence, checksum, segment count. */
private static final int PAGE_HEADER = 27;
/** Packet type 1, "vorbis", a 4-byte version, then the channels and the rate. */
private static final int CHANNELS = 11;
private static final int RATE = 12;
private final int channels;
private final int sampleRate;
private OggVorbisInfo(int channels, int sampleRate) {
this.channels = channels;
this.sampleRate = sampleRate;
}
int channels() {
return channels;
}
int sampleRate() {
return sampleRate;
}
/** The file's header, or null if it doesn't start like an Ogg Vorbis file. */
static @Nullable OggVorbisInfo read(byte[] file) {
if (file.length < PAGE_HEADER || file[0] != 'O' || file[1] != 'g' || file[2] != 'g' || file[3] != 'S') {
return null;
}
int packet = PAGE_HEADER + (file[PAGE_HEADER - 1] & 0xFF);
if (file.length < packet + RATE + 4 || file[packet] != 1) {
return null;
}
String magic = "vorbis";
for (int i = 0; i < magic.length(); i++) {
if (file[packet + 1 + i] != magic.charAt(i)) {
return null;
}
}
int channels = file[packet + CHANNELS] & 0xFF;
int rate = (file[packet + RATE] & 0xFF)
| (file[packet + RATE + 1] & 0xFF) << 8
| (file[packet + RATE + 2] & 0xFF) << 16
| (file[packet + RATE + 3] & 0xFF) << 24;
return channels > 0 && rate > 0 ? new OggVorbisInfo(channels, rate) : null;
}
}
@@ -0,0 +1,70 @@
package incari.platform.web.audio;
/**
* Where a source is in its own samples, in seconds, worked out from the audio context's clock:
* Web Audio's buffer sources can't pause or report their position, so a pause is a stop that
* remembers where it was, and a resume starts a new node there. The rate is the source's pitch,
* which scales how fast it moves through its samples. Plain Java.
*/
final class PlaybackClock {
private double anchorTime;
private double anchorPosition;
private double rate = 1;
private boolean running;
/** Starts (or keeps) moving from the current position at {@code now}. */
void start(double now) {
if (!running) {
anchorTime = now;
running = true;
}
}
/** Stops moving, keeping the position. */
void pause(double now) {
anchorPosition = position(now);
running = false;
}
/** Back to the start, stopped. */
void reset() {
anchorPosition = 0;
running = false;
}
/** Changes the speed from {@code now} on; the position so far is kept. */
void setRate(double now, double newRate) {
anchorPosition = position(now);
anchorTime = now;
rate = newRate;
}
/** Moves to {@code position}, as of {@code now}. */
void seek(double now, double position) {
anchorPosition = position;
anchorTime = now;
}
double rate() {
return rate;
}
boolean running() {
return running;
}
/** The position at context time {@code now}. */
double position(double now) {
return running ? anchorPosition + Math.max(0, now - anchorTime) * rate : anchorPosition;
}
/** The position within a looping sound of {@code duration} seconds. */
static double wrap(double position, double duration) {
if (duration <= 0) {
return 0;
}
double wrapped = position % duration;
return wrapped < 0 ? wrapped + duration : wrapped;
}
}
@@ -0,0 +1,230 @@
package incari.platform.web.audio;
/**
* How loud a source is in each ear, by the model OpenAL Soft uses for stereo output, so the
* browser sounds like the desktop. Hot path, no allocation: the sound thread runs it for every
* playing source every frame.
*
* <p>The model, measured from OpenAL Soft's own output (its wave-file backend; ADR 0013 has the
* numbers and {@code SpatializerTest} holds them):
*
* <ul>
* <li>A source's position is taken into the listener's frame (x right, y up, -z forward) unless
* it's already relative to the listener. A source at the listener counts as straight ahead.
* <li>Distance attenuation is per source: none, OpenAL's default inverse-distance model, or the
* linear model the game uses (full volume at the source, silent at the maximum distance).
* <li>Mono sources are panned by first-order ambisonics decoded to two speakers: each ear gets
* {@code 0.5 ± 0.5·right + 0.0957·front}. Directions in front are first spread by 1.5, as for
* speakers at ±30°, so a source 60° to the side is already fully on that side; one straight
* ahead is 0.596 in each ear, one straight behind 0.404, one straight above 0.5.
* <li>Stereo sources aren't positioned or attenuated at all: each channel plays at the source's
* gain. (That's why the game's positional sounds are mono.)
* </ul>
*/
public final class Spatializer {
/** The omnidirectional term of OpenAL Soft's stereo decoder. */
static final double OMNI = 0.5;
/** The left-right term. */
static final double SIDE = 0.5;
/**
* The front-back term: 0.0552305643 in the decoder's SN3D-scaled matrix, times √3 for the
* N3D-normalized coefficients it's applied to.
*/
static final double FRONT = 0.0552305643 * 1.7320508075688772;
/** How much directions in front are spread: speakers at ±30° cover up to ±90°. */
private static final double FRONT_SPREAD = 1.5;
private static final double HALF_PI = Math.PI / 2;
/** Closer than this, a source is at the listener and sounds straight ahead. */
private static final double MIN_DISTANCE = 1e-6;
// The listener: its position, and its right, up and forward unit vectors.
private double listenerX;
private double listenerY;
private double listenerZ;
private double rightX = 1;
private double rightY;
private double rightZ;
private double upX;
private double upY = 1;
private double upZ;
private double forwardX;
private double forwardY;
private double forwardZ = -1;
// The last computation's results.
private double localX;
private double localY;
private double localZ;
private double level;
private double left;
private double right;
public void setListenerPosition(double x, double y, double z) {
listenerX = x;
listenerY = y;
listenerZ = z;
}
/**
* Sets which way the listener faces. As in OpenAL, the vectors needn't be normalized or
* perpendicular: right is forward × up, and up is made perpendicular to both. A degenerate
* pair (zero, or parallel) is ignored.
*/
public void setListenerOrientation(double fx, double fy, double fz, double ux, double uy, double uz) {
double forwardLength = Math.sqrt(fx * fx + fy * fy + fz * fz);
double sx = fy * uz - fz * uy;
double sy = fz * ux - fx * uz;
double sz = fx * uy - fy * ux;
double sideLength = Math.sqrt(sx * sx + sy * sy + sz * sz);
if (forwardLength < MIN_DISTANCE || sideLength < MIN_DISTANCE) {
return;
}
forwardX = fx / forwardLength;
forwardY = fy / forwardLength;
forwardZ = fz / forwardLength;
rightX = sx / sideLength;
rightY = sy / sideLength;
rightZ = sz / sideLength;
upX = rightY * forwardZ - rightZ * forwardY;
upY = rightZ * forwardX - rightX * forwardZ;
upZ = rightX * forwardY - rightY * forwardX;
}
/**
* Computes a source's position in the listener's frame and the gain of each ear, read back
* with {@link #localX()}... and {@link #left()}/{@link #right()}.
*
* @param relative whether the position is already relative to the listener, in its frame
* @param gain the source's own gain
* @param stereo whether the source has two channels (then it isn't positioned or attenuated)
*/
public void compute(
double x, double y, double z, boolean relative, Attenuation attenuation, double gain, boolean stereo) {
if (relative) {
localX = x;
localY = y;
localZ = z;
} else {
double dx = x - listenerX;
double dy = y - listenerY;
double dz = z - listenerZ;
localX = dx * rightX + dy * rightY + dz * rightZ;
localY = dx * upX + dy * upY + dz * upZ;
localZ = -(dx * forwardX + dy * forwardY + dz * forwardZ);
}
if (stereo) {
level = gain;
left = gain;
right = gain;
return;
}
double distance = Math.sqrt(localX * localX + localY * localY + localZ * localZ);
level = gain * attenuation.gain(distance);
pan(distance);
left *= level;
right *= level;
}
/** The panning gains for the direction of {@link #localX}..., at {@code distance}. */
private void pan(double distance) {
double sideways;
double front;
if (distance < MIN_DISTANCE) {
sideways = 0;
front = 1;
} else {
double horizontal = Math.sqrt(localX * localX + localZ * localZ);
double azimuth = Math.atan2(localX, -localZ);
double spread = Math.abs(azimuth) < HALF_PI
? Math.copySign(Math.min(Math.abs(azimuth) * FRONT_SPREAD, HALF_PI), azimuth)
: azimuth;
// cos(elevation): the horizontal part of the unit direction; elevation itself is unchanged.
double level = horizontal / distance;
sideways = Math.sin(spread) * level;
front = Math.cos(spread) * level;
}
left = OMNI - SIDE * sideways + FRONT * front;
right = OMNI + SIDE * sideways + FRONT * front;
}
/**
* The source's gain after distance attenuation, before panning, from the last {@link
* #compute}: what an HRTF panner, which pans by itself, is given.
*/
public double level() {
return level;
}
/** The left ear's gain from the last {@link #compute}. */
public double left() {
return left;
}
/** The right ear's gain from the last {@link #compute}. */
public double right() {
return right;
}
/** The source's position in the listener's frame (right) from the last {@link #compute}. */
public double localX() {
return localX;
}
/** ...up. */
public double localY() {
return localY;
}
/** ...and backwards: forward is -z, as in OpenAL and Web Audio. */
public double localZ() {
return localZ;
}
/** How a source fades with distance. Mutable, one per source: set without allocating. */
public static final class Attenuation {
private enum Model {
NONE,
INVERSE_CLAMPED,
LINEAR
}
private Model model = Model.INVERSE_CLAMPED;
private double maxDistance;
/** OpenAL's default: inverse distance from 1 block, clamped, with a rolloff of 1. */
public void inverseClamped() {
model = Model.INVERSE_CLAMPED;
}
/** Full volume at any distance. */
public void none() {
model = Model.NONE;
}
/**
* OpenAL's unclamped linear model with a reference distance of 0 and a rolloff of 1: 1 at
* the source, 0 at {@code maxDistance} and beyond. A maximum of 0 means no attenuation, as
* OpenAL skips the model when the maximum equals the reference distance.
*/
public void linear(double maxDistance) {
model = Model.LINEAR;
this.maxDistance = maxDistance;
}
/** The gain at {@code distance} blocks, 0 to 1. */
public double gain(double distance) {
return switch (model) {
case NONE -> 1;
case INVERSE_CLAMPED -> 1 / Math.max(distance, 1);
case LINEAR -> maxDistance == 0 ? 1 : Math.max(0, 1 - Math.min(distance, maxDistance) / maxDistance);
};
}
}
}
@@ -0,0 +1,79 @@
package incari.platform.web.audio;
import java.util.Arrays;
/**
* The bookkeeping of a source playing queued buffers one after another (OpenAL's buffer queue):
* where each queued buffer starts in the stream, which ones have finished at a given position, and
* where the queue ends. Positions are seconds of the stream's samples since the source started.
* Plain Java; the source keeps the buffers themselves in the same order.
*/
final class StreamTimeline {
private double[] durations = new double[8];
private int count;
/** Where the first queued buffer starts: the length of everything released before it. */
private double firstStart;
void add(double duration) {
if (count == durations.length) {
durations = Arrays.copyOf(durations, count * 2);
}
durations[count++] = duration;
}
int size() {
return count;
}
/** Where queued buffer {@code index} starts. */
double startOf(int index) {
double start = firstStart;
for (int i = 0; i < index; i++) {
start += durations[i];
}
return start;
}
/** Where the last queued buffer ends: the source stops there, as OpenAL's does when its queue runs out. */
double end() {
return startOf(count);
}
/** How many queued buffers, from the first, have finished at {@code position}. */
int finishedAt(double position) {
double end = firstStart;
int finished = 0;
while (finished < count) {
end += durations[finished];
if (end > position) {
break;
}
finished++;
}
return finished;
}
/** The queued buffer playing at {@code position}, or {@link #size} if it's past the end. */
int indexAt(double position) {
return finishedAt(position);
}
/** Drops the first {@code n} buffers; the rest keep their places in the stream. */
void release(int n) {
if (n <= 0) {
return;
}
for (int i = 0; i < n; i++) {
firstStart += durations[i];
}
System.arraycopy(durations, n, durations, 0, count - n);
count -= n;
}
/** Empties the queue and starts the stream over. */
void clear() {
count = 0;
firstStart = 0;
}
}
@@ -0,0 +1,75 @@
package incari.platform.web.audio;
import incari.platform.api.audio.AudioDecoder;
import incari.platform.api.audio.AudioDevice;
import incari.platform.api.audio.AudioDeviceList;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.PlatformAudio;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSObject;
/**
* Sound in the browser, over Web Audio (ADR 0013).
*
* <p>The page has one audio context for its whole life, made when the game first opens a device
* or decodes a sound. Devices come and go on it (the game reopens its device when resources
* reload), and decoded sounds outlive them. Browsers start a context suspended until the page gets
* a click or a key press, so opening it also shows the unlock prompt ({@link AudioJs#installUnlock}).
*
* <p>There's one output, the browser's: a page can pick another only with {@code setSinkId},
* which isn't in every browser and asks for a permission; that can come later.
*/
public final class WebAudio implements PlatformAudio {
/** The one device's name, as the game's sound device option lists it. */
static final String DEVICE_NAME = "Browser audio output";
private final WebAudioDecoder decoder = new WebAudioDecoder(this);
private @Nullable JSObject context;
@Override
public AudioDeviceList devices() {
return new AudioDeviceList(DEVICE_NAME, List.of(DEVICE_NAME));
}
@Override
public boolean reportsDeviceChanges() {
return false;
}
@Override
public void setDeviceChangeListener(@Nullable Runnable listener) {}
@Override
public AudioDevice open(@Nullable String deviceName, boolean spatialize) {
if (deviceName != null && !deviceName.equals(DEVICE_NAME)) {
throw new AudioException("No audio device named '" + deviceName + "' in the browser");
}
return new WebAudioDevice(context(), spatialize);
}
@Override
public AudioDecoder decoder() {
return decoder;
}
/**
* The page's audio context, made on first use, with the unlock prompt.
*
* @throws AudioException if the browser has no Web Audio
*/
JSObject context() {
JSObject current = context;
if (current == null) {
current = AudioJs.createContext();
if (current == null) {
throw new AudioException("This browser has no Web Audio");
}
AudioJs.defineHelpers();
AudioJs.installUnlock(current);
context = current;
}
return current;
}
}
@@ -0,0 +1,50 @@
package incari.platform.web.audio;
import incari.platform.api.audio.AudioBuffer;
import incari.platform.api.audio.PcmFormat;
import org.teavm.jso.JSObject;
/**
* Samples a Web Audio buffer holds, playable by any number of sources. The page's garbage
* collector frees it once no source plays it, so closing it only lets go of it.
*/
final class WebAudioBuffer implements AudioBuffer {
private final JSObject buffer;
private final PcmFormat format;
private final int size;
private final double duration;
WebAudioBuffer(JSObject buffer, PcmFormat format, int size, int frames) {
this.buffer = buffer;
this.format = format;
this.size = size;
this.duration = (double) frames / format.sampleRate();
}
JSObject buffer() {
return buffer;
}
/** Seconds, at normal speed. */
double duration() {
return duration;
}
boolean stereo() {
return format.channels() == 2;
}
@Override
public PcmFormat format() {
return format;
}
@Override
public int sizeInBytes() {
return size;
}
@Override
public void close() {}
}
@@ -0,0 +1,69 @@
package incari.platform.web.audio;
import incari.platform.api.audio.AudioDecoder;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.DecodedAudio;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Decodes sound files with the browser's own decoder ({@code decodeAudioData}), which runs natively
* on a thread of its own: a Chromebook decodes the game's Ogg files many times faster than the
* game's Java decoder would on the page's only thread, and the page keeps drawing meanwhile.
*/
final class WebAudioDecoder implements AudioDecoder {
private final WebAudio audio;
WebAudioDecoder(WebAudio audio) {
this.audio = audio;
}
@Override
public DecodedAudio decodeOggVorbis(byte[] file) {
// decodeAudioData takes its buffer away from the page, so it gets a copy of its own.
Outcome outcome = decode(audio.context(), Int8Array.copyFromJavaArray(file));
JSObject buffer = outcome.buffer();
if (buffer == null) {
throw new AudioException("The browser couldn't decode a sound: " + outcome.error());
}
int channels = AudioJs.bufferChannels(buffer);
if (channels != 1 && channels != 2) {
throw new AudioException("Sounds must be mono or stereo, not " + channels + " channels");
}
return new Decoded(buffer, AudioJs.bufferRate(buffer), channels, AudioJs.bufferFrames(buffer));
}
/**
* The decoded buffer, or why decoding failed. A failure comes back as a value and is thrown by
* the caller, not through {@code AsyncCallback.error}: TeaVM's WebAssembly GC runtime would also
* rethrow it out of the JavaScript callback and crash the page, though the game catches it and
* decodes the sound in Java (probe: {@code app-web/probes/FetchFailureProbe}).
*/
private record Outcome(
@Nullable JSObject buffer, @Nullable String error) {}
/** Suspends the calling coroutine until the browser has decoded {@code bytes}: must not be the game's main thread. */
@Async
private static native Outcome decode(JSObject context, Int8Array bytes);
private static void decode(JSObject context, Int8Array bytes, AsyncCallback<Outcome> callback) {
AudioJs.decode(
context,
bytes,
buffer -> callback.complete(new Outcome(buffer, null)),
message -> callback.complete(new Outcome(null, message)));
}
/** A decoded sound: a Web Audio buffer of 32-bit float samples at the context's rate. */
record Decoded(JSObject buffer, int sampleRate, int channels, int frames) implements DecodedAudio {
@Override
public int sizeInBytes() {
return frames * channels * Float.BYTES;
}
}
}
@@ -0,0 +1,168 @@
package incari.platform.web.audio;
import incari.platform.api.audio.AudioBuffer;
import incari.platform.api.audio.AudioDevice;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.AudioListener;
import incari.platform.api.audio.AudioSource;
import incari.platform.api.audio.DecodedAudio;
import incari.platform.api.audio.PcmFormat;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* An open output: a master gain on the page's audio context, and the sources playing into it.
* Called from the game's sound thread (a coroutine on the page's thread).
*/
final class WebAudioDevice implements AudioDevice {
/**
* As many sources as OpenAL Soft gives the desktop by default (255 mono ones), so the game
* splits them into the same pools and drops sounds at the same point.
*/
static final int MAX_SOURCES = 255;
private final JSObject context;
private final JSObject bus;
private final boolean hrtf;
private final Spatializer spatializer = new Spatializer();
private final List<WebAudioSource> sources = new ArrayList<>();
private final AudioListener listener = new AudioListener() {
@Override
public void setPosition(double x, double y, double z) {
// The game sets the orientation right after, and that updates the sources once.
spatializer.setListenerPosition(x, y, z);
}
@Override
public void setOrientation(double fx, double fy, double fz, double ux, double uy, double uz) {
spatializer.setListenerOrientation(fx, fy, fz, ux, uy, uz);
listenerMoved();
}
};
private boolean closed;
WebAudioDevice(JSObject context, boolean hrtf) {
this.context = context;
this.bus = AudioJs.createBus(context, hrtf);
this.hrtf = hrtf;
}
@Override
public String name() {
return WebAudio.DEVICE_NAME;
}
@Override
public boolean isDisconnected() {
return closed || AudioJs.closed(context);
}
@Override
public int maxSources() {
return MAX_SOURCES;
}
@Override
public AudioListener listener() {
return listener;
}
@Override
public @Nullable AudioSource createSource() {
checkOpen();
if (sources.size() >= MAX_SOURCES) {
return null;
}
WebAudioSource source = new WebAudioSource(this, AudioJs.createVoice(bus));
sources.add(source);
return source;
}
@Override
public AudioBuffer createBuffer(ByteBuffer samples, PcmFormat format) {
checkOpen();
int size = samples.remaining();
byte[] bytes = new byte[size];
samples.duplicate().get(bytes);
int frames = size / format.frameSize();
if (frames == 0) {
throw new AudioException("An empty sound buffer");
}
JSObject buffer = AudioJs.pcmBuffer(
context,
Int8Array.copyFromJavaArray(bytes),
format.sampleRate(),
format.channels(),
format.bitsPerSample());
return new WebAudioBuffer(buffer, format, size, frames);
}
@Override
public AudioBuffer createBuffer(DecodedAudio audio) {
checkOpen();
if (!(audio instanceof WebAudioDecoder.Decoded decoded)) {
throw new AudioException("Not decoded by this browser: " + audio);
}
// Float samples, never PCM: the format records their rate and channels, at the depth the
// desktop's decoder would have given them.
PcmFormat format = new PcmFormat(decoded.sampleRate(), decoded.channels(), 16);
return new WebAudioBuffer(decoded.buffer(), format, decoded.sizeInBytes(), decoded.frames());
}
@Override
public boolean streamsOggVorbis() {
return true;
}
@Override
public void close() {
if (closed) {
return;
}
closed = true;
// Closing a source removes it from the list.
for (int i = sources.size() - 1; i >= 0; i--) {
sources.get(i).close();
}
AudioJs.closeBus(bus);
}
JSObject context() {
return context;
}
boolean hrtf() {
return hrtf;
}
Spatializer spatializer() {
return spatializer;
}
/** Context time, in seconds: what sources measure their progress against. */
double now() {
return AudioJs.time(context);
}
/** Hot path, every frame: re-pans every source against the moved listener, without allocating. */
private void listenerMoved() {
for (int i = 0, n = sources.size(); i < n; i++) {
sources.get(i).listenerMoved();
}
}
void forget(WebAudioSource source) {
sources.remove(source);
}
private void checkOpen() {
if (closed) {
throw new AudioException("The audio device is closed");
}
}
}
@@ -0,0 +1,374 @@
package incari.platform.web.audio;
import incari.platform.api.audio.AudioBuffer;
import incari.platform.api.audio.AudioException;
import incari.platform.api.audio.AudioSource;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* One source, with OpenAL's semantics over Web Audio's nodes: a static buffer (paused by
* stopping its node and remembering where), a queue of buffers scheduled back to back, or a
* compressed stream a media element plays. Its gains come from the device's {@link Spatializer}
* and are pushed to the page only when they change.
*/
final class WebAudioSource implements AudioSource {
private enum Content {
NONE,
BUFFER,
QUEUE,
STREAM
}
private final WebAudioDevice device;
private final JSObject voice;
private final Spatializer.Attenuation attenuation = new Spatializer.Attenuation();
private final PlaybackClock clock = new PlaybackClock();
private final StreamTimeline timeline = new StreamTimeline();
private final List<WebAudioBuffer> queue = new ArrayList<>();
private Content content = Content.NONE;
private @Nullable WebAudioBuffer buffer;
private boolean stereo;
private State state = State.INITIAL;
/** After {@link #stop}, every queued buffer counts as finished, as in OpenAL. */
private boolean queueStopped;
private boolean open = true;
private double x;
private double y;
private double z;
private boolean relative;
private float gain = 1;
private float pitch = 1;
private boolean looping;
// What the page was last told, so unchanged gains aren't sent again.
private double sentLeft = Double.NaN;
private double sentRight = Double.NaN;
WebAudioSource(WebAudioDevice device, JSObject voice) {
this.device = device;
this.voice = voice;
}
@Override
public void play() {
if (!open) {
return;
}
double now = device.now();
if (state == State.PLAYING) {
// OpenAL plays a playing source again from the start.
halt();
rewind();
} else if (state == State.STOPPED || state == State.INITIAL) {
rewind();
}
updateGains(true);
switch (content) {
case NONE -> {
// OpenAL: a source with nothing to play stops at once.
state = State.STOPPED;
return;
}
case BUFFER -> {
WebAudioBuffer current = buffer;
if (current == null || (state != State.PAUSED && !AudioJs.startsSoon(device.context()))) {
// Before the page's first click or key press the context may not run for
// minutes: short sounds are dropped rather than all heard at once then.
state = State.STOPPED;
return;
}
double position = clock.position(now);
double offset = looping ? PlaybackClock.wrap(position, current.duration()) : position;
if (offset >= current.duration()) {
state = State.STOPPED;
return;
}
AudioJs.startBuffer(voice, current.buffer(), 0, offset, pitch, looping);
}
case QUEUE -> scheduleQueue(now);
case STREAM -> AudioJs.playMedia(voice);
}
clock.start(now);
state = State.PLAYING;
}
@Override
public void pause() {
if (!open || state != State.PLAYING) {
return;
}
clock.pause(device.now());
halt();
state = State.PAUSED;
}
@Override
public void stop() {
if (!open) {
return;
}
halt();
if (content == Content.STREAM) {
AudioJs.pauseMedia(voice, true);
}
clock.pause(device.now());
// As in OpenAL Soft, a source that never played stays initial.
if (state != State.INITIAL) {
state = State.STOPPED;
queueStopped = content == Content.QUEUE;
}
}
@Override
public State state() {
if (open && state == State.PLAYING && finished()) {
clock.pause(device.now());
state = State.STOPPED;
}
return open ? state : State.STOPPED;
}
/** Whether what's playing has run out: the last buffer ended, or the queue or the stream did. */
private boolean finished() {
return switch (content) {
case NONE -> true;
case BUFFER -> !looping && AudioJs.buffersEnded(voice);
case QUEUE -> clock.position(device.now()) >= timeline.end();
case STREAM -> AudioJs.mediaEnded(voice);
};
}
@Override
public void setPosition(double newX, double newY, double newZ) {
x = newX;
y = newY;
z = newZ;
updateGains(false);
}
@Override
public void setPitch(float newPitch) {
if (!(newPitch > 0)) {
return; // OpenAL rejects a pitch that isn't positive and keeps the old one.
}
double now = device.now();
clock.setRate(now, newPitch);
pitch = newPitch;
if (content == Content.QUEUE) {
if (state == State.PLAYING) {
// Buffers already scheduled at the old speed start at the wrong times: schedule again.
AudioJs.stopBuffers(voice);
scheduleQueue(now);
}
} else {
AudioJs.setRate(voice, newPitch);
}
}
@Override
public void setLooping(boolean newLooping) {
looping = newLooping;
AudioJs.setLoop(voice, newLooping);
}
@Override
public void setGain(float newGain) {
// OpenAL clamps a source's gain to its maximum of 1.
gain = Math.clamp(newGain, 0.0F, 1.0F);
updateGains(false);
}
@Override
public void setRelative(boolean newRelative) {
relative = newRelative;
updateGains(false);
}
@Override
public void disableAttenuation() {
attenuation.none();
updateGains(false);
}
@Override
public void setLinearAttenuation(float maxDistance) {
attenuation.linear(maxDistance);
updateGains(false);
}
@Override
public void setBuffer(AudioBuffer newBuffer) {
if (state == State.PLAYING || state == State.PAUSED) {
throw new AudioException("Can't change the buffer of a playing source");
}
WebAudioBuffer ours = ours(newBuffer);
clearQueue();
buffer = ours;
content = Content.BUFFER;
setStereo(ours.stereo());
}
@Override
public void queue(AudioBuffer newBuffer) {
WebAudioBuffer ours = ours(newBuffer);
if (content == Content.BUFFER || content == Content.STREAM) {
throw new AudioException("Can't queue buffers on a source playing something else");
}
if (content == Content.NONE) {
content = Content.QUEUE;
setStereo(ours.stereo());
}
double now = device.now();
boolean ranOut = state == State.PLAYING && clock.position(now) >= timeline.end();
queue.add(ours);
timeline.add(ours.duration());
if (state != State.PLAYING) {
return;
}
if (ranOut) {
// The queue ran dry before this arrived: OpenAL has stopped the source by now.
clock.pause(now);
state = State.STOPPED;
return;
}
int index = queue.size() - 1;
double start = timeline.startOf(index);
double when = now + (start - clock.position(now)) / pitch;
AudioJs.startBuffer(voice, ours.buffer(), when, 0, pitch, false);
}
@Override
public int releaseProcessedBuffers() {
if (!open || content != Content.QUEUE || queue.isEmpty()) {
return 0;
}
int finished = queueStopped ? queue.size() : timeline.finishedAt(clock.position(device.now()));
for (int i = 0; i < finished; i++) {
queue.get(i).close();
}
queue.subList(0, finished).clear();
timeline.release(finished);
return finished;
}
@Override
public void streamOggVorbis(byte[] file, boolean loop) {
if (content != Content.NONE) {
throw new AudioException("Can't stream on a source playing something else");
}
OggVorbisInfo info = OggVorbisInfo.read(file);
if (info == null) {
throw new AudioException("Not an Ogg Vorbis file");
}
content = Content.STREAM;
looping = loop;
setStereo(info.channels() != 1);
AudioJs.attachMedia(voice, Int8Array.copyFromJavaArray(file), loop, pitch);
}
@Override
public void close() {
if (!open) {
return;
}
open = false;
AudioJs.closeVoice(voice);
clearQueue();
buffer = null;
device.forget(this);
}
/** The listener moved: hot path, every frame for every source, so nothing here allocates. */
void listenerMoved() {
if (!relative) {
updateGains(false);
}
}
private void setStereo(boolean newStereo) {
stereo = newStereo;
AudioJs.route(voice, newStereo);
sentLeft = Double.NaN;
updateGains(true);
}
/** Works out the ear gains and sends them if they changed; {@code immediate} skips smoothing. */
private void updateGains(boolean immediate) {
if (!open) {
return;
}
Spatializer spatializer = device.spatializer();
spatializer.compute(x, y, z, relative, attenuation, gain, stereo);
double left;
double right;
if (device.hrtf() && !stereo) {
// The HRTF panner does the panning; the ears get the attenuated gain.
left = spatializer.level();
right = left;
AudioJs.setPannerPosition(voice, spatializer.localX(), spatializer.localY(), spatializer.localZ());
} else {
left = spatializer.left();
right = spatializer.right();
}
if (left == sentLeft && right == sentRight) {
return;
}
sentLeft = left;
sentRight = right;
AudioJs.setGains(voice, left, right, immediate || state != State.PLAYING);
}
/** Starts the queued buffers from the clock's position: the current one part way, the rest after it. */
private void scheduleQueue(double now) {
double position = clock.position(now);
for (int i = timeline.indexAt(position); i < queue.size(); i++) {
double start = timeline.startOf(i);
if (start <= position) {
AudioJs.startBuffer(voice, queue.get(i).buffer(), 0, position - start, pitch, false);
} else {
AudioJs.startBuffer(voice, queue.get(i).buffer(), now + (start - position) / pitch, 0, pitch, false);
}
}
}
/** Silences whatever is playing, keeping the stream element and the queue. */
private void halt() {
AudioJs.stopBuffers(voice);
if (content == Content.STREAM) {
AudioJs.pauseMedia(voice, false);
}
}
/** Back to the start of what's attached: a queue restarts from its first unreleased buffer. */
private void rewind() {
clock.reset();
if (content == Content.QUEUE) {
clock.seek(device.now(), timeline.startOf(0));
queueStopped = false;
}
}
private void clearQueue() {
for (WebAudioBuffer queued : queue) {
queued.close();
}
queue.clear();
timeline.clear();
queueStopped = false;
}
private static WebAudioBuffer ours(AudioBuffer buffer) {
if (buffer instanceof WebAudioBuffer web) {
return web;
}
throw new AudioException("Not a Web Audio buffer: " + buffer);
}
}
@@ -0,0 +1,5 @@
/** Sound over Web Audio (ADR 0013): devices, sources, decoding, and the autoplay unlock. */
@NullMarked
package incari.platform.web.audio;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,131 @@
package incari.platform.web.fonts;
import incari.platform.api.fonts.FontFace;
import incari.platform.api.fonts.PlatformFonts;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.Int8Array;
/**
* Smooth fonts drawn by the browser: the font file handed to the page as a {@code FontFace}, each
* glyph drawn on a 2D canvas and its coverage read back. The browser has no FreeType for the game's
* own TrueType provider, but it draws text natively, anti-aliased as it draws the page's own.
*
* <p>A font is loaded once per name: loading suspends (the browser parses it off the page's
* thread), so the first {@link #open} must come from a background thread; opening it again at another
* size doesn't suspend.
*/
public final class CanvasFonts implements PlatformFonts {
@Override
public @Nullable FontFace open(byte[] data, String name, float pixelsPerEm) {
if (!loaded(name)) {
String error = load(name, Int8Array.copyFromJavaArray(data));
if (error != null) {
return null;
}
}
return new Face(name, pixelsPerEm);
}
private static final class Face implements FontFace {
private final String css;
Face(String name, float pixelsPerEm) {
this.css = pixelsPerEm + "px \"" + name + "\"";
}
@Override
public FontFace.@Nullable Glyph glyph(int codepoint) {
JSObject drawn = draw(css, new String(Character.toChars(codepoint)));
int width = width(drawn);
int height = height(drawn);
byte[] coverage = width > 0 && height > 0 ? coverage(drawn).copyToJavaArray() : new byte[0];
return new FontFace.Glyph(advance(drawn), left(drawn), top(drawn), width, height, coverage);
}
@Override
public void close() {}
}
@JSBody(params = "name", script = "var f = globalThis.incariFonts; return !!(f && f[name]);")
private static native boolean loaded(String name);
/** Loads the font into the page's fonts; null when it's ready, or why it couldn't be. */
@Async
private static native @Nullable String load(String name, Int8Array bytes);
private static void load(String name, Int8Array bytes, AsyncCallback<@Nullable String> callback) {
loadFont(name, bytes, () -> callback.complete(null), message -> callback.complete(message));
}
@JSFunctor
interface Loaded extends JSObject {
void loaded();
}
@JSFunctor
interface Failed extends JSObject {
void failed(String message);
}
@JSBody(
params = {"name", "bytes", "loaded", "failed"},
script =
"var face = new FontFace(name, bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength));"
+ " face.load().then(function(f) {"
+ " (typeof document !== 'undefined' ? document.fonts : self.fonts).add(f);"
+ " (globalThis.incariFonts = globalThis.incariFonts || {})[name] = true; loaded(); },"
+ " function(e) { failed(String(e)); });")
private static native void loadFont(String name, Int8Array bytes, Loaded loaded, Failed failed);
/**
* Draws one glyph white on a cleared canvas, its box from the browser's measurement padded a
* pixel each side for the anti-aliasing, and returns its metrics and coverage (the canvas's
* alpha channel). The canvas is made once and grown as glyphs need.
*/
@JSBody(
params = {"css", "text"},
script = "var g = globalThis.incariGlyphs;"
+ " if (!g) { var c = typeof OffscreenCanvas !== 'undefined' ? new OffscreenCanvas(64, 64)"
+ " : document.createElement('canvas'); c.width = 64; c.height = 64;"
+ " g = globalThis.incariGlyphs = { canvas: c, ctx: c.getContext('2d', { willReadFrequently: true }) }; }"
+ " var ctx = g.ctx; ctx.font = css; var m = ctx.measureText(text);"
+ " var x0 = Math.floor(-m.actualBoundingBoxLeft) - 1, x1 = Math.ceil(m.actualBoundingBoxRight) + 1;"
+ " var up = Math.ceil(m.actualBoundingBoxAscent) + 1, down = Math.ceil(m.actualBoundingBoxDescent) + 1;"
+ " var w = Math.max(0, x1 - x0), h = Math.max(0, up + down);"
+ " var r = { advance: m.width, left: x0, top: up, width: w, height: h, alpha: null };"
+ " if (w === 0 || h === 0 || /^\\s$/.test(text)) { r.width = 0; r.height = 0; return r; }"
+ " if (g.canvas.width < w || g.canvas.height < h) {"
+ " g.canvas.width = Math.max(g.canvas.width, w); g.canvas.height = Math.max(g.canvas.height, h);"
+ " ctx = g.ctx; ctx.font = css; }"
+ " ctx.clearRect(0, 0, w, h); ctx.fillStyle = '#fff'; ctx.textBaseline = 'alphabetic';"
+ " ctx.fillText(text, -x0, up);"
+ " var px = ctx.getImageData(0, 0, w, h).data; var a = new Int8Array(w * h);"
+ " for (var i = 0; i < a.length; i++) a[i] = px[i * 4 + 3];"
+ " r.alpha = a; return r;")
private static native JSObject draw(String css, String text);
@JSBody(params = "r", script = "return r.advance;")
private static native float advance(JSObject r);
@JSBody(params = "r", script = "return r.left;")
private static native int left(JSObject r);
@JSBody(params = "r", script = "return r.top;")
private static native int top(JSObject r);
@JSBody(params = "r", script = "return r.width;")
private static native int width(JSObject r);
@JSBody(params = "r", script = "return r.height;")
private static native int height(JSObject r);
@JSBody(params = "r", script = "return r.alpha;")
private static native Int8Array coverage(JSObject r);
}
@@ -0,0 +1,5 @@
/** Smooth fonts drawn by the browser: {@code FontFace} and a 2D canvas. */
@NullMarked
package incari.platform.web.fonts;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,5 @@
/** The browser implementation of the platform interfaces. */
@NullMarked
package incari.platform.web;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,596 @@
package incari.platform.web.rtc;
import incari.platform.api.net.NetConnection;
import incari.platform.api.rtc.IceServer;
import incari.platform.api.rtc.Microphone;
import incari.platform.api.rtc.PlatformRtc;
import incari.platform.api.rtc.RemoteVoice;
import incari.platform.api.rtc.RtcPeer;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* WebRTC in the browser (ADR 0019): peer connections for Eagler voice and for worlds shared
* through a relay, and the microphone.
*
* <p>As with sockets, the browser's callbacks never call Java: each peer, data channel and the
* microphone queue what happened in a JavaScript array, and {@link #deliver} hands it to the
* listeners once a frame, on the game's thread.
*
* <p>Voices play through the game's own audio context (ADR 0013), each through a gain and a
* stereo panner the caller sets from where the speaker stands, with an analyser for whether they're
* talking. The microphone goes through a gain into one stream, whose track every voice peer sends;
* each peer gets an audio transceiver when it's made, so a microphone that opens later (the
* permission prompt) is swapped in without renegotiating.
*/
public final class WebRtc implements PlatformRtc {
private final List<Peer> peers = new ArrayList<>();
private final List<Channel> channels = new ArrayList<>();
private final WebMicrophone microphone = new WebMicrophone();
private boolean checked;
private boolean supported;
@Override
public boolean supported() {
if (!checked) {
checked = true;
supported = hasWebRtc();
if (supported) {
installHelpers();
}
}
return supported;
}
@Override
public Microphone microphone() {
requireSupport();
return microphone;
}
@Override
public RtcPeer createPeer(List<IceServer> iceServers, RtcPeer.Listener listener) {
requireSupport();
StringBuilder json = new StringBuilder("[");
for (IceServer server : iceServers) {
if (json.length() > 1) {
json.append(',');
}
json.append("{\"urls\":").append(quote(server.url()));
if (server.username() != null && server.credential() != null) {
json.append(",\"username\":").append(quote(server.username()));
json.append(",\"credential\":").append(quote(server.credential()));
}
json.append('}');
}
json.append(']');
Peer peer = new Peer(newPeer(json.toString()), listener);
peers.add(peer);
return peer;
}
/** Delivers everything the page queued for peers, channels and the microphone. Game thread. */
public void deliver() {
if (!supported) {
return;
}
microphone.update();
if (!peers.isEmpty()) {
for (Peer peer : new ArrayList<>(peers)) {
peer.deliver();
if (peer.closed) {
peers.remove(peer);
}
}
}
if (!channels.isEmpty()) {
for (Channel channel : new ArrayList<>(channels)) {
channel.deliver();
if (channel.finished) {
channels.remove(channel);
}
}
}
}
private void requireSupport() {
if (!supported()) {
throw new UnsupportedOperationException("This browser has no WebRTC");
}
}
private static String quote(String text) {
StringBuilder out = new StringBuilder("\"");
for (int i = 0; i < text.length(); i++) {
char c = text.charAt(i);
if (c == '"' || c == '\\') {
out.append('\\');
}
out.append(c < 0x20 ? ' ' : c);
}
return out.append('"').toString();
}
// --- Peers -------------------------------------------------------------------------------
private final class Peer implements RtcPeer, RemoteVoice {
private final JSObject handle;
private final RtcPeer.Listener listener;
private boolean closed;
Peer(JSObject handle, RtcPeer.Listener listener) {
this.handle = handle;
this.listener = listener;
}
@Override
public void sendMicrophone() {
if (!closed) {
addMicrophone(handle);
}
}
@Override
public NetConnection openDataChannel(String label, NetConnection.Listener channelListener) {
Channel channel = new Channel(newDataChannel(handle, label), label, channelListener);
channels.add(channel);
return channel;
}
@Override
public void createOffer() {
if (!closed) {
offer(handle);
}
}
@Override
public void setRemoteDescription(String json) {
if (!closed) {
remoteDescription(handle, json);
}
}
@Override
public void addIceCandidate(String candidate, int sdpMLineIndex) {
if (!closed) {
iceCandidate(handle, candidate, sdpMLineIndex);
}
}
@Override
public RemoteVoice voice() {
return this;
}
@Override
public void close() {
if (!closed) {
closed = true;
closePeer(handle);
}
}
@Override
public void setVolume(float volume) {
if (!closed) {
voiceVolume(handle, volume);
}
}
@Override
public void setPan(float pan) {
if (!closed) {
voicePan(handle, Math.max(-1, Math.min(1, pan)));
}
}
@Override
public float level() {
return closed ? 0 : (float) voiceLevel(handle);
}
void deliver() {
int count = queued(handle);
for (int i = 0; i < count && !closed; i++) {
switch (queuedType(handle, i)) {
case "desc" -> listener.localDescription(queuedString(handle, i, 1));
case "ice" -> listener.iceCandidate(queuedString(handle, i, 1), queuedInt(handle, i, 2));
case "iceDone" -> listener.iceGatheringComplete();
case "audio" -> listener.remoteAudio();
case "state" -> listener.stateChanged(queuedString(handle, i, 1));
case "error" -> listener.stateChanged("failed");
case "channel" -> incoming(queuedString(handle, i, 1), queuedObject(handle, i, 2));
default -> {}
}
}
dropQueued(handle, count);
}
/** A data channel the peer opened: the listener's to take, else closed. */
private void incoming(String label, JSObject dataChannel) {
boolean[] taken = {false};
listener.dataChannel(label, channelListener -> {
taken[0] = true;
Channel channel = new Channel(dataChannel, label, channelListener);
channels.add(channel);
return channel;
});
if (!taken[0]) {
channelClose(dataChannel);
}
}
}
// --- Data channels -----------------------------------------------------------------------
private static final class Channel implements NetConnection {
private final JSObject handle;
private final String label;
private final NetConnection.Listener listener;
private boolean open;
private boolean closedByUs;
private boolean finished;
Channel(JSObject handle, String label, NetConnection.Listener listener) {
this.handle = handle;
this.label = label;
this.listener = listener;
}
@Override
public void send(ByteBuffer data) {
if (!open || closedByUs) {
return;
}
byte[] bytes = new byte[data.remaining()];
data.get(bytes);
channelSend(handle, Int8Array.copyFromJavaArray(bytes));
}
@Override
public void close() {
if (!closedByUs && !finished) {
closedByUs = true;
open = false;
channelClose(handle);
}
}
@Override
public boolean isOpen() {
return open;
}
@Override
public String remoteDescription() {
return "WebRTC data channel '" + label + "'";
}
void deliver() {
if (finished) {
return;
}
int count = queued(handle);
for (int i = 0; i < count && !finished; i++) {
switch (queuedType(handle, i)) {
case "open" -> {
if (!closedByUs) {
open = true;
listener.connected();
}
}
case "message" -> {
if (!closedByUs) {
byte[] message = new Int8Array(queuedData(handle, i)).copyToJavaArray();
listener.received(ByteBuffer.wrap(message));
}
}
case "close" -> finish(closedByUs ? null : new IOException("The data channel closed"));
default -> {}
}
}
dropQueued(handle, count);
if (closedByUs && !finished) {
finish(null);
}
}
private void finish(@Nullable Throwable cause) {
finished = true;
open = false;
listener.closed(cause);
}
}
// --- The microphone ----------------------------------------------------------------------
private static final class WebMicrophone implements Microphone {
private State state = State.CLOSED;
void update() {
if (state == State.OPENING) {
String now = micState();
if (now.equals("open")) {
state = State.OPEN;
} else if (now.equals("unavailable")) {
state = State.UNAVAILABLE;
}
}
}
@Override
public State state() {
return state;
}
@Override
public void open() {
if (state == State.CLOSED) {
state = State.OPENING;
openMic();
}
}
@Override
public void close() {
if (state != State.CLOSED) {
state = State.CLOSED;
closeMic();
}
}
@Override
public void setTransmitting(boolean transmitting) {
micTransmitting(transmitting);
}
@Override
public void setVolume(float volume) {
micVolume(volume);
}
@Override
public float level() {
return (float) micLevel();
}
}
// --- The page side -----------------------------------------------------------------------
@JSBody(
script = "return typeof RTCPeerConnection !== 'undefined' && !!navigator.mediaDevices"
+ " && typeof navigator.mediaDevices.getUserMedia === 'function';")
private static native boolean hasWebRtc();
/*
* globalThis.incariRtc: the audio context voices play through (the game's), the microphone's
* graph, and the level of a node from its analyser. Peers are plain objects {pc, q, ...};
* q holds queued events as arrays: ["desc", json], ["ice", candidate, index], ["iceDone"],
* ["audio"], ["state", state], ["error", message]. Data channels queue ["open"],
* ["message", ArrayBuffer], ["close"].
*/
@JSBody(
script = "var r = globalThis.incariRtc = { mic: { state: 'closed', track: null, gain: null,"
+ " analyser: null, transmitting: false, volume: 1, peers: [] } };"
+ "r.context = function() { var a = globalThis.incariAudio;"
+ " if (a && a.context) return a.context;"
+ " if (!r.ownContext) { var C = window.AudioContext || window.webkitAudioContext; r.ownContext = new C(); }"
+ " return r.ownContext; };"
+ "r.level = function(analyser) { if (!analyser) return 0;"
+ " var data = r.levelData || (r.levelData = new Float32Array(256));"
+ " analyser.getFloatTimeDomainData(data); var sum = 0;"
+ " for (var i = 0; i < data.length; i++) sum += data[i] * data[i];"
+ " return Math.min(1, Math.sqrt(sum / data.length) * 3); };"
+ "r.attachMic = function(p) { if (p.transceiver && r.mic.track)"
+ " p.transceiver.sender.replaceTrack(r.mic.track).catch(function() {}); };")
private static native void installHelpers();
/**
* A peer connection. Its voice plays through a muted media element as well as Web Audio:
* Chrome feeds a remote stream to Web Audio only while a media element plays it.
*/
@JSBody(
params = "iceJson",
script = "var r = globalThis.incariRtc;"
+ "var pc = new RTCPeerConnection({ iceServers: JSON.parse(iceJson) });"
+ "var p = { pc: pc, q: [], pendingIce: [], remoteSet: false, transceiver: null, wantsMic: false,"
+ " gain: null, pan: null, analyser: null, audio: null, volume: 0, panValue: 0 };"
+ "pc.onicecandidate = function(e) { if (e.candidate) p.q.push(['ice', e.candidate.candidate,"
+ " e.candidate.sdpMLineIndex | 0]); else p.q.push(['iceDone']); };"
+ "pc.onconnectionstatechange = function() { p.q.push(['state', pc.connectionState]); };"
+ "pc.ondatachannel = function(e) { var dc = e.channel; dc.binaryType = 'arraybuffer'; dc.q = [];"
+ " dc.onopen = function() { dc.q.push(['open']); };"
+ " dc.onmessage = function(ev) { dc.q.push(['message', ev.data]); };"
+ " dc.onclose = function() { dc.q.push(['close']); };"
+ " if (dc.readyState === 'open') dc.q.push(['open']);"
+ " p.q.push(['channel', dc.label, dc]); };"
+ "pc.ontrack = function(e) { if (p.gain) return;"
+ " var stream = e.streams && e.streams[0] ? e.streams[0] : new MediaStream([e.track]);"
+ " var el = new Audio(); el.muted = true; el.srcObject = stream; el.play().catch(function() {});"
+ " var ctx = r.context(); var src = ctx.createMediaStreamSource(stream);"
+ " p.analyser = ctx.createAnalyser(); p.analyser.fftSize = 256; src.connect(p.analyser);"
+ " p.gain = ctx.createGain(); p.gain.gain.value = p.volume;"
+ " p.pan = ctx.createStereoPanner(); p.pan.pan.value = p.panValue;"
+ " src.connect(p.gain); p.gain.connect(p.pan); p.pan.connect(ctx.destination);"
+ " p.audio = { el: el, src: src }; p.q.push(['audio']); };"
+ "return p;")
private static native JSObject newPeer(String iceJson);
/*
* The microphone's transceiver is made when the peer's side of the audio is: before an offer
* this side makes, or from the one a peer's offer brings (a transceiver added here before that
* offer wouldn't be matched to it, and nothing would be sent).
*/
@JSBody(params = "p", script = "p.wantsMic = true;")
private static native void addMicrophone(JSObject p);
@JSBody(
params = "p",
script = "var r = globalThis.incariRtc;"
+ "if (p.wantsMic && !p.transceiver) { p.transceiver = p.pc.addTransceiver('audio', { direction: 'sendrecv' });"
+ " r.mic.peers.push(p); r.attachMic(p); }"
+ "p.pc.createOffer().then(function(d) { return p.pc.setLocalDescription(d); })"
+ ".then(function() { p.q.push(['desc', JSON.stringify(p.pc.localDescription)]); })"
+ ".catch(function(e) { p.q.push(['error', String(e)]); });")
private static native void offer(JSObject p);
@JSBody(
params = {"p", "json"},
script =
"var d; try { d = JSON.parse(json); } catch (e) { p.q.push(['error', 'bad description']); return; }"
+ "p.pc.setRemoteDescription(d).then(function() { p.remoteSet = true;"
+ " for (var i = 0; i < p.pendingIce.length; i++) p.pc.addIceCandidate(p.pendingIce[i]).catch(function() {});"
+ " p.pendingIce = [];"
+ " if (d.type !== 'offer') return null;"
+ " if (p.wantsMic && !p.transceiver) { var ts = p.pc.getTransceivers();"
+ " for (var k = 0; k < ts.length; k++) if (ts[k].receiver.track && ts[k].receiver.track.kind === 'audio') {"
+ " p.transceiver = ts[k]; ts[k].direction = 'sendrecv'; break; }"
+ " if (p.transceiver) { var r = globalThis.incariRtc; r.mic.peers.push(p); r.attachMic(p); } }"
+ " return p.pc.createAnswer().then(function(a) { return p.pc.setLocalDescription(a); })"
+ " .then(function() { p.q.push(['desc', JSON.stringify(p.pc.localDescription)]); }); })"
+ ".catch(function(e) { p.q.push(['error', String(e)]); });")
private static native void remoteDescription(JSObject p, String json);
/** One of the peer's candidates; any that come before its description wait for it. */
@JSBody(
params = {"p", "candidate", "index"},
script = "var c = { candidate: candidate, sdpMLineIndex: index };"
+ "if (p.remoteSet) p.pc.addIceCandidate(c).catch(function() {}); else p.pendingIce.push(c);")
private static native void iceCandidate(JSObject p, String candidate, int index);
@JSBody(
params = "p",
script = "var r = globalThis.incariRtc; try { p.pc.close(); } catch (e) {}"
+ "if (p.gain) { try { p.pan.disconnect(); p.gain.disconnect(); p.audio.src.disconnect(); } catch (e) {}"
+ " p.audio.el.srcObject = null; }"
+ "var i = r.mic.peers.indexOf(p); if (i >= 0) r.mic.peers.splice(i, 1);")
private static native void closePeer(JSObject p);
@JSBody(
params = {"p", "volume"},
script = "p.volume = volume; if (p.gain) p.gain.gain.value = volume;")
private static native void voiceVolume(JSObject p, float volume);
@JSBody(
params = {"p", "pan"},
script = "p.panValue = pan; if (p.pan) p.pan.pan.value = pan;")
private static native void voicePan(JSObject p, float pan);
@JSBody(params = "p", script = "return globalThis.incariRtc.level(p.analyser);")
private static native double voiceLevel(JSObject p);
@JSBody(
params = {"p", "label"},
script = "var dc = p.pc.createDataChannel(label); dc.binaryType = 'arraybuffer'; dc.q = [];"
+ "dc.onopen = function() { dc.q.push(['open']); };"
+ "dc.onmessage = function(e) { dc.q.push(['message', e.data]); };"
+ "dc.onclose = function() { dc.q.push(['close']); };"
+ "return dc;")
private static native JSObject newDataChannel(JSObject p, String label);
@JSBody(
params = {"dc", "data"},
script = "if (dc.readyState === 'open') dc.send(data);")
private static native void channelSend(JSObject dc, Int8Array data);
@JSBody(params = "dc", script = "try { dc.close(); } catch (e) {}")
private static native void channelClose(JSObject dc);
/*
* m.gen counts opens and closes: a permission granted after the microphone was closed (or
* opened again) belongs to nobody, and its stream is stopped at once.
*/
@JSBody(
script = "var r = globalThis.incariRtc; var m = r.mic; m.state = 'opening';"
+ "var g = m.gen = (m.gen | 0) + 1;"
+ "navigator.mediaDevices.getUserMedia({ audio: { echoCancellation: true,"
+ " noiseSuppression: true, autoGainControl: true } }).then(function(stream) {"
+ " if (m.gen !== g) { var old = stream.getTracks();"
+ " for (var k = 0; k < old.length; k++) old[k].stop(); return; }"
+ " var ctx = r.context(); var src = ctx.createMediaStreamSource(stream);"
+ " m.gain = ctx.createGain(); m.gain.gain.value = m.volume;"
+ " m.analyser = ctx.createAnalyser(); m.analyser.fftSize = 256;"
+ " var dest = ctx.createMediaStreamDestination();"
+ " src.connect(m.gain); m.gain.connect(dest); m.gain.connect(m.analyser);"
+ " m.raw = stream; m.track = dest.stream.getAudioTracks()[0];"
+ " m.track.enabled = m.transmitting; m.state = 'open';"
+ " for (var i = 0; i < m.peers.length; i++) r.attachMic(m.peers[i]);"
+ "}).catch(function() { if (m.gen === g) m.state = 'unavailable'; });")
private static native void openMic();
/** Stops the microphone's device and graph; peers it went to send nothing until it opens again. */
@JSBody(
script = "var m = globalThis.incariRtc.mic; m.gen = (m.gen | 0) + 1; m.state = 'closed';"
+ "if (m.raw) { var ts = m.raw.getTracks(); for (var i = 0; i < ts.length; i++) ts[i].stop(); }"
+ "if (m.track) m.track.stop();"
+ "try { if (m.gain) m.gain.disconnect(); } catch (e) {}"
+ "m.raw = null; m.track = null; m.gain = null; m.analyser = null;"
+ "for (var k = 0; k < m.peers.length; k++) { var p = m.peers[k];"
+ " if (p.transceiver) p.transceiver.sender.replaceTrack(null).catch(function() {}); }")
private static native void closeMic();
@JSBody(script = "return globalThis.incariRtc.mic.state;")
private static native String micState();
@JSBody(
params = "on",
script = "var m = globalThis.incariRtc.mic; m.transmitting = on; if (m.track) m.track.enabled = on;")
private static native void micTransmitting(boolean on);
@JSBody(
params = "volume",
script = "var m = globalThis.incariRtc.mic; m.volume = volume; if (m.gain) m.gain.gain.value = volume;")
private static native void micVolume(float volume);
@JSBody(
script = "var m = globalThis.incariRtc.mic;"
+ "return m.transmitting ? globalThis.incariRtc.level(m.analyser) : 0;")
private static native double micLevel();
/* Peers and data channels keep their queue in .q. */
@JSBody(params = "o", script = "return o.q.length;")
private static native int queued(JSObject o);
@JSBody(
params = {"o", "i"},
script = "return o.q[i][0];")
private static native String queuedType(JSObject o, int i);
@JSBody(
params = {"o", "i", "field"},
script = "return String(o.q[i][field]);")
private static native String queuedString(JSObject o, int i, int field);
@JSBody(
params = {"o", "i", "field"},
script = "return o.q[i][field] | 0;")
private static native int queuedInt(JSObject o, int i, int field);
@JSBody(
params = {"o", "i"},
script = "return o.q[i][1];")
private static native ArrayBuffer queuedData(JSObject o, int i);
@JSBody(
params = {"o", "i", "field"},
script = "return o.q[i][field];")
private static native JSObject queuedObject(JSObject o, int i, int field);
@JSBody(
params = {"o", "count"},
script = "o.q.splice(0, count);")
private static native void dropQueued(JSObject o, int count);
}
@@ -0,0 +1,5 @@
/** WebRTC in the browser: voice chat's peers and microphone, and relay data channels (ADR 0019). */
@NullMarked
package incari.platform.web.rtc;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,323 @@
package incari.platform.web.storage;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* The page's side of the storage worker ({@code src/main/js/storage-worker.js}), with every
* JavaScript snippet the file system runs. It starts the worker, sends it batches of changes, and
* waits for the two answers the game needs at start-up (the stored files and the client jar).
*
* <p>Waiting suspends the calling coroutine through {@link Async}; the worker's replies complete it
* from a message listener. Nothing else waits: a batch is posted and forgotten, and its outcome is
* read at the next flush ({@link #takeProblem}).
*/
final class BrowserStore {
private BrowserStore() {}
/**
* Starts the worker from its source, and asks the browser not to evict the page's storage under
* pressure (it may refuse). For the browser checks and the console, also offers
* {@code window.incariStorage}: {@code read(path)} (a promise of the file's text),
* {@code list(path)} (the paths under a folder) and {@code pending()} (batches not yet stored).
*/
@JSBody(
params = "source",
script = "var url = URL.createObjectURL(new Blob([source], {type: 'text/javascript'}));\n"
+ "var worker = new Worker(url, {name: 'incari-storage'});\n"
+ "var store = {worker: worker, calls: {}, next: 1, pending: 0, problems: [], failed: []};\n"
+ "worker.onmessage = function(e) { var m = e.data;\n"
+ " if (m.type === 'applied') { store.pending--;"
+ " store.lastOk = !m.error; if (m.error) store.problems.push('saving failed: ' + m.error);"
+ " if (m.failed) for (var i = 0; i < m.failed.length; i++) store.failed.push(m.failed[i]); return; }\n"
+ " var call = store.calls[m.id]; if (call) { delete store.calls[m.id]; call(m); } };\n"
+ "worker.onerror = function(e) { store.problems.push('storage worker: ' + (e.message || e)); };\n"
+ "store.call = function(message, callback) { message.id = store.next++;"
+ " store.calls[message.id] = callback; worker.postMessage(message); };\n"
+ "window.incariStorage = {\n"
+ " read: function(path) { return new Promise(function(resolve) {"
+ " store.call({type: 'read', path: path}, function(m) {"
+ " resolve(m.data ? new TextDecoder().decode(m.data) : null); }); }); },\n"
+ " list: function(path) { return new Promise(function(resolve) {"
+ " store.call({type: 'list', path: path}, function(m) { resolve(m.paths); }); }); },\n"
+ " pending: function() { return store.pending; },\n"
// ADR 0041: a port of the storage worker's own for another worker (singleplayer's
// server), whose changes then go straight to it, in the same queue as the page's.
+ " connect: function() { var channel = new MessageChannel();"
+ " worker.postMessage({type: 'port', port: channel.port1}, [channel.port1]);"
+ " return channel.port2; } };\n"
+ "if (navigator.storage && navigator.storage.persist) {"
+ " navigator.storage.persist().then(function() {}, function() {}); }\n"
+ "return store;")
static native JSObject start(String source);
/**
* In a worker the page gave a port of the storage worker's ({@code connect}, ADR 0041): a store
* object over that port, which the calls here use as they use the page's. Null without one.
*/
@JSBody(
script = "var port = self.__incariStorage; if (!port) return null;"
+ "var store = {worker: port, calls: {}, next: 1, pending: 0, problems: [], failed: []};"
+ "port.onmessage = function(e) { var m = e.data;"
+ " if (m.type === 'applied') { store.pending--;"
+ " store.lastOk = !m.error; if (m.error) store.problems.push('saving failed: ' + m.error);"
+ " if (m.failed) for (var i = 0; i < m.failed.length; i++) store.failed.push(m.failed[i]); return; }"
+ " var call = store.calls[m.id]; if (call) { delete store.calls[m.id]; call(m); } };"
+ "store.call = function(message, callback) { message.id = store.next++;"
+ " store.calls[message.id] = callback; port.postMessage(message); };"
+ "return store;")
static native @Nullable JSObject fromPort();
// --- Opening: the stored files ----------------------------------------------------------
/**
* Loads everything under {@code root}, but for in-place files (ADR 0041), listed with their
* sizes; suspends until the worker has read it all.
*/
@Async
static native JSObject open(JSObject store, String root, String lock);
private static void open(JSObject store, String root, String lock, AsyncCallback<JSObject> callback) {
JSObject message = request("open", "root", root, "lock", lock);
setInPlace(message, InPlaceFiles.WITHIN);
call(store, message, callback::complete);
}
@JSBody(
params = {"message", "within"},
script = "message.inPlace = {within: within, suffixes: ['.mca', '.mcc']};")
private static native void setInPlace(JSObject message, String within);
@JSBody(
params = {"reply", "index"},
script = "return !!reply.entries[index].stored;")
static native boolean entryIsStored(JSObject reply, int index);
@JSBody(
params = {"reply", "index"},
script = "return reply.entries[index].size | 0;")
static native int entrySize(JSObject reply, int index);
// --- In-place files and waiting for the store (ADR 0041) ----------------------------------
/** A stored file's bytes, or null if it isn't stored; suspends until read. */
@Async
static native @Nullable ArrayBuffer read(JSObject store, String path);
private static void read(JSObject store, String path, AsyncCallback<@Nullable ArrayBuffer> callback) {
call(store, request("read", "path", path, "path", path), reply -> callback.complete(dataOrNull(reply)));
}
@JSBody(params = "reply", script = "return reply.data || null;")
private static native @Nullable ArrayBuffer dataOrNull(JSObject reply);
/** Everything stored under {@code path}, with sizes and without bytes ({@code entries}, as {@link #open}'s). */
@Async
static native JSObject stat(JSObject store, String path);
private static void stat(JSObject store, String path, AsyncCallback<JSObject> callback) {
call(store, request("stat", "path", path, "path", path), callback::complete);
}
/** Suspends until everything sent before it is stored. */
@Async
static native JSObject sync(JSObject store);
private static void sync(JSObject store, AsyncCallback<JSObject> callback) {
call(store, request("sync", "id", "0", "id", "0"), callback::complete);
}
@JSBody(params = "reply", script = "return String(reply.backend);")
static native String backend(JSObject reply);
@JSBody(params = "reply", script = "return !!reply.readOnly;")
static native boolean readOnly(JSObject reply);
@JSBody(params = "reply", script = "return !!reply.locked;")
static native boolean locked(JSObject reply);
@JSBody(params = "reply", script = "return String(reply.problems || '');")
static native String problems(JSObject reply);
@JSBody(params = "reply", script = "return reply.entries.length;")
static native int entryCount(JSObject reply);
@JSBody(
params = {"reply", "index"},
script = "return String(reply.entries[index].path);")
static native String entryPath(JSObject reply, int index);
@JSBody(
params = {"reply", "index"},
script = "return !!reply.entries[index].dir;")
static native boolean entryIsDirectory(JSObject reply, int index);
@JSBody(
params = {"reply", "index"},
script = "return +reply.entries[index].mtime;")
static native double entryLastModified(JSObject reply, int index);
/** A file entry's bytes, handed over once: the page's copy is dropped as it's read. */
@JSBody(
params = {"reply", "index"},
script = "var e = reply.entries[index]; var d = e.data; e.data = null;"
+ "return new Int8Array(d || new ArrayBuffer(0));")
static native Int8Array takeEntryData(JSObject reply, int index);
// --- Changes ----------------------------------------------------------------------------
@JSBody(script = "return [];")
static native JSObject newBatch();
@JSBody(
params = {"batch", "path", "mtime"},
script = "batch.push({op: 'mkdir', path: path, mtime: mtime});")
static native void addMkdir(JSObject batch, String path, double mtime);
@JSBody(
params = {"batch", "path", "size", "at", "data", "mtime"},
script = "batch.push({op: 'write', path: path, size: size, at: at,"
// A copy of its own: the batch's buffers are moved to the worker, and under
// TeaVM's JavaScript backend data may be the Java array itself.
+ " data: data ? new Uint8Array(data.buffer.slice(data.byteOffset, data.byteOffset + data.length))"
+ " : null, mtime: mtime});")
static native void addWrite(JSObject batch, String path, int size, int at, @Nullable Int8Array data, double mtime);
@JSBody(
params = {"batch", "path"},
script = "batch.push({op: 'delete', path: path});")
static native void addDelete(JSObject batch, String path);
/** Hands a batch to the worker, its bytes moved rather than copied, without waiting. */
@JSBody(
params = {"store", "batch"},
script = "var buffers = [];"
+ "for (var i = 0; i < batch.length; i++) { var d = batch[i].data;"
+ " if (d && buffers.indexOf(d.buffer) < 0) buffers.push(d.buffer); }"
+ "store.pending++; store.worker.postMessage({type: 'apply', ops: batch}, buffers);")
static native void apply(JSObject store, JSObject batch);
/** Batches handed over but not yet stored. */
@JSBody(params = "store", script = "return store.pending;")
static native int pending(JSObject store);
/** The oldest problem the worker reported and nobody has read yet, or null. */
@JSBody(params = "store", script = "return store.problems.length ? String(store.problems.shift()) : null;")
static native @Nullable String takeProblem(JSObject store);
/**
* The oldest path whose change the worker couldn't store and nobody has read yet, or null. The
* file system sends it again whole ({@code WebFileSystem#flush}).
*/
@JSBody(params = "store", script = "return store.failed.length ? String(store.failed.shift()) : null;")
static native @Nullable String takeFailedPath(JSObject store);
/** Whether the last batch the worker answered for was stored whole (true before any answer). */
@JSBody(params = "store", script = "return store.lastOk !== false;")
static native boolean lastBatchStored(JSObject store);
// --- The client jar ---------------------------------------------------------------------
/**
* The file at {@code url}, from the worker's cache under {@code key} or downloaded (and then
* cached). Suspends until it's there; its bytes stay in the page, outside the game's heap.
*/
@Async
static native JSObject download(JSObject store, String url, String key);
private static void download(JSObject store, String url, String key, AsyncCallback<JSObject> callback) {
call(store, request("jar", "url", absolute(url), "key", key), callback::complete);
}
/** Drops the cached copy under {@code key} (it was damaged); suspends until it's gone. */
@Async
static native JSObject forget(JSObject store, String key);
private static void forget(JSObject store, String key, AsyncCallback<JSObject> callback) {
call(store, request("forget", "key", key, "key", key), callback::complete);
}
@JSBody(params = "reply", script = "return reply.error ? String(reply.error) : null;")
static native @Nullable String error(JSObject reply);
@JSBody(params = "reply", script = "return !!reply.cached;")
static native boolean cached(JSObject reply);
@JSBody(params = "reply", script = "return reply.data;")
static native ArrayBuffer data(JSObject reply);
/** {@code length} bytes of {@code buffer} from {@code position}, copied into the game's heap. */
@JSBody(
params = {"buffer", "position", "length"},
script = "return new Int8Array(buffer.slice(position, position + length));")
static native Int8Array slice(ArrayBuffer buffer, int position, int length);
/** A list for {@link #copyEntries}: local header, compressed size, local header, ... */
@JSBody(script = "return [];")
static native JSObject newRanges();
@JSBody(
params = {"ranges", "start", "length"},
script = "ranges.push(start, length);")
static native void addRange(JSObject ranges, int start, int length);
/**
* The zip entries listed in {@code entries} (each a local header's offset and its data's
* compressed size), copied from {@code buffer} one after another into a new buffer: each its
* local header (30 bytes, then its name and extra field, whose lengths it gives) and its data.
* The reply has the buffer as {@code data}, where each entry now starts as {@code starts}, or
* an {@code error}.
*/
@JSBody(
params = {"buffer", "entries"},
script = "var from = new Uint8Array(buffer), n = entries.length / 2, spans = new Int32Array(n), total = 0;"
+ " for (var i = 0; i < n; i++) { var h = entries[2 * i];"
+ " if (h + 30 > from.length || from[h] !== 0x50 || from[h + 1] !== 0x4b || from[h + 2] !== 3 || from[h + 3] !== 4)"
+ " return {error: 'Corrupt zip file (bad local header at ' + h + ')'};"
+ " spans[i] = 30 + (from[h + 26] | from[h + 27] << 8) + (from[h + 28] | from[h + 29] << 8) + entries[2 * i + 1];"
+ " if (h + spans[i] > from.length) return {error: 'Corrupt zip file (entry past the end at ' + h + ')'};"
+ " total += spans[i]; }"
+ " var to = new Uint8Array(total), starts = new Int32Array(n), at = 0;"
+ " for (var j = 0; j < n; j++) { var s = entries[2 * j];"
+ " to.set(from.subarray(s, s + spans[j]), at); starts[j] = at; at += spans[j]; }"
+ " return {data: to.buffer, starts: starts};")
static native JSObject copyEntries(ArrayBuffer buffer, JSObject entries);
@JSBody(
params = {"copy", "index"},
script = "return copy.starts[index];")
static native int copiedStart(JSObject copy, int index);
// --- Plumbing ---------------------------------------------------------------------------
@JSFunctor
interface Reply extends JSObject {
void reply(JSObject message);
}
@JSBody(
params = {"store", "message", "reply"},
script = "store.call(message, function(m) { reply(m); });")
private static native void call(JSObject store, JSObject message, Reply reply);
@JSBody(
params = {"type", "key1", "value1", "key2", "value2"},
script = "var m = {type: type}; m[key1] = value1; m[key2] = value2; return m;")
private static native JSObject request(String type, String key1, String value1, String key2, String value2);
/**
* The worker runs from a Blob URL, so it can't resolve a URL relative to the page itself. Nor can
* the single-file page by its own URL, which may have no folder (offline.ts).
*/
@JSBody(
params = "url",
script = "return new URL(url, window.incariFiles ? window.incariFiles.base : location.href).href;")
private static native String absolute(String url);
}
@@ -0,0 +1,149 @@
package incari.platform.web.storage;
import java.util.Arrays;
/**
* A file whose bytes live in the tree. Also carries what the {@link Journal} needs between two
* flushes: which bytes were written, and whether the size changed.
*/
final class DataFile extends FileNode {
private static final byte[] EMPTY = new byte[0];
/** How many separate ranges a file keeps between flushes; more merge the closest two. */
static final int MAX_DIRTY_RANGES = 8;
/** Writes closer than this make one range: sending the bytes between is cheaper than another op. */
static final int MERGE_GAP = 512;
byte[] data;
int size;
/**
* Written since the last flush: {@link #dirtyCount} ranges [from, to), as pairs in order and
* apart. A region file's write touches its header at the start and a chunk's sectors further
* on; one range from the first byte to the last would send the store most of the file each
* time, so writes far apart stay apart (ADR 0041).
*/
int[] dirty = new int[2 * MAX_DIRTY_RANGES];
int dirtyCount;
boolean resized;
boolean queued;
DataFile(String name, long lastModified) {
super(name, lastModified);
this.data = EMPTY;
}
DataFile(String name, long lastModified, byte[] contents) {
super(name, lastModified);
this.data = contents;
this.size = contents.length;
}
@Override
int length() {
return size;
}
@Override
Bytes contents() {
return new Bytes(data, size);
}
/** Makes room for {@code capacity} bytes; bytes past {@link #size} are always zero. */
void ensureCapacity(int capacity) {
if (capacity > data.length) {
// Grow by half again, as files tend to be written from start to end in small pieces.
int grown = (int) Math.min(Integer.MAX_VALUE - 8, Math.max(capacity, data.length + (long) data.length / 2));
data = Arrays.copyOf(data, Math.max(grown, 16));
}
}
/** Sets the size, zeroing what a shrink cut off so a later growth reads zeros there. */
void setSize(int newSize) {
if (newSize < size) {
Arrays.fill(data, newSize, size, (byte) 0);
} else {
ensureCapacity(newSize);
}
size = newSize;
}
/** Notes that [from, to) was written. Hot path (every write): no allocation. */
void markWritten(int from, int to) {
if (from >= to) {
return;
}
int[] ranges = dirty;
int count = dirtyCount;
// Most writes continue the last range (a file written front to back).
if (count > 0 && from <= ranges[2 * count - 1] + MERGE_GAP && to >= ranges[2 * count - 2] - MERGE_GAP) {
merge(count - 1, from, to);
return;
}
// The first range that ends at or after from (less the gap) is where it goes or merges.
int at = 0;
while (at < count && ranges[2 * at + 1] + MERGE_GAP < from) {
at++;
}
if (at < count && ranges[2 * at] - MERGE_GAP <= to) {
merge(at, from, to);
return;
}
if (count == MAX_DIRTY_RANGES) {
mergeClosest();
markWritten(from, to);
return;
}
System.arraycopy(ranges, 2 * at, ranges, 2 * at + 2, 2 * (count - at));
ranges[2 * at] = from;
ranges[2 * at + 1] = to;
dirtyCount = count + 1;
}
/** Widens range {@code index} to take in [from, to), then takes in the ranges it now reaches. */
private void merge(int index, int from, int to) {
int[] ranges = dirty;
ranges[2 * index] = Math.min(ranges[2 * index], from);
ranges[2 * index + 1] = Math.max(ranges[2 * index + 1], to);
int count = dirtyCount;
// Earlier ranges it reaches back to.
while (index > 0 && ranges[2 * index - 1] + MERGE_GAP >= ranges[2 * index]) {
ranges[2 * index - 2] = Math.min(ranges[2 * index - 2], ranges[2 * index]);
ranges[2 * index - 1] = Math.max(ranges[2 * index - 1], ranges[2 * index + 1]);
System.arraycopy(ranges, 2 * index + 2, ranges, 2 * index, 2 * (count - index - 1));
count--;
index--;
}
// Later ranges it reaches forward to.
while (index + 1 < count && ranges[2 * index + 1] + MERGE_GAP >= ranges[2 * index + 2]) {
ranges[2 * index + 1] = Math.max(ranges[2 * index + 1], ranges[2 * index + 3]);
System.arraycopy(ranges, 2 * index + 4, ranges, 2 * index + 2, 2 * (count - index - 2));
count--;
}
dirtyCount = count;
}
/** Joins the two neighbouring ranges with the least between them. */
private void mergeClosest() {
int[] ranges = dirty;
int best = 0;
int bestGap = Integer.MAX_VALUE;
for (int i = 0; i + 1 < dirtyCount; i++) {
int gap = ranges[2 * i + 2] - ranges[2 * i + 1];
if (gap < bestGap) {
bestGap = gap;
best = i;
}
}
ranges[2 * best + 1] = ranges[2 * best + 3];
System.arraycopy(ranges, 2 * best + 4, ranges, 2 * best + 2, 2 * (dirtyCount - best - 2));
dirtyCount--;
}
void clearDirty() {
dirtyCount = 0;
resized = false;
queued = false;
}
}
@@ -0,0 +1,65 @@
package incari.platform.web.storage;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Map;
import org.jspecify.annotations.Nullable;
/** A folder in the page's file system. */
@SuppressWarnings("ReferenceEquality") // Nodes are identities: the same file is the same object.
final class Directory extends Node {
private final boolean root;
private final Map<String, Node> children = new HashMap<>();
Directory(String name, long lastModified, boolean root) {
super(name, lastModified);
this.root = root;
}
boolean isRoot() {
return root;
}
@Override
boolean isDirectory() {
return true;
}
@Nullable
Node child(String childName) {
return children.get(childName);
}
boolean isEmpty() {
return children.isEmpty();
}
/** The children's names, sorted: listings come out the same after a reload as before it. */
String[] names() {
String[] names = children.keySet().toArray(new String[0]);
Arrays.sort(names);
return names;
}
Iterable<Node> children() {
return children.values();
}
/** Puts {@code node} here as {@code childName}, replacing whatever had that name. */
void attach(String childName, Node node) {
Node replaced = children.put(childName, node);
if (replaced != null && replaced != node) {
replaced.parent = null;
}
node.name = childName;
node.parent = this;
}
void detach(Node node) {
if (children.get(node.name) == node) {
children.remove(node.name);
}
node.parent = null;
}
}
@@ -0,0 +1,154 @@
package incari.platform.web.storage;
import java.io.IOException;
import java.util.function.LongSupplier;
import org.jspecify.annotations.Nullable;
import org.teavm.runtime.fs.VirtualFileAccessor;
/**
* An open file, as TeaVM's streams and {@code RandomAccessFile} use it: a position in the file's
* bytes. Writes go straight into the tree and are noted in the {@link Journal}; the store hears of
* them at the next flush, so {@link #flush} and {@link #close} have nothing to do.
*
* <p>Hot path for the game's file writes (region files): no allocation per call.
*/
final class FileAccessor implements VirtualFileAccessor {
private static final byte[] NONE = new byte[0];
private final @Nullable DataFile file;
private final byte[] readOnlyBytes;
private final int readOnlySize;
private final @Nullable Journal journal;
private final LongSupplier clock;
private int position;
private boolean closed;
/** An accessor over a file of the tree; {@code journal} is null when it's opened for reading only. */
FileAccessor(DataFile file, @Nullable Journal journal, LongSupplier clock, int position) {
this.file = file;
this.readOnlyBytes = NONE;
this.readOnlySize = 0;
this.journal = journal;
this.clock = clock;
this.position = position;
}
/** A read-only accessor over bytes that aren't in the tree (a mounted zip entry). */
FileAccessor(FileNode.Bytes bytes, LongSupplier clock) {
this.file = null;
this.readOnlyBytes = bytes.data();
this.readOnlySize = bytes.size();
this.journal = null;
this.clock = clock;
}
@Override
public int read(byte[] buffer, int offset, int limit) throws IOException {
ensureOpen();
DataFile open = file;
byte[] data = open != null ? open.data : readOnlyBytes;
int size = open != null ? open.size : readOnlySize;
int count = Math.max(0, Math.min(size - position, limit));
if (count > 0) {
System.arraycopy(data, position, buffer, offset, count);
position += count;
}
return count;
}
@Override
public void write(byte[] buffer, int offset, int limit) throws IOException {
DataFile target = writable();
if (limit <= 0) {
return;
}
long end = (long) position + limit;
if (end > Integer.MAX_VALUE - 8) {
throw new IOException("File too large for the page's file system: " + end + " bytes");
}
target.ensureCapacity((int) end);
System.arraycopy(buffer, offset, target.data, position, limit);
// Bytes between the old end and position are zero already (DataFile keeps them so).
if (end > target.size) {
target.size = (int) end;
}
target.markWritten(position, (int) end);
position = (int) end;
touch(target);
}
@Override
public int tell() throws IOException {
ensureOpen();
return position;
}
@Override
public void seek(int target) throws IOException {
ensureOpen();
if (target < 0) {
throw new IOException("Negative seek offset");
}
position = target;
}
@Override
public void skip(int amount) throws IOException {
ensureOpen();
position = Math.max(0, position + amount);
}
@Override
public int size() throws IOException {
ensureOpen();
DataFile open = file;
return open != null ? open.size : readOnlySize;
}
@Override
public void resize(int size) throws IOException {
DataFile target = writable();
if (size < 0) {
throw new IOException("Negative file size");
}
if (size != target.size) {
target.setSize(size);
target.resized = true;
touch(target);
}
}
@Override
public void close() {
closed = true;
}
@Override
public void flush() throws IOException {
ensureOpen();
}
private DataFile writable() throws IOException {
ensureOpen();
DataFile target = file;
if (target == null || journal == null) {
throw new IOException("File not open for writing");
}
return target;
}
private void touch(DataFile target) {
target.lastModified = clock.getAsLong();
Journal changes = journal;
if (changes != null) {
changes.written(target);
}
}
private void ensureOpen() throws IOException {
if (closed) {
throw new IOException("File closed");
}
}
}
@@ -0,0 +1,168 @@
package incari.platform.web.storage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.io.UncheckedIOException;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
/**
* Files and store changes as bytes, for the page and a copy of the game in a worker (ADR 0039):
* a world's files go to the worker when its server starts and come back when it stops, and the
* worker's changes to them reach the page's store this way.
*/
final class FileBundle {
private FileBundle() {}
/**
* A file or folder as the store would load it. A stored entry is an in-place file (ADR 0041):
* its size, its bytes left in the store.
*/
@SuppressWarnings("ArrayRecordComponent") // Carries bytes; never compared or hashed.
record Entry(
String path, boolean directory, long lastModified, byte @Nullable [] contents, boolean stored, int size) {
static Entry folder(String path, long lastModified) {
return new Entry(path, true, lastModified, null, false, 0);
}
static Entry file(String path, long lastModified, byte[] contents) {
return new Entry(path, false, lastModified, contents, false, contents.length);
}
static Entry stored(String path, long lastModified, int size) {
return new Entry(path, false, lastModified, null, true, size);
}
}
/**
* A folder handed to another copy of the program, or back: its entries, and whether its
* in-place files are left in the store for the other copy to open where they are (ADR 0041).
*/
record Bundle(boolean inPlace, List<Entry> entries) {}
/** How a stored entry's contents length is written: it has none, and a size. */
private static final int STORED = -2;
static byte[] encodeEntries(List<Entry> entries) {
return encode(new Bundle(false, entries));
}
static List<Entry> decodeEntries(byte[] bundle) {
return decode(bundle).entries();
}
static byte[] encode(Bundle bundle) {
List<Entry> entries = bundle.entries();
int size = 4;
for (Entry entry : entries) {
byte[] contents = entry.contents();
size += entry.path().length() * 3 + 2 + 1 + 8 + 4 + 4 + (contents == null ? 0 : contents.length);
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream(size + 1);
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeBoolean(bundle.inPlace());
out.writeInt(entries.size());
for (Entry entry : entries) {
out.writeUTF(entry.path());
out.writeBoolean(entry.directory());
out.writeLong(entry.lastModified());
byte[] contents = entry.contents();
if (entry.stored()) {
out.writeInt(STORED);
out.writeInt(entry.size());
} else {
out.writeInt(contents == null ? -1 : contents.length);
if (contents != null) {
out.write(contents);
}
}
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
static Bundle decode(byte[] bundle) {
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(bundle))) {
boolean inPlace = in.readBoolean();
int count = in.readInt();
List<Entry> entries = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
String path = in.readUTF();
boolean directory = in.readBoolean();
long lastModified = in.readLong();
int length = in.readInt();
if (length == STORED) {
entries.add(Entry.stored(path, lastModified, in.readInt()));
} else if (length < 0) {
entries.add(new Entry(path, directory, lastModified, null, false, 0));
} else {
byte[] contents = new byte[length];
in.readFully(contents);
entries.add(new Entry(path, directory, lastModified, contents, false, length));
}
}
return new Bundle(inPlace, entries);
} catch (IOException e) {
throw new UncheckedIOException("A damaged bundle of files", e);
}
}
static byte[] encodeOps(List<StoreOp> ops) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
try (DataOutputStream out = new DataOutputStream(bytes)) {
out.writeInt(ops.size());
for (StoreOp op : ops) {
out.writeUTF(op.kind().name());
out.writeUTF(op.path());
out.writeInt(op.size());
out.writeInt(op.at());
byte[] data = op.data();
out.writeInt(data == null ? -1 : data.length);
if (data != null) {
out.write(data);
}
out.writeLong(op.lastModified());
}
} catch (IOException e) {
throw new UncheckedIOException(e);
}
return bytes.toByteArray();
}
static List<StoreOp> decodeOps(byte[] encoded) {
try (DataInputStream in = new DataInputStream(new ByteArrayInputStream(encoded))) {
int count = in.readInt();
List<StoreOp> ops = new ArrayList<>(count);
for (int i = 0; i < count; i++) {
StoreOp.Kind kind = StoreOp.Kind.valueOf(in.readUTF());
String path = in.readUTF();
int size = in.readInt();
int at = in.readInt();
byte[] data = readBytes(in);
long lastModified = in.readLong();
ops.add(new StoreOp(kind, path, size, at, data, lastModified));
}
return ops;
} catch (IOException e) {
throw new UncheckedIOException("Damaged store changes", e);
}
}
private static byte @Nullable [] readBytes(DataInputStream in) throws IOException {
int length = in.readInt();
if (length < 0) {
return null;
}
byte[] contents = new byte[length];
in.readFully(contents);
return contents;
}
}
@@ -0,0 +1,25 @@
package incari.platform.web.storage;
import java.io.IOException;
/** A file in the page's file system: its bytes in memory, or an entry of a mounted zip. */
abstract class FileNode extends Node {
FileNode(String name, long lastModified) {
super(name, lastModified);
}
@Override
final boolean isDirectory() {
return false;
}
abstract int length();
/** The file's bytes for reading; mounted entries are inflated here. */
abstract Bytes contents() throws IOException;
/** A file's bytes: the first {@code size} of {@code data}. */
@SuppressWarnings("ArrayRecordComponent") // Carries bytes; never compared or hashed.
record Bytes(byte[] data, int size) {}
}
@@ -0,0 +1,22 @@
package incari.platform.web.storage;
/**
* Which stored files stay where they are instead of being loaded into memory (ADR 0041): a world's
* region files ({@code .mca}, and {@code .mcc} for a chunk too large for its region), the files
* that grow with how much of a world has been explored. The page knows them by their size alone
* and reads one only when something opens it; singleplayer's server in a worker reads and writes
* them in the origin private file system with synchronous access handles. The storage worker
* applies the same rule ({@code storage-worker.js}, told it at {@code open}).
*/
final class InPlaceFiles {
/** A world's files are inside a folder of this name. */
static final String WITHIN = "/saves/";
private InPlaceFiles() {}
/** Whether the file at {@code path} is kept in place. */
static boolean matches(String path) {
return path.contains(WITHIN) && (path.endsWith(".mca") || path.endsWith(".mcc"));
}
}
@@ -0,0 +1,41 @@
package incari.platform.web.storage;
import java.io.IOException;
/**
* Where the tree's in-place files ({@link StoredFile}) keep their bytes (ADR 0041). The page reads
* one whole when something opens it ({@link #opensInPlace} false); singleplayer's server in a
* worker opens it where it is and reads and writes through the handle. Either may suspend (must
* not be called from a JavaScript callback).
*/
interface InPlaceStore {
/** Whether files are opened where they are ({@link #open}) rather than read whole ({@link #read}). */
boolean opensInPlace();
/** The stored file's bytes, all of them; empty if it isn't there. Suspends until read. */
byte[] read(String path) throws IOException;
/** Opens the stored file at {@code path} where it is, creating it (and its folders) if it isn't there. */
Handle open(String path) throws IOException;
/** An open in-place file: reads and writes go straight to where it's kept. One thread. */
interface Handle {
/** Reads up to {@code length} bytes from {@code at} into {@code buffer}; how many it read. */
int read(byte[] buffer, int offset, int length, int at) throws IOException;
/** Writes {@code length} bytes of {@code buffer} at {@code at}, growing the file if need be. */
void write(byte[] buffer, int offset, int length, int at) throws IOException;
int size() throws IOException;
void truncate(int size) throws IOException;
/** Makes what was written durable. */
void flush() throws IOException;
/** Flushes and lets the file go: another program may open it once this returns. */
void close();
}
}
@@ -0,0 +1,171 @@
package incari.platform.web.storage;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.jspecify.annotations.Nullable;
/**
* What changed in the file tree since the last flush, and so what the persistent store must be
* told. It keeps no log of operations, only which paths changed shape (created, deleted, moved)
* and which files had bytes written: a flush reads the tree as it is then, so a file rewritten
* a hundred times in a frame is sent once, and a temporary file created and renamed within one
* is never sent under its temporary name.
*
* <p>Only paths under the persistent root, and outside its transient folders, are recorded.
*/
final class Journal {
private final String persistentRoot;
private final List<String> transientRoots;
private final Set<String> reshaped = new HashSet<>();
private final List<DataFile> written = new ArrayList<>();
/**
* @param persistentRoot the folder whose contents survive a reload
* @param transientRoots folders inside it that don't (scratch space, mounts)
*/
Journal(String persistentRoot, List<String> transientRoots) {
this.persistentRoot = persistentRoot;
this.transientRoots = List.copyOf(transientRoots);
}
String persistentRoot() {
return persistentRoot;
}
boolean persists(String path) {
if (!within(path, persistentRoot)) {
return false;
}
for (String transientRoot : transientRoots) {
if (within(path, transientRoot)) {
return false;
}
}
return true;
}
boolean isEmpty() {
return reshaped.isEmpty() && written.isEmpty();
}
/** Something was created, deleted or moved at {@code path}. */
void reshaped(@Nullable String path) {
if (path != null && persists(path)) {
reshaped.add(path);
}
}
/** {@code file} had bytes written, its size changed or its time set. Hot path: no allocation. */
void written(DataFile file) {
if (!file.queued) {
file.queued = true;
written.add(file);
}
}
/**
* The changes since the last call, in the order the store should apply them: folders before
* what's in them, writes before deletes (so a file replaced by a rename is never missing in
* between), and nothing twice.
*/
List<StoreOp> collect(TreeFileSystem tree) {
List<StoreOp> ops = new ArrayList<>();
List<String> deleted = new ArrayList<>();
Set<String> sent = new HashSet<>();
String[] paths = reshaped.toArray(new String[0]);
// Shallow paths first: a folder's whole contents are sent with it.
Arrays.sort(paths, Comparator.comparingInt(Journal::depth).thenComparing(Comparator.naturalOrder()));
for (String path : paths) {
if (sent.contains(path)) {
continue;
}
Node node = tree.find(path);
if (node == null) {
deleted.add(path);
} else {
sendWhole(node, path, ops, sent);
}
}
for (DataFile file : written) {
String path = file.path();
if (path != null && !sent.contains(path) && persists(path)) {
// A write op for each range still inside the file; one without bytes if none is
// (the size or the time changed).
boolean wrote = false;
for (int i = 0; i < file.dirtyCount; i++) {
int from = file.dirty[2 * i];
int end = Math.min(file.dirty[2 * i + 1], file.size);
if (from < end) {
ops.add(StoreOp.write(
path, file.size, from, Arrays.copyOfRange(file.data, from, end), file.lastModified));
wrote = true;
}
}
if (!wrote) {
ops.add(StoreOp.write(path, file.size, 0, null, file.lastModified));
}
}
file.clearDirty();
}
// A deleted folder takes what was in it; don't delete its contents one by one as well.
Set<String> deletedSet = new HashSet<>(deleted);
for (String path : deleted) {
if (!hasDeletedAncestor(path, deletedSet)) {
ops.add(StoreOp.delete(path));
}
}
reshaped.clear();
written.clear();
return ops;
}
private void sendWhole(Node node, String path, List<StoreOp> ops, Set<String> sent) {
if (!persists(path) || !sent.add(path)) {
return;
}
if (node instanceof Directory directory) {
ops.add(StoreOp.mkdir(path, directory.lastModified));
for (String name : directory.names()) {
Node child = directory.child(name);
if (child != null) {
sendWhole(child, path + "/" + name, ops, sent);
}
}
} else if (node instanceof DataFile file) {
// All its bytes; if it was also written to, the loop over written files skips it.
ops.add(StoreOp.write(path, file.size, 0, Arrays.copyOf(file.data, file.size), file.lastModified));
}
// A mounted file can't be moved or copied into place by the tree, so none is here. An
// in-place file (ADR 0041) is in the store already: its writes went there, and the tree
// moves none (it reads them into memory first).
}
private static boolean hasDeletedAncestor(String path, Set<String> deleted) {
for (int slash = path.lastIndexOf('/'); slash > 0; slash = path.lastIndexOf('/', slash - 1)) {
if (deleted.contains(path.substring(0, slash))) {
return true;
}
}
return false;
}
private static int depth(String path) {
int depth = 0;
for (int i = 0; i < path.length(); i++) {
if (path.charAt(i) == '/') {
depth++;
}
}
return depth;
}
static boolean within(String path, String folder) {
return path.equals(folder)
|| (path.startsWith(folder) && (folder.endsWith("/") || path.charAt(folder.length()) == '/'));
}
}
@@ -0,0 +1,28 @@
package incari.platform.web.storage;
import java.io.IOException;
/** A read-only file whose bytes are an entry of a mounted zip, inflated each time it's opened. */
final class MountedFile extends FileNode {
private final ZipArchive archive;
private final ZipArchive.Entry entry;
MountedFile(String name, long lastModified, ZipArchive archive, ZipArchive.Entry entry) {
super(name, lastModified);
this.archive = archive;
this.entry = entry;
this.readOnly = true;
}
@Override
int length() {
return entry.size();
}
@Override
Bytes contents() throws IOException {
byte[] bytes = archive.read(entry);
return new Bytes(bytes, bytes.length);
}
}
@@ -0,0 +1,61 @@
package incari.platform.web.storage;
import org.jspecify.annotations.Nullable;
/**
* A file or folder in the page's file system ({@link TreeFileSystem}). Game thread only: the page has
* one thread, and nothing here suspends (must not block: coroutines).
*/
@SuppressWarnings("ReferenceEquality") // Nodes are identities: the same file is the same object.
abstract class Node {
String name;
@Nullable
Directory parent;
long lastModified;
/** Read-only nodes refuse writes: the mounted client jar, and whatever the game marks so. */
boolean readOnly;
Node(String name, long lastModified) {
this.name = name;
this.lastModified = lastModified;
}
abstract boolean isDirectory();
/** The node's absolute path ("/" for the root), or null once it's been deleted. */
final @Nullable String path() {
if (this instanceof Directory directory && directory.isRoot()) {
return "/";
}
StringBuilder path = new StringBuilder();
return appendPath(path) ? path.toString() : null;
}
/** Appends "/name" for each folder down to this node; false if it isn't in the tree. */
final boolean appendPath(StringBuilder path) {
Directory up = parent;
if (up == null) {
// Only the root has no parent and is still in the tree; it adds nothing.
return this instanceof Directory directory && directory.isRoot();
}
if (!up.appendPath(path)) {
return false;
}
path.append('/').append(name);
return true;
}
/** Whether {@code ancestor} is this node or contains it. */
final boolean isWithin(Node ancestor) {
for (Node node = this; node != null; node = node.parent) {
if (node == ancestor) {
return true;
}
}
return false;
}
}
@@ -0,0 +1,219 @@
package incari.platform.web.storage;
import java.io.IOException;
import java.util.Arrays;
import org.jspecify.annotations.Nullable;
import org.teavm.interop.Async;
import org.teavm.interop.AsyncCallback;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSFunctor;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
/**
* In-place files in singleplayer's server worker (ADR 0041): the world's region files opened
* straight from the origin private file system, under the same paths the storage worker keeps
* them at, with synchronous access handles (which only workers get). Reads and writes are calls
* on the handle; only opening suspends.
*
* <p>Worker-side: the page has no synchronous handles, and must not touch these files while the
* worker has the world (the storage worker's own writes open handles of their own, which a
* held handle would refuse).
*/
final class OpfsFiles implements InPlaceStore {
private final boolean inPlace;
/**
* @param inPlace whether files are opened where they are; else (no synchronous handles here,
* or the page kept the world in memory) they're read whole
*/
OpfsFiles(boolean inPlace) {
this.inPlace = inPlace;
}
/** Whether this worker can open files where they are. */
@JSBody(
script = "return typeof FileSystemFileHandle !== 'undefined'"
+ " && typeof FileSystemFileHandle.prototype.createSyncAccessHandle === 'function'"
+ " && !!(navigator.storage && navigator.storage.getDirectory);")
static native boolean available();
@Override
public boolean opensInPlace() {
return inPlace;
}
@Override
public byte[] read(String path) throws IOException {
JSObject result = readWhole(path);
String error = errorOf(result);
if (error != null) {
throw new IOException("Couldn't read " + path + ": " + error);
}
ArrayBuffer data = dataOf(result);
return data == null ? new byte[0] : new Int8Array(data).copyToJavaArray();
}
@Override
public Handle open(String path) throws IOException {
JSObject result = openHandle(path);
String error = errorOf(result);
if (error != null) {
throw new IOException("Couldn't open " + path + " in place: " + error);
}
return new OpenFile(handleOf(result));
}
/** A synchronous access handle on one file. */
private static final class OpenFile implements Handle {
private @Nullable JSObject handle;
OpenFile(JSObject handle) {
this.handle = handle;
}
private JSObject handle() throws IOException {
JSObject open = handle;
if (open == null) {
throw new IOException("File closed");
}
return open;
}
@Override
public int read(byte[] buffer, int offset, int length, int at) throws IOException {
Int8Array read = readAt(handle(), length, at);
int count = read.getLength();
if (count > 0) {
System.arraycopy(read.copyToJavaArray(), 0, buffer, offset, count);
}
return count;
}
@Override
public void write(byte[] buffer, int offset, int length, int at) throws IOException {
byte[] part = offset == 0 && length == buffer.length
? buffer
: Arrays.copyOfRange(buffer, offset, offset + length);
int written = writeAt(handle(), Int8Array.copyFromJavaArray(part), at);
if (written != length) {
throw new IOException("Wrote " + written + " of " + length + " bytes");
}
}
@Override
public int size() throws IOException {
return sizeOf(handle());
}
@Override
public void truncate(int size) throws IOException {
truncateTo(handle(), size);
}
@Override
public void flush() throws IOException {
flushHandle(handle());
}
@Override
public void close() {
JSObject open = handle;
handle = null;
if (open != null) {
closeHandle(open);
}
}
}
// --- JavaScript -------------------------------------------------------------------------
@JSFunctor
interface Done extends JSObject {
void done(JSObject result);
}
/** The folder of {@code path}'s file, made if missing, then {@code then(folder, name)}. */
private static final String FOLDER = "function folderOf(path, create) {"
+ " var names = path.split('/').filter(function(p) { return p.length > 0; });"
+ " var name = names.pop();"
+ " var step = navigator.storage.getDirectory();"
+ " names.forEach(function(n) { step = step.then(function(d) { return d.getDirectoryHandle(n, {create: create}); }); });"
+ " return step.then(function(d) { return {folder: d, name: name}; }); }";
/** Opens the file at {@code path} (made if missing) with a synchronous access handle; suspends. */
@Async
private static native JSObject openHandle(String path);
private static void openHandle(String path, AsyncCallback<JSObject> callback) {
startOpen(path, callback::complete);
}
@JSBody(
params = {"path", "done"},
script =
FOLDER
+ "folderOf(path, true)"
+ ".then(function(at) { return at.folder.getFileHandle(at.name, {create: true}); })"
+ ".then(function(file) { return file.createSyncAccessHandle(); })"
+ ".then(function(handle) { done({handle: handle}); },"
+ " function(error) { done({error: String(error && error.name ? error.name + ': ' + error.message : error)}); });")
private static native void startOpen(String path, Done done);
/** The file at {@code path}, read whole ({@code data}, null if it isn't there); suspends. */
@Async
private static native JSObject readWhole(String path);
private static void readWhole(String path, AsyncCallback<JSObject> callback) {
startRead(path, callback::complete);
}
@JSBody(
params = {"path", "done"},
script =
FOLDER
+ "folderOf(path, false)"
+ ".then(function(at) { return at.folder.getFileHandle(at.name); })"
+ ".then(function(file) { return file.getFile(); })"
+ ".then(function(file) { return file.arrayBuffer(); })"
+ ".then(function(data) { done({data: data}); },"
+ " function(error) { if (error && error.name === 'NotFoundError') done({data: null});"
+ " else done({error: String(error && error.name ? error.name + ': ' + error.message : error)}); });")
private static native void startRead(String path, Done done);
@JSBody(params = "result", script = "return result.error === undefined ? null : String(result.error);")
private static native @Nullable String errorOf(JSObject result);
@JSBody(params = "result", script = "return result.handle;")
private static native JSObject handleOf(JSObject result);
@JSBody(params = "result", script = "return result.data || null;")
private static native @Nullable ArrayBuffer dataOf(JSObject result);
@JSBody(
params = {"handle", "length", "at"},
script = "var view = new Int8Array(length); var read = handle.read(view, {at: at});"
+ "return read === length ? view : view.subarray(0, read);")
private static native Int8Array readAt(JSObject handle, int length, int at);
@JSBody(
params = {"handle", "data", "at"},
script = "return handle.write(data, {at: at});")
private static native int writeAt(JSObject handle, Int8Array data, int at);
@JSBody(params = "handle", script = "return handle.getSize();")
private static native int sizeOf(JSObject handle);
@JSBody(
params = {"handle", "size"},
script = "handle.truncate(size);")
private static native void truncateTo(JSObject handle, int size);
@JSBody(params = "handle", script = "handle.flush();")
private static native void flushHandle(JSObject handle);
@JSBody(params = "handle", script = "handle.flush(); handle.close();")
private static native void closeHandle(JSObject handle);
}
@@ -0,0 +1,38 @@
package incari.platform.web.storage;
import org.jspecify.annotations.Nullable;
/**
* One change for the persistent store, as the {@link Journal} collects them at a flush.
*
* @param path the path in the page's file system ("/incari/game/options.txt")
* @param size for a write, the file's size afterwards
* @param at for a write, where {@code data} goes in the file
* @param data for a write, the bytes written since the last flush (all of them for a new file);
* null when only the size or time changed
* @param lastModified the file's or folder's time, milliseconds since the epoch
*/
@SuppressWarnings("ArrayRecordComponent") // Carries bytes; never compared or hashed.
record StoreOp(Kind kind, String path, int size, int at, byte @Nullable [] data, long lastModified) {
enum Kind {
/** A folder exists at the path (replacing a file there). */
MKDIR,
/** A file exists at the path, with this size and these bytes at {@code at}. */
WRITE,
/** Nothing exists at the path any more, folders with everything in them. */
DELETE
}
static StoreOp mkdir(String path, long lastModified) {
return new StoreOp(Kind.MKDIR, path, 0, 0, null, lastModified);
}
static StoreOp write(String path, int size, int at, byte @Nullable [] data, long lastModified) {
return new StoreOp(Kind.WRITE, path, size, at, data, lastModified);
}
static StoreOp delete(String path) {
return new StoreOp(Kind.DELETE, path, 0, 0, null, 0);
}
}
@@ -0,0 +1,43 @@
package incari.platform.web.storage;
import org.jspecify.annotations.Nullable;
/**
* An in-place file ({@link InPlaceFiles}): its bytes stay in the store, and the tree knows its size
* and time (ADR 0041). On the page, opening one reads it whole and puts a {@link DataFile} in its
* place; in singleplayer's server worker, it's opened where it is ({@link #handle}) and stays
* that way until the world is handed back.
*/
final class StoredFile extends FileNode {
/** The file's size, as the store last said or as this program's writes left it. */
int size;
/** Where it's open, in a worker that opens files in place; null until first opened, and once closed. */
InPlaceStore.@Nullable Handle handle;
StoredFile(String name, long lastModified, int size) {
super(name, lastModified);
this.size = size;
}
@Override
int length() {
return size;
}
@Override
Bytes contents() {
// The tree reads a stored file through its store, never through here.
throw new UnsupportedOperationException("An in-place file's bytes are in the store");
}
/** Lets its handle go, if it has one open. */
void close() {
InPlaceStore.Handle open = handle;
handle = null;
if (open != null) {
open.close();
}
}
}
@@ -0,0 +1,123 @@
package incari.platform.web.storage;
import java.io.IOException;
import java.util.function.LongSupplier;
/**
* An open in-place file in a worker that opens them where they are (ADR 0041): every read and write
* goes straight to its handle, none to the tree's memory or its journal (the store is the handle's
* file itself). Closing it leaves the handle open for the next: the server opens a region file's
* channel and closes it as its cache of open regions turns over.
*/
final class StoredFileAccessor implements org.teavm.runtime.fs.VirtualFileAccessor {
private final StoredFile file;
private final InPlaceStore.Handle handle;
private final boolean writable;
private final LongSupplier clock;
private int position;
private boolean closed;
StoredFileAccessor(
StoredFile file, InPlaceStore.Handle handle, boolean writable, LongSupplier clock, int position) {
this.file = file;
this.handle = handle;
this.writable = writable;
this.clock = clock;
this.position = position;
}
@Override
public int read(byte[] buffer, int offset, int limit) throws IOException {
ensureOpen();
int count = Math.max(0, Math.min(file.size - position, limit));
if (count == 0) {
return 0;
}
int read = handle.read(buffer, offset, count, position);
position += read;
return read;
}
@Override
public void write(byte[] buffer, int offset, int limit) throws IOException {
ensureWritable();
if (limit <= 0) {
return;
}
long end = (long) position + limit;
if (end > Integer.MAX_VALUE - 8) {
throw new IOException("File too large for the page's file system: " + end + " bytes");
}
handle.write(buffer, offset, limit, position);
position = (int) end;
file.size = Math.max(file.size, position);
file.lastModified = clock.getAsLong();
}
@Override
public int tell() throws IOException {
ensureOpen();
return position;
}
@Override
public void seek(int target) throws IOException {
ensureOpen();
if (target < 0) {
throw new IOException("Negative seek offset");
}
position = target;
}
@Override
public void skip(int amount) throws IOException {
ensureOpen();
position = Math.max(0, position + amount);
}
@Override
public int size() throws IOException {
ensureOpen();
return file.size;
}
@Override
public void resize(int size) throws IOException {
ensureWritable();
if (size < 0) {
throw new IOException("Negative file size");
}
if (size != file.size) {
handle.truncate(size);
file.size = size;
file.lastModified = clock.getAsLong();
}
}
@Override
public void close() {
closed = true;
}
@Override
public void flush() throws IOException {
ensureOpen();
if (writable) {
handle.flush();
}
}
private void ensureWritable() throws IOException {
ensureOpen();
if (!writable) {
throw new IOException("File not open for writing");
}
}
private void ensureOpen() throws IOException {
if (closed) {
throw new IOException("File closed");
}
}
}
@@ -0,0 +1,692 @@
package incari.platform.web.storage;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.LongSupplier;
import java.util.function.Predicate;
import org.jspecify.annotations.Nullable;
import org.teavm.runtime.fs.VirtualFile;
import org.teavm.runtime.fs.VirtualFileAccessor;
import org.teavm.runtime.fs.VirtualFileSystem;
/**
* The page's file system: a tree in memory, which TeaVM's {@code java.io} and {@code java.nio.file}
* classes read and write through its {@link VirtualFileSystem} interface, and whose changes a
* {@link Journal} collects for the persistent store (ADR 0011).
*
* <p>Everything is synchronous: the game reads and writes files as on the desktop. One kind of
* file call suspends (must not block: coroutines): opening a world's region file that's kept in
* place ({@link StoredFile}, ADR 0041), which the page reads from the store then and the server's
* worker opens where it is; and moving one, on the page. No JavaScript callback opens one. Game
* thread only.
*
* <p>Where TeaVM's own in-memory file system differs from the JDK, this one follows the JDK:
* opening a file for reading and writing ({@code RandomAccessFile(file, "rw")}) keeps its bytes,
* relative paths resolve against the working directory ("/" unless set), a file grown by a seek
* past its end reads zeros in the gap, and a rename may replace a file.
*/
@SuppressWarnings("ReferenceEquality") // Nodes are identities: the same file is the same object.
public final class TreeFileSystem implements VirtualFileSystem {
private final Directory root;
private final Journal journal;
private final LongSupplier clock;
private String workingDirectory = "/";
/** Where in-place files keep their bytes (ADR 0041); null where there are none. */
private @Nullable InPlaceStore inPlace;
/**
* @param journal where changes under its persistent root are recorded
* @param clock milliseconds since the epoch, for file times
*/
TreeFileSystem(Journal journal, LongSupplier clock) {
this.journal = journal;
this.clock = clock;
this.root = new Directory("", clock.getAsLong(), true);
}
Journal journal() {
return journal;
}
/** Where the tree's in-place files ({@link StoredFile}) are read from or opened (ADR 0041). */
void setInPlaceStore(@Nullable InPlaceStore store) {
this.inPlace = store;
}
/** Relative paths resolve against this folder, which must exist. */
void setWorkingDirectory(String path) throws IOException {
String absolute = normalize(path);
mkdirs(absolute, clock.getAsLong(), false);
workingDirectory = absolute;
}
// --- VirtualFileSystem -------------------------------------------------------------------
@Override
public String getUserDir() {
return workingDirectory;
}
@Override
public VirtualFile getFile(String path) {
return new TreeFile(normalize(path));
}
@Override
public boolean isWindows() {
return false;
}
@Override
public String canonicalize(String path) {
return normalize(path);
}
@Override
public String[] getRoots() {
return new String[] {"/"};
}
// --- The tree ----------------------------------------------------------------------------
/** An absolute path with no empty, "." or ".." parts; relative paths start at the working directory. */
String normalize(String path) {
String full = path.startsWith("/") ? path : workingDirectory + "/" + path;
List<String> parts = new ArrayList<>();
int start = 0;
while (start <= full.length()) {
int end = full.indexOf('/', start);
if (end < 0) {
end = full.length();
}
String part = full.substring(start, end);
if (part.equals("..")) {
if (!parts.isEmpty()) {
parts.removeLast();
}
} else if (!part.isEmpty() && !part.equals(".")) {
parts.add(part);
}
start = end + 1;
}
return parts.isEmpty() ? "/" : "/" + String.join("/", parts);
}
/** The node at a normalized absolute path, or null. */
@Nullable
Node find(String path) {
Node node = root;
int start = 1;
while (start < path.length()) {
int end = path.indexOf('/', start);
if (end < 0) {
end = path.length();
}
if (!(node instanceof Directory directory)) {
return null;
}
node = directory.child(path.substring(start, end));
if (node == null) {
return null;
}
start = end + 1;
}
return node;
}
/**
* Makes the folder at a normalized path and any missing parents.
*
* @param record whether to note new folders in the journal (not when loading from the store)
*/
Directory mkdirs(String path, long lastModified, boolean record) throws IOException {
Directory directory = root;
int start = 1;
while (start < path.length()) {
int end = path.indexOf('/', start);
if (end < 0) {
end = path.length();
}
String name = path.substring(start, end);
Node child = directory.child(name);
if (child == null) {
Directory created = new Directory(name, lastModified, false);
directory.attach(name, created);
if (record) {
journal.reshaped(path.substring(0, end));
}
child = created;
} else if (!(child instanceof Directory)) {
throw new IOException("Not a folder: " + path.substring(0, end));
}
directory = (Directory) child;
start = end + 1;
}
return directory;
}
/** Puts a file or folder the store had into the tree, without noting it as a change. */
void load(String path, boolean isDirectory, long lastModified, byte @Nullable [] contents) throws IOException {
String absolute = normalize(path);
if (isDirectory) {
mkdirs(absolute, lastModified, false).lastModified = lastModified;
return;
}
int slash = absolute.lastIndexOf('/');
Directory parent = mkdirs(slash == 0 ? "/" : absolute.substring(0, slash), lastModified, false);
parent.attach(
absolute.substring(slash + 1),
new DataFile("", lastModified, contents == null ? new byte[0] : contents));
}
/**
* Puts an in-place file the store has into the tree (ADR 0041): its size and time, its bytes left
* in the store.
*/
void loadStored(String path, long lastModified, int size) throws IOException {
String absolute = normalize(path);
int slash = absolute.lastIndexOf('/');
Directory parent = mkdirs(slash == 0 ? "/" : absolute.substring(0, slash), lastModified, false);
String name = absolute.substring(slash + 1);
if (parent.child(name) instanceof StoredFile known) {
known.size = size;
known.lastModified = lastModified;
} else if (!(parent.child(name) instanceof DataFile)) {
parent.attach(name, new StoredFile("", lastModified, size));
}
}
/**
* The folder at {@code path} and everything in it that the tree keeps itself (not mounted
* files), as the store would load them, with every file's bytes: for another copy of the
* program (ADR 0039). In-place files are read from the store to go with it.
*/
List<FileBundle.Entry> export(String path) throws IOException {
return export(path, false);
}
/**
* As {@link #export(String)}; with {@code inPlace}, in-place files go as stored entries without
* their bytes (the other copy opens them where they are, ADR 0041), those still in memory too:
* the caller has made sure the store has every write to them.
*/
List<FileBundle.Entry> export(String path, boolean inPlace) throws IOException {
List<FileBundle.Entry> entries = new ArrayList<>();
String absolute = normalize(path);
Node node = find(absolute);
if (node != null) {
export(node, absolute, entries, inPlace);
}
return entries;
}
private void export(Node node, String path, List<FileBundle.Entry> entries, boolean inPlace) throws IOException {
if (node instanceof Directory directory) {
entries.add(FileBundle.Entry.folder(path, directory.lastModified));
for (String name : directory.names()) {
Node child = directory.child(name);
if (child != null) {
export(child, path.equals("/") ? "/" + name : path + "/" + name, entries, inPlace);
}
}
} else if (node instanceof StoredFile stored) {
if (inPlace) {
entries.add(FileBundle.Entry.stored(path, stored.lastModified, stored.size));
} else {
entries.add(FileBundle.Entry.file(path, stored.lastModified, readStored(path)));
}
} else if (node instanceof DataFile file) {
if (inPlace && InPlaceFiles.matches(path)) {
entries.add(FileBundle.Entry.stored(path, file.lastModified, file.size));
} else {
entries.add(FileBundle.Entry.file(path, file.lastModified, Arrays.copyOf(file.data, file.size)));
}
}
}
/** Lets go of every in-place file open under {@code path}, so another program may open them. */
void closeStored(String path) {
Node node = find(normalize(path));
if (node != null) {
closeStored(node);
}
}
private static void closeStored(Node node) {
if (node instanceof Directory directory) {
for (Node child : directory.children()) {
closeStored(child);
}
} else if (node instanceof StoredFile stored) {
stored.close();
}
}
/** Whether {@code node} is an in-place file or a folder with one in it. */
private static boolean holdsStored(Node node) {
if (node instanceof StoredFile) {
return true;
}
if (node instanceof Directory directory) {
for (Node child : directory.children()) {
if (holdsStored(child)) {
return true;
}
}
}
return false;
}
private byte[] readStored(String path) throws IOException {
InPlaceStore store = inPlace;
if (store == null) {
throw new IOException("No store to read " + path + " from");
}
return store.read(path);
}
/**
* Reads an in-place file whole and puts it in the tree as a {@link DataFile}, unchanged as far as
* the store is concerned (the page's way to open one, ADR 0041). Suspends while it's read.
*/
private DataFile materialize(StoredFile stored, String path) throws IOException {
byte[] bytes = readStored(path);
Directory parent = stored.parent;
DataFile file = new DataFile(stored.name, stored.lastModified, bytes);
file.readOnly = stored.readOnly;
if (parent != null) {
parent.attach(stored.name, file);
}
return file;
}
/** Reads every in-place file under {@code node} into memory (before the page moves it). */
private void materializeAll(Node node, String path) throws IOException {
if (node instanceof Directory directory) {
for (String name : directory.names()) {
Node child = directory.child(name);
if (child != null) {
materializeAll(child, path + "/" + name);
}
}
} else if (node instanceof StoredFile stored) {
materialize(stored, path);
}
}
/**
* Drops the folder at {@code path} from the tree without noting it as a change: the store keeps
* it, and another copy of the program has it now (ADR 0039). The caller has flushed first, so
* nothing under it is waiting to be stored.
*/
void forget(String path) {
Node node = find(normalize(path));
if (node != null && node.parent != null) {
node.parent.detach(node);
}
}
/**
* Mounts the entries of {@code archive} that {@code include} accepts (by their names in the
* zip) under the folder at {@code path}, read-only. Mounted files are never persisted: the zip
* is the store.
*
* @return how many files were mounted
*/
int mount(String path, ZipArchive archive, Predicate<String> include) throws IOException {
long now = clock.getAsLong();
String base = normalize(path);
Directory top = mkdirs(base, now, false);
List<Directory> made = new ArrayList<>();
int files = 0;
for (ZipArchive.Entry entry : archive.entries()) {
String name = entry.name();
if (name.endsWith("/") || !include.test(name)) {
continue;
}
String relative = normalize("/" + name);
if (relative.equals("/")) {
continue;
}
Directory parent = top;
int start = 1;
int end = relative.indexOf('/', start);
while (end > 0) {
String part = relative.substring(start, end);
Node child = parent.child(part);
if (child == null) {
Directory created = new Directory(part, now, false);
parent.attach(part, created);
made.add(created);
child = created;
} else if (!(child instanceof Directory)) {
throw new IOException("Zip entry " + name + " is inside a file");
}
parent = (Directory) child;
start = end + 1;
end = relative.indexOf('/', start);
}
parent.attach(relative.substring(start), new MountedFile("", now, archive, entry));
files++;
}
// Read-only once filled: the game can't add to or change the jar's resources.
for (Directory directory : made) {
directory.readOnly = true;
}
top.readOnly = true;
return files;
}
/**
* Marks {@code path} changed as a whole, so the next {@link #collectChanges} sends all of it
* (or its deletion, if it's gone): the store failed to keep its last change.
*/
void resend(String path) {
journal.reshaped(path);
}
/** The changes to persist since the last call. */
List<StoreOp> collectChanges() {
return journal.collect(this);
}
/** Whether anything changed since the last {@link #collectChanges}; cheap, for every frame. */
boolean hasChanges() {
return !journal.isEmpty();
}
/**
* How many files, and bytes in them, are in the tree under {@code path} (mounted files
* excepted): those in memory, then the in-place files left in the store.
*/
long[] measure(String path) {
long[] totals = new long[4];
Node node = find(normalize(path));
if (node != null) {
measure(node, totals);
}
return totals;
}
private static void measure(Node node, long[] totals) {
if (node instanceof Directory directory) {
for (Node child : directory.children()) {
measure(child, totals);
}
} else if (node instanceof DataFile file) {
totals[0]++;
totals[1] += file.size;
} else if (node instanceof StoredFile stored) {
totals[2]++;
totals[3] += stored.size;
}
}
/** A path in the tree, as TeaVM's file classes see it: looked up on every call, like a path string. */
private final class TreeFile implements VirtualFile {
private final String path;
TreeFile(String path) {
this.path = path;
}
private @Nullable Node node() {
return find(path);
}
@Override
public String getName() {
return path.substring(path.lastIndexOf('/') + 1);
}
@Override
public boolean isDirectory() {
return node() instanceof Directory;
}
@Override
public boolean isFile() {
return node() instanceof FileNode;
}
@Override
public String @Nullable [] listFiles() {
return node() instanceof Directory directory ? directory.names() : null;
}
@Override
public @Nullable VirtualFileAccessor createAccessor(boolean readable, boolean writable, boolean append) {
Node node = node();
if (!(node instanceof FileNode file)) {
return null;
}
if (file instanceof StoredFile stored) {
try {
InPlaceStore store = inPlace;
if (store != null && store.opensInPlace()) {
return openInPlace(stored, store, readable, writable, append);
}
// The page's way: the whole file read into memory, then opened as any other.
file = materialize(stored, path);
} catch (IOException e) {
System.err.println("[Incari] Can't open " + path + ": " + e.getMessage());
return null;
}
}
if (!(file instanceof DataFile data)) {
if (writable) {
return null;
}
try {
return new FileAccessor(file.contents(), clock);
} catch (IOException e) {
// Opening fails as a missing file would; say why in the console.
System.err.println("[Incari] Can't read " + path + ": " + e.getMessage());
return null;
}
}
if (!writable) {
return new FileAccessor(data, null, clock, 0);
}
if (data.readOnly) {
return null;
}
// TeaVM's streams ask for write-only to replace a file's contents; RandomAccessFile
// asks for read-write and, as in the JDK, keeps them.
if (!readable && !append && data.size > 0) {
data.setSize(0);
data.resized = true;
data.lastModified = clock.getAsLong();
journal.written(data);
}
return new FileAccessor(data, journal, clock, append ? data.size : 0);
}
/** Opens an in-place file where it is (singleplayer's server worker, ADR 0041). */
private @Nullable VirtualFileAccessor openInPlace(
StoredFile stored, InPlaceStore store, boolean readable, boolean writable, boolean append)
throws IOException {
if (writable && stored.readOnly) {
return null;
}
InPlaceStore.Handle handle = stored.handle;
if (handle == null) {
handle = store.open(path);
stored.handle = handle;
stored.size = handle.size();
}
if (writable && !readable && !append && stored.size > 0) {
// As for a file in memory: write-only replaces the contents.
handle.truncate(0);
stored.size = 0;
stored.lastModified = clock.getAsLong();
}
return new StoredFileAccessor(stored, handle, writable, clock, append ? stored.size : 0);
}
@Override
public boolean createFile(String fileName) throws IOException {
Node node = node();
if (!(node instanceof Directory directory)) {
throw new IOException(node == null ? "No such folder: " + path : "Not a folder: " + path);
}
if (directory.readOnly) {
throw new IOException("Read-only folder: " + path);
}
if (directory.child(fileName) != null) {
return false;
}
long now = clock.getAsLong();
InPlaceStore store = inPlace;
String created = child(fileName);
if (store != null && store.opensInPlace() && InPlaceFiles.matches(created)) {
// Made in the store when first opened; the journal has nothing to send for it.
directory.attach(fileName, new StoredFile(fileName, now, 0));
directory.lastModified = now;
return true;
}
directory.attach(fileName, new DataFile(fileName, now));
directory.lastModified = now;
journal.reshaped(created);
return true;
}
@Override
public boolean createDirectory(String fileName) {
if (!(node() instanceof Directory directory) || directory.readOnly || directory.child(fileName) != null) {
return false;
}
long now = clock.getAsLong();
directory.attach(fileName, new Directory(fileName, now, false));
directory.lastModified = now;
journal.reshaped(child(fileName));
return true;
}
@Override
public boolean delete() {
Node node = node();
Directory parent = node == null ? null : node.parent;
if (node == null || parent == null || parent.readOnly) {
return false;
}
if (node instanceof Directory directory && !directory.isEmpty()) {
return false;
}
if (node instanceof StoredFile stored) {
// The store deletes it at the next flush; it can't while this program holds it.
stored.close();
}
parent.detach(node);
parent.lastModified = clock.getAsLong();
journal.reshaped(path);
return true;
}
@Override
public boolean adopt(VirtualFile file, String fileName) {
if (!(node() instanceof Directory directory) || directory.readOnly || !(file instanceof TreeFile moved)) {
return false;
}
Node node = moved.node();
Directory from = node == null ? null : node.parent;
if (node == null || from == null || from.readOnly || directory.isWithin(node)) {
return false;
}
Node existing = directory.child(fileName);
if (existing == node) {
return true;
}
if (existing instanceof Directory replaced && (!replaced.isEmpty() || !(node instanceof Directory))) {
// As on the desktop: a folder can only replace an empty folder, and a file none.
return false;
}
if (existing instanceof FileNode && node instanceof Directory) {
return false;
}
if (holdsStored(node)) {
InPlaceStore store = inPlace;
if (store == null || store.opensInPlace()) {
// In-place files open where they are don't move: the store has no rename.
return false;
}
// The page's way: read into memory, then moved and sent whole like any other.
try {
materializeAll(node, moved.path);
} catch (IOException e) {
System.err.println("[Incari] Can't move " + moved.path + ": " + e.getMessage());
return false;
}
node = moved.node();
if (node == null) {
return false;
}
}
if (existing instanceof StoredFile replaced) {
replaced.close();
}
long now = clock.getAsLong();
from.detach(node);
directory.attach(fileName, node);
from.lastModified = now;
directory.lastModified = now;
journal.reshaped(moved.path);
journal.reshaped(child(fileName));
return true;
}
@Override
public boolean canRead() {
return node() != null;
}
@Override
public boolean canWrite() {
Node node = node();
return node != null && !node.readOnly;
}
@Override
public long lastModified() {
Node node = node();
return node == null ? 0 : node.lastModified;
}
@Override
public boolean setLastModified(long lastModified) {
Node node = node();
if (node == null || node.readOnly) {
return false;
}
node.lastModified = lastModified;
if (node instanceof DataFile data) {
data.resized = true;
journal.written(data);
}
return true;
}
@Override
public boolean setReadOnly(boolean readOnly) {
Node node = node();
if (node == null || node instanceof MountedFile) {
return false;
}
node.readOnly = readOnly;
return true;
}
@Override
public int length() {
return node() instanceof FileNode file ? file.length() : 0;
}
private String child(String name) {
return path.equals("/") ? "/" + name : path + "/" + name;
}
}
}
@@ -0,0 +1,452 @@
package incari.platform.web.storage;
import incari.platform.api.PlatformNotice;
import java.io.IOException;
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
import java.util.function.Predicate;
import org.jspecify.annotations.Nullable;
import org.teavm.jso.JSBody;
import org.teavm.jso.JSObject;
import org.teavm.jso.typedarrays.ArrayBuffer;
import org.teavm.jso.typedarrays.Int8Array;
import org.teavm.runtime.fs.VirtualFileSystemProvider;
/**
* The browser build's file system (ADR 0011): an in-memory {@link TreeFileSystem} that every
* {@code java.io} and {@code java.nio.file} call in the page goes through, loaded at startup from
* the storage worker (OPFS, or IndexedDB) and written back to it behind the game.
*
* <p>Writes are stored within a frame: {@link #flush}, once a frame, sends the changes to the
* worker. The game's save points (options, the server list, a world's save) are ordinary writes
* and renames. A page closed mid-frame loses what that frame wrote.
*
* <p>A change the store couldn't keep (a full disk) is sent again, whole, a few seconds later: the
* store is sent only the bytes that changed, and a range lost would leave the file damaged. That
* saving fails, or can't happen at all, is told to the player ({@link #takeNotice}).
*/
public final class WebFileSystem {
/** Paths under this folder survive a reload. */
public static final String ROOT = "/incari";
private static final String LOCK = "incari-storage";
/** Off ({@code ?inplace=off}): worlds go to a worker with their bytes, as in ADR 0039, to compare. */
private static boolean inPlaceHandOver = true;
private final TreeFileSystem tree;
/**
* The storage worker: the page's own, or in a copy of the game in a worker the port the page
* gave it (ADR 0041); null in a worker without one, whose page stores its changes for it.
*/
private final @Nullable JSObject store;
/** Whether this is a copy of the game in a worker (ADR 0039). */
private final boolean detached;
private final String backend;
private final boolean readOnly;
private @Nullable String lastProblem;
/** In a worker's copy without a port: changes collected for the page, oldest first ({@link #takeChanges}). */
private final List<StoreOp> pending = new ArrayList<>();
/** In a worker's copy: whether the world it was handed was left in place (ADR 0041). */
private boolean inPlaceSession;
/** How long a change the store couldn't keep waits before it's sent again, in milliseconds. */
private static final double RETRY_MILLIS = 5000;
/** Paths whose change the store couldn't keep, to send again whole at {@link #retryAt}. */
private final Set<String> failedPaths = new LinkedHashSet<>();
private double retryAt;
/** Notices for the player, oldest first ({@link #takeNotice}). */
private final List<PlatformNotice> notices = new ArrayList<>();
/** Saving failed and the player was told; cleared once a batch is stored whole again. */
private boolean failureReported;
private WebFileSystem(
TreeFileSystem tree, @Nullable JSObject store, boolean detached, String backend, boolean readOnly) {
this.tree = tree;
this.store = store;
this.detached = detached;
this.backend = backend;
this.readOnly = readOnly;
}
/** The entry point's choice: false hands worlds over with their bytes (ADR 0041's comparison). */
public static void setInPlaceHandOver(boolean on) {
inPlaceHandOver = on;
}
/**
* The file system of a copy of the game in a worker (ADR 0039): empty at first, filled with the
* files the page hands it ({@link #takeOver}). Changes go to the storage worker through the port
* the page gave it (ADR 0041), or without a port to the page ({@link #takeChanges}).
*/
public static WebFileSystem installDetached(List<String> transientRoots) throws IOException {
TreeFileSystem tree = new TreeFileSystem(new Journal(ROOT, transientRoots), WebFileSystem::nowMillis);
tree.mkdirs("/tmp", nowMillis(), false);
tree.mkdirs(ROOT, nowMillis(), false);
tree.collectChanges();
VirtualFileSystemProvider.setInstance(tree);
return new WebFileSystem(tree, BrowserStore.fromPort(), true, "page", false);
}
/**
* The files under {@code directory}, encoded for another copy of the game (a worker's, or back
* to the page), dropped from this tree without telling the store (ADR 0039). What was waiting to
* be stored is sent first. Where the store is the origin private file system and this page may
* write it, a world's region files stay there for the worker to open in place (ADR 0041): the
* store is waited for until it has every write, and they go as their sizes alone. Otherwise
* they go with their bytes, read from the store if need be. Suspends while it waits or reads.
*/
public byte[] handOver(String directory) throws IOException {
flush();
boolean inPlace =
detached ? inPlaceSession : inPlaceHandOver && store != null && backend.equals("opfs") && !readOnly;
JSObject storage = store;
if (inPlace && storage != null) {
BrowserStore.sync(storage);
}
tree.closeStored(directory);
List<FileBundle.Entry> entries = tree.export(directory, inPlace);
tree.forget(directory);
return FileBundle.encode(new FileBundle.Bundle(inPlace, entries));
}
/**
* Takes files {@link #handOver} encoded into this tree, as if loaded from the store. In a
* worker handed a world in place, its region files are opened where they are when the server
* opens them; back on the page, they're known by size again, as the store has them now (the
* worker may have made more of them, and may have ended before it could say).
*/
public void takeOver(byte[] bundle) throws IOException {
FileBundle.Bundle decoded = FileBundle.decode(bundle);
if (detached) {
inPlaceSession = decoded.inPlace();
tree.setInPlaceStore(inPlaceSession ? new OpfsFiles(OpfsFiles.available()) : null);
}
for (FileBundle.Entry entry : decoded.entries()) {
if (entry.stored()) {
tree.loadStored(entry.path(), entry.lastModified(), entry.size());
} else {
tree.load(entry.path(), entry.directory(), entry.lastModified(), entry.contents());
}
}
JSObject storage = store;
if (!detached
&& decoded.inPlace()
&& storage != null
&& !decoded.entries().isEmpty()) {
refreshStored(storage, decoded.entries().get(0).path());
}
}
/** The in-place files under {@code directory} as the store has them: sizes and times, new ones too. */
private void refreshStored(JSObject storage, String directory) throws IOException {
JSObject reply = BrowserStore.stat(storage, directory);
int count = BrowserStore.entryCount(reply);
for (int i = 0; i < count; i++) {
String path = BrowserStore.entryPath(reply, i);
if (!BrowserStore.entryIsDirectory(reply, i) && InPlaceFiles.matches(path)) {
tree.loadStored(
path, (long) BrowserStore.entryLastModified(reply, i), BrowserStore.entrySize(reply, i));
}
}
}
/** In a worker's copy: what changed since the last call, encoded for the page; null if nothing. */
public byte @Nullable [] takeChanges() {
flush();
if (pending.isEmpty()) {
return null;
}
byte[] encoded = FileBundle.encodeOps(pending);
pending.clear();
return encoded;
}
/** Sends a worker's changes ({@link #takeChanges}) to this page's store. */
public void storeChanges(byte[] changes) {
List<StoreOp> ops = FileBundle.decodeOps(changes);
if (!readOnly && store != null && !ops.isEmpty()) {
send(store, ops);
}
}
/**
* Mounts the entries of a zip already in a JavaScript buffer that {@code include} takes,
* read-only, under {@code directory}: the client jar in a worker's copy of the game, read from
* where the page's storage keeps it. The entries are copied out, still compressed, so the
* buffer isn't held: a server worker keeps the jar's data packs, a few megabytes, not its 40.
*/
public int mountZip(String directory, ArrayBuffer zip, Predicate<String> include) throws IOException {
return tree.mount(directory, ZipArchive.open(new PageBuffer(zip)).compact(include), include);
}
/**
* Starts the storage worker, loads everything stored under {@link #ROOT} into memory (suspends
* until it's read), and makes the result the page's file system. Call it before anything
* touches a file: TeaVM's {@code java.nio.file} binds the file system once, when first used.
*
* <p>Relative paths start at "/", as in TeaVM's own file system: TeaVM's
* {@code Files.createDirectories} creates an absolute path's parents through relative
* sub-paths, so any other working directory would put them in the wrong place.
*
* @param transientRoots folders under {@link #ROOT} that don't survive a reload
*/
public static WebFileSystem install(List<String> transientRoots) throws IOException {
double start = now();
TreeFileSystem tree = new TreeFileSystem(new Journal(ROOT, transientRoots), WebFileSystem::nowMillis);
JSObject store = BrowserStore.start(StorageWorkerSource.SCRIPT);
JSObject reply = BrowserStore.open(store, ROOT, LOCK);
String backend = BrowserStore.backend(reply);
int count = BrowserStore.entryCount(reply);
for (int i = 0; i < count; i++) {
String path = BrowserStore.entryPath(reply, i);
if (!Journal.within(path, ROOT)) {
continue;
}
boolean directory = BrowserStore.entryIsDirectory(reply, i);
long lastModified = (long) BrowserStore.entryLastModified(reply, i);
if (lastModified == 0) {
lastModified = nowMillis();
}
if (BrowserStore.entryIsStored(reply, i)) {
tree.loadStored(path, lastModified, BrowserStore.entrySize(reply, i));
continue;
}
byte[] contents =
directory ? null : BrowserStore.takeEntryData(reply, i).copyToJavaArray();
tree.load(path, directory, lastModified, contents);
}
// Scratch space for Files.createTempFile() and friends, as on a desktop.
tree.mkdirs("/tmp", nowMillis(), false);
tree.collectChanges();
VirtualFileSystemProvider.setInstance(tree);
WebFileSystem files = new WebFileSystem(tree, store, false, backend, BrowserStore.readOnly(reply));
tree.setInPlaceStore(new PageStore(store));
long[] loaded = tree.measure(ROOT);
log("[Incari] Storage: " + backend + ", " + loaded[0] + " files (" + (loaded[1] / 1024) + " KiB) loaded in "
+ Math.round(now() - start) + " ms; " + loaded[2] + " region files (" + (loaded[3] / 1024)
+ " KiB) left in place");
String problems = BrowserStore.problems(reply);
if (!problems.isEmpty()) {
warn("[Incari] Storage: " + problems);
}
if (!BrowserStore.locked(reply)) {
warn("[Incari] Storage: the game is open in another tab, which keeps its files; nothing this tab "
+ "changes will be saved.");
files.notices.add(PlatformNotice.SAVES_HELD_ELSEWHERE);
} else if (backend.equals("memory")) {
warn("[Incari] Storage: this browser offers the page no storage; nothing will be saved.");
files.notices.add(PlatformNotice.SAVES_UNAVAILABLE);
}
return files;
}
/** Where the files are kept: "opfs", "indexeddb", or "memory" (nowhere). */
public String backend() {
return backend;
}
/**
* Sends the store what changed since the last flush, without waiting for it to be stored.
* Every frame: returns at once when nothing changed (hot path, don't allocate).
*/
public void flush() {
JSObject storage = store;
if (storage != null && !readOnly) {
retryFailed(storage);
}
if (tree.hasChanges()) {
List<StoreOp> ops = tree.collectChanges();
if (storage == null) {
pending.addAll(ops);
} else if (!readOnly && !ops.isEmpty()) {
send(storage, ops);
}
}
if (storage == null) {
return;
}
String problem = BrowserStore.takeProblem(storage);
if (problem != null && !problem.equals(lastProblem)) {
// Once per kind of failure: a full disk would otherwise say so every frame.
lastProblem = problem;
warn("[Incari] Storage: " + problem);
}
if (problem != null && !failureReported && !detached) {
failureReported = true;
notices.add(PlatformNotice.SAVE_FAILED);
} else if (failureReported && failedPaths.isEmpty() && BrowserStore.lastBatchStored(storage)) {
// Saving works again: a later failure is news.
failureReported = false;
lastProblem = null;
}
}
/**
* Collects the paths the store reported it couldn't keep, and once their wait is over marks them
* changed in the tree, so this flush sends them again whole (or deletes them, if they're gone).
* Hot path: allocates nothing while nothing failed.
*/
private void retryFailed(JSObject storage) {
String path;
while ((path = BrowserStore.takeFailedPath(storage)) != null) {
if (failedPaths.isEmpty()) {
retryAt = now() + RETRY_MILLIS;
}
failedPaths.add(path);
}
if (failedPaths.isEmpty() || now() < retryAt) {
return;
}
for (String failed : failedPaths) {
tree.resend(failed);
}
failedPaths.clear();
}
/** The oldest notice for the player not yet taken, or null. The page's thread, once a frame. */
public @Nullable PlatformNotice takeNotice() {
return notices.isEmpty() ? null : notices.remove(0);
}
private static void send(JSObject store, List<StoreOp> ops) {
JSObject batch = BrowserStore.newBatch();
for (StoreOp op : ops) {
switch (op.kind()) {
case MKDIR -> BrowserStore.addMkdir(batch, op.path(), (double) op.lastModified());
case WRITE -> {
byte[] data = op.data();
BrowserStore.addWrite(
batch,
op.path(),
op.size(),
op.at(),
data == null ? null : Int8Array.copyFromJavaArray(data),
(double) op.lastModified());
}
case DELETE -> BrowserStore.addDelete(batch, op.path());
}
}
BrowserStore.apply(store, batch);
}
/**
* Mounts a zip from {@code url} read-only under {@code directory}, with the entries
* {@code include} accepts. The zip is kept by the storage worker under {@code cacheKey}, so a
* later load reads it from there instead of downloading it again (a new key replaces it). The
* accepted entries' bytes stay in the page, outside the game's heap, copied out of the zip so
* the rest of it isn't held (the client jar's classes: ADR 0043); each is inflated when opened.
*
* @return how many files were mounted, and whether the zip came from the cache
*/
public Mounted mountZip(String directory, String url, String cacheKey, Predicate<String> include)
throws IOException {
JSObject storage = store;
if (storage == null) {
throw new IOException("A worker's copy of the game has no storage of its own to fetch " + url + " into");
}
JSObject reply = BrowserStore.download(storage, url, cacheKey);
String error = BrowserStore.error(reply);
if (error != null) {
throw new IOException("Couldn't fetch " + url + ": " + error);
}
boolean cached = BrowserStore.cached(reply);
ZipArchive archive;
try {
archive = ZipArchive.open(new PageBuffer(BrowserStore.data(reply)));
} catch (IOException e) {
if (!cached) {
throw e;
}
// A damaged copy (the page closed while caching it?): drop it and download again.
warn("[Incari] Storage: the cached " + cacheKey + " is damaged (" + e.getMessage()
+ "); downloading it again");
BrowserStore.forget(storage, cacheKey);
return mountZip(directory, url, cacheKey, include);
}
return new Mounted(tree.mount(directory, archive.compact(include), include), cached);
}
/** What {@link #mountZip} did: how many files it mounted, and whether the zip was cached. */
public record Mounted(int files, boolean cached) {}
/**
* The page's in-place files (ADR 0041): read whole from the storage worker when something on the
* page opens one (singleplayer's server on the page, a world's download or backup).
*/
private record PageStore(JSObject store) implements InPlaceStore {
@Override
public boolean opensInPlace() {
return false;
}
@Override
public byte[] read(String path) {
ArrayBuffer data = BrowserStore.read(store, path);
return data == null ? new byte[0] : new Int8Array(data).copyToJavaArray();
}
@Override
public Handle open(String path) throws IOException {
throw new IOException("The page reads in-place files whole: " + path);
}
}
/** A zip's bytes in a JavaScript buffer, read a range at a time. */
private record PageBuffer(ArrayBuffer buffer) implements ZipArchive.Source {
@Override
public int size() {
return buffer.getByteLength();
}
@Override
public byte[] read(int position, int length) throws IOException {
if (position < 0 || length < 0 || position > size() - length) {
throw new IOException("Read past the end of the zip");
}
return BrowserStore.slice(buffer, position, length).copyToJavaArray();
}
/** In a new buffer of the page's, outside the game's heap, as the zip's own bytes were. */
@Override
public ZipArchive.Kept keep(int[] localHeaders, int[] compressedSizes) throws IOException {
JSObject entries = BrowserStore.newRanges();
for (int i = 0; i < localHeaders.length; i++) {
BrowserStore.addRange(entries, localHeaders[i], compressedSizes[i]);
}
JSObject copy = BrowserStore.copyEntries(buffer, entries);
String error = BrowserStore.error(copy);
if (error != null) {
throw new IOException(error);
}
int[] starts = new int[localHeaders.length];
for (int i = 0; i < starts.length; i++) {
starts[i] = BrowserStore.copiedStart(copy, i);
}
return new ZipArchive.Kept(new PageBuffer(BrowserStore.data(copy)), starts);
}
}
private static long nowMillis() {
return (long) dateNow();
}
@JSBody(script = "return Date.now();")
private static native double dateNow();
@JSBody(script = "return performance.now();")
private static native double now();
@JSBody(params = "message", script = "console.log(message);")
private static native void log(String message);
@JSBody(params = "message", script = "console.warn(message);")
private static native void warn(String message);
}
@@ -0,0 +1,268 @@
package incari.platform.web.storage;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.function.Predicate;
import java.util.zip.DataFormatException;
import java.util.zip.Inflater;
/**
* A zip file read in place: its central directory is parsed once, and an entry's bytes are read
* and inflated only when someone opens it. Written from the zip format's specification (PKWARE's
* APPNOTE); stored and deflated entries only, no ZIP64, no encryption, which is all a Java jar
* of this size uses.
*/
final class ZipArchive {
/** Where the zip's bytes are: a JavaScript buffer in the page, an array in tests. */
interface Source {
int size();
/** {@code length} bytes from {@code position}. */
byte[] read(int position, int length) throws IOException;
/**
* The entries at these local headers, each its header and {@code compressedSizes[i]} bytes
* of data, copied one after another into a source of their own ({@link #compact}), with
* where each now starts. In an array by default; the page's buffer copies them into a new
* buffer of the page's, in one pass.
*/
default Kept keep(int[] localHeaders, int[] compressedSizes) throws IOException {
int[] spans = new int[localHeaders.length];
long total = 0;
for (int i = 0; i < localHeaders.length; i++) {
byte[] header = read(localHeaders[i], LOCAL_SIZE);
if (int32(header, 0) != LOCAL_SIGNATURE) {
throw new IOException("Corrupt zip file (bad local header at " + localHeaders[i] + ")");
}
spans[i] = LOCAL_SIZE + int16(header, 26) + int16(header, 28) + compressedSizes[i];
total += spans[i];
}
if (total > Integer.MAX_VALUE - 8) {
throw new IOException("The entries to keep don't fit in one buffer");
}
byte[] bytes = new byte[(int) total];
int[] starts = new int[localHeaders.length];
int at = 0;
for (int i = 0; i < localHeaders.length; i++) {
System.arraycopy(read(localHeaders[i], spans[i]), 0, bytes, at, spans[i]);
starts[i] = at;
at += spans[i];
}
return new Kept(new Bytes(bytes), starts);
}
}
/** What {@link Source#keep} copied, and where each entry's local header now starts. */
static final class Kept {
private final Source source;
private final int[] starts;
Kept(Source source, int[] starts) {
this.source = source;
this.starts = starts;
}
Source source() {
return source;
}
/** Where the {@code i}th entry kept now starts. */
int start(int i) {
return starts[i];
}
}
/** A file in the zip, as the central directory describes it. */
record Entry(String name, int method, int compressedSize, int size, int localHeader) {}
private static final int END_SIGNATURE = 0x06054b50;
private static final int CENTRAL_SIGNATURE = 0x02014b50;
private static final int LOCAL_SIGNATURE = 0x04034b50;
private static final int END_SIZE = 22;
private static final int CENTRAL_SIZE = 46;
private static final int LOCAL_SIZE = 30;
private static final int MAX_COMMENT = 0xFFFF;
private static final int STORED = 0;
private static final int DEFLATED = 8;
private final Source source;
private final List<Entry> entries;
private ZipArchive(Source source, List<Entry> entries) {
this.source = source;
this.entries = entries;
}
/** Reads the central directory; fails if {@code source} isn't a zip this class can read. */
static ZipArchive open(Source source) throws IOException {
int size = source.size();
int tailLength = Math.min(size, END_SIZE + MAX_COMMENT);
byte[] tail = source.read(size - tailLength, tailLength);
int end = -1;
// The end record sits before a comment of up to 64 KiB; search back for its signature.
for (int i = tailLength - END_SIZE; i >= 0; i--) {
if (int32(tail, i) == END_SIGNATURE && i + END_SIZE + int16(tail, i + 20) == tailLength) {
end = i;
break;
}
}
if (end < 0) {
throw new IOException("Not a zip file (no end of central directory)");
}
int count = int16(tail, end + 10);
long directorySize = uint32(tail, end + 12);
long directoryStart = uint32(tail, end + 16);
if (count == 0xFFFF || directorySize == 0xFFFFFFFFL || directoryStart == 0xFFFFFFFFL) {
throw new IOException("ZIP64 archives aren't supported");
}
if (directoryStart + directorySize > size) {
throw new IOException("Truncated zip file (central directory past the end)");
}
byte[] directory = source.read((int) directoryStart, (int) directorySize);
List<Entry> entries = new ArrayList<>(count);
int at = 0;
for (int i = 0; i < count; i++) {
if (at + CENTRAL_SIZE > directory.length || int32(directory, at) != CENTRAL_SIGNATURE) {
throw new IOException("Corrupt zip file (bad central directory entry " + i + ")");
}
int flags = int16(directory, at + 8);
int method = int16(directory, at + 10);
long compressedSize = uint32(directory, at + 20);
long entrySize = uint32(directory, at + 24);
int nameLength = int16(directory, at + 28);
int extraLength = int16(directory, at + 30);
int commentLength = int16(directory, at + 32);
long localHeader = uint32(directory, at + 42);
if (at + CENTRAL_SIZE + nameLength > directory.length) {
throw new IOException("Corrupt zip file (name past the central directory)");
}
// Names are UTF-8 when flag bit 11 says so, and in practice ASCII otherwise.
String name = new String(directory, at + CENTRAL_SIZE, nameLength, StandardCharsets.UTF_8);
if ((flags & 1) != 0) {
throw new IOException("Encrypted zip entries aren't supported: " + name);
}
if (compressedSize == 0xFFFFFFFFL || entrySize == 0xFFFFFFFFL || localHeader == 0xFFFFFFFFL) {
throw new IOException("ZIP64 entries aren't supported: " + name);
}
entries.add(new Entry(name, method, (int) compressedSize, (int) entrySize, (int) localHeader));
at += CENTRAL_SIZE + nameLength + extraLength + commentLength;
}
return new ZipArchive(source, List.copyOf(entries));
}
List<Entry> entries() {
return entries;
}
/**
* The entries {@code include} takes, copied out of this zip into an array of their own, still
* compressed (each entry's local header and data, the offsets renumbered), or this archive if it
* takes them all. Whoever reads only some of a large zip's files keeps only those, and the zip's
* own buffer can go: the client jar's classes, most of its 40 MB, are never read in a browser.
*/
ZipArchive compact(Predicate<String> include) throws IOException {
List<Entry> kept = new ArrayList<>();
for (Entry entry : entries) {
if (include.test(entry.name())) {
kept.add(entry);
}
}
if (kept.size() == entries.size()) {
// Everything is kept: nothing to copy out.
return this;
}
int[] localHeaders = new int[kept.size()];
int[] compressedSizes = new int[kept.size()];
for (int i = 0; i < kept.size(); i++) {
localHeaders[i] = kept.get(i).localHeader();
compressedSizes[i] = kept.get(i).compressedSize();
}
Kept copy = source.keep(localHeaders, compressedSizes);
List<Entry> moved = new ArrayList<>(kept.size());
for (int i = 0; i < kept.size(); i++) {
Entry entry = kept.get(i);
moved.add(new Entry(entry.name(), entry.method(), entry.compressedSize(), entry.size(), copy.start(i)));
}
return new ZipArchive(copy.source(), List.copyOf(moved));
}
/** A zip's bytes, or a compacted part of them, in an array. */
private static final class Bytes implements Source {
private final byte[] bytes;
Bytes(byte[] bytes) {
this.bytes = bytes;
}
@Override
public int size() {
return bytes.length;
}
@Override
public byte[] read(int position, int length) throws IOException {
if (position < 0 || length < 0 || position > bytes.length - length) {
throw new IOException("Read past the end of the zip");
}
byte[] out = new byte[length];
System.arraycopy(bytes, position, out, 0, length);
return out;
}
}
/** An entry's uncompressed bytes. */
byte[] read(Entry entry) throws IOException {
byte[] header = source.read(entry.localHeader(), LOCAL_SIZE);
if (int32(header, 0) != LOCAL_SIGNATURE) {
throw new IOException("Corrupt zip file (bad local header for " + entry.name() + ")");
}
// The local header's name and extra field may differ in length from the central one's.
int dataStart = entry.localHeader() + LOCAL_SIZE + int16(header, 26) + int16(header, 28);
byte[] compressed = source.read(dataStart, entry.compressedSize());
return switch (entry.method()) {
case STORED -> compressed;
case DEFLATED -> inflate(entry, compressed);
default -> throw new IOException("Unsupported compression method " + entry.method() + ": " + entry.name());
};
}
private static byte[] inflate(Entry entry, byte[] compressed) throws IOException {
Inflater inflater = new Inflater(true);
try {
inflater.setInput(compressed);
byte[] out = new byte[entry.size()];
int done = 0;
while (done < out.length) {
int inflated = inflater.inflate(out, done, out.length - done);
if (inflated == 0 && (inflater.finished() || inflater.needsInput() || inflater.needsDictionary())) {
break;
}
done += inflated;
}
if (done != out.length) {
throw new IOException(
"Corrupt zip entry " + entry.name() + ": " + done + " of " + out.length + " bytes");
}
return out;
} catch (DataFormatException e) {
throw new IOException("Corrupt zip entry " + entry.name(), e);
} finally {
inflater.end();
}
}
private static int int16(byte[] bytes, int at) {
return (bytes[at] & 0xFF) | (bytes[at + 1] & 0xFF) << 8;
}
private static int int32(byte[] bytes, int at) {
return int16(bytes, at) | int16(bytes, at + 2) << 16;
}
private static long uint32(byte[] bytes, int at) {
return int32(bytes, at) & 0xFFFFFFFFL;
}
}
@@ -0,0 +1,8 @@
/**
* The browser build's file system (ADR 0011): an in-memory tree behind TeaVM's
* {@code java.io} and {@code java.nio.file}, persisted by a storage worker to OPFS or IndexedDB.
*/
@NullMarked
package incari.platform.web.storage;
import org.jspecify.annotations.NullMarked;
@@ -0,0 +1,130 @@
// @ts-check
// A worker running a program of its own beside the game (ADR 0023): the mesher's WebAssembly
// module, which TeaVM compiles apart from the game. It runs as a classic worker from a Blob URL
// (platform-web's WebWorkerPool), so the page needs no extra file; the page's first message says
// where the program's loader and module are.
//
// The program's Java side installs `__incariProgram` on the worker's scope: `input(n)` gives a view
// of n bytes of its memory to copy a message into, `handle(n)` takes the message and answers with
// the length of its reply (or -1 for none), and `output(n)` views the reply.
//
// Messages from the page:
// {kind: "start", runtime, module} -> {kind: "ready"} or {kind: "failed", error}
// {id, buffer, offset, length} -> {id, reply: ArrayBuffer} or {id, error}
// A message's bytes are in `buffer` (an ArrayBuffer handed over, or the page's SharedArrayBuffer)
// from `offset`; id -1 wants no answer. Messages that come before the program has started wait for it.
"use strict";
/**
* What the program installs.
* @typedef {{
* input(length: number): Int8Array,
* handle(length: number): number,
* output(length: number): Int8Array}} Program
*/
/**
* A message for the program.
* @typedef {{id: number, buffer: ArrayBufferLike, offset: number, length: number}} Job
*/
/**
* TeaVM's WebAssembly GC loader, which the program's runtime script defines.
* @typedef {{wasmGC: {load(url: string): Promise<{exports: {main(args: string[]): void}}>}}} TeaVm
*/
/**
* The parts of the worker's global scope this script uses.
* @typedef {{
* postMessage(message: unknown, transfer?: Transferable[]): void,
* onmessage: ((event: {data: Job | {kind: "start", runtime: string, module: string}}) => void) | null,
* importScripts(url: string): void,
* TeaVM?: TeaVm,
* __incariProgram?: Program}} Scope
*/
/**
* Starts serving the page's messages on `scope`.
* @param {Scope} scope
*/
function serve(scope) {
/** @type {Program | null} */
let program = null;
/** @type {Job[]} */
const waiting = [];
/**
* @param {Program} running
* @param {Job} job
*/
function handle(running, job) {
/** @type {Int8Array<ArrayBuffer>} */
let reply;
try {
running.input(job.length).set(new Int8Array(job.buffer, job.offset, job.length));
const length = running.handle(job.length);
if (job.id < 0) {
return;
}
if (length < 0) {
scope.postMessage({ id: job.id, reply: new ArrayBuffer(0) });
return;
}
// A copy of the reply in an ArrayBuffer of its own: the program's memory is reused.
reply = running.output(length).slice();
} catch (error) {
scope.postMessage({ id: job.id, error: describe(error) });
return;
}
scope.postMessage({ id: job.id, reply: reply.buffer }, [reply.buffer]);
}
/**
* @param {string} runtime
* @param {string} module
*/
async function start(runtime, module) {
try {
scope.importScripts(runtime);
const teavm = scope.TeaVM;
if (!teavm) {
throw new Error(`${runtime} didn't define TeaVM's loader`);
}
const loaded = await teavm.wasmGC.load(module);
loaded.exports.main([]);
const installed = scope.__incariProgram;
if (!installed) {
throw new Error("The program didn't install its handlers");
}
program = installed;
scope.postMessage({ kind: "ready" });
for (const job of waiting.splice(0)) {
handle(installed, job);
}
} catch (error) {
scope.postMessage({ kind: "failed", error: describe(error) });
}
}
scope.onmessage = (event) => {
const message = event.data;
if ("kind" in message) {
void start(message.runtime, message.module);
} else if (program === null) {
waiting.push(message);
} else {
handle(program, message);
}
};
}
/**
* @param {unknown} error
* @returns {string}
*/
function describe(error) {
return error instanceof Error ? (error.stack ?? error.message) : String(error);
}
serve(/** @type {Scope} */ (/** @type {unknown} */ (globalThis)));
@@ -0,0 +1,773 @@
// @ts-check
// Incari's storage worker (ADR 0011). The page keeps its file system in memory; this worker
// keeps the durable copy: in the origin private file system (OPFS) where the browser has it,
// written with synchronous access handles (which only workers get), or in IndexedDB where it
// doesn't (insecure origins, older browsers). It also caches the client jar.
//
// Runs as a classic worker created from a Blob URL (platform-web's BrowserStore), so the page needs
// no extra file. Messages, each answered with the same `id` except "apply" (fire and forget):
// {type: "open", id, root, lock, inPlace?} -> {id, backend, readOnly, entries, error?}
// {type: "apply", ops} -> {type: "applied", count, error?, failed}
// (failed: the paths not stored, which the page sends again
// whole; the batch's other changes are stored all the same)
// {type: "jar", id, url, key} -> {id, data?, cached, error?}
// {type: "forget", id, key} -> {id}
// {type: "read", id, path} -> {id, data: ArrayBuffer | null}
// {type: "list", id, path} -> {id, paths: string[]} (everything stored under a folder)
// {type: "stat", id, path} -> {id, entries} (as "open"'s, with sizes and no bytes)
// {type: "sync", id} -> {id} (once everything sent before it is stored)
// {type: "port", port} -> nothing; the port's messages are handled like the page's,
// in the same queue, and answered on it (ADR 0041)
// Messages are handled one at a time, in order, whichever port they come from.
//
// In-place files (ADR 0041): with OPFS, "open" lists the files `inPlace` describes (a world's
// region files) with their sizes and without their bytes ({stored: true}). The page reads one only
// when it opens it, and singleplayer's server in a worker reads and writes them where they are.
"use strict";
/**
* A change to the store: a folder, a file's size and some of its bytes, or nothing at a path.
* @typedef {{op: "mkdir", path: string, mtime: number}
* | {op: "write", path: string, size: number, at: number, data: Uint8Array<ArrayBuffer> | null, mtime: number}
* | {op: "delete", path: string}} Op
*/
/**
* A file or folder of the store, as the page loads it. A stored entry is an in-place file: its
* size, and no bytes.
* @typedef {{path: string, dir: boolean, mtime: number, data: ArrayBuffer | null, size?: number, stored?: boolean}} Entry
*/
/**
* Which files stay where they are, never loaded whole: those inside a folder named `within`
* (anywhere in the path) whose names end with one of `suffixes`.
* @typedef {{within: string, suffixes: string[]}} InPlace
*/
/**
* @param {InPlace | null} inPlace
* @param {string} path
*/
function isInPlace(inPlace, path) {
return inPlace !== null && path.includes(inPlace.within) && inPlace.suffixes.some((suffix) => path.endsWith(suffix));
}
/**
* @typedef {object} Backend
* @property {string} kind "opfs" or "indexeddb" (or "memory": nothing survives)
* @property {(root: string, inPlace: InPlace | null) => Promise<Entry[]>} load everything under a folder
* @property {(root: string) => Promise<Entry[]>} stat everything under a folder: sizes, no bytes
* @property {(ops: Op[]) => Promise<Applied>} apply
* @property {(key: string) => Promise<ArrayBuffer | null>} cached
* @property {(key: string, data: ArrayBuffer) => Promise<void>} cache replaces the whole cache
* @property {(key: string) => Promise<void>} forget
* @property {(path: string) => Promise<ArrayBuffer | null>} read one file
*/
/**
* What applying a batch did: the paths whose change wasn't stored, and why the first one wasn't.
* @typedef {{failed: string[], error: string | null}} Applied
*/
/**
* The paths a batch changes, each once: all of them failed when a batch is stored whole or not at all.
* @param {Op[]} ops
* @returns {string[]}
*/
function pathsOf(ops) {
return [...new Set(ops.map((op) => op.path))];
}
/**
* The parts of a synchronous access handle this worker uses (lib.dom doesn't declare it).
* @typedef {{
* truncate(size: number): void,
* write(data: ArrayBufferView, options: {at: number}): number,
* flush(): void,
* close(): void}} SyncHandle
*/
/**
* The parts of an OPFS directory handle this worker uses.
* @typedef {{
* getDirectoryHandle(name: string, options?: {create?: boolean}): Promise<DirectoryHandle>,
* getFileHandle(name: string, options?: {create?: boolean}): Promise<FileHandle>,
* removeEntry(name: string, options?: {recursive?: boolean}): Promise<void>,
* entries(): AsyncIterable<[string, DirectoryHandle | FileHandle]>,
* kind: "directory"}} DirectoryHandle
*/
/**
* @typedef {{
* getFile(): Promise<File>,
* createSyncAccessHandle?: () => Promise<SyncHandle>,
* createWritable?: (options?: {keepExistingData?: boolean}) => Promise<FileSystemWritableFileStream>,
* kind: "file"}} FileHandle
*/
/** Where the client jar is cached in OPFS: beside the file system's folder, never loaded with it. */
const CACHE_FOLDER = ".incari-cache";
/**
* Whether `error` is a DOMException (or error) of this name. By shape, not by class: the
* browser's DOMExceptions and a test's stand-ins come from different places.
* @param {unknown} error
* @param {string} name
*/
function isError(error, name) {
return typeof error === "object" && error !== null && "name" in error && error.name === name;
}
/** @param {unknown} error */
function describe(error) {
if (typeof error === "object" && error !== null && "name" in error && "message" in error) {
return `${String(error.name)}: ${String(error.message)}`;
}
return String(error);
}
/** @param {string} path */
function parts(path) {
return path.split("/").filter((part) => part.length > 0);
}
/**
* The store in the origin private file system: a folder per folder, a file per file, under the
* same paths as the page's (so "/incari/game/options.txt" is incari/game/options.txt there).
* @param {DirectoryHandle} root
* @returns {Backend}
*/
function opfsBackend(root) {
/**
* @param {string[]} names
* @param {boolean} create
* @returns {Promise<DirectoryHandle | null>}
*/
async function folder(names, create) {
let directory = root;
for (const name of names) {
try {
directory = await directory.getDirectoryHandle(name, { create });
} catch (error) {
if (create && isError(error, "TypeMismatchError")) {
// A file where a folder now is: the page's tree replaced it.
await directory.removeEntry(name);
directory = await directory.getDirectoryHandle(name, { create: true });
} else if (!create && (isError(error, "NotFoundError") || isError(error, "TypeMismatchError"))) {
return null;
} else {
throw error;
}
}
}
return directory;
}
/**
* @param {DirectoryHandle} directory
* @param {string} name
* @returns {Promise<FileHandle>}
*/
async function fileIn(directory, name) {
try {
return await directory.getFileHandle(name, { create: true });
} catch (error) {
if (!isError(error, "TypeMismatchError")) {
throw error;
}
await directory.removeEntry(name, { recursive: true });
return await directory.getFileHandle(name, { create: true });
}
}
/**
* Sets a file's size and writes bytes into it, a range at a time (a file's changes since the
* page's last flush can be several). A synchronous access handle writes in place; where there's
* none, a writable stream copies the file and swaps it in on close.
* @param {FileHandle} handle
* @param {number} size
* @param {{at: number, data: Uint8Array<ArrayBuffer> | null}[]} writes
*/
async function writeInto(handle, size, writes) {
if (handle.createSyncAccessHandle) {
const access = await handle.createSyncAccessHandle();
try {
access.truncate(size);
for (const { at, data } of writes) {
if (data && data.byteLength > 0) {
access.write(data, { at });
}
}
access.flush();
} finally {
access.close();
}
} else if (handle.createWritable) {
const stream = await handle.createWritable({ keepExistingData: true });
await stream.truncate(size);
for (const { at, data } of writes) {
if (data && data.byteLength > 0) {
await stream.write({ type: "write", position: at, data });
}
}
await stream.close();
} else {
throw new Error("This browser can't write to the origin private file system");
}
}
/**
* @param {DirectoryHandle} directory
* @param {string} path
* @param {Entry[]} out
* @param {(path: string) => boolean} storedOnly which files to list without their bytes
*/
async function walk(directory, path, out, storedOnly) {
for await (const [name, handle] of directory.entries()) {
const child = `${path}/${name}`;
if (handle.kind === "directory") {
out.push({ path: child, dir: true, mtime: 0, data: null });
await walk(handle, child, out, storedOnly);
} else {
const file = await handle.getFile();
if (storedOnly(child)) {
out.push({ path: child, dir: false, mtime: file.lastModified, data: null, size: file.size, stored: true });
} else {
out.push({ path: child, dir: false, mtime: file.lastModified, data: await file.arrayBuffer() });
}
}
}
}
/**
* @param {string} rootPath
* @param {(path: string) => boolean} storedOnly
*/
async function loadUnder(rootPath, storedOnly) {
const directory = await folder(parts(rootPath), false);
/** @type {Entry[]} */
const entries = [];
if (directory) {
await walk(directory, rootPath === "/" ? "" : rootPath, entries, storedOnly);
}
return entries;
}
/** @param {string} path */
async function readFile(path) {
const names = parts(path);
const name = names.pop();
const directory = await folder(names, false);
if (!directory || name === undefined) {
return null;
}
try {
const handle = await directory.getFileHandle(name);
return await (await handle.getFile()).arrayBuffer();
} catch (error) {
if (isError(error, "NotFoundError") || isError(error, "TypeMismatchError")) {
return null;
}
throw error;
}
}
return {
kind: "opfs",
load: (rootPath, inPlace) => loadUnder(rootPath, (path) => isInPlace(inPlace, path)),
stat: (rootPath) => loadUnder(rootPath, () => true),
async apply(ops) {
// Each change on its own: one that fails (a full disk, a file held open elsewhere) mustn't
// keep the rest of the batch from being stored. The page sends a failed path again, whole:
// its writes are only the bytes that changed, and a range lost here would leave the file
// damaged for good.
/** @type {Applied} */
const result = { failed: [], error: null };
for (let i = 0; i < ops.length; i++) {
const op = /** @type {Op} */ (ops[i]);
const names = parts(op.path);
try {
if (op.op === "mkdir") {
await folder(names, true);
} else if (op.op === "write") {
// The file's next writes in this batch go through the same handle.
const writes = [{ at: op.at, data: op.data }];
let size = op.size;
for (let next = ops[i + 1]; next?.op === "write" && next.path === op.path; next = ops[i + 1]) {
writes.push({ at: next.at, data: next.data });
size = next.size;
i++;
}
const name = names.pop();
const directory = await folder(names, true);
if (directory && name !== undefined) {
await writeInto(await fileIn(directory, name), size, writes);
}
} else {
const name = names.pop();
const directory = await folder(names, false);
if (directory && name !== undefined) {
try {
await directory.removeEntry(name, { recursive: true });
} catch (error) {
if (!isError(error, "NotFoundError")) {
throw error;
}
}
}
}
} catch (error) {
if (!result.failed.includes(op.path)) {
result.failed.push(op.path);
}
result.error ??= describe(error);
}
}
return result;
},
async cached(key) {
return readFile(`/${CACHE_FOLDER}/${key}`);
},
async cache(key, data) {
const directory = await folder([CACHE_FOLDER], true);
if (!directory) {
return;
}
// One version of each archive at a time: a new version's replaces the old one's.
/** @type {string[]} */
const old = [];
for await (const [name] of directory.entries()) {
if (name !== key && sameArchive(name, key)) {
old.push(name);
}
}
for (const name of old) {
await directory.removeEntry(name, { recursive: true });
}
const bytes = new Uint8Array(data);
await writeInto(await fileIn(directory, key), bytes.byteLength, [{ at: 0, data: bytes }]);
},
async forget(key) {
const directory = await folder([CACHE_FOLDER], false);
if (directory) {
try {
await directory.removeEntry(key);
} catch (error) {
if (!isError(error, "NotFoundError")) {
throw error;
}
}
}
},
read: readFile,
};
}
/**
* Whether two cache keys are versions of the same archive: the part before the first "-" names it
* ("client-26.3.jar", "pack-<hash>"), so caching the asset pack doesn't evict the client jar.
* @param {string} a
* @param {string} b
* @returns {boolean}
*/
function sameArchive(a, b) {
return a.split("-", 1)[0] === b.split("-", 1)[0];
}
/**
* @template T
* @param {IDBRequest<T>} request
* @returns {Promise<T>}
*/
function done(request) {
return new Promise((resolve, reject) => {
request.onsuccess = () => {
resolve(request.result);
};
request.onerror = () => {
reject(request.error ?? new Error("IndexedDB request failed"));
};
});
}
/**
* A stored value, of whatever type it was stored as.
* @param {IDBRequest} request
* @returns {Promise<unknown>}
*/
function value(request) {
return done(request);
}
/** @param {IDBTransaction} transaction */
function committed(transaction) {
return new Promise((resolve, reject) => {
transaction.oncomplete = () => {
resolve(undefined);
};
transaction.onerror = () => {
reject(transaction.error ?? new Error("IndexedDB transaction failed"));
};
transaction.onabort = () => {
reject(transaction.error ?? new Error("IndexedDB transaction aborted"));
};
});
}
/**
* The store in IndexedDB: a record per file or folder, keyed by path. Each batch of changes is
* one transaction, so it lands whole or not at all.
* @param {IDBFactory} factory
* @param {typeof IDBKeyRange} keyRange
* @returns {Promise<Backend>}
*/
async function indexedDbBackend(factory, keyRange) {
const open = factory.open("incari-storage", 1);
open.onupgradeneeded = () => {
open.result.createObjectStore("files", { keyPath: "path" });
open.result.createObjectStore("cache");
};
/** @type {IDBDatabase} */
const db = await done(open);
/** @param {string} path */
function below(path) {
return keyRange.bound(`${path}/`, `${path}/\uffff`);
}
/**
* @param {string} rootPath
* @returns {Promise<Entry[]>}
*/
async function loadAll(rootPath) {
const transaction = db.transaction("files", "readonly");
/** @type {Entry[]} */
const records = await done(transaction.objectStore("files").getAll(below(rootPath === "/" ? "" : rootPath)));
return records.map((record) => ({
path: record.path,
dir: record.dir,
mtime: record.mtime,
data: record.data,
}));
}
return {
kind: "indexeddb",
// Every file loaded whole: IndexedDB stores whole values, so nothing stays in place.
load: (rootPath) => loadAll(rootPath),
async stat(rootPath) {
return (await loadAll(rootPath)).map((entry) => ({
path: entry.path,
dir: entry.dir,
mtime: entry.mtime,
data: null,
size: entry.data ? entry.data.byteLength : 0,
stored: !entry.dir,
}));
},
async apply(ops) {
const transaction = db.transaction("files", "readwrite");
const finished = committed(transaction);
const files = transaction.objectStore("files");
for (const op of ops) {
if (op.op === "mkdir") {
files.put({ path: op.path, dir: true, mtime: op.mtime, data: null });
} else if (op.op === "write") {
let data;
if (op.at === 0 && (op.data?.byteLength ?? 0) === op.size) {
data = op.data ? op.data.slice().buffer : new ArrayBuffer(0);
} else {
// Part of a file: patch the stored copy (IndexedDB only stores whole values).
const stored = /** @type {Entry | undefined} */ (await value(files.get(op.path)));
const bytes = new Uint8Array(op.size);
if (stored?.data) {
bytes.set(new Uint8Array(stored.data, 0, Math.min(stored.data.byteLength, op.size)));
}
if (op.data) {
bytes.set(op.data.subarray(0, Math.max(0, op.size - op.at)), op.at);
}
data = bytes.buffer;
}
files.put({ path: op.path, dir: false, mtime: op.mtime, data });
} else {
files.delete(op.path);
files.delete(below(op.path));
}
}
try {
await finished;
} catch (error) {
// One transaction: none of it was stored.
return { failed: pathsOf(ops), error: describe(error) };
}
return { failed: [], error: null };
},
async cached(key) {
const data = /** @type {ArrayBuffer | undefined} */ (
await value(db.transaction("cache", "readonly").objectStore("cache").get(key))
);
return data ?? null;
},
async cache(key, data) {
const transaction = db.transaction("cache", "readwrite");
const finished = committed(transaction);
const store = transaction.objectStore("cache");
const keys = await done(store.getAllKeys());
for (const name of keys) {
if (typeof name === "string" && name !== key && sameArchive(name, key)) {
store.delete(name);
}
}
store.put(data, key);
await finished;
},
async forget(key) {
const transaction = db.transaction("cache", "readwrite");
const finished = committed(transaction);
transaction.objectStore("cache").delete(key);
await finished;
},
async read(path) {
const record = /** @type {Entry | undefined} */ (
await value(db.transaction("files", "readonly").objectStore("files").get(path))
);
return record && !record.dir ? record.data : null;
},
};
}
/** @returns {Backend} */
function memoryBackend() {
return {
kind: "memory",
load: () => Promise.resolve([]),
stat: () => Promise.resolve([]),
apply: () => Promise.resolve({ failed: [], error: null }),
cached: () => Promise.resolve(null),
cache: () => Promise.resolve(),
forget: () => Promise.resolve(),
read: () => Promise.resolve(null),
};
}
/**
* The best store this browser offers: OPFS, else IndexedDB, else none.
* @param {Scope} scope
* @param {string[]} problems where to say why a better one wasn't used
* @returns {Promise<Backend>}
*/
async function chooseBackend(scope, problems) {
try {
const root = /** @type {DirectoryHandle} */ (/** @type {unknown} */ (await scope.navigator.storage.getDirectory()));
return opfsBackend(root);
} catch (error) {
problems.push(`no origin private file system (${describe(error)})`);
}
if (scope.indexedDB && scope.IDBKeyRange) {
try {
return await indexedDbBackend(scope.indexedDB, scope.IDBKeyRange);
} catch (error) {
problems.push(`no IndexedDB (${describe(error)})`);
}
}
return memoryBackend();
}
/**
* Takes the storage lock if no other tab holds it, and keeps it for the worker's life: two tabs
* writing the same files would each overwrite the other's changes.
* @param {Navigator} navigator
* @param {string} name
* @returns {Promise<boolean>}
*/
function takeLock(navigator, name) {
if (!("locks" in navigator)) {
return Promise.resolve(true);
}
return new Promise((resolve) => {
navigator.locks
.request(name, { ifAvailable: true }, (lock) => {
resolve(lock !== null);
// Held until the worker ends.
return lock ? new Promise(() => undefined) : undefined;
})
.catch(() => {
resolve(true);
});
});
}
/**
* Where a message came from, and where its answer goes: the page (the worker's own scope) or a
* port another worker was given (singleplayer's server, ADR 0041).
* @typedef {{postMessage(message: unknown, transfer: Transferable[]): void}} Sender
*/
/**
* @typedef {{
* postMessage(message: unknown, transfer: Transferable[]): void,
* onmessage: ((event: MessageEvent<Record<string, unknown>>) => void) | null,
* navigator: Navigator,
* indexedDB?: IDBFactory,
* IDBKeyRange?: typeof IDBKeyRange,
* fetch: typeof fetch}} Scope
*/
/**
* Handles the page's messages on `scope` (the worker's global scope; a stand-in in tests), and
* those of the ports it's given.
* @param {Scope} scope
*/
function serve(scope) {
/** @type {Backend} */
let backend = memoryBackend();
let readOnly = true;
/** @type {Promise<unknown>} */
let queue = Promise.resolve();
/**
* @param {Record<string, unknown>} message
* @param {Sender} from
* @returns {Promise<void>}
*/
async function handle(message, from) {
const id = message.id;
switch (message.type) {
case "open": {
/** @type {string[]} */
const problems = [];
const locked = await takeLock(scope.navigator, String(message.lock));
backend = await chooseBackend(scope, problems);
readOnly = !locked || backend.kind === "memory";
const inPlace = /** @type {InPlace | undefined} */ (message.inPlace) ?? null;
/** @type {Entry[]} */
let entries;
try {
entries = await backend.load(String(message.root), inPlace);
} catch (error) {
problems.push(`couldn't load (${describe(error)})`);
entries = [];
}
/** @type {Transferable[]} */
const buffers = entries.flatMap((entry) => (entry.data ? [entry.data] : []));
from.postMessage(
{ id, backend: backend.kind, readOnly, locked, entries, problems: problems.join("; ") },
buffers,
);
return;
}
case "apply": {
const ops = /** @type {Op[]} */ (message.ops);
if (readOnly) {
return;
}
/** @type {Applied} */
let applied;
try {
applied = await backend.apply(ops);
} catch (error) {
applied = { failed: pathsOf(ops), error: describe(error) };
}
if (applied.error === null) {
from.postMessage({ type: "applied", count: ops.length, failed: [] }, []);
} else {
from.postMessage({ type: "applied", count: ops.length, error: applied.error, failed: applied.failed }, []);
}
return;
}
case "jar": {
const key = String(message.key);
try {
let data = await backend.cached(key);
const cached = data !== null;
if (!data) {
const response = await scope.fetch(String(message.url));
if (!response.ok) {
throw new Error(`HTTP ${String(response.status)}`);
}
data = await response.arrayBuffer();
if (!readOnly) {
await backend.cache(key, data);
}
}
from.postMessage({ id, data, cached }, [data]);
} catch (error) {
from.postMessage({ id, error: describe(error) }, []);
}
return;
}
case "forget": {
if (!readOnly) {
await backend.forget(String(message.key));
}
from.postMessage({ id }, []);
return;
}
case "read": {
/** @type {ArrayBuffer | null} */
let data;
try {
data = await backend.read(String(message.path));
} catch {
data = null;
}
from.postMessage({ id, data }, data ? [data] : []);
return;
}
case "list": {
/** @type {string[]} */
let paths;
try {
paths = (await backend.load(String(message.path), null)).map((entry) => entry.path).sort();
} catch {
paths = [];
}
from.postMessage({ id, paths }, []);
return;
}
case "stat": {
/** @type {Entry[]} */
let entries;
try {
entries = await backend.stat(String(message.path));
} catch {
entries = [];
}
from.postMessage({ id, entries }, []);
return;
}
case "sync": {
// Messages are handled in order: everything sent before this is stored by now.
from.postMessage({ id }, []);
return;
}
case "port": {
const port = /** @type {MessagePort} */ (message.port);
port.onmessage = (/** @type {MessageEvent<Record<string, unknown>>} */ event) => {
enqueue(event.data, port);
};
return;
}
default:
from.postMessage({ id, error: `unknown message ${String(message.type)}` }, []);
}
}
/**
* @param {Record<string, unknown>} message
* @param {Sender} from
*/
function enqueue(message, from) {
queue = queue.then(
() => handle(message, from),
() => handle(message, from),
);
}
scope.onmessage = (event) => {
enqueue(event.data, scope);
};
}
serve(/** @type {Scope} */ (/** @type {unknown} */ (globalThis)));
@@ -0,0 +1,31 @@
package incari.platform.web;
import static com.tngtech.archunit.lang.syntax.ArchRuleDefinition.classes;
import com.tngtech.archunit.core.importer.ImportOption;
import com.tngtech.archunit.junit.AnalyzeClasses;
import com.tngtech.archunit.junit.ArchTest;
import com.tngtech.archunit.lang.ArchRule;
/**
* The browser platform talks to the page through TeaVM's JavaScript interop and to the game
* only through platform-api. Of TeaVM's runtime it uses only the file system interface its
* {@code java.io} reads through ({@code org.teavm.runtime.fs}), not TeaVM's own file systems.
*/
@AnalyzeClasses(packages = "incari.platform.web", importOptions = ImportOption.DoNotIncludeTests.class)
class BoundaryTest {
@ArchTest
static final ArchRule onlyPlatformApiAndJso = classes()
.should()
.onlyDependOnClassesThat()
.resideInAnyPackage(
"java..",
"org.jspecify..",
"org.teavm.jso..",
"org.teavm.interop..",
"org.teavm.runtime.fs",
"incari.platform.api..",
"incari.platform.web..")
.allowEmptyShould(true);
}
@@ -0,0 +1,63 @@
package incari.platform.web;
import static org.assertj.core.api.Assertions.assertThat;
import org.junit.jupiter.api.Test;
/** The canvas's size in CSS and device pixels, as resizes, zoom and density changes report it. */
class CanvasSizeTest {
private static final CanvasSize HD = new CanvasSize(1280, 720, 1280, 720, 1);
@Test
void theExactDevicePixelSizeWinsWhereTheBrowserHasOne() {
// 1.25 density (a 125% Windows scale): 1001.6 device pixels, which the browser rounds its way.
CanvasSize size = CanvasSize.measure(801.28, 600, 1001, 750, 1.25, HD);
assertThat(size).isEqualTo(new CanvasSize(801, 600, 1001, 750, 1.25));
}
@Test
void withoutDevicePixelsTheSizeIsTheCssSizeTimesTheDensity() {
assertThat(CanvasSize.measure(640, 360, 0, 0, 2, HD)).isEqualTo(new CanvasSize(640, 360, 1280, 720, 2));
assertThat(CanvasSize.measure(333.5, 200.25, 0, 0, 1.5, HD)).isEqualTo(new CanvasSize(334, 200, 500, 300, 1.5));
}
@Test
void aDensityChangeAloneChangesOnlyThePixels() {
// Moving the window to a denser display, or zooming the page: the same CSS box.
CanvasSize zoomed = CanvasSize.measure(1280, 720, 0, 0, 1.5, HD);
assertThat(zoomed.width()).isEqualTo(1280);
assertThat(zoomed.pixelWidth()).isEqualTo(1920);
assertThat(zoomed.density()).isEqualTo(1.5);
}
@Test
void anUnchangedMeasurementKeepsTheExactPixels() {
// 801 x 1.25 is 1001.25, but the browser said 1002: the page snapped the canvas to pixels its way.
CanvasSize exact = new CanvasSize(801, 600, 1002, 750, 1.25);
assertThat(CanvasSize.measure(801, 600, 0, 0, 1.25, exact)).isEqualTo(exact);
}
@Test
void anEmptyOrHiddenCanvasKeepsTheSizeBefore() {
assertThat(CanvasSize.measure(0, 600, 0, 0, 1, HD)).isSameAs(HD);
assertThat(CanvasSize.measure(800, 0, 0, 0, 1, HD)).isSameAs(HD);
assertThat(CanvasSize.measure(Double.NaN, 600, 0, 0, 1, HD)).isSameAs(HD);
}
@Test
void aMissingDensityCountsAsOne() {
assertThat(CanvasSize.measure(800, 600, 0, 0, 0, HD)).isEqualTo(new CanvasSize(800, 600, 800, 600, 1));
}
@Test
void tinySizesAreAtLeastOnePixel() {
assertThat(CanvasSize.measure(0.2, 0.2, 0, 0, 1, HD)).isEqualTo(new CanvasSize(1, 1, 1, 1, 1));
}
@Test
void theInitialSizeComesFromTheFirstMeasurement() {
assertThat(CanvasSize.initial(1280, 720, 2)).isEqualTo(new CanvasSize(1280, 720, 2560, 1440, 2));
assertThat(CanvasSize.initial(0, 0, 2)).isEqualTo(new CanvasSize(1, 1, 1, 1, 2));
}
}
@@ -0,0 +1,835 @@
package incari.platform.web;
import static incari.platform.web.DomEventQueue.DOM_ALT;
import static incari.platform.web.DomEventQueue.DOM_ALT_GRAPH;
import static incari.platform.web.DomEventQueue.DOM_CAPS_LOCK;
import static incari.platform.web.DomEventQueue.DOM_CTRL;
import static incari.platform.web.DomEventQueue.DOM_META;
import static incari.platform.web.DomEventQueue.DOM_SHIFT;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.input.KeyAction;
import incari.platform.api.input.KeyModifiers;
import incari.platform.api.input.Scancodes;
import incari.platform.api.window.PlatformEventListener;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;
import org.junit.jupiter.api.Test;
class DomEventQueueTest {
private final FakeSurface surface = new FakeSurface();
private final DomEventQueue queue =
new DomEventQueue(surface, new CanvasSize(800, 600, 1600, 1200, 2), false, true);
// --- Keys ---
@Test
void keyPressThenRelease() {
keyDown("KeyW", "w", 0);
keyUp("KeyW", "w", 0);
assertThat(drain()).containsExactly("key 26 119 0 PRESS", "key 26 119 0 RELEASE");
}
// --- F+digit function keys (Chromebooks) ---
@Test
void withoutChordsFIsReportedAtOnce() {
DomEventQueue plain = new DomEventQueue(surface, new CanvasSize(800, 600, 800, 600, 1), false, false);
plain.event("keydown", "KeyF", "f", 0, 0, 0, 0, 0, 0);
assertThat(drain(plain)).containsExactly("key 9 102 0 PRESS");
plain.event("keydown", "Digit3", "3", 0, 0, 0, 0, 0, 0);
plain.event("keyup", "Digit3", "3", 0, 0, 0, 0, 0, 0);
plain.event("keyup", "KeyF", "f", 0, 0, 0, 0, 0, 0);
assertThat(drain(plain)).containsExactly("key 32 51 0 PRESS", "key 32 51 0 RELEASE", "key 9 102 0 RELEASE");
}
// --- Lost graphics ---
@Test
void lostGraphicsKeepTheWindowMinimized() {
queue.event("graphics", "", "", 1, 0, 0, 0, 0, 0);
queue.event("visibility", "", "", 1, 0, 0, 0, 0, 0);
queue.event("visibility", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain())
.filteredOn(e -> e.startsWith("minimized"))
.containsExactly("minimized true", "minimized true", "minimized true");
}
@Test
void fThenDigitIsAFunctionKey() {
keyDown("KeyF", "f", 0);
keyDown("Digit3", "3", 0);
keyUp("Digit3", "3", 0);
keyUp("KeyF", "f", 0);
assertThat(drain()).containsExactly("key 60 1073741884 0 PRESS", "key 60 1073741884 0 RELEASE");
}
@Test
void fPlusDigitPlusAnotherKeyKeepsTheFunctionKeyHeld() {
keyDown("KeyF", "f", 0);
keyDown("Digit3", "3", 0);
assertThat(queue.isKeyDown(Scancodes.F1 + 2)).isTrue();
keyDown("KeyH", "h", 0);
keyUp("KeyH", "h", 0);
keyUp("Digit3", "3", 0);
assertThat(queue.isKeyDown(Scancodes.F1 + 2)).isFalse();
assertThat(drain()).hasSize(4).first().isEqualTo("key 60 1073741884 0 PRESS");
}
@Test
void zeroIsF10() {
keyDown("KeyF", "f", 0);
keyDown("Digit0", "0", 0);
assertThat(drain()).containsExactly("key 67 1073741891 0 PRESS");
}
@Test
void fAloneIsReportedWhenReleased() {
keyDown("KeyF", "f", 0);
assertThat(drain()).isEmpty();
keyUp("KeyF", "f", 0);
assertThat(drain()).containsExactly("key 9 102 0 PRESS", "key 9 102 0 RELEASE");
}
@Test
void fIsReportedFirstWhenAnotherKeyFollows() {
keyDown("KeyF", "f", 0);
keyDown("KeyW", "w", 0);
assertThat(drain()).containsExactly("key 9 102 0 PRESS", "key 26 119 0 PRESS");
}
@Test
void digitsAloneAreDigits() {
keyDown("Digit3", "3", 0);
assertThat(drain()).containsExactly("key 32 51 0 PRESS");
}
@Test
void noChordWhileTyping() {
queue.setTextInput(true);
keyDown("KeyF", "f", 0);
keyDown("Digit3", "3", 0);
assertThat(drain()).contains("key 9 102 0 PRESS", "key 32 51 0 PRESS");
}
@Test
void focusLossReleasesAChordedKey() {
keyDown("KeyF", "f", 0);
keyDown("Digit5", "5", 0);
queue.event("blur", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).contains("key 62 1073741886 0 PRESS", "key 62 1073741886 0 RELEASE");
}
@Test
void repeatsAreReportedAsRepeats() {
keyDown("KeyW", "w", 0);
queue.event("keydown", "KeyW", "w", 1, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("key 26 119 0 PRESS", "key 26 119 0 REPEAT");
}
@Test
void releasesWithoutAPressAreDropped() {
keyUp("KeyW", "w", 0);
assertThat(drain()).isEmpty();
}
@Test
void keysKnownNeitherByPlaceNorMeaningAreDropped() {
// The game's unbound binds all sit on the unknown key: one such press would fire them all.
keyDown("", "Unidentified", 0);
keyUp("", "Unidentified", 0);
assertThat(drain()).isEmpty();
}
@Test
void codelessKeysWithAMeaningStay() {
// A virtual keyboard's Backspace comes without a code; text fields go by its keycode.
keyDown("", "Backspace", 0);
assertThat(drain()).containsExactly("key 0 8 0 PRESS");
}
@Test
void keyStateFollowsTheEvents() {
keyDown("KeyW", "w", 0);
assertThat(queue.isKeyDown(Scancodes.W)).isTrue();
keyUp("KeyW", "w", 0);
assertThat(queue.isKeyDown(Scancodes.W)).isFalse();
assertThat(queue.isKeyDown(-1)).isFalse();
assertThat(queue.isKeyDown(Scancodes.COUNT)).isFalse();
}
@Test
void textArrivesOnlyWhileTextInputIsOn() {
keyDown("KeyT", "t", 0);
queue.setTextInput(true);
keyDown("KeyH", "h", 0);
assertThat(drain()).containsExactly("key 23 116 0 PRESS", "key 11 104 0 PRESS", "text h");
}
@Test
void shortcutsTypeNothingButAltGrDoes() {
queue.setTextInput(true);
keyDown("ControlLeft", "Control", DOM_CTRL);
keyDown("KeyC", "c", DOM_CTRL);
// AltGr+Q on a German keyboard in Windows: Ctrl and Alt both held, and "@" typed.
keyDown("KeyQ", "@", DOM_CTRL | DOM_ALT | DOM_ALT_GRAPH);
keyDown("Enter", "Enter", 0);
assertThat(drain()).filteredOn(e -> e.startsWith("text")).containsExactly("text @");
}
@Test
void composingKeysBelongToTheInputMethod() {
queue.setTextInput(true);
boolean cancelled = queue.event("keydown", "KeyA", "Process", 0, 1, 0, 0, 0, 0);
assertThat(cancelled).isFalse();
assertThat(drain()).isEmpty();
assertThat(queue.isKeyDown(Scancodes.A)).isFalse();
}
@Test
void modifiersSayWhichSide() {
keyDown("ShiftRight", "Shift", DOM_SHIFT);
keyDown("KeyA", "A", DOM_SHIFT | DOM_CAPS_LOCK);
assertThat(queue.modifiers()).isEqualTo(KeyModifiers.RIGHT_SHIFT | KeyModifiers.CAPS_LOCK);
keyDown("ShiftLeft", "Shift", DOM_SHIFT);
assertThat(queue.modifiers()).isEqualTo(KeyModifiers.LEFT_SHIFT | KeyModifiers.RIGHT_SHIFT);
assertThat(drain())
.containsExactly("key 229 1073742053 2 PRESS", "key 4 97 8194 PRESS", "key 225 1073742049 3 PRESS");
}
@Test
void modifiersOfAnUnseenKeyAreTheLeftOnes() {
keyDown("KeyA", "a", DOM_CTRL | DOM_ALT | DOM_META);
assertThat(queue.modifiers())
.isEqualTo(KeyModifiers.LEFT_CTRL | KeyModifiers.LEFT_ALT | KeyModifiers.LEFT_SUPER);
}
@Test
void browserShortcutsTheGameCantUseKeepTheirDefault() {
assertThat(DomEventQueue.consumesKey("Tab", "", 0)).isTrue();
assertThat(DomEventQueue.consumesKey("F5", "", 0)).isTrue();
assertThat(DomEventQueue.consumesKey("F11", "", 0)).isTrue();
assertThat(DomEventQueue.consumesKey("KeyV", "", 0)).isTrue();
assertThat(DomEventQueue.consumesKey("F12", "", 0)).isFalse();
assertThat(DomEventQueue.consumesKey("KeyV", "", DOM_CTRL)).isFalse();
assertThat(DomEventQueue.consumesKey("KeyV", "", DOM_META)).isFalse();
assertThat(DomEventQueue.consumesKey("KeyI", "", DOM_CTRL | DOM_SHIFT)).isFalse();
assertThat(DomEventQueue.consumesKey("KeyI", "", DOM_CTRL)).isTrue();
}
@Test
void deadKeysKeepTheirDefaultForTheComposition() {
assertThat(DomEventQueue.consumesKey("BracketLeft", "Dead", 0)).isFalse();
assertThat(DomEventQueue.consumesKey("BracketLeft", "ü", 0)).isTrue();
// The game still sees the key, as SDL reports a dead key's press.
assertThat(keyDown("BracketLeft", "Dead", 0)).isFalse();
assertThat(drain()).containsExactly("key 47 " + (47 | DomKeys.NON_PRINTABLE) + " 0 PRESS");
}
@Test
void fullscreenLocksAreKeptForTheGame() {
// Keyboard Lock sends these to the page in fullscreen; the page must cancel them too.
for (String code : List.of("KeyW", "KeyT", "KeyN", "KeyQ", "Digit1", "Escape")) {
assertThat(DomEventQueue.consumesKey(code, "", DOM_CTRL)).as(code).isTrue();
}
}
@Test
void copiedTextReadsBack() {
queue.copied("copied");
assertThat(queue.lastPaste()).isEqualTo("copied");
queue.event("paste", "pasted later", "", 0, 0, 0, 0, 0, 0);
assertThat(queue.lastPaste()).isEqualTo("pasted later");
}
// --- Input methods ---
@Test
void aCompositionIsShownThenCommitted() {
queue.setTextInput(true);
queue.event("compose", "に", "", 1, 0, 0, 0, 0, 0);
queue.event("compose", "にほ", "", 2, 0, 0, 0, 0, 0);
queue.event("commit", "日本", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("editing 'に' 1 0", "editing 'にほ' 2 0", "editing '' 0 0", "text 日本");
}
@Test
void aCancelledCompositionIsCleared() {
queue.setTextInput(true);
queue.event("compose", "´", "", 1, 0, 0, 0, 0, 0);
queue.event("compose", "", "", 0, 0, 0, 0, 0, 0);
queue.event("compose", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("editing '´' 1 0", "editing '' 0 0");
}
@Test
void compositionCursorsStayInsideTheText() {
queue.setTextInput(true);
queue.event("compose", "ab", "", 5, 9, 0, 0, 0, 0);
queue.event("compose", "ab", "", 0, 9, 0, 0, 0, 0);
assertThat(drain()).containsExactly("editing 'ab' 2 0", "editing 'ab' 0 2");
}
@Test
void textWithoutKeysIsTyped() {
// A touchscreen keyboard or voice input: text with no key event the page could cancel.
queue.setTextInput(true);
queue.event("commit", "hi\n\tthere", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("text hithere");
}
@Test
void compositionsOutsideTextInputAreIgnored() {
queue.event("compose", "a", "", 1, 0, 0, 0, 0, 0);
queue.event("commit", "a", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).isEmpty();
}
@Test
void stoppingTextInputEndsTheComposition() {
queue.setTextInput(true);
queue.event("compose", "a", "", 1, 0, 0, 0, 0, 0);
queue.setTextInput(false);
queue.event("commit", "a", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("editing 'a' 1 0");
}
// --- Key names ---
@Test
void theKeyboardMapNamesKeys() {
// AZERTY: the key right of Tab types "a", the next "z".
queue.event("keymap", "Digit1 &\nKeyQ a\nKeyW z\nSemicolon m\nSpace \nNumpad1 1", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("keymap");
assertThat(queue.keyName(Scancodes.Q)).isEqualTo("a");
assertThat(queue.keyName(Scancodes.W)).isEqualTo("z");
assertThat(queue.keyName(51)).isEqualTo("m");
assertThat(queue.keyName(Scancodes.DIGIT_1)).isEqualTo("&");
// Keys whose names don't depend on the layout are the game's to name.
assertThat(queue.keyName(Scancodes.SPACE)).isNull();
assertThat(queue.keyName(89)).isNull();
assertThat(queue.keyName(Scancodes.F1)).isNull();
assertThat(queue.keyName(0)).isNull();
assertThat(queue.keyName(Scancodes.COUNT)).isNull();
}
@Test
void anUnchangedKeyboardMapIsntAnnounced() {
queue.event("keymap", "KeyQ a", "", 0, 0, 0, 0, 0, 0);
drain();
queue.event("keymap", "KeyQ a", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).isEmpty();
queue.event("keymap", "KeyQ q", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("keymap");
}
@Test
void theKeyboardMapGivesShiftedKeysTheirKeycode() {
// German: the key right of 0 types "ß", and "?" with Shift.
queue.event("keymap", "Minus ß", "", 0, 0, 0, 0, 0, 0);
drain();
keyDown("Minus", "?", DOM_SHIFT);
assertThat(drain()).containsExactly("key 45 223 " + KeyModifiers.LEFT_SHIFT + " PRESS");
}
@Test
void withoutAKeyboardMapNamesAreLearnedFromTyping() {
keyDown("KeyQ", "a", 0);
keyDown("KeyW", "Z", DOM_SHIFT);
keyDown("KeyE", "E", DOM_CAPS_LOCK);
keyDown("Space", " ", 0);
keyDown("Numpad1", "1", DOM_CAPS_LOCK);
assertThat(queue.keyName(Scancodes.Q)).isEqualTo("a");
// Shift changes what a key types, not its name: the key keeps its US name until it types
// unshifted.
assertThat(queue.keyName(Scancodes.W)).isEqualTo("w");
assertThat(queue.keyName(8)).isEqualTo("e");
assertThat(queue.keyName(Scancodes.SPACE)).isNull();
assertThat(queue.keyName(89)).isNull();
assertThat(drain()).doesNotContain("keymap");
// A key that types something new: the player switched layouts.
keyDown("KeyQ", "q", 0);
assertThat(drain()).containsExactly("keymap", "key 20 113 0 PRESS");
}
@Test
void theKeyboardMapWinsOverTyping() {
queue.event("keymap", "KeyQ a", "", 0, 0, 0, 0, 0, 0);
keyDown("KeyQ", "q", 0);
assertThat(queue.keyName(Scancodes.Q)).isEqualTo("a");
assertThat(drain()).containsExactly("keymap", "key 20 113 0 PRESS");
}
// --- Files ---
@Test
void droppedFilesReachTheGame() {
queue.event("drop", "/incari/dropped/1/pack.zip\n/incari/dropped/1/Folder", "", 0, 0, 0, 0, 0, 0);
queue.event("drop", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("files [/incari/dropped/1/pack.zip, /incari/dropped/1/Folder]");
}
@Test
void aDropSurvivesAFlush() {
queue.event("drop", "/incari/dropped/1/pack.zip", "", 0, 0, 0, 0, 0, 0);
keyDown("KeyW", "w", 0);
queue.flushInput();
assertThat(drain()).containsExactly("files [/incari/dropped/1/pack.zip]");
}
// --- Visibility ---
@Test
void hidingThePageReleasesEverythingAndLosesFocus() {
keyDown("KeyW", "w", 0);
queue.event("visibility", "", "", 1, 0, 0, 0, 0, 0);
assertThat(drain())
.containsExactly("key 26 119 0 PRESS", "key 26 119 0 RELEASE", "focus false", "minimized true");
assertThat(queue.isKeyDown(Scancodes.W)).isFalse();
}
@Test
void hidingAfterBlurDoesntBlurTwice() {
queue.event("blur", "", "", 0, 0, 0, 0, 0, 0);
queue.event("visibility", "", "", 1, 0, 0, 0, 0, 0);
queue.event("visibility", "", "", 0, 0, 0, 0, 0, 0);
queue.event("focus", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("focus false", "minimized true", "minimized false", "focus true");
}
@Test
void pasteTextIsThereWhenTheGameHandlesCtrlV() {
// The page sends the keydown, then (because it wasn't cancelled) the paste event; the
// game reads the clipboard only when it handles the key, on its next poll.
boolean cancelled = keyDown("KeyV", "v", DOM_CTRL);
queue.event("paste", "pasted", "", 0, 0, 0, 0, 0, 0);
assertThat(cancelled).isFalse();
var seen = new ArrayList<String>();
queue.drainTo(new PlatformEventListener() {
@Override
public void key(int scancode, int keyCode, int modifiers, KeyAction action) {
seen.add(keyCode + " " + queue.lastPaste());
}
});
assertThat(seen).containsExactly("118 pasted");
}
@Test
void blurReleasesEverythingHeld() {
keyDown("KeyW", "w", 0);
queue.event("down", "", "", 0, 0, 0, 0, 0, 0);
drain();
queue.event("blur", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("key 26 119 0 RELEASE", "button 1 false 0", "focus false");
assertThat(queue.isKeyDown(Scancodes.W)).isFalse();
// The real releases, if they come, are no longer news.
keyUp("KeyW", "w", 0);
queue.event("up", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).isEmpty();
}
@Test
void commandReleasesKeysOnMac() {
DomEventQueue mac = new DomEventQueue(surface, new CanvasSize(800, 600, 800, 600, 1), true, true);
mac.event("keydown", "MetaLeft", "Meta", 0, 0, 0, 0, 0, DOM_META);
mac.event("keydown", "KeyC", "c", 0, 0, 0, 0, 0, DOM_META);
mac.event("keyup", "MetaLeft", "Meta", 0, 0, 0, 0, 0, 0);
assertThat(drain(mac))
.containsExactly(
"key 227 1073742051 1024 PRESS",
"key 6 99 1024 PRESS",
"key 6 99 0 RELEASE",
"key 227 1073742051 0 RELEASE");
assertThat(mac.isKeyDown(6)).isFalse();
}
// --- Mouse ---
@Test
void buttonsAreNumberedFromOne() {
queue.event("down", "", "", 2, 0, 0, 0, 0, DOM_SHIFT);
queue.event("up", "", "", 2, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("button 3 true 1", "button 3 false 0");
}
@Test
void releasesOfPressesOutsideTheCanvasAreDropped() {
boolean cancelled = queue.event("up", "", "", 0, 0, 0, 0, 0, 0);
assertThat(cancelled).isFalse();
assertThat(drain()).isEmpty();
}
@Test
void releasesOfPressesOnTheCanvasAreCancelled() {
// Cancelling the release stops the back button from leaving the page.
queue.event("down", "", "", 3, 0, 0, 0, 0, 0);
assertThat(queue.event("up", "", "", 3, 0, 0, 0, 0, 0)).isTrue();
assertThat(drain()).containsExactly("button 4 true 0", "button 4 false 0");
}
@Test
void movesBetweenFramesMerge() {
move(10, 20, 1, 2);
move(12, 25, 2, 5);
queue.event("down", "", "", 0, 0, 0, 0, 0, 0);
move(13, 25, 1, 0);
assertThat(drain()).containsExactly("move 12.0 25.0 3.0 7.0", "button 1 true 0", "move 13.0 25.0 1.0 0.0");
assertThat(queue.cursorX()).isEqualTo(13);
assertThat(queue.cursorY()).isEqualTo(25);
}
@Test
void pointerLockKeepsThePositionAndReportsMotion() {
move(100, 50, 0, 0);
queue.setRelativeMouseMode(true);
assertThat(surface.lockRequests).containsExactly(true);
// Until the lock is granted the cursor is free, and its motion mustn't turn the camera.
move(110, 50, 10, 0);
lock(true);
move(100, 50, 7, -3);
assertThat(drain()).containsExactly("move 110.0 50.0 7.0 -3.0");
assertThat(queue.cursorX()).isEqualTo(110);
}
@Test
void escapeOutOfPointerLockReachesTheGame() {
queue.setRelativeMouseMode(true);
lock(true);
drain();
// The browser takes the Escape that leaves the lock; the game gets one in its place.
lock(false);
assertThat(drain()).containsExactly("key 41 27 0 PRESS", "key 41 27 0 RELEASE");
}
@Test
void aRealEscapeIsNotDoubled() {
queue.setRelativeMouseMode(true);
lock(true);
keyDown("Escape", "Escape", 0);
lock(false);
assertThat(drain()).containsExactly("key 41 27 0 PRESS");
}
@Test
void losingTheLockWithFocusMakesNoEscape() {
queue.setRelativeMouseMode(true);
lock(true);
lock(false);
queue.event("blur", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain()).containsExactly("focus false");
}
@Test
void releasingTheMouseMakesNoEscape() {
queue.setRelativeMouseMode(true);
lock(true);
queue.setRelativeMouseMode(false);
lock(false);
assertThat(drain()).isEmpty();
assertThat(surface.lockRequests).containsExactly(true, false);
}
@Test
void wantingTheMouseBackBeforeTheLockEndsMakesNoEscape() {
queue.setRelativeMouseMode(true);
lock(true);
drain();
// A death screen opens and a respawn closes it before the page has left the lock.
queue.setRelativeMouseMode(false);
queue.setRelativeMouseMode(true);
lock(false);
assertThat(drain()).isEmpty();
assertThat(surface.lockRequests).containsExactly(true, false, true);
lock(true);
// The player's own Escape afterwards still reaches the game.
lock(false);
assertThat(drain()).containsExactly("key 41 27 0 PRESS", "key 41 27 0 RELEASE");
}
@Test
void aClickTakesTheLockBack() {
queue.setRelativeMouseMode(true);
lock(true);
lock(false);
drain();
// Asking again without a click would fail, so the queue doesn't.
queue.setRelativeMouseMode(true);
assertThat(surface.lockRequests).containsExactly(true);
// The click that takes it back is the lock's, not the game's.
assertThat(queue.event("down", "", "", 0, 0, 0, 0, 0, 0)).isTrue();
queue.event("up", "", "", 0, 0, 0, 0, 0, 0);
assertThat(surface.lockRequests).containsExactly(true, true);
assertThat(drain()).isEmpty();
}
@Test
void aLockGrantedAfterTheGameLetGoIsLeft() {
queue.setRelativeMouseMode(true);
queue.setRelativeMouseMode(false);
lock(true);
assertThat(surface.lockRequests).containsExactly(true, false);
}
// --- Wheel ---
@Test
void wheelNotchesAreOneEach() {
// Chrome: 100 pixels a notch at 100% zoom, and wheelDelta 120.
assertThat(DomEventQueue.wheelSteps(100, 0, 0)).isEqualTo(1);
assertThat(DomEventQueue.wheelSteps(50, 0, 120)).isEqualTo(1);
// Firefox: 3 lines a notch.
assertThat(DomEventQueue.wheelSteps(3, 1, 0)).isEqualTo(1);
assertThat(DomEventQueue.wheelSteps(1, 2, 0)).isEqualTo(1);
}
@Test
void wheelPointsUpAndRight() {
// A notch toward the player (DOM deltaY positive), then one right.
queue.event("wheel", "", "", 0, 100, 0, 0, -120, 0);
drain();
queue.event("wheel", "", "", 3, 0, 1, 0, 0, 0);
assertThat(drain()).containsExactly("wheel 1.0 0.0 0");
queue.event("wheel", "", "", 0, -100, 0, 0, 120, 0);
assertThat(drain()).containsExactly("wheel 0.0 1.0 0");
}
@Test
void wheelTurnsBetweenFramesAddUp() {
queue.event("wheel", "", "", 0, -100, 0, 0, 120, 0);
queue.event("wheel", "", "", 0, -100, 0, 0, 120, 0);
assertThat(drain()).containsExactly("wheel 0.0 2.0 0");
}
@Test
void shiftWheelStaysVertical() {
// Chrome sends Shift+wheel-down as scrolling right.
queue.event("wheel", "", "", 100, 0, 0, -120, 0, DOM_SHIFT);
assertThat(drain()).containsExactly("wheel 0.0 -1.0 1");
}
// --- Canvas size ---
@Test
void resizesAreReportedOnTheNextPoll() {
queue.event("resize", "", "", 1000.4, 500, 2001, 1000, 2, 0);
assertThat(queue.size().width()).isEqualTo(800);
assertThat(drain()).containsExactly("windowResized 1000 500", "framebufferResized 2001 1000");
assertThat(queue.size()).isEqualTo(new CanvasSize(1000, 500, 2001, 1000, 2));
assertThat(surface.backingSizes).containsExactly("1600x1200", "2001x1000");
}
@Test
void manyResizesBetweenFramesAreOne() {
queue.event("resize", "", "", 900, 600, 0, 0, 2, 0);
queue.event("resize", "", "", 1000, 600, 0, 0, 2, 0);
assertThat(drain()).containsExactly("windowResized 1000 600", "framebufferResized 2000 1200");
}
@Test
void aDensityChangeResizesTheFramebufferOnly() {
// Moving to a 1x display: same CSS size, half the pixels.
queue.event("resize", "", "", 800, 600, 0, 0, 1, 0);
assertThat(drain()).containsExactly("framebufferResized 800 600");
assertThat(queue.size().density()).isEqualTo(1);
}
@Test
void anUnchangedSizeIsntReported() {
queue.event("resize", "", "", 800, 600, 1600, 1200, 2, 0);
assertThat(drain()).isEmpty();
}
@Test
void theSizeCanBeReportedOnRequest() {
queue.forceSizeReport();
assertThat(drain()).containsExactly("windowResized 800 600", "framebufferResized 1600 1200");
assertThat(drain()).isEmpty();
}
@Test
void anEmptyCanvasKeepsItsSize() {
queue.event("resize", "", "", 0, 0, 0, 0, 2, 0);
assertThat(drain()).isEmpty();
}
@Test
void measurementsWithoutDevicePixelsKeepTheExactOnes() {
CanvasSize exact = new CanvasSize(1001, 500, 2003, 1000, 2);
assertThat(CanvasSize.measure(1001, 500, 0, 0, 2, exact)).isEqualTo(exact);
assertThat(CanvasSize.measure(1002, 500, 0, 0, 2, exact)).isEqualTo(new CanvasSize(1002, 500, 2004, 1000, 2));
assertThat(CanvasSize.initial(1280, 720, 1.25)).isEqualTo(new CanvasSize(1280, 720, 1600, 900, 1.25));
}
// --- Window events and flushing ---
@Test
void windowEventsAreDelivered() {
queue.event("visibility", "", "", 1, 0, 0, 0, 0, 0);
queue.event("focus", "", "", 0, 0, 0, 0, 0, 0);
queue.event("fullscreen", "", "", 1, 0, 0, 0, 0, 0);
queue.event("enter", "", "", 0, 0, 0, 0, 0, 0);
assertThat(drain())
.containsExactly("focus false", "minimized true", "focus true", "fullscreen true", "entered");
}
@Test
void aFullscreenAnswerEndsTheRequest() {
queue.fullscreenRequested(true);
assertThat(queue.pendingFullscreen()).isTrue();
queue.event("fullscreen", "", "", 0, 0, 0, 0, 0, 0);
assertThat(queue.pendingFullscreen()).isNull();
}
@Test
void flushingKeepsReleasesAndWindowEvents() {
keyDown("KeyW", "w", 0);
drain();
move(1, 1, 1, 1);
keyDown("KeyE", "e", 0);
keyUp("KeyW", "w", 0);
queue.event("focus", "", "", 0, 0, 0, 0, 0, 0);
queue.flushInput();
assertThat(drain()).containsExactly("key 26 119 0 RELEASE", "focus true");
}
@Test
void theQueueIsBounded() {
for (int i = 0; i < 2 * DomEventQueue.MAX_PENDING; i++) {
queue.event("wheel", "", "", 0, 0, 0, 0, 0, 0);
keyDown("KeyW", "w", 0);
keyUp("KeyW", "w", 0);
}
List<String> delivered = drain();
// Past the bound only releases get in, so every key the game saw pressed is released.
assertThat(delivered.size()).isLessThanOrEqualTo(DomEventQueue.MAX_PENDING + 2 * DomEventQueue.MAX_PENDING);
long presses = delivered.stream().filter(e -> e.endsWith("PRESS")).count();
long releases = delivered.stream().filter(e -> e.endsWith("RELEASE")).count();
assertThat(releases).isGreaterThanOrEqualTo(presses);
assertThat(delivered.get(delivered.size() - 1)).isEqualTo("key 26 119 0 RELEASE");
}
// --- Helpers ---
private boolean keyDown(String code, String key, int flags) {
return queue.event("keydown", code, key, 0, 0, 0, 0, 0, flags);
}
private void keyUp(String code, String key, int flags) {
queue.event("keyup", code, key, 0, 0, 0, 0, 0, flags);
}
private void move(double x, double y, double dx, double dy) {
queue.event("move", "", "", x, y, dx, dy, 0, 0);
}
private void lock(boolean locked) {
queue.event("lock", "", "", locked ? 1 : 0, 0, 0, 0, 0, 0);
}
private List<String> drain() {
return drain(queue);
}
private static List<String> drain(DomEventQueue from) {
Recorder recorder = new Recorder();
from.drainTo(recorder);
return recorder.events;
}
private static final class FakeSurface implements DomEventQueue.Surface {
final List<String> backingSizes = new ArrayList<>();
final List<Boolean> lockRequests = new ArrayList<>();
@Override
public void setBackingSize(int pixelWidth, int pixelHeight) {
backingSizes.add(pixelWidth + "x" + pixelHeight);
}
@Override
public void setPointerLock(boolean locked) {
lockRequests.add(locked);
}
}
/** Writes each event as a line, so tests compare what the game would see. */
private static final class Recorder implements PlatformEventListener {
final List<String> events = new ArrayList<>();
@Override
public void windowResized(int width, int height) {
events.add("windowResized " + width + " " + height);
}
@Override
public void framebufferResized(int width, int height) {
events.add("framebufferResized " + width + " " + height);
}
@Override
public void displayChanged() {
events.add("displayChanged");
}
@Override
public void minimizedChanged(boolean minimized) {
events.add("minimized " + minimized);
}
@Override
public void focusChanged(boolean focused) {
events.add("focus " + focused);
}
@Override
public void fullscreenChanged(boolean fullscreen) {
events.add("fullscreen " + fullscreen);
}
@Override
public void cursorEnteredOrLeft() {
events.add("entered");
}
@Override
public void key(int scancode, int keyCode, int modifiers, KeyAction action) {
events.add("key " + scancode + " " + keyCode + " " + modifiers + " " + action);
}
@Override
public void textInput(String text) {
events.add("text " + text);
}
@Override
public void textEditing(String text, int start, int length) {
events.add("editing '" + text + "' " + start + " " + length);
}
@Override
public void keymapChanged() {
events.add("keymap");
}
@Override
public void filesDropped(List<String> paths) {
events.add("files " + paths);
}
@Override
public void mouseMoved(double x, double y, double dx, double dy) {
events.add(String.format(Locale.ROOT, "move %.1f %.1f %.1f %.1f", x, y, dx, dy));
}
@Override
public void mouseButton(int button, boolean pressed, int modifiers) {
events.add("button " + button + " " + pressed + " " + modifiers);
}
@Override
public void mouseWheel(double dx, double dy, int modifiers) {
events.add(String.format(Locale.ROOT, "wheel %.1f %.1f %d", dx, dy, modifiers));
}
}
}
@@ -0,0 +1,549 @@
package incari.platform.web;
import static org.assertj.core.api.Assertions.assertThat;
import incari.platform.api.input.Scancodes;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
class DomKeysTest {
private static final int NP = DomKeys.NON_PRINTABLE;
/** Every value checked against the HID usage tables, keyboard/keypad page (0x07). */
@ParameterizedTest
@CsvSource({
"KeyA, 4",
"KeyQ, 20",
"KeyW, 26",
"KeyZ, 29",
"Digit1, 30",
"Digit9, 38",
"Digit0, 39",
"Enter, 40",
"Escape, 41",
"Backspace, 42",
"Tab, 43",
"Space, 44",
"Minus, 45",
"Equal, 46",
"BracketLeft, 47",
"BracketRight, 48",
"Backslash, 49",
"Semicolon, 51",
"Quote, 52",
"Backquote, 53",
"Comma, 54",
"Period, 55",
"Slash, 56",
"CapsLock, 57",
"F1, 58",
"F10, 67",
"F12, 69",
"PrintScreen, 70",
"ScrollLock, 71",
"Pause, 72",
"Insert, 73",
"Home, 74",
"PageUp, 75",
"Delete, 76",
"End, 77",
"PageDown, 78",
"ArrowRight, 79",
"ArrowLeft, 80",
"ArrowDown, 81",
"ArrowUp, 82",
"NumLock, 83",
"NumpadDivide, 84",
"NumpadMultiply, 85",
"NumpadSubtract, 86",
"NumpadAdd, 87",
"NumpadEnter, 88",
"Numpad1, 89",
"Numpad5, 93",
"Numpad9, 97",
"Numpad0, 98",
"NumpadDecimal, 99",
"IntlBackslash, 100",
"ContextMenu, 101",
"NumpadEqual, 103",
"F13, 104",
"F20, 111",
"F24, 115",
"AudioVolumeMute, 127",
"AudioVolumeUp, 128",
"AudioVolumeDown, 129",
"NumpadComma, 133",
"IntlRo, 135",
"KanaMode, 136",
"IntlYen, 137",
"Convert, 138",
"NonConvert, 139",
"Lang1, 144",
"Lang2, 145",
"ControlLeft, 224",
"ShiftLeft, 225",
"AltLeft, 226",
"MetaLeft, 227",
"OSLeft, 227",
"ControlRight, 228",
"ShiftRight, 229",
"AltRight, 230",
"MetaRight, 231",
"OSRight, 231",
"Lang3, 146",
"Lang4, 147",
"Lang5, 148",
"Katakana, 146",
"Hiragana, 147",
"Power, 102",
"Open, 116",
"Help, 117",
"Select, 119",
"Again, 121",
"Undo, 122",
"Cut, 123",
"Copy, 124",
"Paste, 125",
"Find, 126",
"NumpadParenLeft, 182",
"NumpadParenRight, 183",
"NumpadBackspace, 187",
"NumpadHash, 204",
"NumpadStar, 85",
"NumpadMemoryStore, 208",
"NumpadMemoryRecall, 209",
"NumpadMemoryClear, 210",
"NumpadMemoryAdd, 211",
"NumpadMemorySubtract, 212",
"NumpadClear, 216",
"NumpadClearEntry, 217",
// SDL3's own numbers for the consumer page (SDL_scancode.h).
"Sleep, 258",
"WakeUp, 259",
"MediaPlay, 262",
"MediaPause, 263",
"MediaRecord, 264",
"MediaFastForward, 265",
"MediaRewind, 266",
"MediaTrackNext, 267",
"MediaTrackPrevious, 268",
"MediaStop, 269",
"Eject, 270",
"MediaPlayPause, 271",
"MediaSelect, 272",
"LaunchMediaPlayer, 272",
"BrowserSearch, 280",
"BrowserHome, 281",
"BrowserBack, 282",
"BrowserForward, 283",
"BrowserStop, 284",
"BrowserRefresh, 285",
"BrowserFavorites, 286",
})
void mapsCodesToHidUsages(String code, int scancode) {
assertThat(DomKeys.scancode(code)).isEqualTo(scancode);
}
@ParameterizedTest
@CsvSource({"''", "Unidentified", "Fn", "F0", "F25", "Fx", "Key", "Keya", "Digit", "NumpadX", "F1a"})
void unknownCodesAreUnknown(String code) {
assertThat(DomKeys.scancode(code)).isEqualTo(Scancodes.UNKNOWN);
}
@Test
void lettersAndDigitsAreContiguous() {
for (char letter = 'A'; letter <= 'Z'; letter++) {
assertThat(DomKeys.scancode("Key" + letter)).isEqualTo(Scancodes.A + letter - 'A');
}
for (int number = 1; number <= 12; number++) {
assertThat(DomKeys.scancode("F" + number)).isEqualTo(Scancodes.F1 + number - 1);
}
}
/**
* Every code in the UI Events KeyboardEvent code tables (W3C), plus F13-F24 and the older
* names browsers still send. Each either has a scancode or is deliberately unknown.
*/
private static final List<String> ALL_CODES = List.of(
// Writing system keys
"Backquote",
"Backslash",
"BracketLeft",
"BracketRight",
"Comma",
"Digit0",
"Digit1",
"Digit2",
"Digit3",
"Digit4",
"Digit5",
"Digit6",
"Digit7",
"Digit8",
"Digit9",
"Equal",
"IntlBackslash",
"IntlRo",
"IntlYen",
"KeyA",
"KeyB",
"KeyC",
"KeyD",
"KeyE",
"KeyF",
"KeyG",
"KeyH",
"KeyI",
"KeyJ",
"KeyK",
"KeyL",
"KeyM",
"KeyN",
"KeyO",
"KeyP",
"KeyQ",
"KeyR",
"KeyS",
"KeyT",
"KeyU",
"KeyV",
"KeyW",
"KeyX",
"KeyY",
"KeyZ",
"Minus",
"Period",
"Quote",
"Semicolon",
"Slash",
// Functional keys
"AltLeft",
"AltRight",
"Backspace",
"CapsLock",
"ContextMenu",
"ControlLeft",
"ControlRight",
"Enter",
"MetaLeft",
"MetaRight",
"ShiftLeft",
"ShiftRight",
"Space",
"Tab",
"Convert",
"KanaMode",
"Lang1",
"Lang2",
"Lang3",
"Lang4",
"Lang5",
"NonConvert",
// Control pad and arrows
"Delete",
"End",
"Help",
"Home",
"Insert",
"PageDown",
"PageUp",
"ArrowDown",
"ArrowLeft",
"ArrowRight",
"ArrowUp",
// Numpad
"NumLock",
"Numpad0",
"Numpad1",
"Numpad2",
"Numpad3",
"Numpad4",
"Numpad5",
"Numpad6",
"Numpad7",
"Numpad8",
"Numpad9",
"NumpadAdd",
"NumpadBackspace",
"NumpadClear",
"NumpadClearEntry",
"NumpadComma",
"NumpadDecimal",
"NumpadDivide",
"NumpadEnter",
"NumpadEqual",
"NumpadHash",
"NumpadMemoryAdd",
"NumpadMemoryClear",
"NumpadMemoryRecall",
"NumpadMemoryStore",
"NumpadMemorySubtract",
"NumpadMultiply",
"NumpadParenLeft",
"NumpadParenRight",
"NumpadStar",
"NumpadSubtract",
// Function keys
"Escape",
"F1",
"F2",
"F3",
"F4",
"F5",
"F6",
"F7",
"F8",
"F9",
"F10",
"F11",
"F12",
"F13",
"F14",
"F15",
"F16",
"F17",
"F18",
"F19",
"F20",
"F21",
"F22",
"F23",
"F24",
"Fn",
"FnLock",
"PrintScreen",
"ScrollLock",
"Pause",
// Media keys
"BrowserBack",
"BrowserFavorites",
"BrowserForward",
"BrowserHome",
"BrowserRefresh",
"BrowserSearch",
"BrowserStop",
"Eject",
"LaunchApp1",
"LaunchApp2",
"LaunchMail",
"MediaPlayPause",
"MediaSelect",
"MediaStop",
"MediaTrackNext",
"MediaTrackPrevious",
"Power",
"Sleep",
"AudioVolumeDown",
"AudioVolumeMute",
"AudioVolumeUp",
"WakeUp",
// Legacy, non-standard and special keys
"Hyper",
"Super",
"Turbo",
"Abort",
"Resume",
"Suspend",
"Again",
"Copy",
"Cut",
"Find",
"Open",
"Paste",
"Props",
"Select",
"Undo",
"Hiragana",
"Katakana",
"Unidentified",
// Older browsers' names, and Chromium's extra media codes
"OSLeft",
"OSRight",
"VolumeMute",
"VolumeUp",
"VolumeDown",
"MediaPlay",
"MediaPause",
"MediaRecord",
"MediaFastForward",
"MediaRewind",
"LaunchMediaPlayer");
/** Codes SDL3 has no scancode for, so the game can't see them on a desktop either. */
private static final Set<String> UNMAPPED = Set.of(
"Fn",
"FnLock",
"LaunchApp1",
"LaunchApp2",
"LaunchMail",
"Hyper",
"Super",
"Turbo",
"Abort",
"Resume",
"Suspend",
"Props",
"Unidentified");
/** Codes that name the same key as another: older names, and the phone keypad's "*". */
private static final Set<String> ALIASES = Set.of(
"OSLeft",
"OSRight",
"VolumeMute",
"VolumeUp",
"VolumeDown",
"Katakana",
"Hiragana",
"NumpadStar",
"LaunchMediaPlayer");
@Test
void everyStandardCodeIsMappedOrDeliberatelyUnknown() {
Map<Integer, String> seen = new HashMap<>();
for (String code : ALL_CODES) {
int scancode = DomKeys.scancode(code);
if (UNMAPPED.contains(code)) {
assertThat(scancode).as(code).isEqualTo(Scancodes.UNKNOWN);
continue;
}
assertThat(scancode).as(code).isBetween(1, Scancodes.COUNT - 1);
if (!ALIASES.contains(code)) {
String other = seen.put(scancode, code);
assertThat(other).as(code + " has the scancode of " + other).isNull();
}
}
}
@Test
void layoutKeysHaveUsNamesToFallBackOn() {
assertThat(DomKeys.usName(Scancodes.A)).isEqualTo("a");
assertThat(DomKeys.usName(Scancodes.Z)).isEqualTo("z");
assertThat(DomKeys.usName(Scancodes.DIGIT_1)).isEqualTo("1");
assertThat(DomKeys.usName(Scancodes.DIGIT_0)).isEqualTo("0");
assertThat(DomKeys.usName(DomKeys.scancode("Semicolon"))).isEqualTo(";");
assertThat(DomKeys.usName(DomKeys.scancode("Slash"))).isEqualTo("/");
assertThat(DomKeys.usName(DomKeys.scancode("Minus"))).isEqualTo("-");
// Keys the game names itself.
assertThat(DomKeys.usName(Scancodes.SPACE)).isNull();
assertThat(DomKeys.usName(Scancodes.F1)).isNull();
assertThat(DomKeys.usName(50)).isNull();
assertThat(DomKeys.usName(DomKeys.scancode("Numpad1"))).isNull();
}
@Test
void aliasesNameTheKeyTheirOriginalDoes() {
assertThat(DomKeys.scancode("OSLeft")).isEqualTo(DomKeys.scancode("MetaLeft"));
assertThat(DomKeys.scancode("VolumeUp")).isEqualTo(DomKeys.scancode("AudioVolumeUp"));
assertThat(DomKeys.scancode("Katakana")).isEqualTo(DomKeys.scancode("Lang3"));
assertThat(DomKeys.scancode("NumpadStar")).isEqualTo(DomKeys.scancode("NumpadMultiply"));
assertThat(DomKeys.scancode("LaunchMediaPlayer")).isEqualTo(DomKeys.scancode("MediaSelect"));
}
private static int keyCode(String code, String key) {
return keyCode(code, key, false, new int[Scancodes.COUNT]);
}
private static int keyCode(String code, String key, boolean shifted, int[] learned) {
return DomKeys.keyCode(code, DomKeys.scancode(code), key, shifted, learned);
}
@Test
void printableKeysGiveTheirCharacterInLowerCase() {
assertThat(keyCode("KeyA", "a")).isEqualTo('a');
assertThat(keyCode("KeyA", "A")).isEqualTo('a');
assertThat(keyCode("Space", " ")).isEqualTo(' ');
assertThat(keyCode("Minus", "-")).isEqualTo('-');
// AZERTY: the key right of Tab types "a".
assertThat(keyCode("KeyQ", "a")).isEqualTo('a');
// German: the key right of L types "ö".
assertThat(keyCode("Semicolon", "ö")).isEqualTo('ö');
}
/** The keycodes the game's screens compare against (EditBox, TextFieldHelper, ChatScreen). */
@Test
void namedKeysGiveSdlKeycodes() {
assertThat(keyCode("Enter", "Enter")).isEqualTo(13);
assertThat(keyCode("Escape", "Escape")).isEqualTo(27);
assertThat(keyCode("Backspace", "Backspace")).isEqualTo(8);
assertThat(keyCode("Tab", "Tab")).isEqualTo(9);
assertThat(keyCode("Delete", "Delete")).isEqualTo(127);
assertThat(keyCode("Home", "Home")).isEqualTo(1073741898);
assertThat(keyCode("End", "End")).isEqualTo(1073741901);
assertThat(keyCode("F5", "F5")).isEqualTo(1073741886);
assertThat(keyCode("ControlLeft", "Control")).isEqualTo(1073742048);
assertThat(keyCode("ControlRight", "Control")).isEqualTo(1073742052);
assertThat(keyCode("ArrowUp", "ArrowUp")).isEqualTo(82 | NP);
assertThat(keyCode("Unidentified", "Unidentified")).isEqualTo(NP);
}
@Test
void keypadKeysHaveTheirOwnKeycodes() {
assertThat(keyCode("Numpad1", "1")).isEqualTo(89 | NP);
assertThat(keyCode("NumpadAdd", "+")).isEqualTo(87 | NP);
// The game accepts either Enter (AddFriendWidget), and SDL's is the keypad's own.
assertThat(keyCode("NumpadEnter", "Enter")).isEqualTo(1073741912);
}
@Test
void keypadWithNumLockOffGivesNavigationKeys() {
assertThat(keyCode("Numpad1", "End")).isEqualTo(77 | NP);
assertThat(keyCode("Numpad8", "ArrowUp")).isEqualTo(82 | NP);
assertThat(keyCode("NumpadDecimal", "Delete")).isEqualTo(127);
assertThat(keyCode("Numpad5", "Clear")).isEqualTo(156 | NP);
}
@Test
void digitKeysAlwaysGiveDigits() {
assertThat(keyCode("Digit1", "1")).isEqualTo('1');
// Shift+1 on US, and unshifted on French AZERTY.
assertThat(keyCode("Digit1", "!")).isEqualTo('1');
assertThat(keyCode("Digit1", "&")).isEqualTo('1');
assertThat(keyCode("Digit0", "à")).isEqualTo('0');
}
@Test
void nonLatinLettersGiveUsLetters() {
// Russian: the key where US has C types "с", and Ctrl+C must still copy.
assertThat(keyCode("KeyC", "с")).isEqualTo('c');
// Greek.
assertThat(keyCode("KeyV", "ω")).isEqualTo('v');
}
@Test
void shiftedKeysGiveTheUnshiftedCharacterSeenBefore() {
int[] learned = new int[Scancodes.COUNT];
// Nothing seen yet: a US layout stands in.
assertThat(keyCode("Minus", "_", true, learned)).isEqualTo('-');
// German: this key types "ß" and, shifted, "?".
assertThat(keyCode("Minus", "ß", false, learned)).isEqualTo('ß');
assertThat(keyCode("Minus", "?", true, learned)).isEqualTo('ß');
}
@Test
void altGrLettersGiveTheLetter() {
// German AltGr+Q types "@"; the key is still Q.
assertThat(keyCode("KeyQ", "@", true, new int[Scancodes.COUNT])).isEqualTo('q');
}
@Test
void letterKeysTypingSymbolsKeepThem() {
// Dvorak: the key where US has Q types an apostrophe.
int[] learned = new int[Scancodes.COUNT];
assertThat(keyCode("KeyQ", "'", false, learned)).isEqualTo('\'');
assertThat(keyCode("KeyQ", "\"", true, learned)).isEqualTo('\'');
}
@Test
void singleCodePointHandlesSurrogatePairs() {
assertThat(DomKeys.singleCodePoint("a")).isEqualTo('a');
assertThat(DomKeys.singleCodePoint("😀")).isEqualTo(0x1F600);
assertThat(DomKeys.singleCodePoint("Enter")).isEqualTo(-1);
assertThat(DomKeys.singleCodePoint("")).isEqualTo(-1);
}
}
@@ -0,0 +1,135 @@
package incari.platform.web;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.File;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.io.TempDir;
class DroppedFilesTest {
@TempDir
Path root;
@Test
void filesAndFoldersAreCopiedAndTheDroppedOnesReported() throws IOException {
DroppedFiles drops = new DroppedFiles(root.toFile());
List<String> paths = drops.store(
1,
new Drop()
.file("pack.zip", "zip")
.folder("My Pack")
.file("My Pack/pack.mcmeta", "{}")
.folder("My Pack/assets")
.file("My Pack/assets/a.png", "png"));
Path drop = root.resolve("1");
assertThat(paths)
.containsExactly(
drop.resolve("pack.zip").toString(),
drop.resolve("My Pack").toString());
assertThat(drop.resolve("pack.zip")).hasContent("zip");
assertThat(drop.resolve("My Pack/pack.mcmeta")).hasContent("{}");
assertThat(drop.resolve("My Pack/assets/a.png")).hasContent("png");
}
@Test
void filesInAFolderArriveBeforeTheFolderItself() throws IOException {
// The page reads folders asynchronously, so their entries can come in any order.
List<String> paths = new DroppedFiles(root.toFile())
.store(
1,
new Drop()
.file("Pack/data/x.json", "1")
.folder("Pack/data")
.folder("Pack"));
assertThat(paths).containsExactly(root.resolve("1/Pack").toString());
assertThat(root.resolve("1/Pack/data/x.json")).hasContent("1");
}
@Test
void onlyTheLatestDropIsKept() throws IOException {
DroppedFiles drops = new DroppedFiles(root.toFile());
drops.store(1, new Drop().folder("A").file("A/a.txt", "a"));
drops.store(2, new Drop().file("b.txt", "b"));
assertThat(root.resolve("1")).doesNotExist();
assertThat(root.resolve("2/b.txt")).hasContent("b");
}
@Test
void namesCantLeaveTheDropsFolder() throws IOException {
List<String> paths = new DroppedFiles(root.toFile())
.store(1, new Drop().file("../../escape.txt", "x").file("/abs/./x.txt", "y"));
assertThat(paths)
.containsExactly(
root.resolve("1/escape.txt").toString(),
root.resolve("1/abs").toString());
assertThat(root.resolve("escape.txt")).doesNotExist();
assertThat(root.resolve("1/abs/x.txt")).hasContent("y");
}
@Test
void safePathsDropDotsAndReplaceWhatFileSystemsReject() {
assertThat(DroppedFiles.safePath("a/b.zip")).isEqualTo("a/b.zip");
assertThat(DroppedFiles.safePath("a//./../b")).isEqualTo("a/b");
assertThat(DroppedFiles.safePath("what?:*<>|\"\\x\u0001.zip")).isEqualTo("what________x_.zip");
assertThat(DroppedFiles.safePath("Ünïcødé pack.zip")).isEqualTo("Ünïcødé pack.zip");
assertThat(DroppedFiles.safePath("")).isNull();
assertThat(DroppedFiles.safePath("../..")).isNull();
}
@Test
void emptyEntriesAreSkipped() throws IOException {
List<String> paths = new DroppedFiles(root.toFile())
.store(1, new Drop().file("..", "x").file("ok", ""));
assertThat(paths).containsExactly(root.resolve("1/ok").toString());
assertThat(new File(root.toFile(), "1/ok")).exists().isEmpty();
}
/** A drop as the page would hand it over. */
private static final class Drop implements DroppedFiles.Source {
private final List<String> paths = new ArrayList<>();
private final List<byte @Nullable []> contents = new ArrayList<>();
Drop file(String path, String content) {
paths.add(path);
contents.add(content.getBytes(StandardCharsets.UTF_8));
return this;
}
Drop folder(String path) {
paths.add(path);
contents.add(null);
return this;
}
@Override
public int count() {
return paths.size();
}
@Override
public String path(int index) {
return paths.get(index);
}
@Override
public boolean isFolder(int index) {
return contents.get(index) == null;
}
@Override
public byte[] bytes(int index) {
byte[] content = contents.get(index);
if (content == null) {
throw new IllegalStateException("A folder has no contents");
}
return content;
}
}
}
@@ -0,0 +1,331 @@
package incari.platform.web;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Future;
import java.util.concurrent.RejectedExecutionException;
import java.util.concurrent.TimeUnit;
import org.jspecify.annotations.Nullable;
import org.junit.jupiter.api.Test;
class IdleTimeExecutorTest {
/** A clock each task moves on by its cost, and a count of the slots asked for. */
private static final class FakeSlots implements IdleTimeExecutor.Slots {
double now;
int armed;
@Override
public void arm() {
armed++;
}
@Override
public double await() {
throw new UnsupportedOperationException("the tests run slots themselves");
}
@Override
public double now() {
return now;
}
}
private final FakeSlots slots = new FakeSlots();
private final List<Runnable> workers = new ArrayList<>();
private final IdleTimeExecutor executor = new IdleTimeExecutor(slots, workers::add);
private final List<String> ran = new ArrayList<>();
private Runnable task(String name, double millis) {
return () -> {
ran.add(name);
slots.now += millis;
};
}
@Test
void submittingOnlyQueuesAndAsksForASlot() {
executor.execute(task("a", 1));
assertThat(ran).isEmpty();
assertThat(executor.queued()).isEqualTo(1);
assertThat(slots.armed).isEqualTo(1);
assertThat(workers).hasSize(1);
}
@Test
void theWorkerStartsOnce() {
executor.execute(task("a", 1));
executor.execute(task("b", 1));
assertThat(workers).hasSize(1);
}
@Test
void aSlotRunsTasksInOrderUntilItsDeadline() {
for (String name : List.of("a", "b", "c", "d")) {
executor.execute(task(name, 3));
}
assertThat(executor.runUntil(5)).isEqualTo(2);
assertThat(ran).containsExactly("a", "b");
assertThat(executor.queued()).isEqualTo(2);
}
@Test
void aSlotRunsAtLeastOneTaskEvenPastItsDeadline() {
slots.now = 10;
executor.execute(task("a", 3));
executor.execute(task("b", 3));
assertThat(executor.runUntil(5)).isEqualTo(1);
assertThat(ran).containsExactly("a");
}
@Test
void tasksQueuedDuringASlotRunInIt() {
executor.execute(() -> {
ran.add("first");
executor.execute(task("resubmitted", 1));
});
assertThat(executor.runUntil(100)).isEqualTo(2);
assertThat(ran).containsExactly("first", "resubmitted");
}
@Test
void aFailingTaskGoesToTheUncaughtHandlerAndTheSlotGoesOn() {
List<Throwable> caught = new ArrayList<>();
Thread thread = Thread.currentThread();
Thread.@Nullable UncaughtExceptionHandler previous = thread.getUncaughtExceptionHandler();
thread.setUncaughtExceptionHandler((t, e) -> caught.add(e));
try {
executor.execute(() -> {
throw new IllegalStateException("broken");
});
executor.execute(task("after", 1));
executor.runUntil(100);
} finally {
thread.setUncaughtExceptionHandler(previous);
}
assertThat(caught).singleElement().isInstanceOf(IllegalStateException.class);
assertThat(ran).containsExactly("after");
}
@Test
void futuresCompleteWhenTheirSlotRuns() throws Exception {
Future<String> future = executor.submit(() -> "done");
assertThat(future.isDone()).isFalse();
executor.runUntil(100);
assertThat(future.get(0, TimeUnit.SECONDS)).isEqualTo("done");
}
@Test
void shutdownRejectsNewTasksAndNeverWaits() {
executor.execute(task("a", 1));
executor.shutdown();
assertThat(executor.isShutdown()).isTrue();
assertThat(executor.awaitTermination(3, TimeUnit.SECONDS)).isFalse();
assertThatThrownBy(() -> executor.execute(task("b", 1))).isInstanceOf(RejectedExecutionException.class);
assertThat(executor.shutdownNow()).hasSize(1);
}
@Test
void anUnusedPoolTerminatesAtShutdown() {
executor.shutdown();
assertThat(executor.isTerminated()).isTrue();
assertThat(workers).isEmpty();
}
/** Slots that come at once, each 10 ms long, on the real clock: for runners on real threads. */
private static final class ImmediateSlots implements IdleTimeExecutor.Slots {
@Override
public void arm() {}
@Override
public double await() {
return now() + 10;
}
@Override
public double now() {
return System.nanoTime() / 1e6;
}
}
@Test
void aTaskWaitingOutsideLetsTheOthersRunAndGoesOnAfter() throws Exception {
List<Thread> threads = java.util.Collections.synchronizedList(new ArrayList<>());
IdleTimeExecutor pool = new IdleTimeExecutor(new ImmediateSlots(), work -> {
Thread thread = new Thread(work, "runner");
thread.setDaemon(true);
threads.add(thread);
thread.start();
});
java.util.concurrent.CountDownLatch outsideDone = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.CountDownLatch othersRan = new java.util.concurrent.CountDownLatch(2);
List<String> order = java.util.Collections.synchronizedList(new ArrayList<>());
java.util.concurrent.atomic.AtomicInteger running = new java.util.concurrent.atomic.AtomicInteger();
java.util.concurrent.atomic.AtomicBoolean overlapped = new java.util.concurrent.atomic.AtomicBoolean();
Runnable exclusive = () -> {
if (running.incrementAndGet() > 1) {
overlapped.set(true);
}
};
Runnable done = running::decrementAndGet;
pool.execute(() -> {
exclusive.run();
order.add("waiting");
done.run();
String answer = IdleTimeExecutor.awaitOutside(() -> {
try {
// The others run while this waits.
assertThat(othersRan.await(5, TimeUnit.SECONDS)).isTrue();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
return "answer";
});
exclusive.run();
order.add("after " + answer);
done.run();
outsideDone.countDown();
});
for (String name : List.of("b", "c")) {
pool.execute(() -> {
exclusive.run();
order.add(name);
done.run();
othersRan.countDown();
});
}
assertThat(outsideDone.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(order).containsExactly("waiting", "b", "c", "after answer");
assertThat(overlapped).isFalse();
assertThat(pool.runners()).isEqualTo(2);
pool.shutdown();
}
@Test
void aTaskThatBlocksOnWorkQueuedBehindItGivesThePoolUp() throws Exception {
IdleTimeExecutor pool = new IdleTimeExecutor(new ImmediateSlots(), work -> {
Thread thread = new Thread(work, "runner");
thread.setDaemon(true);
thread.start();
});
java.util.concurrent.CountDownLatch inner = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.CountDownLatch outerDone = new java.util.concurrent.CountDownLatch(1);
java.util.concurrent.CountDownLatch afterRan = new java.util.concurrent.CountDownLatch(1);
List<String> order = java.util.Collections.synchronizedList(new ArrayList<>());
pool.execute(() -> {
order.add("outer");
// What it waits for is queued behind it, as world generation's structure placement
// joins work it queued itself.
pool.execute(() -> {
order.add("inner");
inner.countDown();
});
try {
// In the page, web-classlib's Waits calls this before the wait.
IdleTimeExecutor.beforeWait();
assertThat(inner.await(5, TimeUnit.SECONDS)).isTrue();
} catch (InterruptedException e) {
throw new IllegalStateException(e);
}
order.add("outer done");
outerDone.countDown();
});
assertThat(outerDone.await(5, TimeUnit.SECONDS)).isTrue();
// The runner that gave the pool up queues for it again, and the pool goes on.
pool.execute(() -> {
order.add("after");
afterRan.countDown();
});
assertThat(afterRan.await(5, TimeUnit.SECONDS)).isTrue();
assertThat(order).containsExactly("outer", "inner", "outer done", "after");
assertThat(pool.runners()).isEqualTo(2);
pool.shutdown();
}
@Test
void waitingOutsideThePoolChangesNothing() {
IdleTimeExecutor.beforeWait();
assertThat(executor.runners()).isZero();
}
/** Slots on a clock the test moves: each await is a new slot, 10 ms long, counted. */
private static final class CountedSlots implements IdleTimeExecutor.Slots {
private double now;
final java.util.concurrent.atomic.AtomicInteger slots = new java.util.concurrent.atomic.AtomicInteger();
@Override
public void arm() {}
@Override
public synchronized double await() {
slots.incrementAndGet();
now += 20;
return now + 10;
}
@Override
public synchronized double now() {
return now;
}
synchronized void advance(double millis) {
now += millis;
}
}
@Test
void aLongTaskPausesForTheNextSlotWhenItsSlotIsOverAndKeepsThePool() throws Exception {
CountedSlots counted = new CountedSlots();
IdleTimeExecutor pool = new IdleTimeExecutor(counted, work -> {
Thread thread = new Thread(work, "runner");
thread.setDaemon(true);
thread.start();
});
java.util.concurrent.CountDownLatch finished = new java.util.concurrent.CountDownLatch(2);
List<String> order = java.util.Collections.synchronizedList(new ArrayList<>());
List<Integer> slotOfPart = java.util.Collections.synchronizedList(new ArrayList<>());
pool.execute(() -> {
for (int part = 0; part < 3; part++) {
slotOfPart.add(counted.slots.get());
order.add("part " + part);
// Each part takes 8 ms of a 10 ms slot: the second ends past the slot and pauses.
counted.advance(8);
IdleTimeExecutor.pauseIfLate();
}
finished.countDown();
});
pool.execute(() -> {
order.add("next");
finished.countDown();
});
assertThat(finished.await(5, TimeUnit.SECONDS)).isTrue();
// The long task kept the pool through its pause, and its last part ran in the next slot.
assertThat(order).containsExactly("part 0", "part 1", "part 2", "next");
assertThat(slotOfPart).containsExactly(1, 1, 2);
pool.shutdown();
}
@Test
void pausingOutsideThePoolReturnsAtOnce() {
IdleTimeExecutor.pauseIfLate();
}
}
@@ -0,0 +1,108 @@
package incari.platform.web.audio;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import java.nio.charset.StandardCharsets;
import org.junit.jupiter.api.Test;
/** The bookkeeping behind pausing, pitch changes and buffer queues, which Web Audio doesn't keep. */
class PlaybackTest {
@Test
void clockFollowsPausesAndPitch() {
PlaybackClock clock = new PlaybackClock();
assertThat(clock.position(5)).isZero();
clock.start(10);
assertThat(clock.position(12)).isEqualTo(2);
// Twice the pitch from 12 on: twice as fast through the samples.
clock.setRate(12, 2);
assertThat(clock.position(13)).isEqualTo(4);
clock.pause(13);
assertThat(clock.position(100)).isEqualTo(4);
clock.start(100);
assertThat(clock.position(100.5)).isEqualTo(5);
// A context clock read slightly behind the anchor never moves it back.
assertThat(clock.position(99)).isEqualTo(4);
clock.reset();
assertThat(clock.position(200)).isZero();
assertThat(clock.running()).isFalse();
clock.seek(200, 3);
assertThat(clock.position(300)).isEqualTo(3);
}
@Test
void loopsWrapWithinTheSound() {
assertThat(PlaybackClock.wrap(2.5, 1)).isCloseTo(0.5, within(1e-12));
assertThat(PlaybackClock.wrap(0.25, 1)).isEqualTo(0.25);
assertThat(PlaybackClock.wrap(-0.25, 1)).isEqualTo(0.75);
assertThat(PlaybackClock.wrap(3, 0)).isZero();
}
@Test
void queueFinishesBuffersInOrder() {
StreamTimeline timeline = new StreamTimeline();
for (int i = 0; i < 4; i++) {
timeline.add(1);
}
assertThat(timeline.end()).isEqualTo(4);
assertThat(timeline.finishedAt(0.5)).isZero();
assertThat(timeline.finishedAt(1)).isEqualTo(1);
assertThat(timeline.finishedAt(2.9)).isEqualTo(2);
assertThat(timeline.indexAt(2.9)).isEqualTo(2);
assertThat(timeline.startOf(2)).isEqualTo(2);
// Released buffers keep their places in the stream: the next one still starts at 3.
timeline.release(3);
assertThat(timeline.size()).isEqualTo(1);
assertThat(timeline.startOf(0)).isEqualTo(3);
timeline.add(0.5);
assertThat(timeline.end()).isEqualTo(4.5);
assertThat(timeline.finishedAt(4.2)).isEqualTo(1);
assertThat(timeline.finishedAt(10)).isEqualTo(2);
for (int i = 0; i < 20; i++) {
timeline.add(0.25);
}
assertThat(timeline.end()).isEqualTo(9.5);
timeline.clear();
assertThat(timeline.size()).isZero();
assertThat(timeline.end()).isZero();
}
@Test
void readsTheOggVorbisHeader() {
assertThat(OggVorbisInfo.read(oggHeader(1, 44100))).satisfies(info -> {
assertThat(info.channels()).isEqualTo(1);
assertThat(info.sampleRate()).isEqualTo(44100);
});
OggVorbisInfo stereo = OggVorbisInfo.read(oggHeader(2, 48000));
assertThat(stereo).isNotNull();
assertThat(stereo.channels()).isEqualTo(2);
assertThat(OggVorbisInfo.read("not a sound".getBytes(StandardCharsets.US_ASCII)))
.isNull();
byte[] opus = oggHeader(2, 48000);
opus[28] = 'O';
assertThat(OggVorbisInfo.read(opus)).isNull();
}
/** The first page of an Ogg Vorbis file: its identification header, as the format lays it out. */
private static byte[] oggHeader(int channels, int rate) {
byte[] page = new byte[27 + 1 + 30];
byte[] magic = "OggS".getBytes(StandardCharsets.US_ASCII);
System.arraycopy(magic, 0, page, 0, 4);
page[5] = 2; // Beginning of stream.
page[26] = 1; // One segment...
page[27] = 30; // ...of 30 bytes: the identification header.
int packet = 28;
page[packet] = 1;
byte[] vorbis = "vorbis".getBytes(StandardCharsets.US_ASCII);
System.arraycopy(vorbis, 0, page, packet + 1, 6);
page[packet + 11] = (byte) channels;
page[packet + 12] = (byte) rate;
page[packet + 13] = (byte) (rate >> 8);
page[packet + 14] = (byte) (rate >> 16);
page[packet + 15] = (byte) (rate >> 24);
return page;
}
}
@@ -0,0 +1,148 @@
package incari.platform.web.audio;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.within;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.CsvSource;
/**
* The browser's panning and attenuation against the desktop's, measured. Each row is a 441 Hz
* tone played through LWJGL 3.4.3's OpenAL Soft (the game's) with its wave-file backend writing
* stereo at 48 kHz: HRTF off and the output limiter on, as the desktop opens its device; the
* listener at the origin facing -z with +y up; the RMS of each channel over the middle of the
* tone, divided by the tone's own. {@code linear} is the game's linear model (maximum distance
* 16); {@code none} is no attenuation. ADR 0013 describes the measurement.
*/
class SpatializerTest {
/** OpenAL Soft's measured output is within this of the model everywhere. */
private static final double TOLERANCE = 0.003;
@ParameterizedTest(name = "({0}, {1}, {2}) {3} relative={4} stereo={5}")
@CsvSource({
// x, y, z, attenuation, relative, stereo, measured left, measured right
"0, 0, -4, linear, false, false, 0.4466, 0.4466",
"4, 0, 0, linear, false, false, 0.0000, 0.7497",
"-4, 0, 0, linear, false, false, 0.7497, 0.0000",
"2.828, 0, -2.828, linear, false, false, 0.0560, 0.7486",
"2, 0, -3.464, linear, false, false, 0.1605, 0.6906",
"3.464, 0, -2, linear, false, false, 0.0000, 0.7497",
"2.828, 0, 2.828, linear, false, false, 0.0591, 0.5892",
"0, 0, 4, linear, false, false, 0.3031, 0.3031",
"0, 4, 0, linear, false, false, 0.3748, 0.3748",
"2.828, 2.828, 0, linear, false, false, 0.1098, 0.6399",
"8, 0, 0, linear, false, false, 0.0000, 0.4998",
"12, 0, 0, linear, false, false, 0.0000, 0.2499",
"16, 0, 0, linear, false, false, 0.0000, 0.0000",
"20, 0, 0, linear, false, false, 0.0000, 0.0000",
"1, 0, 0, linear, false, false, 0.0000, 0.9371",
"0.1, 0, 0, linear, false, false, 0.0000, 0.9933",
"0, 0, 0, linear, false, false, 0.5954, 0.5954",
"0.5, 0, -4, linear, false, false, 0.3748, 0.5135",
"1, 0, -4, linear, false, false, 0.3040, 0.5705",
"4, 0, 0, none, false, false, 0.0000, 0.9996",
"0, 0, 0, none, true, false, 0.5954, 0.5954",
"4, 0, 0, linear, false, true, 0.9996, 0.9996",
"0, 0, 0, none, true, true, 0.9996, 0.9996",
})
void matchesOpenAlSoft(
double x,
double y,
double z,
String attenuation,
boolean relative,
boolean stereo,
double left,
double right) {
Spatializer spatializer = new Spatializer();
spatializer.setListenerPosition(0, 0, 0);
spatializer.setListenerOrientation(0, 0, -1, 0, 1, 0);
Spatializer.Attenuation model = new Spatializer.Attenuation();
if (attenuation.equals("linear")) {
model.linear(16);
} else {
model.none();
}
spatializer.compute(x, y, z, relative, model, 1, stereo);
assertThat(spatializer.left()).isCloseTo(left, within(TOLERANCE));
assertThat(spatializer.right()).isCloseTo(right, within(TOLERANCE));
}
@Test
void followsTheListenerAsTheGameMovesIt() {
// The game's camera at yaw 0 faces +z (south); its right is then -x.
Spatializer spatializer = new Spatializer();
spatializer.setListenerPosition(10, 65.62, 10);
spatializer.setListenerOrientation(0, 0, 1, 0, 1, 0);
Spatializer.Attenuation model = new Spatializer.Attenuation();
model.linear(16);
spatializer.compute(6, 65.62, 10, false, model, 1, false);
assertThat(spatializer.localX()).isCloseTo(4, within(1e-9));
assertThat(spatializer.left()).isCloseTo(0, within(1e-9));
assertThat(spatializer.right()).isCloseTo(0.75, within(1e-9));
// Relative sources ignore where the listener is.
spatializer.compute(0, 0, 0, true, model, 0.5, false);
assertThat(spatializer.left()).isCloseTo(0.5 * (Spatializer.OMNI + Spatializer.FRONT), within(1e-9));
}
@Test
void orientationNeedNotBeNormalizedOrPerpendicular() {
Spatializer spatializer = new Spatializer();
spatializer.setListenerOrientation(0, -3, -3, 0, 1, 0);
Spatializer.Attenuation model = new Spatializer.Attenuation();
model.none();
// Straight ahead along the tilted view.
spatializer.compute(0, -1, -1, false, model, 1, false);
assertThat(spatializer.localX()).isCloseTo(0, within(1e-9));
assertThat(spatializer.localY()).isCloseTo(0, within(1e-9));
assertThat(spatializer.localZ()).isCloseTo(-Math.sqrt(2), within(1e-9));
// A degenerate orientation is ignored.
spatializer.setListenerOrientation(0, 1, 0, 0, 1, 0);
spatializer.compute(0, -1, -1, false, model, 1, false);
assertThat(spatializer.localZ()).isCloseTo(-Math.sqrt(2), within(1e-9));
}
@Test
void attenuationModels() {
Spatializer.Attenuation model = new Spatializer.Attenuation();
assertThat(model.gain(0.5)).isEqualTo(1);
assertThat(model.gain(4)).isEqualTo(0.25);
model.linear(10);
assertThat(model.gain(0)).isEqualTo(1);
assertThat(model.gain(5)).isEqualTo(0.5);
assertThat(model.gain(15)).isEqualTo(0);
model.linear(0);
assertThat(model.gain(15)).isEqualTo(1);
model.none();
assertThat(model.gain(1000)).isEqualTo(1);
}
/** The ratios app-web/browser-checks/audio-positional.steps expects the page to measure. */
@Test
void browserCheckExpectations() {
Spatializer spatializer = new Spatializer();
spatializer.setListenerPosition(0.5, 201.625, 0.5);
spatializer.setListenerOrientation(0, 0, 1, 0, 1, 0);
Spatializer.Attenuation model = new Spatializer.Attenuation();
model.linear(16);
spatializer.compute(-3.5, 201.625, 0.5, false, model, 1, false);
assertThat(spatializer.left()).isCloseTo(0, within(1e-9));
assertThat(spatializer.right()).isCloseTo(0.75, within(1e-9));
spatializer.compute(2.5, 201.625, 4, false, model, 1, false);
assertThat(spatializer.right() / spatializer.left()).isCloseTo(0.2360, within(1e-4));
spatializer.compute(0.5, 201.625, 4.5, false, model, 1, false);
double ahead = spatializer.left();
assertThat(spatializer.right()).isCloseTo(ahead, within(1e-12));
spatializer.compute(0.5, 201.625, -3.5, false, model, 1, false);
assertThat(spatializer.left() / ahead).isCloseTo(0.6788, within(1e-4));
spatializer.compute(0.5, 201.625, 12.5, false, model, 1, false);
assertThat(spatializer.left() / ahead).isCloseTo(1.0 / 3, within(1e-9));
}
}
@@ -0,0 +1,56 @@
package incari.platform.web.storage;
import static org.assertj.core.api.Assertions.assertThat;
import java.util.BitSet;
import java.util.Random;
import org.junit.jupiter.api.Test;
/** A file's written ranges cover every byte written, in few ranges kept apart. */
class DataFileTest {
@Test
void rangesCoverEveryWriteAndStayFewAndApart() {
Random random = new Random(41);
for (int round = 0; round < 500; round++) {
DataFile file = new DataFile("f", 0);
BitSet written = new BitSet();
int writes = 1 + random.nextInt(40);
for (int i = 0; i < writes; i++) {
int from = random.nextInt(200_000);
int to = from + 1 + random.nextInt(random.nextBoolean() ? 64 : 8_000);
file.markWritten(from, to);
written.set(from, to);
check(file, written);
}
}
}
@Test
void writesInOrderMakeOneRange() {
DataFile file = new DataFile("f", 0);
for (int at = 0; at < 100_000; at += 100) {
file.markWritten(at, at + 100);
}
assertThat(file.dirtyCount).isEqualTo(1);
assertThat(file.dirty[0]).isZero();
assertThat(file.dirty[1]).isEqualTo(100_000);
}
private static void check(DataFile file, BitSet written) {
assertThat(file.dirtyCount).isBetween(1, DataFile.MAX_DIRTY_RANGES);
BitSet covered = new BitSet();
for (int i = 0; i < file.dirtyCount; i++) {
int from = file.dirty[2 * i];
int to = file.dirty[2 * i + 1];
assertThat(from).isLessThan(to);
if (i > 0) {
assertThat(from).isGreaterThan(file.dirty[2 * i - 1] + DataFile.MERGE_GAP);
}
covered.set(from, to);
}
BitSet missed = (BitSet) written.clone();
missed.andNot(covered);
assertThat(missed.isEmpty()).isTrue();
}
}
@@ -0,0 +1,73 @@
package incari.platform.web.storage;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.Test;
import org.teavm.runtime.fs.VirtualFileAccessor;
/** A world's folder handed to a worker's copy of the game and back (ADR 0039). */
class HandOverTest {
private final TreeFileSystem page = new TreeFileSystem(new Journal("/incari", List.of()), () -> 1_000);
private final TreeFileSystem worker = new TreeFileSystem(new Journal("/incari", List.of()), () -> 2_000);
@Test
void aFolderGoesOverWithoutTellingTheStoreAndComesBack() throws IOException {
page.load("/incari/game/saves/World/level.dat", false, 500, bytes("level"));
page.load("/incari/game/saves/World/region", true, 600, null);
page.load("/incari/game/saves/World/region/r.0.0.mca", false, 700, bytes("chunks"));
page.load("/incari/game/options.txt", false, 800, bytes("fov:90"));
page.collectChanges();
byte[] bundle = FileBundle.encodeEntries(page.export("/incari/game/saves/World"));
page.forget("/incari/game/saves/World");
assertThat(page.getFile("/incari/game/saves/World").exists()).isFalse();
assertThat(page.getFile("/incari/game/options.txt").exists()).isTrue();
assertThat(page.collectChanges()).isEmpty();
for (FileBundle.Entry entry : FileBundle.decodeEntries(bundle)) {
worker.load(entry.path(), entry.directory(), entry.lastModified(), entry.contents());
}
assertThat(read(worker, "/incari/game/saves/World/region/r.0.0.mca")).isEqualTo("chunks");
assertThat(worker.getFile("/incari/game/saves/World/level.dat").lastModified())
.isEqualTo(500);
assertThat(worker.collectChanges()).isEmpty();
}
@Test
void changesGoToThePageAsTheyWereMade() throws IOException {
worker.load("/incari/game/saves/World/level.dat", false, 500, bytes("level"));
worker.collectChanges();
VirtualFileAccessor file =
worker.getFile("/incari/game/saves/World/level.dat").createAccessor(true, true, false);
file.seek(5);
file.write(bytes("!"), 0, 1);
file.close();
List<StoreOp> sent = FileBundle.decodeOps(FileBundle.encodeOps(worker.collectChanges()));
assertThat(sent).singleElement().satisfies(op -> {
assertThat(op.kind()).isEqualTo(StoreOp.Kind.WRITE);
assertThat(op.path()).isEqualTo("/incari/game/saves/World/level.dat");
assertThat(op.size()).isEqualTo(6);
assertThat(op.at()).isEqualTo(5);
assertThat(op.data()).containsExactly('!');
});
}
private static byte[] bytes(String text) {
return text.getBytes(StandardCharsets.UTF_8);
}
private static String read(TreeFileSystem files, String path) throws IOException {
VirtualFileAccessor file = files.getFile(path).createAccessor(true, false, false);
byte[] buffer = new byte[file.size()];
file.read(buffer, 0, buffer.length);
file.close();
return new String(buffer, StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,252 @@
package incari.platform.web.storage;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.junit.jupiter.api.Test;
import org.teavm.runtime.fs.VirtualFileAccessor;
/**
* A world's region files left in the store (ADR 0041): the page reads one only when it opens it,
* the server's worker opens them where they are, and neither sends the store what it already has.
*/
class InPlaceTest {
private static final String WORLD = "/incari/game/saves/World";
private static final String REGION = WORLD + "/region/r.0.0.mca";
/** The store: files by path, opened handles counted. */
private static final class Store implements InPlaceStore {
final Map<String, byte[]> files = new HashMap<>();
final boolean inPlace;
int reads;
int open;
final List<String> opened = new ArrayList<>();
Store(boolean inPlace) {
this.inPlace = inPlace;
}
@Override
public boolean opensInPlace() {
return inPlace;
}
@Override
public byte[] read(String path) {
reads++;
byte[] bytes = files.get(path);
return bytes == null ? new byte[0] : bytes.clone();
}
@Override
public Handle open(String path) {
opened.add(path);
open++;
files.putIfAbsent(path, new byte[0]);
return new Handle() {
boolean closed;
@Override
public int read(byte[] buffer, int offset, int length, int at) {
byte[] bytes = files.get(path);
int count = Math.max(0, Math.min(length, bytes.length - at));
System.arraycopy(bytes, at, buffer, offset, count);
return count;
}
@Override
public void write(byte[] buffer, int offset, int length, int at) {
byte[] bytes = files.get(path);
if (at + length > bytes.length) {
bytes = Arrays.copyOf(bytes, at + length);
}
System.arraycopy(buffer, offset, bytes, at, length);
files.put(path, bytes);
}
@Override
public int size() {
return files.get(path).length;
}
@Override
public void truncate(int size) {
files.put(path, Arrays.copyOf(files.get(path), size));
}
@Override
public void flush() {}
@Override
public void close() {
if (!closed) {
closed = true;
open--;
}
}
};
}
}
private static TreeFileSystem tree(Store store) {
TreeFileSystem files = new TreeFileSystem(new Journal("/incari", List.of()), () -> 3_000);
files.setInPlaceStore(store);
return files;
}
@Test
void thePageReadsARegionFileOnlyWhenItOpensIt() throws IOException {
Store store = new Store(false);
store.files.put(REGION, bytes("chunks"));
TreeFileSystem page = tree(store);
page.loadStored(REGION, 700, 6);
page.collectChanges();
assertThat(page.getFile(REGION).length()).isEqualTo(6);
assertThat(store.reads).isZero();
assertThat(read(page, REGION)).isEqualTo("chunks");
assertThat(read(page, REGION)).isEqualTo("chunks");
assertThat(store.reads).isEqualTo(1);
// Read, not changed: nothing to tell the store.
assertThat(page.collectChanges()).isEmpty();
}
@Test
void theWorkerOpensRegionFilesWhereTheyAreAndTheJournalHasNothingToSend() throws IOException {
Store store = new Store(true);
store.files.put(REGION, bytes("chunks"));
TreeFileSystem worker = tree(store);
worker.load(WORLD, true, 1, null);
worker.load(WORLD + "/region", true, 1, null);
worker.loadStored(REGION, 700, 6);
worker.collectChanges();
VirtualFileAccessor region = worker.getFile(REGION).createAccessor(true, true, false);
region.seek(6);
region.write(bytes("+more"), 0, 5);
region.close();
assertThat(store.files.get(REGION)).isEqualTo(bytes("chunks+more"));
assertThat(worker.getFile(REGION).length()).isEqualTo(11);
assertThat(read(worker, REGION)).isEqualTo("chunks+more");
assertThat(store.opened).containsExactly(REGION);
// A new region file is made in the store when the server first opens it.
worker.getFile(WORLD + "/region").createFile("r.1.0.mca");
VirtualFileAccessor next = worker.getFile(WORLD + "/region/r.1.0.mca").createAccessor(true, true, false);
next.write(bytes("new"), 0, 3);
assertThat(store.files.get(WORLD + "/region/r.1.0.mca")).isEqualTo(bytes("new"));
assertThat(worker.collectChanges()).isEmpty();
// Handed back: sizes only, every handle let go.
worker.closeStored(WORLD);
assertThat(store.open).isZero();
assertThat(worker.export(WORLD, true))
.filteredOn(FileBundle.Entry::stored)
.extracting(FileBundle.Entry::path, FileBundle.Entry::size)
.containsExactlyInAnyOrder(
org.assertj.core.groups.Tuple.tuple(REGION, 11),
org.assertj.core.groups.Tuple.tuple(WORLD + "/region/r.1.0.mca", 3));
}
@Test
void handedOverInPlaceTheBundleCarriesSizesAndComesBackTheSame() throws IOException {
Store store = new Store(false);
TreeFileSystem page = tree(store);
page.load(WORLD + "/level.dat", false, 500, bytes("level"));
page.loadStored(REGION, 700, 6);
// Written on the page (an imported world): in the store once flushed, sent as a size too.
page.load(WORLD + "/region/r.5.5.mca", false, 800, bytes("imported"));
page.collectChanges();
byte[] encoded = FileBundle.encode(new FileBundle.Bundle(true, page.export(WORLD, true)));
FileBundle.Bundle bundle = FileBundle.decode(encoded);
assertThat(bundle.inPlace()).isTrue();
assertThat(bundle.entries())
.extracting(FileBundle.Entry::path, FileBundle.Entry::stored, FileBundle.Entry::size)
.contains(
org.assertj.core.groups.Tuple.tuple(WORLD + "/level.dat", false, 5),
org.assertj.core.groups.Tuple.tuple(REGION, true, 6),
org.assertj.core.groups.Tuple.tuple(WORLD + "/region/r.5.5.mca", true, 8));
assertThat(store.reads).isZero();
}
@Test
void handedOverWithTheirBytesWhenNotInPlace() throws IOException {
Store store = new Store(false);
store.files.put(REGION, bytes("chunks"));
TreeFileSystem page = tree(store);
page.loadStored(REGION, 700, 6);
List<FileBundle.Entry> entries = page.export(WORLD, false);
assertThat(entries)
.filteredOn(entry -> entry.path().equals(REGION))
.singleElement()
.satisfies(entry -> {
assertThat(entry.stored()).isFalse();
assertThat(entry.contents()).isEqualTo(bytes("chunks"));
});
}
@Test
void thePageMovesARegionFileByReadingItAndTheWorkerWont() throws IOException {
Store pageStore = new Store(false);
pageStore.files.put(REGION, bytes("chunks"));
TreeFileSystem page = tree(pageStore);
page.load("/incari/game/saves", true, 1, null);
page.loadStored(REGION, 700, 6);
page.collectChanges();
assertThat(page.getFile("/incari/game/saves").adopt(page.getFile(WORLD), "Renamed"))
.isTrue();
assertThat(read(page, "/incari/game/saves/Renamed/region/r.0.0.mca")).isEqualTo("chunks");
assertThat(page.collectChanges())
.extracting(StoreOp::kind, StoreOp::path)
.contains(org.assertj.core.groups.Tuple.tuple(
StoreOp.Kind.WRITE, "/incari/game/saves/Renamed/region/r.0.0.mca"));
Store workerStore = new Store(true);
TreeFileSystem worker = tree(workerStore);
worker.load("/incari/game/saves", true, 1, null);
worker.loadStored(REGION, 700, 6);
assertThat(worker.getFile("/incari/game/saves").adopt(worker.getFile(WORLD), "Renamed"))
.isFalse();
}
@Test
void deletingARegionFileLetsItsHandleGoAndDeletesItFromTheStore() throws IOException {
Store store = new Store(true);
store.files.put(REGION, bytes("chunks"));
TreeFileSystem worker = tree(store);
worker.loadStored(REGION, 700, 6);
worker.collectChanges();
worker.getFile(REGION).createAccessor(true, true, false).close();
assertThat(store.open).isEqualTo(1);
assertThat(worker.getFile(REGION).delete()).isTrue();
assertThat(store.open).isZero();
assertThat(worker.collectChanges())
.extracting(StoreOp::kind, StoreOp::path)
.containsExactly(org.assertj.core.groups.Tuple.tuple(StoreOp.Kind.DELETE, REGION));
}
private static byte[] bytes(String text) {
return text.getBytes(StandardCharsets.UTF_8);
}
private static String read(TreeFileSystem files, String path) throws IOException {
VirtualFileAccessor file = files.getFile(path).createAccessor(true, false, false);
byte[] buffer = new byte[file.size()];
int count = file.read(buffer, 0, buffer.length);
file.close();
return new String(buffer, 0, count, StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,191 @@
package incari.platform.web.storage;
import static incari.platform.web.storage.TreeFileSystemTest.bytes;
import static org.assertj.core.api.Assertions.assertThat;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.teavm.runtime.fs.VirtualFile;
import org.teavm.runtime.fs.VirtualFileAccessor;
/** What a flush tells the store, for the ways the game changes its files. */
class JournalTest {
private TreeFileSystem files;
@BeforeEach
void setUp() throws IOException {
files = new TreeFileSystem(
new Journal("/incari", List.of("/incari/dropped", "/incari/classpath")), () -> 1_000);
files.load("/incari/game", true, 1, null);
files.load("/incari/dropped", true, 1, null);
files.collectChanges();
}
@Test
void aNewFileIsSentWholeOnce() throws IOException {
game().createFile("options.txt");
write("/incari/game/options.txt", "fov:90\n");
write("/incari/game/options.txt", "fov:100\n");
assertThat(describe(files.collectChanges())).containsExactly("write /incari/game/options.txt 8 @0 fov:100\n");
assertThat(files.hasChanges()).isFalse();
assertThat(files.collectChanges()).isEmpty();
}
@Test
void writesToAnExistingFileSendOnlyWhatChanged() throws IOException {
files.load("/incari/game/r.0.0.mca", false, 1, bytes("0123456789"));
VirtualFileAccessor region = files.getFile("/incari/game/r.0.0.mca").createAccessor(true, true, false);
region.seek(2);
region.write(bytes("ab"), 0, 2);
region.seek(6);
region.write(bytes("cd"), 0, 2);
assertThat(describe(files.collectChanges())).containsExactly("write /incari/game/r.0.0.mca 10 @2 ab45cd");
region.resize(4);
assertThat(describe(files.collectChanges())).containsExactly("write /incari/game/r.0.0.mca 4 @0 -");
}
@Test
void aFileTheStoreFailedToKeepIsSentWholeAgain() throws IOException {
files.load("/incari/game/r.0.0.mca", false, 1, bytes("0123456789"));
VirtualFileAccessor region = files.getFile("/incari/game/r.0.0.mca").createAccessor(true, true, false);
region.seek(2);
region.write(bytes("ab"), 0, 2);
files.collectChanges();
// That range never reached the store: what's sent now must cover it too.
files.resend("/incari/game/r.0.0.mca");
assertThat(describe(files.collectChanges())).containsExactly("write /incari/game/r.0.0.mca 10 @0 01ab456789");
}
@Test
void aDeleteTheStoreFailedToKeepIsSentAgain() throws IOException {
files.resend("/incari/game/gone.txt");
assertThat(describe(files.collectChanges())).containsExactly("delete /incari/game/gone.txt");
}
@Test
void writesFarApartAreSentApart() throws IOException {
// A region file's write: the chunk's offset in the header, then its sectors much further on.
files.load("/incari/game/r.0.0.mca", false, 1, new byte[20_000]);
VirtualFileAccessor region = files.getFile("/incari/game/r.0.0.mca").createAccessor(true, true, false);
region.seek(16_384);
region.write(bytes("chunk"), 0, 5);
region.seek(8);
region.write(bytes("hd"), 0, 2);
assertThat(describe(files.collectChanges()))
.containsExactly(
"write /incari/game/r.0.0.mca 20000 @8 hd", "write /incari/game/r.0.0.mca 20000 @16384 chunk");
}
@Test
void theServerListsSafeReplaceLeavesTheNewFileInPlace() throws IOException {
files.load("/incari/game/servers.dat", false, 1, bytes("old"));
// Util.safeReplaceFile: a temporary file, the old one moved to a backup, then the rename.
game().createFile("servers42.dat");
write("/incari/game/servers42.dat", "new");
game().adopt(files.getFile("/incari/game/servers.dat"), "servers.dat_old");
game().adopt(files.getFile("/incari/game/servers42.dat"), "servers.dat");
assertThat(describe(files.collectChanges()))
.containsExactly(
"write /incari/game/servers.dat 3 @0 new",
"write /incari/game/servers.dat_old 3 @0 old",
"delete /incari/game/servers42.dat");
}
@Test
void aNewFolderIsSentWithEverythingInIt() throws IOException {
game().createDirectory("resourcepacks");
files.getFile("/incari/game/resourcepacks").createFile("pack.zip");
write("/incari/game/resourcepacks/pack.zip", "PK");
assertThat(describe(files.collectChanges()))
.containsExactly(
"mkdir /incari/game/resourcepacks", "write /incari/game/resourcepacks/pack.zip 2 @0 PK");
}
@Test
void aMovedFolderIsSentWholeAtItsNewPathAndDeletedAtItsOld() throws IOException {
files.load("/incari/game/saves/A/level.dat", false, 1, bytes("L"));
files.getFile("/incari/game/saves").adopt(files.getFile("/incari/game/saves/A"), "B");
assertThat(describe(files.collectChanges()))
.containsExactly(
"mkdir /incari/game/saves/B",
"write /incari/game/saves/B/level.dat 1 @0 L",
"delete /incari/game/saves/A");
}
@Test
void aDeletedFolderIsOneDelete() throws IOException {
files.load("/incari/game/saves/A/level.dat", false, 1, bytes("L"));
files.getFile("/incari/game/saves/A/level.dat").delete();
files.getFile("/incari/game/saves/A").delete();
assertThat(describe(files.collectChanges())).containsExactly("delete /incari/game/saves/A");
}
@Test
void aFileCreatedAndDeletedInOneFrameStillDeletesWhateverWasStored() throws IOException {
game().createFile("tmp");
write("/incari/game/tmp", "x");
files.getFile("/incari/game/tmp").delete();
// The store may have a file there from before; deleting nothing is harmless.
assertThat(describe(files.collectChanges())).containsExactly("delete /incari/game/tmp");
}
@Test
void transientFoldersAndPathsOutsideTheRootArentSent() throws IOException {
files.getFile("/incari/dropped").createDirectory("1");
files.getFile("/incari/dropped/1").createFile("pack.zip");
write("/incari/dropped/1/pack.zip", "PK");
files.getFile("/").createDirectory("tmp");
files.getFile("/tmp").createFile("x");
assertThat(files.collectChanges()).isEmpty();
}
@Test
void aFileCopiedOutOfATransientFolderIsSent() throws IOException {
files.load("/incari/dropped/1/pack.zip", false, 1, bytes("PK"));
files.getFile("/incari/game").createDirectory("resourcepacks");
files.getFile("/incari/game/resourcepacks").adopt(files.getFile("/incari/dropped/1/pack.zip"), "pack.zip");
assertThat(describe(files.collectChanges()))
.containsExactly(
"mkdir /incari/game/resourcepacks", "write /incari/game/resourcepacks/pack.zip 2 @0 PK");
}
@Test
void settingATimeSendsNoBytes() throws IOException {
files.load("/incari/game/level.dat", false, 1, bytes("L"));
files.getFile("/incari/game/level.dat").setLastModified(99);
assertThat(files.collectChanges()).singleElement().satisfies(op -> {
assertThat(op.data()).isNull();
assertThat(op.lastModified()).isEqualTo(99);
assertThat(op.size()).isEqualTo(1);
});
}
private VirtualFile game() {
return files.getFile("/incari/game");
}
private void write(String path, String text) throws IOException {
VirtualFileAccessor accessor = files.getFile(path).createAccessor(false, true, false);
byte[] bytes = bytes(text);
accessor.write(bytes, 0, bytes.length);
accessor.close();
}
private static List<String> describe(List<StoreOp> ops) {
return ops.stream()
.map(op -> switch (op.kind()) {
case MKDIR -> "mkdir " + op.path();
case DELETE -> "delete " + op.path();
case WRITE -> {
byte[] data = op.data();
yield "write " + op.path() + " " + op.size() + " @" + op.at() + " "
+ (data == null ? "-" : new String(data, StandardCharsets.UTF_8));
}
})
.toList();
}
}
@@ -0,0 +1,186 @@
package incari.platform.web.storage;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.List;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.teavm.runtime.fs.VirtualFile;
import org.teavm.runtime.fs.VirtualFileAccessor;
/** The tree as TeaVM's file classes use it, through {@code VirtualFile} and its accessors. */
class TreeFileSystemTest {
private long time = 1_000;
private TreeFileSystem files;
@BeforeEach
void setUp() throws IOException {
files = new TreeFileSystem(new Journal("/incari", List.of("/incari/dropped")), () -> time);
files.setWorkingDirectory("/incari/game");
}
@Test
void pathsAreNormalizedAndRelativeOnesStartAtTheWorkingDirectory() {
assertThat(files.normalize("/a//b/./c/../d/")).isEqualTo("/a/b/d");
assertThat(files.normalize("/..")).isEqualTo("/");
assertThat(files.normalize("options.txt")).isEqualTo("/incari/game/options.txt");
assertThat(files.canonicalize("../x")).isEqualTo("/incari/x");
assertThat(files.getUserDir()).isEqualTo("/incari/game");
assertThat(files.getFile("/").isDirectory()).isTrue();
}
@Test
void filesAreCreatedWrittenAndRead() throws IOException {
VirtualFile game = files.getFile("/incari/game");
assertThat(game.createFile("options.txt")).isTrue();
assertThat(game.createFile("options.txt")).isFalse();
write("/incari/game/options.txt", "fov:90");
assertThat(read("/incari/game/options.txt")).isEqualTo("fov:90");
assertThat(files.getFile("options.txt").length()).isEqualTo(6);
assertThat(game.listFiles()).containsExactly("options.txt");
assertThat(files.getFile("/incari/game/options.txt").isFile()).isTrue();
assertThat(files.getFile("/incari/game/options.txt/x").exists()).isFalse();
}
@Test
void writingWithoutReadingReplacesTheContentsButReadWriteKeepsThem() throws IOException {
files.getFile("/incari/game").createFile("f");
write("/incari/game/f", "hello world");
// RandomAccessFile(file, "rw"): TeaVM's own file system empties the file here, the JDK doesn't.
VirtualFileAccessor both = files.getFile("/incari/game/f").createAccessor(true, true, false);
assertThat(both.size()).isEqualTo(11);
both.seek(6);
both.write(bytes("there"), 0, 5);
both.close();
assertThat(read("/incari/game/f")).isEqualTo("hello there");
// FileOutputStream(file): a new file's worth.
write("/incari/game/f", "hi");
assertThat(read("/incari/game/f")).isEqualTo("hi");
// FileOutputStream(file, true): appended.
VirtualFileAccessor append = files.getFile("/incari/game/f").createAccessor(false, true, true);
append.write(bytes("!"), 0, 1);
assertThat(read("/incari/game/f")).isEqualTo("hi!");
}
@Test
void aSeekPastTheEndLeavesZerosAndAShrinkForgetsWhatWasCut() throws IOException {
files.getFile("/incari/game").createFile("f");
VirtualFileAccessor file = files.getFile("/incari/game/f").createAccessor(true, true, false);
file.write(bytes("abcdef"), 0, 6);
file.resize(2);
file.seek(4);
file.write(bytes("z"), 0, 1);
assertThat(file.size()).isEqualTo(5);
byte[] all = new byte[5];
file.seek(0);
assertThat(file.read(all, 0, 5)).isEqualTo(5);
assertThat(all).containsExactly('a', 'b', 0, 0, 'z');
assertThat(file.read(all, 0, 5)).isZero();
}
@Test
void foldersAreMadeListedAndDeletedWhenEmpty() {
VirtualFile game = files.getFile("/incari/game");
assertThat(game.createDirectory("saves")).isTrue();
assertThat(game.createDirectory("saves")).isFalse();
assertThat(files.getFile("/incari/game/saves").createDirectory("World")).isTrue();
assertThat(files.getFile("/incari/game/saves").delete()).isFalse();
assertThat(files.getFile("/incari/game/saves/World").delete()).isTrue();
assertThat(files.getFile("/incari/game/saves").delete()).isTrue();
assertThat(files.getFile("/incari/game/saves").exists()).isFalse();
assertThat(files.getFile("/").delete()).isFalse();
}
@Test
void createFileInAMissingFolderFails() {
assertThatThrownBy(() -> files.getFile("/incari/nowhere").createFile("x"))
.isInstanceOf(IOException.class);
}
@Test
void renamesMoveFilesAndReplaceFilesButNotFolders() throws IOException {
VirtualFile game = files.getFile("/incari/game");
game.createFile("servers123.dat");
write("/incari/game/servers123.dat", "new");
game.createFile("servers.dat");
write("/incari/game/servers.dat", "old");
assertThat(game.adopt(files.getFile("/incari/game/servers123.dat"), "servers.dat"))
.isTrue();
assertThat(read("/incari/game/servers.dat")).isEqualTo("new");
assertThat(files.getFile("/incari/game/servers123.dat").exists()).isFalse();
game.createDirectory("dir");
files.getFile("/incari/game/dir").createFile("inside");
assertThat(game.adopt(files.getFile("/incari/game/servers.dat"), "dir")).isFalse();
// A folder can't go inside itself.
assertThat(files.getFile("/incari/game/dir").adopt(files.getFile("/incari/game/dir"), "again"))
.isFalse();
assertThat(files.getFile("/incari").adopt(files.getFile("/incari/game/dir"), "moved"))
.isTrue();
assertThat(files.getFile("/incari/moved/inside").isFile()).isTrue();
}
@Test
void anOpenFileKeepsWorkingAfterItsDeleted() throws IOException {
files.getFile("/incari/game").createFile("f");
VirtualFileAccessor open = files.getFile("/incari/game/f").createAccessor(true, true, false);
assertThat(files.getFile("/incari/game/f").delete()).isTrue();
open.write(bytes("still"), 0, 5);
assertThat(open.size()).isEqualTo(5);
assertThat(files.getFile("/incari/game/f").exists()).isFalse();
}
@Test
void timesFollowWrites() throws IOException {
files.getFile("/incari/game").createFile("f");
time = 5_000;
write("/incari/game/f", "x");
assertThat(files.getFile("/incari/game/f").lastModified()).isEqualTo(5_000);
assertThat(files.getFile("/incari/game/f").setLastModified(42)).isTrue();
assertThat(files.getFile("/incari/game/f").lastModified()).isEqualTo(42);
}
@Test
void readOnlyFilesRefuseWriters() throws IOException {
files.getFile("/incari/game").createFile("f");
assertThat(files.getFile("/incari/game/f").setReadOnly(true)).isTrue();
assertThat(files.getFile("/incari/game/f").canWrite()).isFalse();
assertThat(files.getFile("/incari/game/f").createAccessor(false, true, false))
.isNull();
assertThat(files.getFile("/incari/game/f").createAccessor(true, false, false))
.isNotNull();
}
@Test
void storedFilesLoadWithoutCountingAsChanges() throws IOException {
files.load("/incari/game/servers.dat", false, 77, bytes("stored"));
files.load("/incari/game/saves", true, 78, null);
assertThat(read("/incari/game/servers.dat")).isEqualTo("stored");
assertThat(files.getFile("/incari/game/servers.dat").lastModified()).isEqualTo(77);
assertThat(files.getFile("/incari/game/saves").isDirectory()).isTrue();
assertThat(files.hasChanges()).isFalse();
}
private void write(String path, String text) throws IOException {
VirtualFileAccessor accessor = files.getFile(path).createAccessor(false, true, false);
byte[] bytes = bytes(text);
accessor.write(bytes, 0, bytes.length);
accessor.close();
}
private String read(String path) throws IOException {
VirtualFileAccessor accessor = files.getFile(path).createAccessor(true, false, false);
byte[] bytes = new byte[accessor.size()];
int read = accessor.read(bytes, 0, bytes.length);
accessor.close();
return new String(bytes, 0, read, StandardCharsets.UTF_8);
}
static byte[] bytes(String text) {
return text.getBytes(StandardCharsets.UTF_8);
}
}
@@ -0,0 +1,183 @@
package incari.platform.web.storage;
import static incari.platform.web.storage.TreeFileSystemTest.bytes;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.List;
import java.util.Random;
import java.util.zip.CRC32;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import org.junit.jupiter.api.Test;
import org.teavm.runtime.fs.VirtualFileAccessor;
/** The client jar mounted in place: its central directory read once, entries inflated on open. */
class ZipMountTest {
private final TreeFileSystem files =
new TreeFileSystem(new Journal("/incari", List.of("/incari/classpath")), () -> 5);
@Test
void includedEntriesMountReadOnlyAndReadBack() throws IOException {
byte[] noise = new byte[100_000];
new Random(1).nextBytes(noise);
byte[] zip = zip(
deflated("version.json", bytes("{\"id\":\"26.3\"}")),
stored("assets/minecraft/lang/en_us.json", bytes("{\"menu.singleplayer\":\"Singleplayer\"}")),
deflated("assets/minecraft/textures/noise.bin", noise),
deflated("net/minecraft/client/Minecraft.class", bytes("class")),
deflated("META-INF/MANIFEST.MF", bytes("Manifest-Version: 1.0")),
directory("data/"),
deflated("pack.png", new byte[0]));
int mounted = files.mount(
"/incari/classpath",
ZipArchive.open(source(zip)),
name -> !name.endsWith(".class") && !name.startsWith("META-INF/"));
assertThat(mounted).isEqualTo(4);
assertThat(read("/incari/classpath/version.json")).isEqualTo("{\"id\":\"26.3\"}");
assertThat(read("/incari/classpath/assets/minecraft/lang/en_us.json")).contains("Singleplayer");
assertThat(readBytes("/incari/classpath/assets/minecraft/textures/noise.bin"))
.isEqualTo(noise);
assertThat(files.getFile("/incari/classpath/assets/minecraft/textures/noise.bin")
.length())
.isEqualTo(noise.length);
assertThat(read("/incari/classpath/pack.png")).isEmpty();
assertThat(files.getFile("/incari/classpath/net").exists()).isFalse();
assertThat(files.getFile("/incari/classpath").listFiles())
.containsExactly("assets", "pack.png", "version.json");
// Read-only: no writers, no new files, no deletes, no renames out.
assertThat(files.getFile("/incari/classpath/version.json").createAccessor(true, true, false))
.isNull();
assertThat(files.getFile("/incari/classpath/version.json").canWrite()).isFalse();
assertThatThrownBy(() -> files.getFile("/incari/classpath/assets").createFile("x"))
.isInstanceOf(IOException.class);
assertThat(files.getFile("/incari/classpath/assets").createDirectory("x"))
.isFalse();
assertThat(files.getFile("/incari/classpath/version.json").delete()).isFalse();
files.getFile("/incari").createDirectory("game");
assertThat(files.getFile("/incari/game").adopt(files.getFile("/incari/classpath/version.json"), "v"))
.isFalse();
assertThat(files.hasChanges()).isTrue();
assertThat(files.collectChanges()).extracting(StoreOp::path).containsExactly("/incari/game");
}
@Test
void theEndRecordIsFoundBehindAComment() throws IOException {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
zip.setComment("x".repeat(1000));
zip.putNextEntry(new ZipEntry("a.txt"));
zip.write(bytes("a"));
}
ZipArchive archive = ZipArchive.open(source(out.toByteArray()));
assertThat(archive.entries()).extracting(ZipArchive.Entry::name).containsExactly("a.txt");
assertThat(archive.read(archive.entries().getFirst())).isEqualTo(bytes("a"));
}
@Test
void somethingElseIsntAZip() {
assertThatThrownBy(() -> ZipArchive.open(source(bytes("not a zip at all, just text"))))
.isInstanceOf(IOException.class)
.hasMessageContaining("Not a zip");
byte[] zip = zip(deflated("a.txt", bytes("aaaa")));
assertThatThrownBy(() -> ZipArchive.open(source(Arrays.copyOf(zip, zip.length - 30))))
.isInstanceOf(IOException.class);
}
@Test
void compactedEntriesReadAsTheZipsDo() throws IOException {
byte[] noise = new byte[100_000];
new Random(2).nextBytes(noise);
byte[] zip = zip(
deflated("version.json", bytes("{\"id\":\"26.3\"}")),
deflated("assets/minecraft/textures/noise.bin", noise),
stored("data/minecraft/tags/block/logs.json", bytes("{\"values\":[]}")),
deflated("data/minecraft/noise.bin", noise),
deflated("net/minecraft/server/Main.class", bytes("class")));
ZipArchive compacted = ZipArchive.open(source(zip)).compact(name -> !name.startsWith("assets/"));
// Only what was kept, still compressed: far smaller than the zip with its 100 kB of noise.
assertThat(compacted.entries())
.extracting(ZipArchive.Entry::name)
.containsExactly(
"version.json",
"data/minecraft/tags/block/logs.json",
"data/minecraft/noise.bin",
"net/minecraft/server/Main.class");
int mounted = files.mount("/incari/classpath", compacted, name -> !name.endsWith(".class"));
assertThat(mounted).isEqualTo(3);
assertThat(read("/incari/classpath/version.json")).isEqualTo("{\"id\":\"26.3\"}");
assertThat(read("/incari/classpath/data/minecraft/tags/block/logs.json"))
.isEqualTo("{\"values\":[]}");
assertThat(readBytes("/incari/classpath/data/minecraft/noise.bin")).isEqualTo(noise);
assertThat(files.getFile("/incari/classpath/assets").exists()).isFalse();
}
private String read(String path) throws IOException {
return new String(readBytes(path), StandardCharsets.UTF_8);
}
private byte[] readBytes(String path) throws IOException {
VirtualFileAccessor accessor = files.getFile(path).createAccessor(true, false, false);
byte[] bytes = new byte[accessor.size()];
int done = 0;
while (done < bytes.length) {
done += accessor.read(bytes, done, bytes.length - done);
}
return bytes;
}
private static ZipArchive.Source source(byte[] zip) {
return new ZipArchive.Source() {
@Override
public int size() {
return zip.length;
}
@Override
public byte[] read(int position, int length) {
return Arrays.copyOfRange(zip, position, position + length);
}
};
}
@SuppressWarnings("ArrayRecordComponent") // Test data, never compared.
private record Item(ZipEntry entry, byte[] data) {}
private static Item deflated(String name, byte[] data) {
return new Item(new ZipEntry(name), data);
}
private static Item stored(String name, byte[] data) {
ZipEntry entry = new ZipEntry(name);
entry.setMethod(ZipEntry.STORED);
entry.setSize(data.length);
CRC32 crc = new CRC32();
crc.update(data);
entry.setCrc(crc.getValue());
return new Item(entry, data);
}
private static Item directory(String name) {
return new Item(new ZipEntry(name), new byte[0]);
}
private static byte[] zip(Item... items) {
ByteArrayOutputStream out = new ByteArrayOutputStream();
try (ZipOutputStream zip = new ZipOutputStream(out)) {
for (Item item : items) {
zip.putNextEntry(item.entry());
zip.write(item.data());
zip.closeEntry();
}
} catch (IOException e) {
throw new IllegalStateException(e);
}
return out.toByteArray();
}
}
@@ -0,0 +1,136 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, it } from "node:test";
import { runInThisContext } from "node:vm";
// The program worker's bootstrap as the page runs it: its source, run against a stand-in for the
// worker's global scope whose TeaVM loader "loads" a program written here, driven through the
// messages the page sends.
const source = readFileSync(new URL("../../main/js/program-worker.js", import.meta.url), "utf8");
type Message = Record<string, unknown>;
/** A stand-in program: answers each message with its bytes reversed; an empty one gets no answer. */
function reversingProgram() {
let memory = new Int8Array(16);
let reply = new Int8Array(0);
return {
input(length: number): Int8Array {
if (memory.length < length) {
memory = new Int8Array(length);
}
return memory.subarray(0, length);
},
handle(length: number): number {
if (length === 0) {
return -1;
}
reply = memory.slice(0, length).reverse();
return length;
},
output(length: number): Int8Array {
return reply.subarray(0, length);
},
};
}
class Worker {
readonly posted: Message[] = [];
private onmessage: ((event: { data: Message }) => void) | null = null;
private readonly waiting: { match: (message: Message) => boolean; resolve: (message: Message) => void }[] = [];
readonly imported: string[] = [];
constructor(program: ReturnType<typeof reversingProgram> | null) {
const listen = (handler: ((event: { data: Message }) => void) | null) => {
this.onmessage = handler;
};
const scope: Record<string, unknown> = {
postMessage: (message: Message) => {
this.posted.push(message);
const index = this.waiting.findIndex((wait) => wait.match(message));
if (index >= 0) {
const [wait] = this.waiting.splice(index, 1);
wait?.resolve(message);
}
},
set onmessage(handler: ((event: { data: Message }) => void) | null) {
listen(handler);
},
importScripts: (url: string) => {
this.imported.push(url);
scope.TeaVM = {
wasmGC: {
load: (module: string) => {
this.imported.push(module);
return Promise.resolve({
exports: {
main: () => {
if (program) {
scope.__incariProgram = program;
}
},
},
});
},
},
};
},
};
const start = runInThisContext(`(function(globalThis) {\n${source}\n})`) as (scope: unknown) => void;
start(scope);
}
send(message: Message): void {
this.onmessage?.({ data: message });
}
waitFor(match: (message: Message) => boolean): Promise<Message> {
const already = this.posted.find(match);
return already ? Promise.resolve(already) : new Promise((resolve) => this.waiting.push({ match, resolve }));
}
}
function job(id: number, bytes: number[], shared = false): Message {
const buffer = shared ? new SharedArrayBuffer(64) : new ArrayBuffer(64);
new Int8Array(buffer, 8, bytes.length).set(bytes);
return { id, buffer, offset: 8, length: bytes.length };
}
describe("the program worker", () => {
it("loads the program, then answers each message with the program's reply", async () => {
const worker = new Worker(reversingProgram());
// A message before the program has started waits for it.
worker.send(job(1, [1, 2, 3]));
worker.send({ kind: "start", runtime: "https://page/mesher.wasm-runtime.js", module: "https://page/mesher.wasm" });
await worker.waitFor((message) => message.kind === "ready");
assert.deepEqual(worker.imported, ["https://page/mesher.wasm-runtime.js", "https://page/mesher.wasm"]);
const first = await worker.waitFor((message) => message.id === 1);
assert.deepEqual([...new Int8Array(first.reply as ArrayBuffer)], [3, 2, 1]);
worker.send(job(2, [9, 8], true));
const second = await worker.waitFor((message) => message.id === 2);
assert.deepEqual([...new Int8Array(second.reply as ArrayBuffer)], [8, 9]);
});
it("answers a message the program doesn't reply to with nothing, and one with no id not at all", async () => {
const worker = new Worker(reversingProgram());
worker.send({ kind: "start", runtime: "r.js", module: "m.wasm" });
await worker.waitFor((message) => message.kind === "ready");
worker.send(job(-1, [5]));
worker.send(job(3, []));
const answer = await worker.waitFor((message) => message.id === 3);
assert.equal((answer.reply as ArrayBuffer).byteLength, 0);
assert.equal(
worker.posted.some((message) => message.id === -1),
false,
);
});
it("says so when the program doesn't start", async () => {
const worker = new Worker(null);
worker.send({ kind: "start", runtime: "r.js", module: "m.wasm" });
const failed = await worker.waitFor((message) => message.kind === "failed");
assert.match(String(failed.error), /didn't install its handlers/);
});
});
@@ -0,0 +1,576 @@
import assert from "node:assert/strict";
import { readFileSync } from "node:fs";
import { describe, it } from "node:test";
import { runInThisContext } from "node:vm";
import { IDBFactory, IDBKeyRange } from "fake-indexeddb";
// The storage worker as the page runs it: its source, run against a stand-in for the worker's
// global scope, driven through the same messages the page sends.
const source = readFileSync(new URL("../../main/js/storage-worker.js", import.meta.url), "utf8");
type Message = Record<string, unknown>;
function domError(name: string, message: string): Error {
const error = new Error(message);
error.name = name;
return error;
}
/** An origin private file system in memory, as much of it as the worker uses. */
class FakeFile {
readonly kind = "file";
data = new Uint8Array(0);
lastModified = 1;
openHandles = 0;
readonly withSyncHandles: boolean;
constructor(withSyncHandles: boolean) {
this.withSyncHandles = withSyncHandles;
}
reads = 0;
getFile(): Promise<{ lastModified: number; size: number; arrayBuffer(): Promise<ArrayBuffer> }> {
const copy = this.data.slice();
const lastModified = this.lastModified;
return Promise.resolve({
lastModified,
size: copy.byteLength,
arrayBuffer: () => {
this.reads++;
return Promise.resolve(copy.buffer);
},
});
}
get createSyncAccessHandle(): (() => Promise<unknown>) | undefined {
if (!this.withSyncHandles) {
return undefined;
}
return () => {
if (this.openHandles > 0) {
return Promise.reject(domError("NoModificationAllowedError", "already open"));
}
this.openHandles++;
return Promise.resolve({
truncate: (size: number) => {
const next = new Uint8Array(size);
next.set(this.data.subarray(0, Math.min(size, this.data.length)));
this.data = next;
},
write: (data: Uint8Array, options: { at: number }) => {
const end = options.at + data.byteLength;
if (end > this.data.length) {
const next = new Uint8Array(end);
next.set(this.data);
this.data = next;
}
this.data.set(data, options.at);
this.lastModified++;
return data.byteLength;
},
flush: () => undefined,
close: () => {
this.openHandles--;
},
});
};
}
get createWritable(): (() => Promise<unknown>) | undefined {
if (this.withSyncHandles) {
return undefined;
}
return () => {
let copy = this.data.slice();
return Promise.resolve({
truncate: (size: number) => {
const next = new Uint8Array(size);
next.set(copy.subarray(0, Math.min(size, copy.length)));
copy = next;
return Promise.resolve();
},
write: (params: { position: number; data: Uint8Array }) => {
const end = params.position + params.data.byteLength;
if (end > copy.length) {
const next = new Uint8Array(end);
next.set(copy);
copy = next;
}
copy.set(params.data, params.position);
return Promise.resolve();
},
close: () => {
this.data = copy;
return Promise.resolve();
},
});
};
}
}
class FakeDirectory {
readonly kind = "directory";
readonly children = new Map<string, FakeDirectory | FakeFile>();
readonly withSyncHandles: boolean;
constructor(withSyncHandles = true) {
this.withSyncHandles = withSyncHandles;
}
getDirectoryHandle(name: string, options?: { create?: boolean }): Promise<FakeDirectory> {
const child = this.children.get(name);
if (child instanceof FakeDirectory) {
return Promise.resolve(child);
}
if (child) {
return Promise.reject(domError("TypeMismatchError", `${name} is a file`));
}
if (!options?.create) {
return Promise.reject(domError("NotFoundError", `no ${name}`));
}
const made = new FakeDirectory(this.withSyncHandles);
this.children.set(name, made);
return Promise.resolve(made);
}
getFileHandle(name: string, options?: { create?: boolean }): Promise<FakeFile> {
const child = this.children.get(name);
if (child instanceof FakeFile) {
return Promise.resolve(child);
}
if (child) {
return Promise.reject(domError("TypeMismatchError", `${name} is a folder`));
}
if (!options?.create) {
return Promise.reject(domError("NotFoundError", `no ${name}`));
}
const made = new FakeFile(this.withSyncHandles);
this.children.set(name, made);
return Promise.resolve(made);
}
removeEntry(name: string, options?: { recursive?: boolean }): Promise<void> {
const child = this.children.get(name);
if (!child) {
return Promise.reject(domError("NotFoundError", `no ${name}`));
}
if (child instanceof FakeDirectory && child.children.size > 0 && !options?.recursive) {
return Promise.reject(domError("InvalidModificationError", `${name} isn't empty`));
}
this.children.delete(name);
return Promise.resolve();
}
async *entries(): AsyncGenerator<[string, FakeDirectory | FakeFile]> {
for (const entry of [...this.children.entries()]) {
await Promise.resolve();
yield entry;
}
}
}
/** The text of the file at a path in a stand-in file system, or undefined. */
function textAt(root: FakeDirectory, path: string): string | undefined {
const names = path.split("/").filter((part) => part.length > 0);
let node: FakeDirectory | FakeFile | undefined = root;
for (const name of names) {
node = node instanceof FakeDirectory ? node.children.get(name) : undefined;
}
return node instanceof FakeFile ? new TextDecoder().decode(node.data) : undefined;
}
interface Options {
opfs?: FakeDirectory | null;
indexedDB?: IDBFactory;
lockTaken?: boolean;
fetch?: (url: string) => Promise<Response>;
}
/** A worker started on a stand-in scope, and a way to talk to it. */
class Worker {
readonly posted: Message[] = [];
private readonly waiting: { match: (message: Message) => boolean; resolve: (message: Message) => void }[] = [];
private onmessage: ((event: { data: Message }) => void) | null = null;
private next = 1;
constructor(options: Options) {
const listen = (handler: ((event: { data: Message }) => void) | null) => {
this.onmessage = handler;
};
const scope = {
postMessage: (message: Message) => {
this.posted.push(message);
const index = this.waiting.findIndex((wait) => wait.match(message));
if (index >= 0) {
const [wait] = this.waiting.splice(index, 1);
wait?.resolve(message);
}
},
set onmessage(handler: ((event: { data: Message }) => void) | null) {
listen(handler);
},
navigator: {
storage: {
getDirectory: () =>
options.opfs ? Promise.resolve(options.opfs) : Promise.reject(domError("SecurityError", "no OPFS here")),
},
locks: {
request: (_name: string, _options: unknown, callback: (lock: object | null) => unknown) => {
void callback(options.lockTaken ? null : {});
return Promise.resolve();
},
},
},
indexedDB: options.indexedDB,
IDBKeyRange,
fetch: options.fetch ?? (() => Promise.reject(new Error("no network in this test"))),
};
const start = runInThisContext(`(function(globalThis) {\n${source}\n})`) as (scope: unknown) => void;
start(scope);
}
send(message: Message): void {
this.onmessage?.({ data: message });
}
/** Sends a message with a new id and waits for the answer with that id. */
request(message: Message): Promise<Message> {
const id = this.next++;
const answer = this.waitFor((reply) => reply.id === id);
this.send({ ...message, id });
return answer;
}
/** Sends a batch of changes and waits until they're stored. */
apply(ops: Message[]): Promise<Message> {
const done = this.waitFor((reply) => reply.type === "applied");
this.send({ type: "apply", ops });
return done;
}
waitFor(match: (message: Message) => boolean): Promise<Message> {
return new Promise((resolve) => this.waiting.push({ match, resolve }));
}
open(inPlace?: { within: string; suffixes: string[] }): Promise<Message> {
return this.request({ type: "open", root: "/incari", lock: "incari-storage", inPlace });
}
}
/**
* One end of a message channel, as the worker sees a port: what it posts is recorded, and what's
* sent to it before it has a handler waits for one, as a real port's messages do.
*/
class FakePort {
readonly posted: Message[] = [];
private handler: ((event: { data: Message }) => void) | null = null;
private readonly early: Message[] = [];
private readonly waiting: { match: (message: Message) => boolean; resolve: (message: Message) => void }[] = [];
get onmessage(): ((event: { data: Message }) => void) | null {
return this.handler;
}
set onmessage(handler: ((event: { data: Message }) => void) | null) {
this.handler = handler;
for (const message of this.early.splice(0)) {
handler?.({ data: message });
}
}
postMessage(message: Message): void {
this.posted.push(message);
const index = this.waiting.findIndex((wait) => wait.match(message));
if (index >= 0) {
const [wait] = this.waiting.splice(index, 1);
wait?.resolve(message);
}
}
/** Sends the worker a message on this port, and waits for an answer that matches. */
ask(message: Message, match: (reply: Message) => boolean): Promise<Message> {
const answer = new Promise<Message>((resolve) => this.waiting.push({ match, resolve }));
if (this.handler) {
this.handler({ data: message });
} else {
this.early.push(message);
}
return answer;
}
}
/** The stand-in file at a path, or undefined. */
function fileAt(root: FakeDirectory, path: string): FakeFile | undefined {
const names = path.split("/").filter((part) => part.length > 0);
let node: FakeDirectory | FakeFile | undefined = root;
for (const name of names) {
node = node instanceof FakeDirectory ? node.children.get(name) : undefined;
}
return node instanceof FakeFile ? node : undefined;
}
function bytes(text: string): Uint8Array {
return new TextEncoder().encode(text);
}
interface Entry {
path: string;
dir: boolean;
data: ArrayBuffer | null;
}
/** The entries an "open" answered, as "path" for folders and "path=text" for files, sorted. */
function listing(reply: Message): string[] {
const entries = reply.entries as Entry[];
return entries
.map((entry) => (entry.dir ? entry.path : `${entry.path}=${new TextDecoder().decode(entry.data ?? undefined)}`))
.sort();
}
const changes: Message[] = [
{ op: "mkdir", path: "/incari/game", mtime: 1 },
{ op: "write", path: "/incari/game/options.txt", size: 7, at: 0, data: bytes("fov:0.5"), mtime: 2 },
{ op: "write", path: "/incari/game/servers.dat", size: 3, at: 0, data: bytes("abc"), mtime: 3 },
{ op: "mkdir", path: "/incari/game/resourcepacks", mtime: 4 },
{ op: "write", path: "/incari/game/resourcepacks/p.zip", size: 2, at: 0, data: bytes("PK"), mtime: 5 },
// Part of a file: bytes 1-2 of servers.dat, which also grows to 5 bytes.
{ op: "write", path: "/incari/game/servers.dat", size: 5, at: 1, data: bytes("XY"), mtime: 6 },
{ op: "delete", path: "/incari/game/resourcepacks" },
];
const afterChanges = ["/incari/game", "/incari/game/options.txt=fov:0.5", "/incari/game/servers.dat=aXY\0\0"];
describe("the storage worker", () => {
for (const withSyncHandles of [true, false]) {
it(`keeps files in the origin private file system (${withSyncHandles ? "sync handles" : "writable streams"})`, async () => {
const opfs = new FakeDirectory(withSyncHandles);
const first = new Worker({ opfs });
const opened = await first.open();
assert.equal(opened.backend, "opfs");
assert.equal(opened.readOnly, false);
assert.deepEqual(opened.entries, []);
const applied = await first.apply(changes);
assert.equal(applied.error, undefined);
assert.equal(textAt(opfs, "/incari/game/options.txt"), "fov:0.5");
// The next page load.
const second = new Worker({ opfs });
assert.deepEqual(listing(await second.open()), afterChanges);
const read = await second.request({ type: "read", path: "/incari/game/options.txt" });
assert.equal(new TextDecoder().decode(read.data as ArrayBuffer), "fov:0.5");
assert.equal((await second.request({ type: "read", path: "/incari/nothing" })).data, null);
assert.deepEqual((await second.request({ type: "list", path: "/incari/game" })).paths, [
"/incari/game/options.txt",
"/incari/game/servers.dat",
]);
});
}
it("lists in-place files with their sizes and leaves their bytes where they are", async () => {
const opfs = new FakeDirectory();
const first = new Worker({ opfs });
await first.open();
const region = "/incari/game/saves/World/region/r.0.0.mca";
await first.apply([
{ op: "write", path: region, size: 5, at: 0, data: bytes("chunk"), mtime: 1 },
{ op: "write", path: "/incari/game/saves/World/level.dat", size: 1, at: 0, data: bytes("L"), mtime: 1 },
{ op: "write", path: "/incari/game/r.0.0.mca", size: 3, at: 0, data: bytes("not"), mtime: 1 },
]);
const reads = fileAt(opfs, region)?.reads ?? -1;
const second = new Worker({ opfs });
const opened = await second.open({ within: "/saves/", suffixes: [".mca", ".mcc"] });
const entries = opened.entries as (Entry & { size?: number; stored?: boolean })[];
const stored = entries.find((entry) => entry.path === region);
assert.deepEqual([stored?.stored, stored?.size, stored?.data], [true, 5, null]);
assert.equal(fileAt(opfs, region)?.reads, reads);
// Only inside a saves folder.
assert.equal(entries.find((entry) => entry.path === "/incari/game/r.0.0.mca")?.stored, undefined);
assert.ok(listing(opened).includes("/incari/game/saves/World/level.dat=L"));
const stat = await second.request({ type: "stat", path: "/incari/game/saves/World" });
const sizes = (stat.entries as { path: string; size?: number }[])
.filter((entry) => entry.size !== undefined)
.map((entry) => `${entry.path}:${String(entry.size)}`)
.sort();
assert.deepEqual(sizes, ["/incari/game/saves/World/level.dat:1", `${region}:5`]);
});
it("stores the rest of a batch when one change fails, and names the one that did", async () => {
const opfs = new FakeDirectory();
const worker = new Worker({ opfs });
await worker.open();
await worker.apply([{ op: "write", path: "/incari/held", size: 1, at: 0, data: bytes("h"), mtime: 1 }]);
const held = (opfs.children.get("incari") as FakeDirectory).children.get("held") as FakeFile;
held.openHandles = 1;
const applied = await worker.apply([
{ op: "write", path: "/incari/held", size: 2, at: 1, data: bytes("2"), mtime: 2 },
{ op: "write", path: "/incari/fine", size: 1, at: 0, data: bytes("f"), mtime: 2 },
]);
assert.match(String(applied.error), /NoModificationAllowedError/);
assert.deepEqual(applied.failed, ["/incari/held"]);
assert.equal(textAt(opfs, "/incari/fine"), "f");
assert.equal(textAt(opfs, "/incari/held"), "h");
});
it("writes a file's ranges through one handle, in order", async () => {
const opfs = new FakeDirectory();
const worker = new Worker({ opfs });
await worker.open();
await worker.apply([{ op: "write", path: "/incari/r.mca", size: 10, at: 0, data: bytes("0123456789"), mtime: 1 }]);
const applied = await worker.apply([
{ op: "write", path: "/incari/r.mca", size: 12, at: 1, data: bytes("ab"), mtime: 2 },
{ op: "write", path: "/incari/r.mca", size: 12, at: 9, data: bytes("XYZ"), mtime: 2 },
{ op: "write", path: "/incari/other", size: 1, at: 0, data: bytes("o"), mtime: 2 },
]);
assert.equal(applied.error, undefined);
assert.equal(textAt(opfs, "/incari/r.mca"), "0ab345678XYZ");
assert.equal(textAt(opfs, "/incari/other"), "o");
});
it("takes changes from a port, in the page's queue, and answers there", async () => {
const opfs = new FakeDirectory();
const worker = new Worker({ opfs });
await worker.open();
const port = new FakePort();
worker.send({ type: "port", port });
const applied = await port.ask(
{
type: "apply",
ops: [{ op: "write", path: "/incari/game/saves/W/level.dat", size: 1, at: 0, data: bytes("1"), mtime: 1 }],
},
(reply) => reply.type === "applied",
);
assert.equal(applied.error, undefined);
assert.equal(textAt(opfs, "/incari/game/saves/W/level.dat"), "1");
const synced = await port.ask({ type: "sync", id: 7 }, (reply) => reply.id === 7);
assert.equal(synced.error, undefined);
// The page's own requests still answer the page.
assert.equal((await worker.request({ type: "sync" })).error, undefined);
assert.equal(port.posted.length, 2);
});
it("replaces a file with a folder and a folder with a file", async () => {
const opfs = new FakeDirectory();
const worker = new Worker({ opfs });
await worker.open();
await worker.apply([
{ op: "write", path: "/incari/a", size: 1, at: 0, data: bytes("1"), mtime: 1 },
{ op: "mkdir", path: "/incari/b/c", mtime: 1 },
]);
await worker.apply([
{ op: "mkdir", path: "/incari/a", mtime: 2 },
{ op: "write", path: "/incari/b", size: 1, at: 0, data: bytes("2"), mtime: 2 },
{ op: "delete", path: "/incari/never-there" },
]);
assert.deepEqual(listing(await new Worker({ opfs }).open()), ["/incari/a", "/incari/b=2"]);
});
it("falls back to IndexedDB where there's no origin private file system", async () => {
const indexedDB = new IDBFactory();
const first = new Worker({ opfs: null, indexedDB });
const opened = await first.open();
assert.equal(opened.backend, "indexeddb");
assert.match(String(opened.problems), /no origin private file system/);
const applied = await first.apply(changes);
assert.equal(applied.error, undefined);
const second = new Worker({ opfs: null, indexedDB });
assert.deepEqual(listing(await second.open()), afterChanges);
});
it("keeps nothing when the browser offers no storage", async () => {
const worker = new Worker({ opfs: null });
const opened = await worker.open();
assert.equal(opened.backend, "memory");
assert.equal(opened.readOnly, true);
});
it("saves nothing while another tab holds the lock", async () => {
const opfs = new FakeDirectory();
const worker = new Worker({ opfs, lockTaken: true });
const opened = await worker.open();
assert.equal(opened.readOnly, true);
assert.equal(opened.locked, false);
worker.send({ type: "apply", ops: changes });
await worker.request({ type: "read", path: "/incari/game/options.txt" });
assert.equal(opfs.children.size, 0);
});
for (const kind of ["opfs", "indexeddb"]) {
it(`downloads the client jar once and then reads it from the cache (${kind})`, async () => {
const opfs = kind === "opfs" ? new FakeDirectory() : null;
const indexedDB = new IDBFactory();
let downloads = 0;
const fetch = (url: string) => {
downloads++;
assert.equal(url, "http://localhost/client.jar");
return Promise.resolve(new Response("PK jar bytes"));
};
const first = new Worker({ opfs, indexedDB, fetch });
await first.open();
const fetched = await first.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.3.jar" });
assert.equal(fetched.cached, false);
assert.equal(new TextDecoder().decode(fetched.data as ArrayBuffer), "PK jar bytes");
const second = new Worker({ opfs, indexedDB, fetch });
await second.open();
const cached = await second.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.3.jar" });
assert.equal(cached.cached, true);
assert.equal(new TextDecoder().decode(cached.data as ArrayBuffer), "PK jar bytes");
assert.equal(downloads, 1);
// The cache isn't part of the file system the page loads.
assert.deepEqual((await new Worker({ opfs, indexedDB, fetch }).open()).entries, []);
// A new version's jar replaces the old one; a damaged copy can be dropped.
await second.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.4.jar" });
await second.request({ type: "forget", key: "client-26.4.jar" });
const again = await second.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.3.jar" });
assert.equal(again.cached, false);
assert.equal(downloads, 3);
});
it(`keeps the client jar and the asset pack side by side (${kind})`, async () => {
const opfs = kind === "opfs" ? new FakeDirectory() : null;
const indexedDB = new IDBFactory();
let downloads = 0;
const fetch = () => {
downloads++;
return Promise.resolve(new Response("PK bytes"));
};
const first = new Worker({ opfs, indexedDB, fetch });
await first.open();
await first.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.3.jar" });
await first.request({ type: "jar", url: "http://localhost/incari.pack?v=1", key: "pack-1" });
// A new build's pack replaces the old pack, and only it.
await first.request({ type: "jar", url: "http://localhost/incari.pack?v=2", key: "pack-2" });
const second = new Worker({ opfs, indexedDB, fetch });
await second.open();
assert.equal(
(await second.request({ type: "jar", url: "http://localhost/client.jar", key: "client-26.3.jar" })).cached,
true,
);
assert.equal(
(await second.request({ type: "jar", url: "http://localhost/incari.pack?v=2", key: "pack-2" })).cached,
true,
);
assert.equal(
(await second.request({ type: "jar", url: "http://localhost/incari.pack?v=1", key: "pack-1" })).cached,
false,
);
assert.equal(downloads, 4);
});
}
it("reports a failed download", async () => {
const worker = new Worker({
opfs: new FakeDirectory(),
fetch: () => Promise.resolve(new Response("gone", { status: 404 })),
});
await worker.open();
const reply = await worker.request({ type: "jar", url: "http://localhost/client.jar", key: "k" });
assert.match(String(reply.error), /HTTP 404/);
});
});