imsd-messages/interfaces/ImsdMessages.Ui-App.cppm
Jorijn van der Graaf 07c6c3e5bd
Ui, main: closing the window hides it; Activate shows it again
The resident model: a close tears the window down — a fling stops, the
device finishes its frame, the listeners let go, the frame driver and
the canvas go — and keeps the process, the store, the screens and the
bus subscription. Show builds the window again, with a conversation left
open coming back (its caret blinking again; an Open or a Show that lands
between a close and its deferred teardown keeps the window); the Wayland
display source is kept across a hide. A text that arrives for the kept
conversation while the window is hidden — from the close on, not from
its deferred teardown — stays unread and keeps its notification, like
any other conversation's; showing the window again marks it read and
closes the notification. Without a session bus, where nothing could show
the window again, a close ends the process as before. A second launch
reaches the running instance over the bus name and a notification's tap
through its ActionInvoked signal, as before.

--hide-after and --hide-every drive the cycle from the bench as closes
(without a session bus such a close ends the process, as any close does
there), and are window flags as --screenshot is.
2026-11-18 01:12:27 +01:00

618 lines
28 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 the first Show and
again after a Hide, 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 :Compose;
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);
if (repeatTimer) g_source_remove(repeatTimer);
if (hideIdle) g_source_remove(hideIdle);
}
// 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 and the canvas go, and
// the display source last.
void Shutdown() {
Teardown();
source.reset();
}
private:
void Teardown() {
if (!canvas) return;
StopFling();
vkDeviceWaitIdle(Crafter::Device::device);
if (blinkTimer) g_source_remove(blinkTimer);
blinkTimer = 0;
downSub.reset();
upSub.reset();
moveSub.reset();
scrollSub.reset();
keySub.reset();
keyUpSub.reset();
textSub.reset();
resizeSub.reset();
closeSub.reset();
day.reset();
frames.reset();
canvas.reset();
gestures = GestureDetector{};
hits.clear();
hitKeys.clear();
hitMessages.clear();
}
static gboolean OnHideIdle(gpointer data) {
App& self = *static_cast<App*>(data);
self.hideIdle = 0;
self.Hide();
return G_SOURCE_REMOVE;
}
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));
self.exitCode = 0; // a failure until written (main)
} 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;
bool closeQuits = false; // no session bus: a close ends the process, since nothing could show the window again
std::function<void()> onQuit; // the screenshot's run is over, or the window closed with no bus to come back on
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(); }
// Cancels a close's deferred Hide: a Show or an Open before it runs
// keeps the window. True when there was one.
bool KeepWindow() {
if (!hideIdle) return false;
g_source_remove(hideIdle);
hideIdle = 0;
return true;
}
// Whether the window shows the screens: it is up, and no close is
// waiting for its Hide.
bool OnScreen() const noexcept { return canvas.has_value() && hideIdle == 0; }
// Creates the window; shows it again after a Hide.
void Show() {
const bool kept = KeepWindow();
if (canvas) {
if (kept) Opened(); // a close taken back: the kept conversation is on screen again
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;
}
if (!source) {
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) { Key(code); });
keyUpSub.emplace(&w.onRawKeyUp, [this](Crafter::KeyCode) {
if (canvas->Window().heldKeys.empty() && repeatTimer) {
g_source_remove(repeatTimer);
repeatTimer = 0;
}
});
textSub.emplace(&w.onTextInput, [this](const std::string_view text) {
if (!view) return;
ComposeInsert(view->compose, text);
ShowCaret();
});
resizeSub.emplace(&w.onResize, [this] { Dirty(); });
closeSub.emplace(&w.onClose, [this] { Close(); });
Reload();
Opened();
if (view && view->compose.focused) ShowCaret(); // the blink a hide stopped
w.Render();
frames->RequestRedraw();
}
// The window's close, the compositor's or the bench's (--hide-after,
// --hide-every). Closing hides: the process stays for the next text
// (the resident model); --quit or a signal ends it. The library runs
// onClose from inside its own listener, so the teardown is deferred
// to the loop; a Show before it runs keeps the window. The
// conversation is off the screen from here, not from the Hide: a
// text for it meanwhile is unread, and notified. Without a session
// bus nothing could show the window again, so there a close ends
// the process.
void Close() {
if (!canvas) return;
if (closeQuits) {
Log("window closed; no session bus to come back on: quitting");
if (onQuit) onQuit();
return;
}
if (hideIdle) return;
if (sync) sync->SetOpenConversation(std::nullopt);
hideIdle = g_idle_add(OnHideIdle, this);
}
// Tears the window down and keeps everything else: the store, the
// screens (a conversation left open comes back on Show; its texts
// stay unread meanwhile), the bus.
void Hide() {
if (!canvas) return;
Teardown();
Log("window hidden; still running");
}
// Shows the window on a conversation. Without a window (Show says
// why) nothing is on screen, so nothing is read or opened. `dialled`
// is the address as the user typed or a link gave it, what a text
// from here is sent to and what the status re-keys the conversation
// from (Status); "" from the list or a notification, where the
// latest message's address is (Destination).
void Open(std::string_view key, std::string_view dialled = "") {
// 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();
KeepWindow();
if (!view || view->key != key) {
KeepDraft();
view.emplace();
view->key = std::string(key);
view->compose = drafts.Take(key);
}
view->dialled = std::string(dialled);
view->dialledPlan = sync ? sync->Plan() : SimPlan{}; // for an address typed or linked now: the SIM's as known now
view->stickToBottom = true;
view->messages = store.Conversation(key);
if (canvas) Opened();
else Show();
ShowCaret();
}
// The conversation the window shows: read, its notification gone,
// Sync told (a text for it is stored read).
void Opened() {
if (!view) return;
if (store.MarkRead(view->key) > 0) Reload();
if (sync) sync->SetOpenConversation(view->key);
if (onConversationOpened) onConversationOpened(view->key);
}
void Back() {
if (!view) return;
StopFling();
CancelGesture();
KeepDraft();
view.reset();
if (blinkTimer) {
g_source_remove(blinkTimer);
blinkTimer = 0;
}
if (sync) sync->SetOpenConversation(std::nullopt);
Dirty();
}
// Puts text into the open conversation's field (the bench's typing).
void Prefill(std::string_view text) {
if (!view) return;
ComposeInsert(view->compose, text);
Dirty();
}
// The address a text from the open conversation is sent to (Model's
// SendAddress: as the user typed or a link gave it, else the latest
// message's, never the key); "" when none is known or it belongs to
// another SIM's plan, and Send is off.
std::string Destination() const { return SendAddress(view->dialled, view->dialledPlan, view->messages, sync ? sync->Plan() : SimPlan{}); }
// Sends the field's text to the open conversation.
void SendDraft() {
if (!view || !sync || view->compose.value.empty() || !CanSend(status) || Destination().empty()) return;
std::string text = view->compose.value;
while (!text.empty() && (text.back() == '\n' || text.back() == ' ')) text.pop_back();
// A store that refuses the text (its disk full) keeps the draft.
if (!text.empty() && sync->Send(view->key, Destination(), text) == Sync::kNotStored) return;
view->compose = ComposeState{};
view->stickToBottom = true;
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;
// The open conversation's key and its typed address's plan follow
// the status of the SIM the address was typed under (Number's
// AfterStatus): one opened from a link or a typed number before
// imsd's status brought the code was keyed as its digits, and a
// text sent meanwhile (CanSend needs no code — a status without
// one, a registration before the re-read) keeps the conversation
// on the key its rows carry.
if (view && s.statusKnown && sync && !view->dialled.empty()) {
TypedKey typed = AfterStatus(view->dialled, { view->key, view->dialledPlan }, sync->Plan(), sync->CountryCode(), store.Conversation(view->key).empty());
view->dialledPlan = std::move(typed.plan);
if (typed.key != view->key) {
view->key = std::move(typed.key);
view->messages = store.Conversation(view->key);
// Shown as Open shows a conversation: at its latest message,
// whatever a turn of the wheel did over the empty one.
view->scroll = ScrollState{};
view->stickToBottom = true;
if (OnScreen()) Opened(); // hidden, the kept conversation stays unread and keeps its notification: Show opens it
}
}
// The drafts of the typed addresses that were left follow it too.
if (s.statusKnown && sync) drafts.Status(sync->Plan(), sync->CountryCode(), [this](std::string_view key) { return store.Conversation(key).empty(); });
Dirty();
}
void Changed() { Reload(); }
private:
void Log(std::string_view line) {
if (onLog) onLog(line);
}
void Dirty() {
if (frames) frames->RequestRedraw();
}
// Leaving a conversation keeps what its field holds, by its key
// (Edit's Drafts); Open takes it up again.
void KeepDraft() {
if (view) drafts.Keep(view->key, view->compose, view->dialled, view->dialledPlan);
}
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;
// Shown texts are read; a conversation kept across a hide is
// not on screen, and its new texts stay unread until it is.
if (OnScreen() && 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);
area = view->DrawComposeBar(c, area, CanSend(status) && !Destination().empty(), hits);
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,
// so a fresh detector after a teardown has them too.
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;
}
// A key: Escape goes back; Ctrl+Enter sends; the rest edits the field.
void Key(Crafter::KeyCode code) {
using Crafter::CrafterKeys;
if (code == Crafter::Key(CrafterKeys::Escape)) {
Back();
return;
}
if (!view) return;
const std::unordered_set<Crafter::KeyCode>& held = canvas->Window().heldKeys;
const bool ctrl = held.contains(Crafter::Key(CrafterKeys::LeftCtrl)) || held.contains(Crafter::Key(CrafterKeys::RightCtrl));
if (ctrl && (code == Crafter::Key(CrafterKeys::Enter) || code == Crafter::Key(CrafterKeys::keypad_enter))) {
SendDraft();
return;
}
if (ComposeKey(view->compose, code)) ShowCaret();
// The library repeats a held key only while frames run; with frames
// on demand a timer ticks the repeat instead.
if (!repeatTimer) repeatTimer = g_timeout_add(30, OnRepeat, this);
}
static gboolean OnRepeat(gpointer data) {
App& self = *static_cast<App*>(data);
if (!self.canvas || self.canvas->Window().heldKeys.empty()) {
self.repeatTimer = 0;
return G_SOURCE_REMOVE;
}
Crafter::Device::TickKeyRepeats();
return G_SOURCE_CONTINUE;
}
// The caret shows at once after an edit and blinks from there while
// the window is up (without one nothing draws it; Show starts the
// blink again).
void ShowCaret() {
if (!view) return;
view->caretVisible = true;
if (blinkTimer) g_source_remove(blinkTimer);
blinkTimer = canvas ? g_timeout_add(500, OnBlink, this) : 0;
Dirty();
}
static gboolean OnBlink(gpointer data) {
App& self = *static_cast<App*>(data);
if (!self.view) {
self.blinkTimer = 0;
return G_SOURCE_REMOVE;
}
self.view->caretVisible = !self.view->caretVisible;
self.Dirty();
return G_SOURCE_CONTINUE;
}
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::compose) {
if (!view) return;
view->compose.focused = true;
view->compose.cursor = ComposeHit(*canvas, view->compose, view->composeLayout, at);
ShowCaret();
} else if (*id == Hit::send) {
SendDraft();
} 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;
Drafts drafts; // what was typed in the conversations left and not sent
GestureDetector gestures;
std::vector<HitRegion> hits;
guint longPressTimer = 0;
guint repeatTimer = 0;
guint blinkTimer = 0;
guint hideIdle = 0; // a close's Hide, deferred to the loop
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<Crafter::KeyCode>> keyUpSub;
std::optional<Crafter::EventListener<const std::string_view>> textSub;
std::optional<Crafter::EventListener<void>> resizeSub;
std::optional<Crafter::EventListener<void>> closeSub;
};
}