Ui: the window on Crafter.Graphics, driven from the GLib main loop

The window library. Loop makes the Wayland display a GSource
(libwayland's prepare_read protocol) so D-Bus and the window are served
from one thread without the library's StartSync, which runs a loop of
its own that serves no GMainContext and would starve the bus; the app
owns its frame callback too — a redraw is a frame request and a bare
commit, the compositor's done runs one Window::Update, and nothing
re-arms unless something is dirty or animating — or the day changes: the
captions name the day and an idle window draws no frame by itself, so a
timer on the wall clock, which wakes at the next local midnight and
whenever that clock is set, asks for one when the local date is another
one (DayWatch); when the compositor's connection breaks the source stops
and says so (App's onDisplayLost), since the process cannot connect its
display again. Canvas initialises the device once per process and holds
the window, the font with a word wrapper and a text width over its
unrounded advances, as DrawText draws them, and four compositing layers
(background, the clipped scrolling content, the chrome, an overlay):
within one fused dispatch all quads composite before all text, so the
layers are separate dispatches in that order. The layers' buffer slots
hand their numbers back to the descriptor heap when they go, so the heap
is declared before them and outlives them. Screens draw the conversation
list (avatars, previews, time captions, unread badges, the
new-conversation button, with room under the last row to scroll clear of
it) and one conversation (day separators, wrapped bubbles, clock and
state captions — only what is in view, the layer's glyph budget being
finite) and record the regions a tap can hit. App wires them to the
store and Sync: mouse events become gestures (the detector's slop and
fling threshold set from the window's scale, the positions being buffer
pixels), a tap is resolved against the last frame's regions (which name
the conversation or message they drew, not a position a reload may
shift), scrolling is by wheel, drag or fling (a press stops a fling; a
screen change stops a fling and cancels the press under it, so the
scroll left behind keeps no velocity for a return to revive and a
release after a link's or a notification's Open is no tap on the new
screen), the window is created on the first Show (when the library
cannot and says so — no display, a compositor without wl_shm,
wl_compositor or xdg_wm_base, no Vulkan driver — Show logs why, Open
opens nothing, and the app runs on without one; a later Show fails at
once, the device's set-up running only once) and torn down in order on
Shutdown. ScreenshotThenQuit renders one frame outside the compositor's
pacing and saves it; a window it creates first waits 600 ms for the
compositor's configure, which sizes it (to the screen, on a phone). A
capture with no window to render it — none could be made, or it went
before the frame — is logged and sets App's exitCode to 1.

project.cpp gains Crafter.Graphics (--local takes the branch worktree with
the Wayland input work until it is merged), the imsd-messages-ui library,
and libevdev from the prefix of packaging/build-libevdev.sh on the
library's include path and the executable's library path (a sysroot
build looks for it in the sysroot instead).
This commit is contained in:
Jorijn van der Graaf 2026-10-18 00:26:09 +02:00
commit 6eea7228d0
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
8 changed files with 1132 additions and 3 deletions

View file

@ -0,0 +1,222 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// lint-disable-file no-char-pointer
/*
ImsdMessages.Ui:Loop — GLib owns the main loop. The Wayland display is a
GSource (the libwayland prepare_read protocol), so D-Bus and the window are
served from one thread without the library's StartSync, which runs a loop
of its own that serves no GMainContext and would starve the bus. The
app owns its frame callback as well: a redraw is requested with a frame
request and a bare commit, the compositor's done runs one Window::Update,
and nothing re-arms unless something is dirty or animating — no frames
while idle, no frames for an unmapped surface. The day's change is a source
too (DayWatch): an idle window draws no frame by itself, and its captions
name the day.
*/
module;
#include <errno.h>
#include <gio/gio.h>
#include <glib-unix.h>
#include <sys/timerfd.h>
#include <time.h>
#include <unistd.h>
#include <wayland-client.h>
export module ImsdMessages.Ui:Loop;
import std;
import Crafter.Graphics;
export namespace ImsdMessages::Ui {
class WaylandSource {
public:
explicit WaylandSource(wl_display* display) : display(display) {
static GSourceFuncs funcs = { Prepare, Check, Dispatch, nullptr, nullptr, nullptr };
source = g_source_new(&funcs, sizeof(Source));
reinterpret_cast<Source*>(source)->self = this;
g_source_set_name(source, "wayland-display");
tag = g_source_add_unix_fd(source, wl_display_get_fd(display), static_cast<GIOCondition>(G_IO_IN | G_IO_ERR | G_IO_HUP));
g_source_attach(source, nullptr);
}
~WaylandSource() {
if (reading) wl_display_cancel_read(display);
g_source_destroy(source);
g_source_unref(source);
}
WaylandSource(const WaylandSource&) = delete;
WaylandSource& operator=(const WaylandSource&) = delete;
// Called once, when the connection to the compositor breaks: the
// source stops, and the process's display cannot reconnect. It must
// not destroy the source.
std::function<void()> onLost;
private:
struct Source {
GSource base;
WaylandSource* self;
};
static WaylandSource& Self(GSource* src) { return *reinterpret_cast<Source*>(src)->self; }
static gboolean Prepare(GSource* src, gint* timeout) {
WaylandSource& self = Self(src);
*timeout = -1;
if (self.reading) {
wl_display_cancel_read(self.display);
self.reading = false;
}
// Events already queued (by a roundtrip of the library, or a
// previous read): dispatch them now instead of polling.
if (wl_display_prepare_read(self.display) != 0) return TRUE;
self.reading = true;
// A flush that fails is not handled here: EAGAIN (the socket
// full) flushes the rest at the next Prepare, and EPIPE (it dead)
// is left to the read — the fd polls hung up, the read sets the
// display's error, and Dispatch reports it.
wl_display_flush(self.display);
return FALSE;
}
static gboolean Check(GSource* src) {
WaylandSource& self = Self(src);
if (!self.reading) return TRUE;
self.reading = false;
const GIOCondition cond = g_source_query_unix_fd(src, self.tag);
if (cond & (G_IO_IN | G_IO_ERR | G_IO_HUP)) {
wl_display_read_events(self.display);
return TRUE;
}
wl_display_cancel_read(self.display);
return FALSE;
}
static gboolean Dispatch(GSource* src, GSourceFunc, gpointer) {
WaylandSource& self = Self(src);
if (wl_display_dispatch_pending(self.display) < 0) {
std::println("imsd-messages: the Wayland display is gone (error {})", wl_display_get_error(self.display));
if (self.onLost) self.onLost();
return G_SOURCE_REMOVE;
}
return G_SOURCE_CONTINUE;
}
wl_display* display;
GSource* source = nullptr;
gpointer tag = nullptr;
bool reading = false;
};
class FrameDriver {
public:
explicit FrameDriver(Crafter::Window& window) : window(window) {}
~FrameDriver() {
if (pending) wl_callback_destroy(pending);
}
FrameDriver(const FrameDriver&) = delete;
FrameDriver& operator=(const FrameDriver&) = delete;
// Draws one frame (Window::Update); set by the app.
std::function<void()> onFrame;
// A frame as soon as the compositor allows one.
void RequestRedraw() {
dirty = true;
if (pending) return;
pending = wl_surface_frame(window.surface);
wl_callback_add_listener(pending, &listener, this);
wl_surface_commit(window.surface);
}
// Frames keep coming while on (a fling, a caret blink is a timer instead).
void SetAnimating(bool on) {
animating = on;
if (on) RequestRedraw();
}
bool Animating() const noexcept { return animating; }
private:
static void Done(void* data, wl_callback* cb, std::uint32_t) {
FrameDriver& self = *static_cast<FrameDriver*>(data);
wl_callback_destroy(cb);
self.pending = nullptr;
self.dirty = false;
if (self.onFrame) self.onFrame();
if (self.animating || self.dirty) self.RequestRedraw();
}
inline static const wl_callback_listener listener = { Done };
Crafter::Window& window;
wl_callback* pending = nullptr;
bool dirty = false;
bool animating = false;
};
// Tells when the local date has changed. The source wakes at the next
// local midnight — a timer on the wall clock, so one that passed while
// the system slept expires when it wakes — and whenever that clock is
// set (TFD_TIMER_CANCEL_ON_SET: the read fails then, which wakes the
// source as an expiry does); the date is read at each wake, and told
// when it is another one.
class DayWatch {
public:
DayWatch() {
fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);
if (fd < 0) return; // no timer: the captions wait for the next frame something else asks for
Arm();
source = g_unix_fd_add(fd, G_IO_IN, OnReady, this);
}
~DayWatch() {
if (source) g_source_remove(source);
if (fd >= 0) close(fd);
}
DayWatch(const DayWatch&) = delete;
DayWatch& operator=(const DayWatch&) = delete;
std::function<void()> onDay;
private:
// Arms the next local midnight by the zone's own rules (mktime), as
// an absolute time on the wall clock — read as the timer reads it:
// time() may still give the second before an expiry, and the
// midnight just passed would be armed again, to expire at once.
// True when the local date is not the one of the arming before.
bool Arm() {
tzset();
timespec now{};
clock_gettime(CLOCK_REALTIME, &now);
tm local{};
localtime_r(&now.tv_sec, &local);
const std::int32_t today = (local.tm_year + 1900) * 1000 + local.tm_yday;
const bool changed = today != date;
date = today;
local.tm_mday += 1;
local.tm_hour = 0;
local.tm_min = 0;
local.tm_sec = 0;
local.tm_isdst = -1;
itimerspec at{};
at.it_value.tv_sec = mktime(&local);
// A midnight the zone's rules leave out, or none found: looked
// for again in a minute, never at once.
if (at.it_value.tv_sec <= now.tv_sec) at.it_value.tv_sec = now.tv_sec + 60;
timerfd_settime(fd, TFD_TIMER_ABSTIME | TFD_TIMER_CANCEL_ON_SET, &at, nullptr);
return changed;
}
static gboolean OnReady(gint fd, GIOCondition, gpointer data) {
DayWatch& self = *static_cast<DayWatch*>(data);
// The expiries' count, or ECANCELED once the clock was set:
// either way the date is read anew, and the read empties the fd.
std::uint64_t expiries = 0;
if (read(fd, &expiries, sizeof expiries) < 0 && errno == EAGAIN) return G_SOURCE_CONTINUE;
if (self.Arm() && self.onDay) self.onDay();
return G_SOURCE_CONTINUE;
}
std::int32_t fd = -1;
guint source = 0;
std::int32_t date = 0; // the local date armed for: its year and the day in it
};
}