Files
chandra/compositor/kms/kms_stub.c
T
nandi 1205329abd
CI / test (push) Canceled after 0s
KMS: map touch to the left pointer button; toolchain: add aarch64
- kms: touch down, move and up drive the pointer and send BTN_LEFT, so touchscreens work without a mouse. Only the first finger (tracked by seat slot) controls the pointer.
- A held touch is released on VT switch and on close, so the button is never left stuck down.
- setup-toolchain.sh: fetch wasm-tools, wit-bindgen, wasmtime and the wasmer C API for aarch64 as well as x86_64. Other architectures still fail with an error.
2026-11-27 22:24:33 -08:00

670 lines
24 KiB
C

/* Native display backend: libseat (device access + VT switching), DRM/KMS
* (dumb buffers, page flips, hardware cursor), libinput (keyboard + pointer),
* xkbcommon (keymap + modifier state). One display, one seat, single global
* state: the compositor is a single-instance session process.
*
* Everything the MoonBit side needs is exposed as small int/bytes functions
* (mp_kms_*). Input events are queued here and drained with mp_kms_next_event.
*/
#include <moonbit.h>
#include <errno.h>
#include <fcntl.h>
#include <poll.h>
#include <stdint.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/ioctl.h>
#include <sys/mman.h>
#include <unistd.h>
#include <libseat.h>
#include <libinput.h>
#include <libudev.h>
#include <xkbcommon/xkbcommon.h>
#include <xf86drm.h>
#include <xf86drmMode.h>
#define KEY_BACKSPACE_CODE 14
#define KEY_F1_CODE 59
#define KEY_F10_CODE 68
#define KEY_F11_CODE 87
#define KEY_F12_CODE 88
#define BTN_LEFT_CODE 0x110
/* ---- damage ---- */
/* What each scanout buffer is missing of the frame: the part changed since it was last written
* (x0, y0, x1, y1; empty when x0 >= x1). Both start (and after a seat switch, are) fully stale. */
static int g_stale[2][4];
static void stale_add(int x0, int y0, int x1, int y1) {
for (int i = 0; i < 2; i++) {
int *s = g_stale[i];
if (s[0] >= s[2] || s[1] >= s[3]) { s[0] = x0; s[1] = y0; s[2] = x1; s[3] = y1; continue; }
if (x0 < s[0]) s[0] = x0;
if (y0 < s[1]) s[1] = y0;
if (x1 > s[2]) s[2] = x1;
if (y1 > s[3]) s[3] = y1;
}
}
/* ---- seat ---------------------------------------------------------------- */
static struct libseat *g_seat;
static int g_seat_enabled;
static int g_seat_lost; /* disable event arrived; must ack from the main loop */
static int g_suspended; /* VT switched away; resume when the seat is enabled again */
static void seat_enable(struct libseat *s, void *u) {
(void)s; (void)u;
g_seat_enabled = 1;
stale_add(0, 0, 1 << 16, 1 << 16); /* another session may have drawn in the buffers */
}
static void seat_disable(struct libseat *s, void *u) {
(void)s; (void)u;
g_seat_enabled = 0;
g_seat_lost = 1;
}
static const struct libseat_seat_listener g_seat_listener = {
.enable_seat = seat_enable,
.disable_seat = seat_disable,
};
/* fd -> libseat device id, for close_restricted. */
#define MAX_DEV 128
static struct { int fd; int id; } g_devs[MAX_DEV];
static int dev_open(const char *path, int flags, void *u) {
(void)flags; (void)u;
int fd = -1;
int id = libseat_open_device(g_seat, path, &fd);
if (id < 0) return errno ? -errno : -EACCES;
for (int i = 0; i < MAX_DEV; i++) {
if (g_devs[i].fd == 0) { g_devs[i].fd = fd; g_devs[i].id = id; return fd; }
}
libseat_close_device(g_seat, id);
close(fd);
return -EMFILE;
}
static void dev_close(int fd, void *u) {
(void)u;
for (int i = 0; i < MAX_DEV; i++) {
if (g_devs[i].fd == fd) {
libseat_close_device(g_seat, g_devs[i].id);
g_devs[i].fd = 0;
break;
}
}
close(fd);
}
static const struct libinput_interface g_li_iface = {
.open_restricted = dev_open,
.close_restricted = dev_close,
};
/* ---- input event queue --------------------------------------------------- */
enum { EV_MOVE = 1, EV_BUTTON = 2, EV_KEY = 3, EV_MODS = 4, EV_AXIS = 5 };
#define QCAP 512
static int32_t g_q[QCAP][5];
static int g_qh, g_qt; /* head (read), tail (write) */
static int32_t g_cur[5];
static void q_push(int32_t t, int32_t a, int32_t b, int32_t c, int32_t d) {
int nt = (g_qt + 1) % QCAP;
if (nt == g_qh) return; /* full: drop */
g_q[g_qt][0] = t; g_q[g_qt][1] = a; g_q[g_qt][2] = b; g_q[g_qt][3] = c; g_q[g_qt][4] = d;
g_qt = nt;
}
/* ---- DRM ----------------------------------------------------------------- */
struct fbuf {
uint32_t handle, fb, pitch;
size_t size;
uint8_t *map;
};
static int g_drm = -1;
static int g_drm_dev_id = -1;
static uint32_t g_crtc, g_conn;
static drmModeModeInfo g_mode;
static drmModeCrtc *g_saved_crtc;
static struct fbuf g_fb[2];
static int g_front; /* index currently scanned out */
static int g_flip_pending;
static int g_need_modeset;
static int g_width, g_height;
static int g_blank; /* screen turned off (DPMS) by mp_kms_set_power */
static int fb_create(struct fbuf *b, int w, int h) {
struct drm_mode_create_dumb c = { .width = (uint32_t)w, .height = (uint32_t)h, .bpp = 32 };
if (drmIoctl(g_drm, DRM_IOCTL_MODE_CREATE_DUMB, &c) < 0) return -1;
b->handle = c.handle; b->pitch = c.pitch; b->size = (size_t)c.size;
if (drmModeAddFB(g_drm, (uint32_t)w, (uint32_t)h, 24, 32, b->pitch, b->handle, &b->fb) < 0) return -1;
struct drm_mode_map_dumb m = { .handle = b->handle };
if (drmIoctl(g_drm, DRM_IOCTL_MODE_MAP_DUMB, &m) < 0) return -1;
b->map = mmap(NULL, b->size, PROT_READ | PROT_WRITE, MAP_SHARED, g_drm, (off_t)m.offset);
if (b->map == MAP_FAILED) { b->map = NULL; return -1; }
memset(b->map, 0, b->size);
return 0;
}
static void page_flip_done(int fd, unsigned seq, unsigned sec, unsigned usec, void *u) {
(void)fd; (void)seq; (void)sec; (void)usec; (void)u;
g_flip_pending = 0;
}
/* Choose a connected connector with modes and a CRTC for it. 0 on success. */
static int pick_output(int fd) {
drmModeRes *res = drmModeGetResources(fd);
if (!res) return -1;
int ok = -1;
for (int i = 0; i < res->count_connectors && ok < 0; i++) {
drmModeConnector *c = drmModeGetConnector(fd, res->connectors[i]);
if (!c) continue;
if (c->connection == DRM_MODE_CONNECTED && c->count_modes > 0) {
int mi = 0;
for (int m = 0; m < c->count_modes; m++) {
if (c->modes[m].type & DRM_MODE_TYPE_PREFERRED) { mi = m; break; }
}
uint32_t crtc = 0;
drmModeEncoder *enc = c->encoder_id ? drmModeGetEncoder(fd, c->encoder_id) : NULL;
if (enc && enc->crtc_id) crtc = enc->crtc_id;
if (enc) drmModeFreeEncoder(enc);
for (int e = 0; !crtc && e < c->count_encoders; e++) {
drmModeEncoder *en = drmModeGetEncoder(fd, c->encoders[e]);
if (!en) continue;
for (int k = 0; k < res->count_crtcs; k++) {
if (en->possible_crtcs & (1u << k)) { crtc = res->crtcs[k]; break; }
}
drmModeFreeEncoder(en);
}
if (crtc) {
g_conn = c->connector_id; g_crtc = crtc; g_mode = c->modes[mi];
ok = 0;
}
}
drmModeFreeConnector(c);
}
drmModeFreeResources(res);
return ok;
}
/* ---- cursor -------------------------------------------------------------- */
#define CUR 64
static struct fbuf g_cur_buf;
static int g_cur_ready;
static int g_cur_shape = -1;
static int g_px, g_py; /* pointer position (hotspot) */
static int g_hotx, g_hoty;
static int g_touch_active;
static int32_t g_touch_slot;
static const char *ART_ARROW[] = {
"X...........", "XX..........", "XoX.........", "XooX........", "XoooX.......",
"XooooX......", "XoooooX.....", "XooooooX....", "XoooooooX...", "XooooooooX..",
"XoooooXXXXX.", "XooXooX.....", "XoX.XooX....", "XX..XooX....", "X....XooX...",
".....XooX...", "......XX....", NULL };
static const char *ART_HAND[] = {
".....XX.........", "....XooX........", "....XooX........", "....XooX........",
"....XooXXX......", "....XooXooXXX...", ".XX.XooXooXooX..", "X..XXoooooooooX.",
"X.XooXooooooooX.", ".XooooooooooooX.", "..XooooooooooX..", "..XooooooooooX..",
"...XoooooooooX..", "...XoooooooooX..", "....XooooooooX..", "....XXXXXXXXXX..", NULL };
static const char *ART_IBEAM[] = {
"XXXXXXX", "XooXooX", "XXXoXXX", "..XoX..", "..XoX..", "..XoX..", "..XoX..",
"..XoX..", "..XoX..", "..XoX..", "..XoX..", "XXXoXXX", "XooXooX", "XXXXXXX", NULL };
static void cursor_draw(int shape) {
const char **art = ART_ARROW;
g_hotx = 0; g_hoty = 0;
if (shape == 4) { art = ART_HAND; g_hotx = 5; g_hoty = 0; }
else if (shape == 9) { art = ART_IBEAM; g_hotx = 3; g_hoty = 7; }
uint32_t *px = (uint32_t *)g_cur_buf.map;
memset(px, 0, (size_t)CUR * CUR * 4);
for (int y = 0; art[y] && y < CUR; y++) {
for (int x = 0; art[y][x] && x < CUR; x++) {
char ch = art[y][x];
if (ch == 'X') px[y * (g_cur_buf.pitch / 4) + x] = 0xFF000000u;
else if (ch == 'o') px[y * (g_cur_buf.pitch / 4) + x] = 0xFFFFFFFFu;
}
}
}
static void cursor_apply(void) {
if (!g_cur_ready || !g_seat_enabled) return;
drmModeSetCursor(g_drm, g_crtc, g_cur_buf.handle, CUR, CUR);
drmModeMoveCursor(g_drm, g_crtc, g_px - g_hotx, g_py - g_hoty);
}
/* ---- xkb + libinput ------------------------------------------------------ */
static struct xkb_context *g_xkb;
static struct xkb_keymap *g_keymap;
static struct xkb_state *g_xkb_state;
static struct udev *g_udev;
static struct libinput *g_li;
static int g_quit;
static void push_mods(void) {
q_push(EV_MODS,
(int32_t)xkb_state_serialize_mods(g_xkb_state, XKB_STATE_MODS_DEPRESSED),
(int32_t)xkb_state_serialize_mods(g_xkb_state, XKB_STATE_MODS_LATCHED),
(int32_t)xkb_state_serialize_mods(g_xkb_state, XKB_STATE_MODS_LOCKED),
(int32_t)xkb_state_serialize_layout(g_xkb_state, XKB_STATE_LAYOUT_EFFECTIVE));
}
static void clamp_pointer(void) {
if (g_px < 0) g_px = 0;
if (g_py < 0) g_py = 0;
if (g_px >= g_width) g_px = g_width - 1;
if (g_py >= g_height) g_py = g_height - 1;
}
static void handle_li_event(struct libinput_event *ev) {
switch (libinput_event_get_type(ev)) {
case LIBINPUT_EVENT_KEYBOARD_KEY: {
struct libinput_event_keyboard *k = libinput_event_get_keyboard_event(ev);
uint32_t key = libinput_event_keyboard_get_key(k);
int down = libinput_event_keyboard_get_key_state(k) == LIBINPUT_KEY_STATE_PRESSED;
/* Ctrl+Alt+F1..F12 switches VT; Ctrl+Alt+Backspace quits the session. */
if (down) {
int ctrl = xkb_state_mod_name_is_active(g_xkb_state, XKB_MOD_NAME_CTRL, XKB_STATE_MODS_EFFECTIVE) > 0;
int alt = xkb_state_mod_name_is_active(g_xkb_state, XKB_MOD_NAME_ALT, XKB_STATE_MODS_EFFECTIVE) > 0;
if (ctrl && alt) {
int vt = 0;
if (key >= KEY_F1_CODE && key <= KEY_F10_CODE) vt = (int)(key - KEY_F1_CODE) + 1;
else if (key == KEY_F11_CODE) vt = 11;
else if (key == KEY_F12_CODE) vt = 12;
if (vt && g_seat) { libseat_switch_session(g_seat, vt); break; }
if (key == KEY_BACKSPACE_CODE) { g_quit = 1; break; }
}
}
enum xkb_state_component ch = xkb_state_update_key(
g_xkb_state, key + 8, down ? XKB_KEY_DOWN : XKB_KEY_UP);
q_push(EV_KEY, (int32_t)key, down, 0, 0);
if (ch & (XKB_STATE_MODS_DEPRESSED | XKB_STATE_MODS_LATCHED | XKB_STATE_MODS_LOCKED | XKB_STATE_LAYOUT_EFFECTIVE))
push_mods();
break;
}
case LIBINPUT_EVENT_POINTER_MOTION: {
struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev);
g_px += (int)libinput_event_pointer_get_dx(p);
g_py += (int)libinput_event_pointer_get_dy(p);
clamp_pointer();
q_push(EV_MOVE, g_px, g_py, 0, 0);
cursor_apply();
break;
}
case LIBINPUT_EVENT_POINTER_MOTION_ABSOLUTE: {
struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev);
g_px = (int)libinput_event_pointer_get_absolute_x_transformed(p, (uint32_t)g_width);
g_py = (int)libinput_event_pointer_get_absolute_y_transformed(p, (uint32_t)g_height);
clamp_pointer();
q_push(EV_MOVE, g_px, g_py, 0, 0);
cursor_apply();
break;
}
case LIBINPUT_EVENT_POINTER_BUTTON: {
struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev);
q_push(EV_BUTTON, (int32_t)libinput_event_pointer_get_button(p),
libinput_event_pointer_get_button_state(p) == LIBINPUT_BUTTON_STATE_PRESSED, 0, 0);
break;
}
case LIBINPUT_EVENT_POINTER_AXIS: {
/* Legacy axis event: still emitted alongside the libinput >= 1.19 scroll events, so one
* handler covers wheels, touchpads and trackpoints on every libinput version. Value is in
* pointer-motion units (~15 per wheel notch), sent as 24.8 fixed point. */
struct libinput_event_pointer *p = libinput_event_get_pointer_event(ev);
int wheel = libinput_event_pointer_get_axis_source(p) == LIBINPUT_POINTER_AXIS_SOURCE_WHEEL;
static const enum libinput_pointer_axis axes[2] = {
LIBINPUT_POINTER_AXIS_SCROLL_VERTICAL, LIBINPUT_POINTER_AXIS_SCROLL_HORIZONTAL };
for (int i = 0; i < 2; i++) {
if (!libinput_event_pointer_has_axis(p, axes[i])) continue;
double v = libinput_event_pointer_get_axis_value(p, axes[i]);
int steps = wheel ? (int)libinput_event_pointer_get_axis_value_discrete(p, axes[i]) : 0;
if (v == 0.0 && steps == 0) continue; /* scroll stop */
q_push(EV_AXIS, i, (int32_t)(v * 256.0), steps, 0);
}
break;
}
case LIBINPUT_EVENT_TOUCH_DOWN: {
struct libinput_event_touch *t = libinput_event_get_touch_event(ev);
if (!g_touch_active) {
g_touch_active = 1;
g_touch_slot = libinput_event_touch_get_seat_slot(t);
g_px = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_width);
g_py = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_height);
clamp_pointer();
q_push(EV_MOVE, g_px, g_py, 0, 0);
q_push(EV_BUTTON, BTN_LEFT_CODE, 1, 0, 0);
cursor_apply();
}
break;
}
case LIBINPUT_EVENT_TOUCH_MOTION: {
struct libinput_event_touch *t = libinput_event_get_touch_event(ev);
if (g_touch_active && libinput_event_touch_get_seat_slot(t) == g_touch_slot) {
g_px = (int)libinput_event_touch_get_x_transformed(t, (uint32_t)g_width);
g_py = (int)libinput_event_touch_get_y_transformed(t, (uint32_t)g_height);
clamp_pointer();
q_push(EV_MOVE, g_px, g_py, 0, 0);
cursor_apply();
}
break;
}
case LIBINPUT_EVENT_TOUCH_UP:
case LIBINPUT_EVENT_TOUCH_CANCEL: {
struct libinput_event_touch *t = libinput_event_get_touch_event(ev);
if (g_touch_active && libinput_event_touch_get_seat_slot(t) == g_touch_slot) {
g_touch_active = 0;
q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0);
}
break;
}
default:
break;
}
}
static void dispatch_input(void) {
if (!g_li) return;
libinput_dispatch(g_li);
struct libinput_event *ev;
while ((ev = libinput_get_event(g_li)) != NULL) {
handle_li_event(ev);
libinput_event_destroy(ev);
}
}
/* ---- modeset / resume ---------------------------------------------------- */
static void do_modeset(void) {
if (drmModeSetCrtc(g_drm, g_crtc, g_fb[g_front].fb, 0, 0, &g_conn, 1, &g_mode) < 0)
fprintf(stderr, "kms: drmModeSetCrtc failed: %s\n", strerror(errno));
g_flip_pending = 0;
g_need_modeset = 0;
cursor_apply();
}
/* Legacy DPMS on the output's connector (the modeset path here is legacy too). */
static void set_dpms(int on) {
drmModeObjectProperties *props = drmModeObjectGetProperties(g_drm, g_conn, DRM_MODE_OBJECT_CONNECTOR);
if (!props) return;
for (uint32_t i = 0; i < props->count_props; i++) {
drmModePropertyRes *p = drmModeGetProperty(g_drm, props->props[i]);
if (!p) continue;
if (!strcmp(p->name, "DPMS")) {
if (drmModeConnectorSetProperty(g_drm, g_conn, p->prop_id, on ? DRM_MODE_DPMS_ON : DRM_MODE_DPMS_OFF) < 0)
fprintf(stderr, "kms: DPMS %s failed: %s\n", on ? "on" : "off", strerror(errno));
}
drmModeFreeProperty(p);
}
drmModeFreeObjectProperties(props);
}
/* ---- exported API -------------------------------------------------------- */
/* Turn the screen off (0) or on (1). While off, no frame is presented; on redoes the modeset so
* the last frame shows again. */
MOONBIT_FFI_EXPORT
void mp_kms_set_power(int32_t on) {
if (!g_seat || (on ? !g_blank : g_blank)) return;
g_blank = !on;
if (!g_seat_enabled || g_suspended) return; /* applied when the VT comes back */
if (on) {
set_dpms(1);
do_modeset();
} else {
set_dpms(0);
}
}
/* Open seat, DRM output and input. Returns 0 on success, negative step code on failure. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_open(void) {
g_seat = libseat_open_seat(&g_seat_listener, NULL);
if (!g_seat) { fprintf(stderr, "kms: cannot open a seat (run from a login VT, with seatd or logind)\n"); return -1; }
for (int i = 0; i < 50 && !g_seat_enabled; i++) libseat_dispatch(g_seat, 100);
if (!g_seat_enabled) { fprintf(stderr, "kms: seat was not enabled (is this VT active?)\n"); return -2; }
/* DRM device: first card with a connected output. */
for (int n = 0; n < 8 && g_drm < 0; n++) {
char path[32];
snprintf(path, sizeof path, "/dev/dri/card%d", n);
int fd = -1;
int id = libseat_open_device(g_seat, path, &fd);
if (id < 0) continue;
if (pick_output(fd) == 0) { g_drm = fd; g_drm_dev_id = id; }
else { libseat_close_device(g_seat, id); close(fd); }
}
if (g_drm < 0) { fprintf(stderr, "kms: no DRM device with a connected display\n"); return -3; }
g_width = g_mode.hdisplay; g_height = g_mode.vdisplay;
g_saved_crtc = drmModeGetCrtc(g_drm, g_crtc);
if (fb_create(&g_fb[0], g_width, g_height) < 0 || fb_create(&g_fb[1], g_width, g_height) < 0) {
fprintf(stderr, "kms: cannot create framebuffers\n");
return -4;
}
g_front = 0;
stale_add(0, 0, 1 << 16, 1 << 16);
do_modeset();
/* Hardware cursor (optional: fall back to no cursor if unsupported). */
if (fb_create(&g_cur_buf, CUR, CUR) == 0) {
g_cur_ready = 1;
g_cur_shape = 1;
cursor_draw(1);
g_px = g_width / 2; g_py = g_height / 2;
cursor_apply();
}
/* xkb keymap from the environment (XKB_DEFAULT_*), default "us". */
g_xkb = xkb_context_new(XKB_CONTEXT_NO_FLAGS);
struct xkb_rule_names names = {0};
g_keymap = xkb_keymap_new_from_names(g_xkb, &names, XKB_KEYMAP_COMPILE_NO_FLAGS);
if (!g_keymap) { fprintf(stderr, "kms: cannot compile the xkb keymap\n"); return -5; }
g_xkb_state = xkb_state_new(g_keymap);
g_udev = udev_new();
g_li = libinput_udev_create_context(&g_li_iface, NULL, g_udev);
if (!g_li || libinput_udev_assign_seat(g_li, libseat_seat_name(g_seat)) != 0) {
fprintf(stderr, "kms: cannot start libinput on seat %s\n", g_seat ? libseat_seat_name(g_seat) : "?");
return -6;
}
dispatch_input();
return 0;
}
MOONBIT_FFI_EXPORT int32_t mp_kms_width(void) { return g_width; }
MOONBIT_FFI_EXPORT int32_t mp_kms_height(void) { return g_height; }
MOONBIT_FFI_EXPORT int32_t mp_kms_quit_requested(void) { return g_quit; }
/* Service seat, DRM and input fds without blocking. Returns 1 while the seat is active. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_poll(void) {
if (!g_seat) return 0;
struct pollfd pfd[3];
int n = 0;
pfd[n].fd = libseat_get_fd(g_seat); pfd[n].events = POLLIN; n++;
pfd[n].fd = g_drm; pfd[n].events = POLLIN; n++;
int lifd = g_li ? libinput_get_fd(g_li) : -1;
pfd[n].fd = lifd; pfd[n].events = POLLIN; n++;
poll(pfd, (nfds_t)n, 0);
libseat_dispatch(g_seat, 0);
if (pfd[1].revents & POLLIN) {
drmEventContext ctx = { .version = 2, .page_flip_handler = page_flip_done };
drmHandleEvent(g_drm, &ctx);
}
if (g_seat_lost) {
/* VT switched away: stop input, give up DRM master, acknowledge. */
g_seat_lost = 0;
g_suspended = 1;
if (g_touch_active) {
g_touch_active = 0;
q_push(EV_BUTTON, BTN_LEFT_CODE, 0, 0, 0);
}
if (g_li) libinput_suspend(g_li);
drmDropMaster(g_drm);
libseat_disable_seat(g_seat);
} else if (g_seat_enabled && g_suspended) {
/* Back on our VT: retake DRM master, resume input, redo the modeset. */
g_suspended = 0;
drmSetMaster(g_drm);
if (g_li) libinput_resume(g_li);
do_modeset();
if (g_blank) set_dpms(0);
}
if (g_li) dispatch_input();
return g_seat_enabled;
}
/* The fds mp_kms_poll services (0 seat, 1 DRM, 2 libinput), for an idle loop to block on;
-1 when not open. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_fd(int32_t i) {
if (!g_seat) return -1;
switch (i) {
case 0: return libseat_get_fd(g_seat);
case 1: return g_drm;
case 2: return g_li ? libinput_get_fd(g_li) : -1;
default: return -1;
}
}
/* True when a new frame may be presented (seat active, no flip in flight). */
MOONBIT_FFI_EXPORT
int32_t mp_kms_frame_ready(void) {
return g_seat_enabled && !g_flip_pending && !g_blank;
}
/* RGBA8888 rows -> the scanout buffer's XRGB8888 (B, G, R, X), one pixel as one 32-bit word. */
static void copy_rows(struct fbuf *b, const uint8_t *src, int w, int x0, int y0, int x1, int y1) {
for (int y = y0; y < y1; y++) {
uint32_t *d = (uint32_t *)(b->map + (size_t)y * b->pitch);
const uint32_t *s = (const uint32_t *)(src + (size_t)y * (size_t)w * 4);
for (int x = x0; x < x1; x++) {
uint32_t v = s[x];
d[x] = 0xff000000u | (v & 0x0000ff00u) | ((v >> 16) & 0xffu) | ((v & 0xffu) << 16);
}
}
}
/* Present an RGBA8888 frame of w x h (must match the mode). */
MOONBIT_FFI_EXPORT
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h);
/* Show an RGBA8888 frame of which only (dx, dy, dw, dh) changed since the last call: only what the
* back buffer is missing is copied into it (the change now, and the one shown last time). */
MOONBIT_FFI_EXPORT
int32_t mp_kms_present_damage(moonbit_bytes_t pixels, int32_t w, int32_t h, int32_t dx, int32_t dy, int32_t dw,
int32_t dh) {
int cw = w < g_width ? w : g_width;
int ch = h < g_height ? h : g_height;
int x0 = dx < 0 ? 0 : dx, y0 = dy < 0 ? 0 : dy;
int x1 = dx + dw > cw ? cw : dx + dw, y1 = dy + dh > ch ? ch : dy + dh;
if (x0 < x1 && y0 < y1) stale_add(x0, y0, x1, y1);
if (!g_seat_enabled || g_flip_pending || g_blank) return 0;
int back = 1 - g_front;
struct fbuf *b = &g_fb[back];
int *s = g_stale[back];
int sx0 = s[0] < 0 ? 0 : s[0], sy0 = s[1] < 0 ? 0 : s[1];
int sx1 = s[2] > cw ? cw : s[2], sy1 = s[3] > ch ? ch : s[3];
if (sx0 < sx1 && sy0 < sy1) copy_rows(b, (const uint8_t *)pixels, w, sx0, sy0, sx1, sy1);
s[0] = s[1] = s[2] = s[3] = 0;
if (drmModePageFlip(g_drm, g_crtc, b->fb, DRM_MODE_PAGE_FLIP_EVENT, NULL) < 0) {
/* Fall back to a synchronous set. */
if (drmModeSetCrtc(g_drm, g_crtc, b->fb, 0, 0, &g_conn, 1, &g_mode) < 0) return -1;
} else {
g_flip_pending = 1;
}
g_front = back;
return 1;
}
MOONBIT_FFI_EXPORT
int32_t mp_kms_present(moonbit_bytes_t pixels, int32_t w, int32_t h) {
return mp_kms_present_damage(pixels, w, h, 0, 0, w, h);
}
/* Cursor image by wp_cursor_shape_v1 value (4 pointer hand, 9 text, else arrow). */
MOONBIT_FFI_EXPORT
void mp_kms_set_cursor_shape(int32_t shape) {
if (!g_cur_ready) return;
int s = shape == 4 ? 4 : (shape == 9 ? 9 : 1);
if (s == g_cur_shape) return;
g_cur_shape = s;
cursor_draw(s);
cursor_apply();
}
/* Next queued input event: returns its type (0 = none) and stores args for mp_kms_arg. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_next_event(void) {
if (g_qh == g_qt) return 0;
memcpy(g_cur, g_q[g_qh], sizeof g_cur);
g_qh = (g_qh + 1) % QCAP;
return g_cur[0];
}
MOONBIT_FFI_EXPORT
int32_t mp_kms_arg(int32_t i) { return (i >= 1 && i <= 4) ? g_cur[i] : 0; }
/* Pointer position, for the initial MoveTo. */
MOONBIT_FFI_EXPORT int32_t mp_kms_pointer_x(void) { return g_px; }
MOONBIT_FFI_EXPORT int32_t mp_kms_pointer_y(void) { return g_py; }
/* xkb keymap text (format v1, NUL-terminated). Length includes the NUL; 0 if none. */
MOONBIT_FFI_EXPORT
int32_t mp_kms_keymap_len(void) {
if (!g_keymap) return 0;
char *s = xkb_keymap_get_as_string(g_keymap, XKB_KEYMAP_FORMAT_TEXT_V1);
if (!s) return 0;
int32_t n = (int32_t)strlen(s) + 1;
free(s);
return n;
}
MOONBIT_FFI_EXPORT
int32_t mp_kms_keymap_copy(moonbit_bytes_t out) {
if (!g_keymap) return 0;
char *s = xkb_keymap_get_as_string(g_keymap, XKB_KEYMAP_FORMAT_TEXT_V1);
if (!s) return 0;
int32_t cap = Moonbit_array_length(out);
int32_t n = (int32_t)strlen(s) + 1;
if (n > cap) n = cap;
memcpy(out, s, (size_t)n);
free(s);
return n;
}
MOONBIT_FFI_EXPORT
void mp_kms_close(void) {
g_touch_active = 0;
if (g_li) { libinput_unref(g_li); g_li = NULL; }
if (g_udev) { udev_unref(g_udev); g_udev = NULL; }
if (g_xkb_state) { xkb_state_unref(g_xkb_state); g_xkb_state = NULL; }
if (g_keymap) { xkb_keymap_unref(g_keymap); g_keymap = NULL; }
if (g_xkb) { xkb_context_unref(g_xkb); g_xkb = NULL; }
if (g_drm >= 0) {
if (g_seat_enabled && g_saved_crtc) {
drmModeSetCrtc(g_drm, g_saved_crtc->crtc_id, g_saved_crtc->buffer_id,
g_saved_crtc->x, g_saved_crtc->y, &g_conn, 1, &g_saved_crtc->mode);
}
if (g_saved_crtc) { drmModeFreeCrtc(g_saved_crtc); g_saved_crtc = NULL; }
if (g_drm_dev_id >= 0 && g_seat) libseat_close_device(g_seat, g_drm_dev_id);
close(g_drm);
g_drm = -1;
}
if (g_seat) { libseat_close_seat(g_seat); g_seat = NULL; }
}