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

@ -26,9 +26,10 @@ and §7.9 (Messaging) and §8.1 (the frozen one).
| Path | What it is | | Path | What it is |
|---|---| |---|---|
| `project.cpp` | The build description for Crafter.Build: three products (below) and the tests. | | `project.cpp` | The build description for Crafter.Build: four products (below) and the tests. |
| `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, gestures, the store, the sync logic. | | `interfaces/ImsdMessages*.cppm` | `imsd-messages-core`: std + Crafter.DB, no GLib, no window — numbers, time, the model, word wrap, gestures, the store, the sync logic. |
| `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name. | | `interfaces/ImsdMessages.Bus*.cppm` | `imsd-messages-bus`: GLib/GDBus — imsd's dictionaries, the client, notifications, the app's own bus name. |
| `interfaces/ImsdMessages.Ui*.cppm` | `imsd-messages-ui`: the window on Crafter.Graphics, driven from the GLib main loop. |
| `implementations/main.cpp` | The executable `imsd-messages`. | | `implementations/main.cpp` | The executable `imsd-messages`. |
| `tests/<Name>/main.cpp` | One test per directory, declared in `project.cpp`. | | `tests/<Name>/main.cpp` | One test per directory, declared in `project.cpp`. |
| `assets/` | The bundled font (Noto Sans, OFL 1.1). | | `assets/` | The bundled font (Noto Sans, OFL 1.1). |

View file

@ -0,0 +1,397 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
// lint-disable-file no-char-pointer
/*
ImsdMessages.Ui:App — the window as a whole: created on first Show, fed by
Sync through the shell, drawn from the store on demand. Mouse events
become gestures (touch joins them once Crafter.Graphics delivers it), a
tap is resolved against the regions the last frame recorded, scrolling is
by wheel, drag or fling, and nothing is drawn while nothing changes.
*/
module;
#include <gio/gio.h>
#include <time.h>
#include "vulkan/vulkan.h"
export module ImsdMessages.Ui:App;
import std;
import Crafter.Graphics;
import Crafter.Event;
import ImsdMessages;
import :Loop;
import :Canvas;
import :Screens;
export namespace ImsdMessages::Ui {
class App {
public:
App(MessageStore& store, std::filesystem::path assetDir, std::filesystem::path cacheDir) : store(store), assetDir(std::move(assetDir)), cacheDir(std::move(cacheDir)) {}
~App() {
Shutdown();
if (longPressTimer) g_source_remove(longPressTimer);
}
// Tears the window down in order: the GPU first finishes the frame
// it may still be drawing from the item buffers, then the listeners
// let go of the window, then the frame driver, the display source
// and the canvas go.
void Shutdown() {
if (!canvas) return;
vkDeviceWaitIdle(Crafter::Device::device);
downSub.reset();
upSub.reset();
moveSub.reset();
scrollSub.reset();
keySub.reset();
resizeSub.reset();
closeSub.reset();
day.reset();
frames.reset();
source.reset();
canvas.reset();
}
private:
static gboolean OnScreenshot(gpointer data) {
App& self = *static_cast<App*>(data);
if (self.canvas) {
self.canvas->Window().Update();
self.canvas->Window().SaveFrame(self.screenshotPath);
self.Log(std::format("screenshot written to {} ({}x{} px)", self.screenshotPath.string(), self.canvas->Window().width, self.canvas->Window().height));
} else {
// No window to render it — none could be made, or it went
// between the request and the capture: logged, and the run
// ends with exit 1, so a bench learns it from both.
self.Log(std::format("screenshot not written to {}: no window", self.screenshotPath.string()));
self.exitCode = 1;
}
if (self.onQuit) self.onQuit();
return G_SOURCE_REMOVE;
}
public:
App(const App&) = delete;
App& operator=(const App&) = delete;
Sync* sync = nullptr;
std::function<void()> onQuit; // the window was closed, or the screenshot's run is over
std::function<void(const std::string&)> onConversationOpened; // the notification goes
std::function<void(std::string_view)> onLog;
std::function<void()> onDisplayLost; // the compositor's connection broke
std::int32_t exitCode = 0; // what main returns when nothing else decided: 1 for a screenshot not written
bool Visible() const noexcept { return canvas.has_value(); }
// Creates the window on the first call.
void Show() {
if (canvas) return;
canvas.emplace();
try {
canvas->Create(400, 800, "Messages", assetDir, cacheDir);
} catch (const std::exception& e) {
// No display, a compositor without a global the library
// needs, no Vulkan device: the library throws, and the app
// has no window. It says so and runs on without one — a
// resident instance keeps importing; a later Show fails at
// once with the same reason, the device's set-up running
// only once.
canvas.reset();
Log(std::format("no window: {}", e.what()));
return;
}
source.emplace(Crafter::Device::display);
source->onLost = [this] {
if (onDisplayLost) onDisplayLost();
};
frames.emplace(canvas->Window());
frames->onFrame = [this] { canvas->Window().Update(); };
day.emplace();
// The captions name the day ("Today", a clock time for today's
// text): drawn again when it changes.
day->onDay = [this] {
Log("the day changed");
Dirty();
};
canvas->onDraw = [this](VkCommandBuffer cmd) { Build(cmd); };
Crafter::Window& w = canvas->Window();
downSub.emplace(&w.onMouseLeftClick, [this] { Pointer(PointerPhase::Down); });
upSub.emplace(&w.onMouseLeftRelease, [this] { Pointer(PointerPhase::Up); });
moveSub.emplace(&w.onMouseMove, [this] {
if (gestures.Pressed()) Pointer(PointerPhase::Move);
});
scrollSub.emplace(&w.onMouseScroll, [this](std::uint32_t raw) {
const std::int32_t detents = static_cast<std::int32_t>(raw);
ActiveScroll().ScrollBy(static_cast<float>(detents) * canvas->Dp(48));
if (view) view->stickToBottom = false;
Dirty();
});
keySub.emplace(&w.onRawKeyDown, [this](Crafter::KeyCode code) {
if (code == Crafter::Key(Crafter::CrafterKeys::Escape)) Back();
});
resizeSub.emplace(&w.onResize, [this] { Dirty(); });
closeSub.emplace(&w.onClose, [this] {
if (onQuit) onQuit();
});
Reload();
w.Render();
frames->RequestRedraw();
}
// Shows the window on a conversation. Without a window (Show says
// why) nothing is on screen, so nothing is read or opened.
void Open(std::string_view key) {
// The view may point into what opening replaces (a row's key in
// `hitKeys`, the notifier's record of the tapped notification):
// owned before anything runs.
const std::string opening(key);
key = opening;
StopFling();
CancelGesture();
Show();
if (!canvas) return;
if (!view || view->key != key) {
view.emplace();
view->key = std::string(key);
}
view->stickToBottom = true;
view->messages = store.Conversation(key);
if (store.MarkRead(key) > 0) Reload();
if (sync) sync->SetOpenConversation(view->key);
if (onConversationOpened) onConversationOpened(view->key);
Dirty();
}
void Back() {
if (!view) return;
StopFling();
CancelGesture();
view.reset();
if (sync) sync->SetOpenConversation(std::nullopt);
Dirty();
}
// Renders one frame now, outside the compositor's pacing, saves it as
// a PNG and asks to quit: the verification path for a machine without
// eyes, which must not depend on a desktop that repaints. A window
// created here first gets a moment for the compositor's configure,
// which sizes it (to the screen, on a phone) before the frame.
void ScreenshotThenQuit(const std::filesystem::path& path) {
const bool created = !canvas;
Show();
screenshotPath = path;
if (created && canvas) g_timeout_add(600, OnScreenshot, this);
else OnScreenshot(this); // a window already up, or none to come: now
}
// ---- fed by the shell from Sync's events ------------------------------
void Status(const AppStatus& s) {
status = s;
Dirty();
}
void Changed() { Reload(); }
private:
void Log(std::string_view line) {
if (onLog) onLog(line);
}
void Dirty() {
if (frames) frames->RequestRedraw();
}
void Reload() {
convs = GroupConversations(store.All());
if (view) {
const std::size_t before = view->messages.size();
view->messages = store.Conversation(view->key);
if (view->messages.size() > before) view->stickToBottom = true;
if (sync && store.MarkRead(view->key) > 0) convs = GroupConversations(store.All());
}
Dirty();
}
static std::int64_t NowEpoch() {
return std::chrono::duration_cast<std::chrono::seconds>(std::chrono::system_clock::now().time_since_epoch()).count();
}
static std::int64_t NowMs() {
return std::chrono::duration_cast<std::chrono::milliseconds>(std::chrono::steady_clock::now().time_since_epoch()).count();
}
static std::int32_t OffsetAt(std::int64_t epoch) {
std::tm tm{};
const time_t t = static_cast<time_t>(epoch);
localtime_r(&t, &tm);
return static_cast<std::int32_t>(tm.tm_gmtoff / 60);
}
ScrollState& ActiveScroll() { return view ? view->scroll : list.scroll; }
// A screen change stops a fling: the scroll left behind keeps no
// velocity for a return to revive, and the frames stop asking.
void StopFling() {
list.scroll.velocity = 0;
if (view) view->scroll.velocity = 0;
if (frames) frames->SetAnimating(false);
}
// A screen change under a finger cancels the press: its release is no
// tap on what the new screen drew where the finger went down (a
// forwarded link's or a notification's Open by the other thumb, Back
// from a key), and its long press does not fire.
void CancelGesture() {
if (gestures.Pressed()) gestures.Feed(PointerPhase::Cancel, Point{}, NowMs());
if (longPressTimer) {
g_source_remove(longPressTimer);
longPressTimer = 0;
}
}
void Build(VkCommandBuffer) {
tzset(); // the zone may have changed since the last frame: the captions read it
Canvas& c = *canvas;
hits.clear();
const std::int64_t now = NowEpoch();
const ZoneFn zone = OffsetAt;
const auto frameTime = std::chrono::steady_clock::now();
const float dt = lastFrame.time_since_epoch().count() == 0 ? 0.0f : std::chrono::duration<float>(frameTime - lastFrame).count();
lastFrame = frameTime;
if (frames->Animating()) {
if (!ActiveScroll().Tick(std::min(dt, 0.05f))) frames->SetAnimating(false);
}
if (view) {
Box area = DrawHeader(c, DisplayNumber(view->key), true, hits);
area = DrawBanner(c, area, status);
const Box compose{ area.x, area.Bottom() - c.Dp(56), area.w, c.Dp(56) };
c.chrome.Quad(compose, c.theme.surface);
c.chrome.Quad({ compose.x, compose.y, compose.w, c.Dp(1) }, c.theme.divider);
c.chrome.Text("Composing comes in a later step", compose.x + c.Dp(16), c.CenteredBaseline(compose, c.Dp(14)), c.Font(), c.Dp(14), c.theme.muted);
area.h -= compose.h;
view->Draw(c, area, now, zone, hits);
} else {
Box area = DrawHeader(c, "Messages", false, hits);
area = DrawBanner(c, area, status);
list.Draw(c, area, convs, now, zone, hits);
}
// What the regions name, as drawn: a reload before the next frame
// re-sorts the vectors, so a gesture resolves against these.
hitKeys.clear();
for (const auto& conv : convs) hitKeys.push_back(conv.key);
hitMessages.clear();
if (view) for (const Message& m : view->messages) hitMessages.push_back(m.id);
if (c.Overflowed() && !overflowLogged) {
overflowLogged = true;
Log("a layer ran out of items this frame; the buffers are too small for this screen");
}
}
void Pointer(PointerPhase phase) {
const Point p{ canvas->Window().currentMousePos.x, canvas->Window().currentMousePos.y };
// Buffer pixels: the slop and the fling threshold follow the
// window's scale like every other distance, set at the point of use.
gestures.slopPx = canvas->Dp(8);
gestures.flingMinPxPerS = canvas->Dp(60);
if (phase == PointerPhase::Down) ActiveScroll().velocity = 0; // a finger down stops the fling under it
if (phase == PointerPhase::Down) pressedOn = Target(p);
Handle(gestures.Feed(phase, p, NowMs()));
if (phase == PointerPhase::Down) {
if (longPressTimer) g_source_remove(longPressTimer);
longPressTimer = g_timeout_add(static_cast<guint>(gestures.longPressMs), OnLongPress, this);
} else if (phase != PointerPhase::Move && longPressTimer) {
g_source_remove(longPressTimer);
longPressTimer = 0;
}
}
static gboolean OnLongPress(gpointer data) {
App& self = *static_cast<App*>(data);
self.longPressTimer = 0;
self.Handle(self.gestures.Timeout(NowMs()));
return G_SOURCE_REMOVE;
}
void Handle(const GestureEvent& e) {
// A tap or a long press acts on what the press went down on: a
// frame drawn meanwhile (a new text snapped the conversation, the
// list re-sorted) that moved another bubble or row under the
// finger names something else, and the release acts on nothing.
if ((e.kind == GestureEvent::Kind::Tap || e.kind == GestureEvent::Kind::LongPress) && Target(e.at) != pressedOn) return;
switch (e.kind) {
case GestureEvent::Kind::None: return;
case GestureEvent::Kind::Tap: Tap(e.at); return;
case GestureEvent::Kind::LongPress: Log("long press (actions come in a later step)"); return;
case GestureEvent::Kind::DragStart:
case GestureEvent::Kind::Drag:
frames->SetAnimating(false);
ActiveScroll().ScrollBy(-e.delta.y);
if (view) view->stickToBottom = false;
Dirty();
return;
case GestureEvent::Kind::Fling:
ActiveScroll().Fling(-e.velocity.y);
frames->SetAnimating(true);
return;
case GestureEvent::Kind::Release: return;
}
}
// What a frame's regions name at a point (Gesture's TargetAt).
std::optional<HitTarget> Target(Point p) const { return TargetAt(hits, p, Hit::rowBase, hitKeys, Hit::messageBase, hitMessages); }
// The message a frame's region named, if the conversation still
// holds it.
const Message* HitMessage(std::size_t i) const {
if (!view || i >= hitMessages.size()) return nullptr;
for (const Message& m : view->messages) {
if (m.id == hitMessages[i]) return &m;
}
return nullptr;
}
void Tap(Point at) {
const std::optional<std::uint32_t> id = HitTest(hits, at);
if (!id) return;
if (*id == Hit::back) {
Back();
} else if (*id == Hit::fab) {
Log("new conversation (comes in a later step)");
} else if (*id >= Hit::messageBase) {
if (!view || !sync) return;
const Message* m = HitMessage(*id - Hit::messageBase);
if (m && m->state == MessageState::Failed) sync->Retry(m->id);
} else if (*id >= Hit::rowBase) {
const std::size_t i = *id - Hit::rowBase;
if (i < hitKeys.size()) Open(hitKeys[i]);
}
}
MessageStore& store;
std::filesystem::path assetDir;
std::filesystem::path cacheDir;
AppStatus status;
std::vector<Conversation> convs;
std::optional<Canvas> canvas;
std::vector<std::string> hitKeys; // the conversation each row region named, as drawn
std::vector<std::uint64_t> hitMessages; // the message each bubble region named, as drawn
std::optional<HitTarget> pressedOn; // what the press went down on, as drawn then
std::optional<WaylandSource> source;
std::optional<FrameDriver> frames;
std::optional<DayWatch> day; // while the window is up
ListScreen list;
std::optional<ViewScreen> view;
GestureDetector gestures;
std::vector<HitRegion> hits;
guint longPressTimer = 0;
std::chrono::steady_clock::time_point lastFrame{};
bool overflowLogged = false;
std::filesystem::path screenshotPath;
std::optional<Crafter::EventListener<void>> downSub;
std::optional<Crafter::EventListener<void>> upSub;
std::optional<Crafter::EventListener<void>> moveSub;
std::optional<Crafter::EventListener<std::uint32_t>> scrollSub;
std::optional<Crafter::EventListener<Crafter::KeyCode>> keySub;
std::optional<Crafter::EventListener<void>> resizeSub;
std::optional<Crafter::EventListener<void>> closeSub;
};
}

View file

@ -0,0 +1,232 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages.Ui:Canvas — the window and what every screen draws with: the
font, the word wrapper over it, and four compositing layers. Within one
fused dispatch all quads composite before all text, so the scrolling
content (clipped to its area), the chrome above it and any sheet above that
are separate dispatches in that order; the background is a quad of its own
because the swapchain is never cleared.
*/
module;
#include "vulkan/vulkan.h"
export module ImsdMessages.Ui:Canvas;
import std;
import Crafter.Graphics;
import Crafter.Event;
import ImsdMessages;
export namespace ImsdMessages::Ui {
using Color = std::array<float, 4>;
struct Theme {
Color bg = { 0.96f, 0.96f, 0.97f, 1.0f };
Color surface = { 1.0f, 1.0f, 1.0f, 1.0f };
Color text = { 0.11f, 0.11f, 0.12f, 1.0f };
Color muted = { 0.43f, 0.43f, 0.45f, 1.0f };
Color accent = { 0.18f, 0.44f, 0.93f, 1.0f };
Color onAccent = { 1.0f, 1.0f, 1.0f, 1.0f };
Color bubbleIn = { 0.91f, 0.91f, 0.92f, 1.0f };
Color bubbleOut = { 0.18f, 0.44f, 0.93f, 1.0f };
Color banner = { 1.0f, 0.95f, 0.80f, 1.0f };
Color bannerText = { 0.40f, 0.30f, 0.01f, 1.0f };
Color divider = { 0.88f, 0.88f, 0.89f, 1.0f };
Color danger = { 0.80f, 0.16f, 0.16f, 1.0f };
Color scrim = { 0.0f, 0.0f, 0.0f, 0.35f };
};
// One compositing layer: its own item buffers, one fused dispatch.
class Layer {
public:
void Create(Crafter::UIRenderer& ui, Crafter::FontAtlas& atlas, std::uint32_t quadCap, std::uint32_t circleCap, std::uint32_t glyphCap) {
constexpr VkBufferUsageFlags usage = VK_BUFFER_USAGE_STORAGE_BUFFER_BIT | VK_BUFFER_USAGE_SHADER_DEVICE_ADDRESS_BIT;
constexpr VkMemoryPropertyFlags memory = VK_MEMORY_PROPERTY_HOST_VISIBLE_BIT | VK_MEMORY_PROPERTY_DEVICE_LOCAL_BIT;
quads.Create(usage, memory, quadCap);
circles.Create(usage, memory, circleCap);
glyphs.Create(usage, memory, glyphCap);
quadSlot.emplace(ui.RegisterBuffer(quads));
circleSlot.emplace(ui.RegisterBuffer(circles));
glyphSlot.emplace(ui.RegisterBuffer(glyphs));
this->quadCap = quadCap;
this->circleCap = circleCap;
this->glyphCap = glyphCap;
buf.quads = quads.value;
buf.quadCount = &quadCount;
buf.quadCap = quadCap;
buf.glyphs = glyphs.value;
buf.glyphCount = &glyphCount;
buf.glyphCap = glyphCap;
buf.atlas = &atlas;
buf.renderer = &ui;
}
void Begin() {
quadCount = 0;
circleCount = 0;
glyphCount = 0;
clip = { 0.0f, 0.0f, 1e9f, 1e9f };
overflow = false;
}
void SetClip(Box b) { clip = { b.x, b.y, b.w, b.h }; }
Crafter::UIBuffer& Buf() noexcept { return buf; }
void Quad(Box b, Color c, float radius = 0, float outline = 0, Color outlineColor = {}) {
if (quadCount >= quadCap) {
overflow = true;
return;
}
quads.value[quadCount++] = Crafter::QuadItem{ b.x, b.y, b.w, b.h, c[0], c[1], c[2], c[3], radius, radius, radius, radius, outline, outlineColor[0], outlineColor[1], outlineColor[2] };
}
void Circle(Point center, float radius, Color c) {
if (circleCount >= circleCap) {
overflow = true;
return;
}
circles.value[circleCount++] = Crafter::CircleItem{ center.x, center.y, radius, 0, c[0], c[1], c[2], c[3], 0, 0, 0, 0 };
}
// One line; returns its advance.
float Text(std::string_view text, float x, float baselineY, Crafter::Font& font, float px, Color c, Crafter::TextAlign align = Crafter::TextAlign::Left) {
const std::uint32_t before = glyphCount;
const float advance = Crafter::DrawText(buf, text, x, baselineY, font, px, c, align);
if (glyphCount == before && !text.empty() && glyphCount >= glyphCap) overflow = true;
return advance;
}
void Submit(VkCommandBuffer cmd, Crafter::UIRenderer& ui) {
if (quadCount) quads.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
if (circleCount) circles.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
if (glyphCount) glyphs.FlushDevice(cmd, VK_ACCESS_SHADER_READ_BIT, VK_PIPELINE_STAGE_COMPUTE_SHADER_BIT);
if (!quadCount && !circleCount && !glyphCount) return;
ui.DispatchFused(cmd, { *quadSlot, quadCount, clip }, { *circleSlot, circleCount, clip }, {}, { *glyphSlot, glyphCount, clip });
}
bool Overflowed() const noexcept { return overflow; }
private:
Crafter::GraphicsBuffer<Crafter::QuadItem, true> quads;
Crafter::GraphicsBuffer<Crafter::CircleItem, true> circles;
Crafter::GraphicsBuffer<Crafter::GlyphItem, true> glyphs;
std::optional<Crafter::BufferSlot> quadSlot;
std::optional<Crafter::BufferSlot> circleSlot;
std::optional<Crafter::BufferSlot> glyphSlot;
std::uint32_t quadCap = 0;
std::uint32_t circleCap = 0;
std::uint32_t glyphCap = 0;
std::uint32_t quadCount = 0;
std::uint32_t circleCount = 0;
std::uint32_t glyphCount = 0;
std::array<float, 4> clip = { 0.0f, 0.0f, 1e9f, 1e9f };
bool overflow = false;
Crafter::UIBuffer buf;
};
class Canvas {
// Declared first so they die last: a layer's buffer slots hand their
// numbers back to the heap when they go, so the heap (and the
// renderer, which holds slots of its own) must still exist then.
// Members are destroyed in the reverse order of their declaration,
// whatever their access.
std::optional<Crafter::Window> window;
Crafter::GraphicsDescriptorHeap heap;
std::optional<Crafter::Font> font;
Crafter::FontAtlas atlas;
Crafter::UIRenderer ui;
std::optional<Crafter::EventListener<Crafter::UIBuildArgs>> buildSub;
std::optional<WordWrapper> wrapper;
public:
Theme theme;
Layer background;
Layer content;
Layer chrome;
Layer overlay;
// The screens draw into the layers from here, once per frame.
std::function<void(VkCommandBuffer)> onDraw;
// The device once per process, then the window, the heap, the font,
// the atlas, the renderer and the layers. Sizes in dp; the
// compositor decides the real size on a phone anyway.
void Create(std::uint32_t widthDp, std::uint32_t heightDp, std::string_view title, const std::filesystem::path& assetDir, const std::filesystem::path& cacheDir) {
static bool deviceReady = false;
static std::string deviceError; // the library's set-up cannot run twice: a failure is final
if (!deviceError.empty()) throw std::runtime_error(deviceError);
if (!deviceReady) {
std::error_code ec;
std::filesystem::create_directories(cacheDir, ec);
Crafter::Device::pipelineCachePath = cacheDir / "pipeline_cache.bin";
try {
Crafter::Device::Initialize();
} catch (const std::exception& e) {
deviceError = std::format("{} (the device's set-up cannot be run again)", e.what());
throw;
}
deviceReady = true;
}
window.emplace(widthDp, heightDp, title);
VkCommandBuffer init = window->StartInit();
heap.Initialize(16, 32, 4);
window->descriptorHeap = &heap;
font.emplace(assetDir / "NotoSans-Regular.ttf");
atlas.Initialize(init);
ui.fontAtlas = &atlas;
ui.Initialize(*window, heap, init, assetDir / "ui-quads.comp.spv", assetDir / "ui-circles.comp.spv", assetDir / "ui-images.comp.spv", assetDir / "ui-text.comp.spv", assetDir / "ui-fused.comp.spv");
window->passes.push_back(&ui);
background.Create(ui, atlas, 4, 4, 64);
content.Create(ui, atlas, 2048, 256, 16384);
chrome.Create(ui, atlas, 256, 32, 2048);
overlay.Create(ui, atlas, 128, 16, 1024);
buildSub.emplace(&ui.onBuild, [this](Crafter::UIBuildArgs a) { Frame(a.cmd); });
wrapper.emplace([this](std::uint32_t cp, float px) { return static_cast<float>(font->AdvanceUnits(cp)) * font->ScaleForSize(px); });
window->FinishInit();
}
Crafter::Window& Window() noexcept { return *window; }
Crafter::Font& Font() noexcept { return *font; }
WordWrapper& Wrapper() noexcept { return *wrapper; }
float Scale() const noexcept { return window->scale > 0 ? window->scale : 1.0f; }
float Dp(float dp) const noexcept { return std::round(dp * Scale()); }
float Width() const noexcept { return static_cast<float>(window->width); }
float Height() const noexcept { return static_cast<float>(window->height); }
float Ascent(float px) { return font->AscentPx(px); }
float LineHeight(float px) { return font->LineHeight(px); }
// A line's width as DrawText advances it (the font's unrounded
// advances, none for a newline), so a caret or a following run lands
// where the glyphs end.
float TextWidth(std::string_view text, float px) {
const float scale = font->ScaleForSize(px);
float width = 0;
for (std::size_t i = 0; i < text.size();) {
const std::uint32_t cp = DecodeUtf8(text, i);
if (cp == 0) break;
if (cp != '\n') width += static_cast<float>(font->AdvanceUnits(cp)) * scale;
}
return width;
}
// The baseline that centres one line of text in a box.
float CenteredBaseline(Box b, float px) { return b.y + (b.h - LineHeight(px)) / 2.0f + Ascent(px); }
// True when any layer dropped items this frame (buffers too small).
bool Overflowed() const noexcept { return background.Overflowed() || content.Overflowed() || chrome.Overflowed() || overlay.Overflowed(); }
private:
void Frame(VkCommandBuffer cmd) {
background.Begin();
content.Begin();
chrome.Begin();
overlay.Begin();
background.Quad({ 0, 0, Width(), Height() }, theme.bg);
if (onDraw) onDraw(cmd);
background.Submit(cmd, ui);
content.Submit(cmd, ui);
chrome.Submit(cmd, ui);
overlay.Submit(cmd, ui);
}
};
}

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
};
}

View file

@ -0,0 +1,216 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages.Ui:Screens — the two screens of the baseline, drawn into the
canvas's layers: the conversation list and one conversation. A screen
lays out and draws in the same pass, records the regions a tap can hit,
and keeps its scroll state; the app decides what a hit means.
*/
module;
#include "vulkan/vulkan.h"
export module ImsdMessages.Ui:Screens;
import std;
import Crafter.Graphics;
import ImsdMessages;
import :Canvas;
export namespace ImsdMessages::Ui {
// The local UTC offset, in minutes, at an instant.
using ZoneFn = std::function<std::int32_t(std::int64_t)>;
// Hit ids: the fixed controls, then the list's rows and the messages.
namespace Hit {
constexpr std::uint32_t fab = 1;
constexpr std::uint32_t back = 2;
constexpr std::uint32_t rowBase = 1000;
constexpr std::uint32_t messageBase = 100000;
}
Box Intersect(Box a, Box b) {
const float x = std::max(a.x, b.x);
const float y = std::max(a.y, b.y);
const float r = std::min(a.Right(), b.Right());
const float bottom = std::min(a.Bottom(), b.Bottom());
if (r <= x || bottom <= y) return {};
return { x, y, r - x, bottom - y };
}
// The letter on an avatar: a number gets '#'.
std::string Initial(std::string_view name) {
if (name.empty()) return "?";
const char c = name.front();
if (c == '+' || (c >= '0' && c <= '9')) return "#";
std::size_t i = 0;
const std::uint32_t cp = DecodeUtf8(name, i);
std::string out(name.substr(0, i));
if (cp < 0x80) out[0] = static_cast<char>(std::toupper(static_cast<std::uint8_t>(out[0])));
return out;
}
std::string OneLine(std::string_view text) {
std::string out(text);
for (char& c : out) {
if (c == '\n' || c == '\r') c = ' ';
}
return out;
}
// The header: a title and, below the list, a back control. Returns the
// box under it.
Box DrawHeader(Canvas& c, std::string_view title, bool back, std::vector<HitRegion>& hits) {
const Box header{ 0, 0, c.Width(), c.Dp(56) };
c.chrome.Quad(header, c.theme.surface);
c.chrome.Quad({ 0, header.Bottom() - c.Dp(1), c.Width(), c.Dp(1) }, c.theme.divider);
float x = c.Dp(16);
if (back) {
const Box b{ 0, 0, c.Dp(56), c.Dp(56) };
c.chrome.Text("‹", c.Dp(24), c.CenteredBaseline(b, c.Dp(34)), c.Font(), c.Dp(34), c.theme.accent, Crafter::TextAlign::Center);
hits.push_back({ b, Hit::back });
x = c.Dp(56);
}
c.chrome.Text(c.Wrapper().Ellipsize(title, c.Dp(20), c.Width() - x - c.Dp(16)), x, c.CenteredBaseline(header, c.Dp(20)), c.Font(), c.Dp(20), c.theme.text);
return { 0, header.Bottom(), c.Width(), c.Height() - header.Bottom() };
}
// The strip under the header while the status needs saying; returns the
// box under it.
Box DrawBanner(Canvas& c, Box below, const AppStatus& status) {
const std::string text = BannerText(status);
if (text.empty()) return below;
const Box strip{ below.x, below.y, below.w, c.Dp(30) };
c.chrome.Quad(strip, c.theme.banner);
c.chrome.Text(c.Wrapper().Ellipsize(text, c.Dp(13), strip.w - c.Dp(32)), c.Dp(16), c.CenteredBaseline(strip, c.Dp(13)), c.Font(), c.Dp(13), c.theme.bannerText);
return { below.x, strip.Bottom(), below.w, below.h - strip.h };
}
class ListScreen {
public:
ScrollState scroll;
void Draw(Canvas& c, Box area, std::span<const Conversation> convs, std::int64_t now, const ZoneFn& zone, std::vector<HitRegion>& hits) {
const float rowH = c.Dp(72);
c.content.SetClip(area);
scroll.viewport = area.h;
scroll.content = rowH * static_cast<float>(convs.size()) + c.Dp(88); // room under the last row to scroll clear of the + button (56 dp, its 16 dp margin, 16 dp of air)
scroll.Clamp();
if (convs.empty()) c.content.Text("No messages yet", area.x + area.w / 2, c.CenteredBaseline(area, c.Dp(16)), c.Font(), c.Dp(16), c.theme.muted, Crafter::TextAlign::Center);
const std::int32_t nowOffset = zone(now);
for (std::size_t i = 0; i < convs.size(); ++i) {
const Box row{ area.x, area.y - scroll.offset + rowH * static_cast<float>(i), area.w, rowH };
if (row.Bottom() < area.y || row.y > area.Bottom()) continue;
const Conversation& conv = convs[i];
const std::string name = DisplayNumber(conv.key);
const Point avatar{ row.x + c.Dp(36), row.y + rowH / 2 };
c.content.Circle(avatar, c.Dp(20), c.theme.accent);
c.content.Text(Initial(name), avatar.x, c.CenteredBaseline({ row.x, row.y, row.w, rowH }, c.Dp(18)), c.Font(), c.Dp(18), c.theme.onAccent, Crafter::TextAlign::Center);
const float textX = row.x + c.Dp(72);
const float right = row.Right() - c.Dp(16);
const std::string time = ListCaption(conv.lastTime, zone(conv.lastTime), now, nowOffset);
const float timeW = c.TextWidth(time, c.Dp(12));
c.content.Text(time, right, row.y + c.Dp(28), c.Font(), c.Dp(12), c.theme.muted, Crafter::TextAlign::Right);
c.content.Text(c.Wrapper().Ellipsize(name, c.Dp(16), right - timeW - c.Dp(8) - textX), textX, row.y + c.Dp(28), c.Font(), c.Dp(16), c.theme.text);
const float previewW = right - (conv.unread ? c.Dp(32) : 0.0f) - textX;
const std::string preview = conv.lastDirection == Direction::Outgoing ? std::format("You: {}", OneLine(conv.lastText)) : OneLine(conv.lastText);
c.content.Text(c.Wrapper().Ellipsize(preview, c.Dp(14), previewW), textX, row.y + c.Dp(52), c.Font(), c.Dp(14), c.theme.muted);
if (conv.unread > 0) {
const Point badge{ right - c.Dp(10), row.y + c.Dp(46) };
c.content.Circle(badge, c.Dp(10), c.theme.accent);
c.content.Text(std::to_string(conv.unread), badge.x, c.CenteredBaseline({ badge.x - c.Dp(10), badge.y - c.Dp(10), c.Dp(20), c.Dp(20) }, c.Dp(11)), c.Font(), c.Dp(11), c.theme.onAccent, Crafter::TextAlign::Center);
}
c.content.Quad({ textX, row.Bottom() - c.Dp(1), row.Right() - textX, c.Dp(1) }, c.theme.divider);
hits.push_back({ Intersect(row, area), Hit::rowBase + static_cast<std::uint32_t>(i) });
}
const Point fab{ area.Right() - c.Dp(44), area.Bottom() - c.Dp(44) };
const Box fabBox{ fab.x - c.Dp(28), fab.y - c.Dp(28), c.Dp(56), c.Dp(56) };
c.chrome.Circle(fab, c.Dp(28), c.theme.accent);
c.chrome.Text("+", fab.x, c.CenteredBaseline(fabBox, c.Dp(30)), c.Font(), c.Dp(30), c.theme.onAccent, Crafter::TextAlign::Center);
hits.push_back({ fabBox, Hit::fab });
}
};
class ViewScreen {
public:
std::string key;
std::vector<Message> messages;
ScrollState scroll;
bool stickToBottom = true;
void Draw(Canvas& c, Box area, std::int64_t now, const ZoneFn& zone, std::vector<HitRegion>& hits) {
const float px = c.Dp(16);
const float lineH = c.LineHeight(px);
const float padX = c.Dp(12);
const float padY = c.Dp(8);
const float captionPx = c.Dp(11);
const float captionH = c.LineHeight(captionPx);
const float sepPx = c.Dp(12);
const float maxW = area.w * 0.78f;
const std::int32_t nowOffset = zone(now);
struct Placed {
const Message* message;
Box bubble;
std::vector<WrappedLine> lines;
std::string separator;
float separatorBaseline;
};
std::vector<Placed> placed;
placed.reserve(messages.size());
float y = c.Dp(8);
std::int64_t lastDay = std::numeric_limits<std::int64_t>::min();
for (const Message& m : messages) {
Placed p{ &m, {}, {}, "", 0 };
const std::int32_t offset = zone(m.sortTime);
const std::int64_t day = LocalDay(m.sortTime, offset);
if (day != lastDay) {
p.separator = DayCaption(m.sortTime, offset, now, nowOffset);
y += c.Dp(6);
p.separatorBaseline = y + c.Ascent(sepPx);
y += c.LineHeight(sepPx) + c.Dp(10);
lastDay = day;
}
p.lines = c.Wrapper().Wrap(m.text, px, maxW - 2 * padX);
float w = 0;
for (const WrappedLine& l : p.lines) w = std::max(w, l.width);
const float h = lineH * static_cast<float>(p.lines.size()) + 2 * padY;
const bool out = m.direction == Direction::Outgoing;
const float bw = w + 2 * padX;
p.bubble = { out ? area.Right() - c.Dp(12) - bw : area.x + c.Dp(12), y, bw, h };
y += h + c.Dp(2) + captionH + c.Dp(8);
placed.push_back(std::move(p));
}
scroll.viewport = area.h;
scroll.content = y + c.Dp(8);
if (stickToBottom) scroll.offset = scroll.Max();
scroll.Clamp();
c.content.SetClip(area);
const float base = area.y - scroll.offset;
const float sepH = c.LineHeight(sepPx);
for (std::size_t i = 0; i < placed.size(); ++i) {
const Placed& p = placed[i];
const Message& m = *p.message;
// Only what is in view goes to the layer: its glyph budget is
// finite, and a long conversation is not.
if (!p.separator.empty() && base + p.separatorBaseline + sepH >= area.y && base + p.separatorBaseline - sepH <= area.Bottom()) c.content.Text(p.separator, area.x + area.w / 2, base + p.separatorBaseline, c.Font(), sepPx, c.theme.muted, Crafter::TextAlign::Center);
const Box bubble{ p.bubble.x, base + p.bubble.y, p.bubble.w, p.bubble.h };
if (bubble.Bottom() + captionH + c.Dp(10) < area.y || bubble.y > area.Bottom()) continue;
const bool out = m.direction == Direction::Outgoing;
c.content.Quad(bubble, out ? c.theme.bubbleOut : c.theme.bubbleIn, c.Dp(14));
float baseline = bubble.y + padY + c.Ascent(px);
for (const WrappedLine& l : p.lines) {
if (baseline + lineH >= area.y && baseline - lineH <= area.Bottom()) c.content.Text(m.text.substr(l.begin, l.end - l.begin), bubble.x + padX, baseline, c.Font(), px, out ? c.theme.onAccent : c.theme.text);
baseline += lineH;
}
std::string caption = ClockCaption(m.sortTime, zone(m.sortTime));
if (out) {
caption = std::format("{} · {}", caption, StateCaption(m.state));
if (m.state == MessageState::Failed) caption = m.stateReason.empty() ? std::format("{} · tap to retry", caption) : std::format("{} — {} · tap to retry", caption, m.stateReason);
}
const float captionBaseline = bubble.Bottom() + c.Dp(2) + c.Ascent(captionPx);
if (out) c.content.Text(c.Wrapper().Ellipsize(caption, captionPx, area.w - 2 * c.Dp(12)), bubble.Right(), captionBaseline, c.Font(), captionPx, m.state == MessageState::Failed ? c.theme.danger : c.theme.muted, Crafter::TextAlign::Right);
else c.content.Text(caption, bubble.x, captionBaseline, c.Font(), captionPx, c.theme.muted);
hits.push_back({ Intersect(bubble, area), Hit::messageBase + static_cast<std::uint32_t>(i) });
}
}
};
}

View file

@ -0,0 +1,15 @@
// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages.Ui — the window: Crafter.Graphics driven from the GLib main
loop. Loop makes the Wayland display a GSource and owns the frame callback,
Canvas holds the window, the font and the four compositing layers, Screens
draw the conversation list and a conversation, App wires them to the store
and to Sync.
*/
export module ImsdMessages.Ui;
export import :Loop;
export import :Canvas;
export import :Screens;
export import :App;

View file

@ -6,7 +6,7 @@ ImsdMessages — the core of imsd-messages: the parts that need neither the
bus nor a window (numbers, time, the message model, word wrap, gestures, bus nor a window (numbers, time, the message model, word wrap, gestures,
the store and the sync logic), so each of them is unit-testable on a dev box the store and the sync logic), so each of them is unit-testable on a dev box
with no phone, no imsd and no GPU. The bus layer is ImsdMessages.Bus, the with no phone, no imsd and no GPU. The bus layer is ImsdMessages.Bus, the
window is the executable. window ImsdMessages.Ui.
*/ */
export module ImsdMessages; export module ImsdMessages;
export import :Number; export import :Number;

View file

@ -77,6 +77,11 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
Configuration* db = local Configuration* db = local
? LocalProject({ .projectFile = "../Crafter/Crafter.DB/project.cpp", .args = depArgs }) ? LocalProject({ .projectFile = "../Crafter/Crafter.DB/project.cpp", .args = depArgs })
: GitProject({ .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.DB.git" }, .args = depArgs }); : GitProject({ .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.DB.git" }, .args = depArgs });
// The window library. --local takes the branch worktree with the Wayland
// input work until it is merged.
Configuration* graphics = local
? LocalProject({ .projectFile = "../Crafter/Crafter.Graphics-imsd-messages/project.cpp", .args = depArgs })
: GitProject({ .source = { .url = "https://forgejo.catcrafts.net/Catcrafts/Crafter.Graphics.git" }, .args = depArgs });
// imsd-messages-core — numbers, time, the model, word wrap, gestures, // imsd-messages-core — numbers, time, the model, word wrap, gestures,
// the store and the sync logic: std + Crafter.DB, no GLib, so every // the store and the sync logic: std + Crafter.DB, no GLib, so every
@ -127,6 +132,28 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
const GioFlags gio = ComputeGioFlags(*Bus); const GioFlags gio = ComputeGioFlags(*Bus);
ApplyGioFlags(*Bus, gio); ApplyGioFlags(*Bus, gio);
// imsd-messages-ui — the window: Crafter.Graphics driven from the GLib
// main loop.
static auto Ui = std::make_unique<Configuration>();
Ui->path = "./";
Ui->name = "imsd-messages-ui";
Ui->outputName = "imsd-messages-ui";
ApplyStandardArgs(*Ui, args);
Ui->type = ConfigurationType::LibraryStatic;
Ui->dependencies = { Core.get(), graphics };
{
std::array<fs::path, 5> ifaces = {
"interfaces/ImsdMessages.Ui",
"interfaces/ImsdMessages.Ui-Loop",
"interfaces/ImsdMessages.Ui-Canvas",
"interfaces/ImsdMessages.Ui-Screens",
"interfaces/ImsdMessages.Ui-App",
};
std::array<fs::path, 0> impls = {};
Ui->GetInterfacesAndImplementations(ifaces, impls);
}
ApplyGioFlags(*Ui, gio);
// imsd-messages — the executable: the command line, the window and the // imsd-messages — the executable: the command line, the window and the
// wiring between the bus layer and the UI. // wiring between the bus layer and the UI.
Configuration cfg; Configuration cfg;
@ -135,13 +162,32 @@ extern "C" Configuration CrafterBuildProject(std::span<const std::string_view> a
cfg.outputName = "imsd-messages"; cfg.outputName = "imsd-messages";
ApplyStandardArgs(cfg, args); ApplyStandardArgs(cfg, args);
cfg.type = ConfigurationType::Executable; cfg.type = ConfigurationType::Executable;
cfg.dependencies = { Core.get(), Bus.get(), db }; cfg.dependencies = { Core.get(), Bus.get(), Ui.get(), db };
{ {
std::array<fs::path, 0> ifaces = {}; std::array<fs::path, 0> ifaces = {};
std::array<fs::path, 1> impls = { "implementations/main" }; std::array<fs::path, 1> impls = { "implementations/main" };
cfg.GetInterfacesAndImplementations(ifaces, impls); cfg.GetInterfacesAndImplementations(ifaces, impls);
} }
ApplyGioFlags(cfg, gio); ApplyGioFlags(cfg, gio);
cfg.files.push_back("assets/NotoSans-Regular.ttf");
// libevdev, for Crafter.Graphics's gamepad backend: the crafter-build
// Flatpak's SDK has none, so a sysroot build looks for it in the
// sysroot and a native build in the prefix of
// packaging/build-libevdev.sh. Crafter.Graphics itself names
// the host's directory, which is an ignored, absent path in the sandbox.
if (!cfg.sysroot.empty()) {
graphics->compileFlags.push_back("-I=/usr/include/libevdev-1.0");
} else {
const std::string arch = cfg.target.substr(0, cfg.target.find('-'));
const char* env = std::getenv("IMSD_MESSAGES_LIBEVDEV");
const char* home = std::getenv("HOME");
const fs::path prefix = env ? fs::path(env) : fs::path(home ? home : ".") / ".cache" / "imsd-messages" / std::format("libevdev-{}", arch);
if (!fs::exists(prefix / "include" / "libevdev-1.0")) std::println(std::cerr, "imsd-messages: no libevdev at {} — run packaging/build-libevdev.sh first", prefix.string());
graphics->compileFlags.push_back(std::format("-I{}", (prefix / "include" / "libevdev-1.0").string()));
cfg.linkFlags.push_back(std::format("-L{}", (prefix / "lib").string()));
cfg.linkFlags.push_back(std::format("-Wl,-rpath,{}", (prefix / "lib").string()));
}
cfg.AddTest("Number").Dependencies({ Core.get() }); cfg.AddTest("Number").Dependencies({ Core.get() });
cfg.AddTest("Time").Dependencies({ Core.get() }); cfg.AddTest("Time").Dependencies({ Core.get() });