DRM/KMS + libinput backend and a Moon Plasma login session

compositor/kms: libseat (device access, VT switching), DRM dumb buffers with page
flips and a hardware cursor, libinput keyboard/pointer, xkbcommon keymap and
modifiers. --drm runs the compositor on the real display at the monitor's native
mode. session/ holds the display-manager entry, launcher script and installer
(just install-session). Untested on hardware: refuses to start inside another
session.

Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
nandiandClaude Sonnet 5.5 committed 2026-11-24 20:59:54 -08:00
1 parent 7a37039673
commit b2557aca52
9 files changed
+829 -2

No files matched your search

+55 -2
View File
@@ -7,8 +7,9 @@ fn main {
let mut theme_path = "config/themes/moon-night.json"
let mut gfx_out = ""
let mut windowed = false
let width = 1280
let height = 720
let mut drm = false
let mut width = 1280
let mut height = 720
let mut i = 1
while i < args.length() {
@@ -22,6 +23,9 @@ fn main {
} else if a == "--window" {
windowed = true
i = i + 1
} else if a == "--drm" {
drm = true
i = i + 1
} else if a == "--gfx-out" && i + 1 < args.length() {
gfx_out = args[i + 1]
i = i + 2
@@ -41,6 +45,24 @@ fn main {
@scene.ThemeTokens::moon_night()
}
// Login-session mode: take over the display via DRM/KMS + libinput, and size
// the desktop to the monitor's native mode.
let kms = if drm {
match @kms.Kms::open() {
Some(k) => {
width = k.width
height = k.height
Some(k)
}
None => {
println("failed to start the DRM backend (run from a login VT, not inside another session)")
return
}
}
} else {
None
}
let gfx_surface = @gfx.Surface::new({
width: Some(width),
height: Some(height),
@@ -77,9 +99,31 @@ fn main {
} else {
None
}
match kms {
Some(k) => comp.server.set_keymap(k.keymap)
None => ()
}
println("moon-plasma compositor listening on " + socket_path + " (wasi-gfx surface active)")
while true {
comp.step()
match kms {
Some(k) => {
if !k.poll() {
break
}
let now_ms = @env.now().to_uint()
for ev in k.take_input() {
comp.handle_input(ev, now_ms)
}
k.set_cursor_shape(comp.desired_cursor())
if k.frame_ready() {
k.present(comp.present_to_gfx(gfx_ctx))
}
@sys.sleep_ms(8)
continue
}
None => ()
}
match nested {
Some(n) => {
if !n.poll() {
@@ -104,8 +148,17 @@ fn main {
}
@sys.sleep_ms(16)
}
match kms {
Some(k) => k.close()
None => ()
}
comp.close()
}
None => {
match kms {
Some(k) => k.close()
None => ()
}
println("failed to bind Wayland socket at " + socket_path)
}
}
+10
View File
@@ -7,8 +7,18 @@ import {
"moonplasma/desktop/compositor/gfx" @gfx,
"moonplasma/desktop/compositor/host" @host,
"moonplasma/desktop/compositor/nested" @nested,
"moonplasma/desktop/compositor/kms" @kms,
}
supported_targets = "-all+native"
pkgtype(kind: "executable")
// System libraries behind the DRM/KMS backend (compositor/kms).
options(
link: {
"native": {
"cc-link-flags": "-ldrm -linput -lseat -lxkbcommon -ludev",
},
},
)
+120
View File
@@ -0,0 +1,120 @@
///| Native display backend for running moon-plasma as a login session: DRM/KMS
/// output (dumb buffers, page flips, hardware cursor), libinput keyboard and
/// pointer, xkbcommon keymap, libseat for device access and VT switching.
/// All state lives in the C shim (kms_stub.c); this wrapper exposes it with the
/// same shape as `@nested.NestedWindow` so the main loop can drive either.
///|
extern "C" fn c_open() -> Int = "mp_kms_open"
///|
extern "C" fn c_width() -> Int = "mp_kms_width"
///|
extern "C" fn c_height() -> Int = "mp_kms_height"
///|
extern "C" fn c_quit_requested() -> Int = "mp_kms_quit_requested"
///|
extern "C" fn c_poll() -> Int = "mp_kms_poll"
///|
extern "C" fn c_frame_ready() -> Int = "mp_kms_frame_ready"
///|
extern "C" fn c_present(pixels : FixedArray[Byte], w : Int, h : Int) -> Int = "mp_kms_present"
///|
extern "C" fn c_set_cursor_shape(shape : Int) = "mp_kms_set_cursor_shape"
///|
extern "C" fn c_next_event() -> Int = "mp_kms_next_event"
///|
extern "C" fn c_arg(i : Int) -> Int = "mp_kms_arg"
///|
extern "C" fn c_keymap_len() -> Int = "mp_kms_keymap_len"
///|
extern "C" fn c_keymap_copy(out : FixedArray[Byte]) -> Int = "mp_kms_keymap_copy"
///|
extern "C" fn c_close() = "mp_kms_close"
///|
pub(all) struct Kms {
width : Int
height : Int
keymap : Bytes
}
///| Open the seat, the first connected DRM output and libinput. Returns None
/// (after printing why to stderr) when not running on an active login VT.
pub fn Kms::open() -> Kms? {
if c_open() != 0 {
c_close()
return None
}
let n = c_keymap_len()
let buf : FixedArray[Byte] = FixedArray::make(n, b'\x00')
let got = if n > 0 { c_keymap_copy(buf) } else { 0 }
let keymap = Bytes::from_fixedarray(buf, len=got)
Some({ width: c_width(), height: c_height(), keymap })
}
///| Service the seat, DRM and input fds. False once Ctrl+Alt+Backspace was pressed.
pub fn Kms::poll(_self : Kms) -> Bool {
ignore(c_poll())
c_quit_requested() == 0
}
///| True when a new frame can be presented (seat active, no page flip in flight).
pub fn Kms::frame_ready(_self : Kms) -> Bool {
c_frame_ready() != 0
}
///| Present a composed frame (its size must match the output mode).
pub fn Kms::present(_self : Kms, pixmap : @renderer.Pixmap) -> Unit {
ignore(c_present(pixmap.data, pixmap.width, pixmap.height))
}
///| Show the cursor for a wp_cursor_shape_v1 value.
pub fn Kms::set_cursor_shape(_self : Kms, shape : UInt) -> Unit {
c_set_cursor_shape(shape.reinterpret_as_int())
}
///| Input queued since the last call, in the compositor's event type.
pub fn Kms::take_input(_self : Kms) -> Array[@nested.InputEvent] {
let out : Array[@nested.InputEvent] = []
while true {
let t = c_next_event()
if t == 0 {
break
}
let a = c_arg(1)
let b = c_arg(2)
match t {
1 => out.push(PointerMove(a.to_double(), b.to_double()))
2 => out.push(PointerButton(a.reinterpret_as_uint(), b != 0))
3 => out.push(Key(a.reinterpret_as_uint(), b != 0))
4 =>
out.push(
Modifiers(
a.reinterpret_as_uint(),
b.reinterpret_as_uint(),
c_arg(3).reinterpret_as_uint(),
c_arg(4).reinterpret_as_uint(),
),
)
_ => ()
}
}
out
}
///| Restore the previous video mode and release the seat.
pub fn Kms::close(_self : Kms) -> Unit {
c_close()
}
+524
View File
@@ -0,0 +1,524 @@
/* 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
/* ---- 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;
}
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 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 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;
}
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();
}
/* ---- exported API -------------------------------------------------------- */
/* 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;
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_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_li) dispatch_input();
return g_seat_enabled;
}
/* 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;
}
/* 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) {
if (!g_seat_enabled || g_flip_pending) return 0;
int back = 1 - g_front;
struct fbuf *b = &g_fb[back];
int cw = w < g_width ? w : g_width;
int ch = h < g_height ? h : g_height;
const uint8_t *src = (const uint8_t *)pixels;
for (int y = 0; y < ch; y++) {
uint8_t *dst = b->map + (size_t)y * b->pitch;
const uint8_t *s = src + (size_t)y * (size_t)w * 4;
for (int x = 0; x < cw; x++) {
dst[x * 4 + 0] = s[x * 4 + 2]; /* B */
dst[x * 4 + 1] = s[x * 4 + 1]; /* G */
dst[x * 4 + 2] = s[x * 4 + 0]; /* R */
dst[x * 4 + 3] = 0xff;
}
}
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;
}
/* 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) {
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; }
}
+16
View File
@@ -0,0 +1,16 @@
import {
"moonbitlang/core/builtin",
"moonplasma/desktop/compositor/renderer" @renderer,
"moonplasma/desktop/compositor/nested" @nested,
}
supported_targets = "-all+native"
options(
"native-stub": [ "kms_stub.c" ],
link: {
"native": {
"stub-cc-flags": "-I/usr/include/libdrm",
},
},
)
+13
View File
@@ -44,6 +44,19 @@ run-headless: build
rm -f {{socket}}
{{exe}} --socket {{socket}} --theme {{theme}}
# Run the compositor on the real display (DRM/KMS + libinput). Run from a login VT (Ctrl+Alt+F3), not inside another session. Ctrl+Alt+Backspace quits, Ctrl+Alt+F<n> switches VT.
run-drm: build-release
rm -f {{socket}}
{{release_exe}} --drm --socket {{socket}} --theme {{theme}}
# Install the Moon Plasma login session (display-manager entry); asks for root once.
install-session: build-release
run0 python3 session/install.py
# Remove the login session again.
uninstall-session:
run0 python3 session/install.py --remove
# Start a Wayland client inside the running compositor (default: foot).
client *cmd="foot":
WAYLAND_DISPLAY={{socket}} {{cmd}}
+56
View File
@@ -0,0 +1,56 @@
#!/usr/bin/env python3
"""Install (or remove) the Moon Plasma login session. Run as root, once:
run0 python3 session/install.py # install
run0 python3 session/install.py --remove # uninstall
Installs:
/usr/local/bin/moon-plasma release compositor binary
/usr/local/bin/moon-plasma-session session launcher
/usr/local/share/moon-plasma/{config,wit}/ files the compositor reads at runtime
/usr/share/wayland-sessions/moon-plasma.desktop display-manager entry
"""
import os, shutil, sys
root = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
exe = os.path.join(root, "_build/native/release/build/compositor/bin/bin.exe")
share = "/usr/local/share/moon-plasma"
targets = [
"/usr/local/bin/moon-plasma",
"/usr/local/bin/moon-plasma-session",
"/usr/share/wayland-sessions/moon-plasma.desktop",
]
if "--remove" in sys.argv:
for t in targets:
if os.path.exists(t):
os.remove(t)
print("removed", t)
if os.path.isdir(share):
shutil.rmtree(share)
print("removed", share)
sys.exit(0)
if os.geteuid() != 0:
sys.exit("run as root: run0 python3 session/install.py")
if not os.path.exists(exe):
sys.exit("missing %s - run `just build-release` first" % exe)
def put(src, dst, mode):
os.makedirs(os.path.dirname(dst), exist_ok=True)
shutil.copyfile(src, dst + ".new")
os.chmod(dst + ".new", mode)
os.replace(dst + ".new", dst) # atomic: safe to reinstall over a running binary
print("installed", dst)
put(exe, "/usr/local/bin/moon-plasma", 0o755)
put(os.path.join(root, "session/moon-plasma-session"), "/usr/local/bin/moon-plasma-session", 0o755)
put(os.path.join(root, "session/moon-plasma.desktop"), "/usr/share/wayland-sessions/moon-plasma.desktop", 0o644)
for d in ("config", "wit"):
dst = os.path.join(share, d)
if os.path.isdir(dst):
shutil.rmtree(dst)
os.makedirs(share, exist_ok=True)
shutil.copytree(os.path.join(root, d), dst)
print("installed", dst)
print("done: pick 'Moon Plasma' in the session menu of your login screen")
+28
View File
@@ -0,0 +1,28 @@
#!/bin/sh
# Login-session entry point for Moon Plasma (started by the display manager).
# Runs the native compositor on the seat's display via DRM/KMS + libinput and
# logs to ~/.local/state/moon-plasma/session.log.
share=/usr/local/share/moon-plasma
export XDG_SESSION_TYPE=wayland
export XDG_CURRENT_DESKTOP=moon-plasma
export XDG_SESSION_DESKTOP=moon-plasma
export MOZ_ENABLE_WAYLAND=1
export QT_QPA_PLATFORM=wayland
export SDL_VIDEODRIVER=wayland
mkdir -p "$HOME/.local/state/moon-plasma"
log="$HOME/.local/state/moon-plasma/session.log"
# The compositor reads wit/ and config/ relative to its working directory.
cd "$share" || exit 1
sock="${XDG_RUNTIME_DIR:-/tmp}/wayland-moon-0"
rm -f "$sock"
if [ -z "$DBUS_SESSION_BUS_ADDRESS" ] && command -v dbus-run-session >/dev/null 2>&1; then
exec dbus-run-session -- /usr/local/bin/moon-plasma --drm --socket "$sock" \
--theme "$share/config/themes/moon-night.json" >"$log" 2>&1
fi
exec /usr/local/bin/moon-plasma --drm --socket "$sock" \
--theme "$share/config/themes/moon-night.json" >"$log" 2>&1
+7
View File
@@ -0,0 +1,7 @@
[Desktop Entry]
Name=Moon Plasma
Comment=Moon Plasma desktop (native MoonBit Wayland compositor)
Exec=/usr/local/bin/moon-plasma-session
TryExec=/usr/local/bin/moon-plasma-session
Type=Application
DesktopNames=moon-plasma