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).
397 lines
18 KiB
C++
397 lines
18 KiB
C++
// 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;
|
|
};
|
|
}
|