Start maybe working on a native app

This commit is contained in:
2026-11-22 17:38:28 -03:00
parent 681d3afb4d
commit a552883795
31 changed files with 1881 additions and 678 deletions
+69
View File
@@ -0,0 +1,69 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// what the desktop app serves its client from: the client's files (updated from the site, see client_updates.ts),
// and singleplayer, whose worlds are played on a game server of the app's own with the mods each world picked from
// its data folder (see saves.ts). the client is shown by main.ts in chromium, or by native.ts in a window of its own
import { fromFileUrl, join } from "@std/path";
import { serve_static } from "../server/host.ts";
import { PROTOCOL_VERSION } from "../common/protocol.ts";
import { current_client, update_client } from "./client_updates.ts";
import { data_dir, install_mods } from "./saves.ts";
import { singleplayer_server } from "./singleplayer.ts";
// where the project was built from: build/ and server_mods/ (the .cubi files) are bundled into the app with --include
const ROOT = fromFileUrl(new URL("../", import.meta.url));
const BUILD_DIR = join(ROOT, "build");
// how long the first page waits for an update, a slower one is played next time
const UPDATE_WAIT_MS = 3000;
export function desktop_app(on_fatal: (message: string) => void) {
const data = data_dir();
install_mods(join(ROOT, "server_mods"), data);
// the server the address field starts with. "" leaves it empty for the player to fill in
const config: { server?: string; client_updates?: string } = JSON.parse(
Deno.readTextFileSync(new URL("./config.json", import.meta.url)),
);
const default_server = Deno.env.get("CUBI_SERVER") ?? config.server ?? "";
// the site the client updates from, see client_updates.ts. CUBI_CLIENT_UPDATES=off plays the client the app was
// built with (to test a local build), or it can point at a local server to test updating
const updates_from = (Deno.env.get("CUBI_CLIENT_UPDATES") ?? config.client_updates ?? "off").replace(/\/+$/, "");
const client_options = {
source: updates_from,
bundled_dir: BUILD_DIR,
cache_dir: join(data, "client"),
protocol: PROTOCOL_VERSION,
};
const client_dir: Promise<string> = updates_from === "off" || updates_from === ""
? Promise.resolve(BUILD_DIR)
: Promise.race([
update_client(client_options),
new Promise<string>((resolve) => setTimeout(() => resolve(current_client(client_options)), UPDATE_WAIT_MS)),
]);
client_dir.then((dir) => console.log(`Playing the client in ${dir}`));
const singleplayer = singleplayer_server({ build_dir: BUILD_DIR, data_dir: data, on_fatal });
return {
data_dir: data,
client_dir,
singleplayer,
// the client's page at origin. ?server= fills in the address field, without it the field would start with
// this app's own address. ?singleplayer shows the main menu instead of the browser's title screen
start_page(origin: string) {
const start = new URL("/client/", origin);
start.searchParams.set("server", default_server);
start.searchParams.set("singleplayer", "");
return start;
},
// singleplayer's requests and the client's files
async handle(req: Request, url: URL): Promise<Response> {
const response = await singleplayer.handle(req, url);
if (response) return response;
return serve_static(await client_dir, req, url);
},
};
}
+9 -56
View File
@@ -7,64 +7,24 @@
// webgpu (firefox) can still play. its title screen is a main menu like luanti's: singleplayer worlds are played on
// a game server of its own, with the mods each world picked from its data folder, see saves.ts. build it with deno
// task desktop, see the desktop/ docs for how deno desktop works
import { fromFileUrl, join } from "@std/path";
import { serve_static } from "../server/host.ts";
import { PROTOCOL_VERSION } from "../common/protocol.ts";
import { current_client, update_client } from "./client_updates.ts";
import { guard_shortcuts } from "./shortcuts.ts";
import { center_mouse } from "./center_mouse.ts";
import { data_dir, install_mods } from "./saves.ts";
import { singleplayer_server } from "./singleplayer.ts";
import { desktop_app } from "./app.ts";
// where the project was built from: build/ and server_mods/ (the .cubi files) are bundled into the app with --include
const ROOT = fromFileUrl(new URL("../", import.meta.url));
const BUILD_DIR = join(ROOT, "build");
const DATA_DIR = data_dir();
install_mods(join(ROOT, "server_mods"), DATA_DIR);
// the server the address field starts with. "" leaves it empty for the player to fill in
const config: { server?: string; client_updates?: string } = JSON.parse(
await Deno.readTextFile(new URL("./config.json", import.meta.url)),
);
const default_server = Deno.env.get("CUBI_SERVER") ?? config.server ?? "";
// the site the client updates from, see client_updates.ts. CUBI_CLIENT_UPDATES=off plays the client the app was
// built with (to test a local build), or it can point at a local server to test updating
const updates_from = (Deno.env.get("CUBI_CLIENT_UPDATES") ?? config.client_updates ?? "off").replace(/\/+$/, "");
// how long the first page waits for an update, a slower one is played next time
const UPDATE_WAIT_MS = 3000;
const client_options = {
source: updates_from,
bundled_dir: BUILD_DIR,
cache_dir: join(DATA_DIR, "client"),
protocol: PROTOCOL_VERSION,
};
const client_dir: Promise<string> = updates_from === "off" || updates_from === ""
? Promise.resolve(BUILD_DIR)
: Promise.race([
update_client(client_options),
new Promise<string>((resolve) => setTimeout(() => resolve(current_client(client_options)), UPDATE_WAIT_MS)),
]);
client_dir.then((dir) => console.log(`Playing the client in ${dir}`));
const app = desktop_app((message) => {
console.error(message);
alert(`The singleplayer world stopped: ${message}`);
Deno.exit(1);
});
const win = new Deno.BrowserWindow({ title: "bworld", width: 1280, height: 720 });
guard_shortcuts(win);
const singleplayer = singleplayer_server({
build_dir: BUILD_DIR,
data_dir: DATA_DIR,
on_fatal(message) {
console.error(message);
alert(`The singleplayer world stopped: ${message}`);
Deno.exit(1);
},
});
// the world gets saved before the app closes. it always exits by itself: deno desktop's own shutdown freezes on the
// last frame when chromium's ctrl+w closed the window, and Deno.serve keeps the process alive anyway
win.addEventListener("close", async (event) => {
event.preventDefault();
await singleplayer.stop();
await app.singleplayer.stop();
Deno.exit(0);
});
@@ -76,19 +36,12 @@ if (Deno.env.get("DEBUG")) {
Deno.serve(async (req) => {
const url = new URL(req.url);
if (url.pathname === "/") {
// ?server= fills in the address field, without it the field would start with this app's own address.
// ?singleplayer shows the main menu instead of the browser's title screen
const start = new URL("/client/", url);
start.searchParams.set("server", default_server);
start.searchParams.set("singleplayer", "");
return Response.redirect(start, 302);
return Response.redirect(app.start_page(url.origin), 302);
}
// the page let go of the mouse, see center_mouse.ts
if (url.pathname === "/desktop/center_mouse" && req.method === "POST") {
center_mouse();
return new Response(null, { status: 204 });
}
const response = await singleplayer.handle(req, url);
if (response) return response;
return serve_static(await client_dir, req, url);
return await app.handle(req, url);
});
+126
View File
@@ -0,0 +1,126 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the desktop app without a browser: an sdl window (sdl.ts) that the client draws into with deno's own webgpu. the
// client runs in a worker (client/native/main.ts) loaded from the client's files like a page, and this thread passes
// it the window's events and does what it asks, like grabbing the mouse. the client's files and singleplayer are
// served on a local address like main.ts's chromium window has them, see app.ts
import { join, toFileUrl } from "@std/path";
import { desktop_app } from "./app.ts";
import { SdlWindow } from "./sdl.ts";
import type { ClientMessage, WindowMessage } from "../client/native/messages.ts";
// how often the window's events are looked at, in milliseconds
const POLL_MS = 2;
const game_window = new SdlWindow("bworld", 1280, 720);
const app = desktop_app((message) => {
console.error(message);
game_window.show_error("bworld", `The singleplayer world stopped: ${message}`);
Deno.exit(1);
});
const server = Deno.serve(
{ hostname: "127.0.0.1", port: 0, onListen() {} },
(req) => app.handle(req, new URL(req.url)),
);
const start_page = app.start_page(`http://127.0.0.1:${server.addr.port}`);
// what the client remembers, see Platform.storage
const STORAGE_FILE = join(app.data_dir, "client_storage.json");
let storage: Record<string, string> = {};
try {
storage = JSON.parse(Deno.readTextFileSync(STORAGE_FILE));
} catch {
// nothing saved yet
}
let client: Worker | undefined;
// a fresh client, like loading the page again. the old one is gone with everything it loaded
async function start_client(page: URL) {
client?.terminate();
game_window.set_grabbed(false);
const client_dir = await app.client_dir;
const worker = new Worker(toFileUrl(join(client_dir, "client", "native.js")), {
type: "module",
deno: {
// the servers it plays on, and its own files. ffi is for drawing into the window, it gives it up after
permissions: { net: true, read: [client_dir], ffi: true, write: false, run: false, env: false, sys: false },
},
});
worker.onmessage = (event: MessageEvent<ClientMessage>) => handle(event.data);
worker.onerror = (event) => {
console.error(`The client stopped: ${event.message}`);
};
client = worker;
send({
type: "start",
page: page.href,
surface: game_window.surface_handles(),
...game_window.pixel_size(),
storage,
});
}
function send(message: WindowMessage) {
client?.postMessage(message);
}
function handle(message: ClientMessage) {
switch (message.type) {
case "grab":
game_window.set_grabbed(message.grab);
break;
case "fullscreen":
game_window.toggle_fullscreen();
break;
case "restart": {
const page = new URL(message.page);
// only its own pages
start_client(page.origin === start_page.origin ? page : start_page);
break;
}
// the client can't run at all, like without webgpu
case "fatal":
game_window.set_grabbed(false);
game_window.show_error("bworld", message.message);
close();
break;
case "ask":
game_window.set_grabbed(false);
send({
type: "answer",
id: message.id,
yes: game_window.ask(message.title, message.text, message.yes, message.no),
});
break;
case "read_clipboard":
send({ type: "clipboard", id: message.id, text: game_window.read_clipboard() });
break;
case "write_clipboard":
game_window.write_clipboard(message.text);
break;
case "store":
storage[message.key] = message.value;
Deno.writeTextFileSync(STORAGE_FILE, JSON.stringify(storage, null, "\t"));
break;
}
}
let closing = false;
// the world gets saved before the app closes
async function close() {
if (closing) return;
closing = true;
clearInterval(polling);
client?.terminate();
await app.singleplayer.stop();
game_window.close();
Deno.exit(0);
}
const polling = setInterval(() => game_window.poll(send, close), POLL_MS);
start_client(start_page);
+346
View File
@@ -0,0 +1,346 @@
// SPDX-FileCopyrightText: 2026 Paula Wisnievski
// SPDX-License-Identifier: AGPL-3.0-or-later
// the desktop app's window, with sdl3 through ffi: its native handles for webgpu to draw into, and its events as
// the client's messages (see client/native/messages.ts), keys named like the dom's. sdl's relative mouse mode grabs
// the mouse, which unlike a browser's pointer lock never gets taken away by escape or held back after letting go
import type { SurfaceHandles, WindowMessage } from "../client/native/messages.ts";
const LIBRARY = { linux: "libSDL3.so.0", windows: "SDL3.dll", darwin: "libSDL3.0.dylib" }[Deno.build.os as string];
const SYMBOLS = {
SDL_Init: { parameters: ["u32"], result: "bool" },
SDL_Quit: { parameters: [], result: "void" },
SDL_GetError: { parameters: [], result: "pointer" },
SDL_free: { parameters: ["pointer"], result: "void" },
SDL_GetCurrentVideoDriver: { parameters: [], result: "pointer" },
SDL_CreateWindow: { parameters: ["buffer", "i32", "i32", "u64"], result: "pointer" },
SDL_GetWindowProperties: { parameters: ["pointer"], result: "u32" },
SDL_GetPointerProperty: { parameters: ["u32", "buffer", "pointer"], result: "pointer" },
SDL_GetNumberProperty: { parameters: ["u32", "buffer", "i64"], result: "i64" },
SDL_GetWindowSizeInPixels: { parameters: ["pointer", "buffer", "buffer"], result: "bool" },
SDL_GetWindowSize: { parameters: ["pointer", "buffer", "buffer"], result: "bool" },
SDL_GetWindowFlags: { parameters: ["pointer"], result: "u64" },
SDL_SetWindowFullscreen: { parameters: ["pointer", "bool"], result: "bool" },
SDL_SetWindowRelativeMouseMode: { parameters: ["pointer", "bool"], result: "bool" },
SDL_WarpMouseInWindow: { parameters: ["pointer", "f32", "f32"], result: "void" },
SDL_StartTextInput: { parameters: ["pointer"], result: "bool" },
SDL_GetModState: { parameters: [], result: "u16" },
SDL_PollEvent: { parameters: ["buffer"], result: "bool" },
SDL_GetClipboardText: { parameters: [], result: "pointer" },
SDL_SetClipboardText: { parameters: ["buffer"], result: "bool" },
SDL_ShowSimpleMessageBox: { parameters: ["u32", "buffer", "buffer", "pointer"], result: "bool" },
SDL_ShowMessageBox: { parameters: ["buffer", "buffer"], result: "bool" },
} as const;
const INIT_VIDEO = 0x20;
const WINDOW_FULLSCREEN = 0x1n;
const WINDOW_RESIZABLE = 0x20n;
const MESSAGEBOX_ERROR = 0x10;
const MESSAGEBOX_WARNING = 0x20;
const BUTTON_RETURNKEY_DEFAULT = 0x1;
const BUTTON_ESCAPEKEY_DEFAULT = 0x2;
const EVENT_QUIT = 0x100;
const EVENT_WINDOW_SHOWN = 0x202;
const EVENT_WINDOW_HIDDEN = 0x203;
const EVENT_WINDOW_EXPOSED = 0x204;
const EVENT_WINDOW_PIXEL_SIZE_CHANGED = 0x207;
const EVENT_WINDOW_MINIMIZED = 0x209;
const EVENT_WINDOW_MAXIMIZED = 0x20a;
const EVENT_WINDOW_RESTORED = 0x20b;
const EVENT_WINDOW_FOCUS_GAINED = 0x20e;
const EVENT_WINDOW_FOCUS_LOST = 0x20f;
const EVENT_WINDOW_CLOSE_REQUESTED = 0x210;
const EVENT_WINDOW_OCCLUDED = 0x216;
const EVENT_KEY_DOWN = 0x300;
const EVENT_KEY_UP = 0x301;
const EVENT_TEXT_INPUT = 0x303;
const EVENT_MOUSE_MOTION = 0x400;
const EVENT_MOUSE_BUTTON_DOWN = 0x401;
const EVENT_MOUSE_BUTTON_UP = 0x402;
const EVENT_MOUSE_WHEEL = 0x403;
const KMOD_CTRL = 0x00c0;
const KMOD_ALT = 0x0300;
const KMOD_GUI = 0x0c00;
// a wheel notch, in the dom's pixels
const WHEEL_NOTCH = 100;
// sdl's scancodes (usb's key numbers) as the dom's KeyboardEvent.code
const KEY_CODES: Record<number, string> = {
40: "Enter",
41: "Escape",
42: "Backspace",
43: "Tab",
44: "Space",
45: "Minus",
46: "Equal",
47: "BracketLeft",
48: "BracketRight",
49: "Backslash",
50: "Backslash",
51: "Semicolon",
52: "Quote",
53: "Backquote",
54: "Comma",
55: "Period",
56: "Slash",
57: "CapsLock",
70: "PrintScreen",
71: "ScrollLock",
72: "Pause",
73: "Insert",
74: "Home",
75: "PageUp",
76: "Delete",
77: "End",
78: "PageDown",
79: "ArrowRight",
80: "ArrowLeft",
81: "ArrowDown",
82: "ArrowUp",
83: "NumLock",
84: "NumpadDivide",
85: "NumpadMultiply",
86: "NumpadSubtract",
87: "NumpadAdd",
88: "NumpadEnter",
98: "Numpad0",
99: "NumpadDecimal",
100: "IntlBackslash",
101: "ContextMenu",
224: "ControlLeft",
225: "ShiftLeft",
226: "AltLeft",
227: "MetaLeft",
228: "ControlRight",
229: "ShiftRight",
230: "AltRight",
231: "MetaRight",
};
for (let i = 0; i < 26; i++) KEY_CODES[4 + i] = `Key${String.fromCharCode(65 + i)}`;
for (let i = 0; i < 9; i++) KEY_CODES[30 + i] = `Digit${i + 1}`;
KEY_CODES[39] = "Digit0";
for (let i = 0; i < 12; i++) KEY_CODES[58 + i] = `F${i + 1}`;
for (let i = 0; i < 9; i++) KEY_CODES[89 + i] = `Numpad${i + 1}`;
const encoder = new TextEncoder();
const c_string = (text: string) => encoder.encode(text + "\0");
const read_string = (pointer: Deno.PointerValue) => pointer ? Deno.UnsafePointerView.getCString(pointer) : "";
export class SdlWindow {
#sdl: Deno.DynamicLibrary<typeof SYMBOLS>["symbols"];
#window: Deno.PointerObject;
#event = new Uint8Array(128);
#event_view = new DataView(this.#event.buffer);
#relative = false;
// the grabbed mouse's movement and the cursor's last place since the last message, sent as one
#look = { x: 0, y: 0 };
#cursor: { x: number; y: number } | undefined;
// throws when there's no sdl3 or no window can be made
constructor(title: string, width: number, height: number) {
if (!LIBRARY) throw new Error(`There's no sdl3 for ${Deno.build.os}`);
this.#sdl = Deno.dlopen(LIBRARY, SYMBOLS).symbols;
if (!this.#sdl.SDL_Init(INIT_VIDEO)) throw new Error(`Couldn't start sdl: ${this.#error()}`);
// not high pixel density: frames are drawn at the window's size and the os scales them, like a page's canvas
const window = this.#sdl.SDL_CreateWindow(c_string(title), width, height, WINDOW_RESIZABLE);
if (!window) throw new Error(`Couldn't open a window: ${this.#error()}`);
this.#window = window;
this.#sdl.SDL_StartTextInput(window);
}
#error() {
return read_string(this.#sdl.SDL_GetError());
}
// what webgpu needs to draw into the window
surface_handles(): SurfaceHandles {
const sdl = this.#sdl;
const properties = sdl.SDL_GetWindowProperties(this.#window);
const pointer = (name: string) =>
Deno.UnsafePointer.value(sdl.SDL_GetPointerProperty(properties, c_string(name), null));
const driver = read_string(sdl.SDL_GetCurrentVideoDriver());
switch (driver) {
case "wayland":
return {
system: "wayland",
window: pointer("SDL.window.wayland.surface"),
display: pointer("SDL.window.wayland.display"),
};
case "x11":
return {
system: "x11",
window: BigInt(sdl.SDL_GetNumberProperty(properties, c_string("SDL.window.x11.window"), 0n)),
display: pointer("SDL.window.x11.display"),
};
case "windows":
return {
system: "win32",
window: pointer("SDL.window.win32.hwnd"),
display: pointer("SDL.window.win32.instance"),
};
default:
throw new Error(`Can't draw into ${driver} windows`);
}
}
// in pixels
pixel_size() {
const [width, height] = [new Int32Array(1), new Int32Array(1)];
this.#sdl.SDL_GetWindowSizeInPixels(this.#window, width, height);
return { width: width[0], height: height[0] };
}
// the mouse turns the camera instead of moving a cursor. letting go puts the cursor in the middle
set_grabbed(grab: boolean) {
if (grab === this.#relative) return;
this.#relative = grab;
if (!grab) {
const [width, height] = [new Int32Array(1), new Int32Array(1)];
this.#sdl.SDL_GetWindowSize(this.#window, width, height);
this.#sdl.SDL_WarpMouseInWindow(this.#window, width[0] / 2, height[0] / 2);
this.#cursor = { x: width[0] / 2, y: height[0] / 2 };
}
this.#sdl.SDL_SetWindowRelativeMouseMode(this.#window, grab);
}
toggle_fullscreen() {
const fullscreen = (this.#sdl.SDL_GetWindowFlags(this.#window) & WINDOW_FULLSCREEN) !== 0n;
this.#sdl.SDL_SetWindowFullscreen(this.#window, !fullscreen);
}
read_clipboard(): string {
const text = this.#sdl.SDL_GetClipboardText();
const result = read_string(text);
this.#sdl.SDL_free(text);
return result;
}
write_clipboard(text: string) {
this.#sdl.SDL_SetClipboardText(c_string(text));
}
show_error(title: string, text: string) {
this.#sdl.SDL_ShowSimpleMessageBox(MESSAGEBOX_ERROR, c_string(title), c_string(text), this.#window);
}
// waits for the player to pick yes or no, no if the box can't be shown
ask(title: string, text: string, yes: string, no: string): boolean {
const [title_text, message, yes_text, no_text] = [title, text, yes, no].map(c_string);
const ptr = (buffer: Uint8Array<ArrayBuffer>) =>
BigInt(Deno.UnsafePointer.value(Deno.UnsafePointer.of(buffer)));
// SDL_MessageBoxButtonData: flags, id, text
const buttons = new ArrayBuffer(32);
const button_view = new DataView(buttons);
button_view.setUint32(0, BUTTON_ESCAPEKEY_DEFAULT, true);
button_view.setInt32(4, 0, true);
button_view.setBigUint64(8, ptr(no_text), true);
button_view.setUint32(16, BUTTON_RETURNKEY_DEFAULT, true);
button_view.setInt32(20, 1, true);
button_view.setBigUint64(24, ptr(yes_text), true);
// SDL_MessageBoxData: flags, window, title, message, button count, buttons, colors
const data = new ArrayBuffer(56);
const data_view = new DataView(data);
data_view.setUint32(0, MESSAGEBOX_WARNING, true);
data_view.setBigUint64(8, BigInt(Deno.UnsafePointer.value(this.#window)), true);
data_view.setBigUint64(16, ptr(title_text), true);
data_view.setBigUint64(24, ptr(message), true);
data_view.setInt32(32, 2, true);
data_view.setBigUint64(40, ptr(new Uint8Array(buttons)), true);
const picked = new Int32Array([0]);
const shown = this.#sdl.SDL_ShowMessageBox(new Uint8Array(data), picked);
return shown && picked[0] === 1;
}
// everything that happened since the last call, as the client's messages. on_close is for the window being closed
poll(send: (message: WindowMessage) => void, on_close: () => void) {
const sdl = this.#sdl;
const event = this.#event_view;
const flush = () => {
if (this.#look.x || this.#look.y) send({ type: "look", ...this.#look });
if (this.#cursor) send({ type: "cursor", ...this.#cursor });
this.#look = { x: 0, y: 0 };
this.#cursor = undefined;
};
while (sdl.SDL_PollEvent(this.#event)) {
const type = event.getUint32(0, true);
// motion comes in often, so it's added up and sent before anything else
if (type === EVENT_MOUSE_MOTION) {
if (this.#relative) {
this.#look.x += event.getFloat32(36, true);
this.#look.y += event.getFloat32(40, true);
} else {
this.#cursor = { x: event.getFloat32(28, true), y: event.getFloat32(32, true) };
}
continue;
}
flush();
switch (type) {
case EVENT_QUIT:
case EVENT_WINDOW_CLOSE_REQUESTED:
on_close();
break;
case EVENT_WINDOW_PIXEL_SIZE_CHANGED:
send({ type: "resize", width: event.getInt32(20, true), height: event.getInt32(24, true) });
break;
case EVENT_WINDOW_FOCUS_GAINED:
send({ type: "focus", focused: true });
send({ type: "shown", shown: true });
break;
case EVENT_WINDOW_FOCUS_LOST:
send({ type: "focus", focused: false });
break;
case EVENT_WINDOW_SHOWN:
case EVENT_WINDOW_EXPOSED:
case EVENT_WINDOW_RESTORED:
case EVENT_WINDOW_MAXIMIZED:
send({ type: "shown", shown: true });
break;
case EVENT_WINDOW_HIDDEN:
case EVENT_WINDOW_MINIMIZED:
case EVENT_WINDOW_OCCLUDED:
send({ type: "shown", shown: false });
break;
case EVENT_KEY_DOWN:
case EVENT_KEY_UP: {
const code = KEY_CODES[event.getUint32(24, true)];
if (!code) break;
const keycode = event.getUint32(28, true);
const shortcut = is_shortcut(event.getUint16(32, true));
// a letter with ctrl held is a shortcut, see InputManager.key_down. typing comes as text
const key = shortcut && keycode >= 0x20 && keycode < 0x7f ? String.fromCharCode(keycode) : "";
send({ type: "key", down: type === EVENT_KEY_DOWN, code, key, shortcut });
break;
}
case EVENT_TEXT_INPUT: {
// ctrl+c is a shortcut, not a c
if (is_shortcut(sdl.SDL_GetModState())) break;
const text = Deno.UnsafePointer.create(event.getBigUint64(24, true));
send({ type: "text", text: read_string(text) });
break;
}
case EVENT_MOUSE_BUTTON_DOWN:
case EVENT_MOUSE_BUTTON_UP:
// sdl counts from 1: left, middle, right, back, forward. the dom from 0
send({ type: "button", down: type === EVENT_MOUSE_BUTTON_DOWN, button: event.getUint8(24) - 1 });
break;
case EVENT_MOUSE_WHEEL:
send({ type: "scroll", amount: -event.getFloat32(28, true) * WHEEL_NOTCH });
break;
}
}
flush();
}
close() {
this.#sdl.SDL_Quit();
}
}
// ctrl (cmd on macs) held for a shortcut, not altgr, which some systems have as ctrl+alt
function is_shortcut(mod: number) {
return (mod & KMOD_GUI) !== 0 || ((mod & KMOD_CTRL) !== 0 && (mod & KMOD_ALT) === 0);
}