imsd-messages/interfaces/ImsdMessages-Model.cppm

230 lines
12 KiB
Text
Raw Normal View History

// SPDX-License-Identifier: GPL-3.0-only
// SPDX-FileCopyrightText: Copyright (C) 2026 Catcrafts®
/*
ImsdMessages:Model — what a message and a conversation are to the app, and
the app's status as the banner reads it. Plain data and pure functions; the
store persists Message, the bus layer fills ReceivedMessage from imsd's
dictionary, the window draws the rest.
*/
export module ImsdMessages:Model;
import std;
import :Number;
import :Time;
export namespace ImsdMessages {
packaging: the aarch64 flatpak crafter-build cross-compiles the executable for aarch64, which on an x86_64 machine needs no emulation, and flatpak's build commands assemble the flatpak; there is no flatpak-builder manifest. make-flatpak-sysroot.sh makes the sysroot: the aarch64 Freedesktop Sdk 26.08 with LLVM's libc++ of the release crafter-build carries (23.1.2, the tarball and hash of Crafter.Build's manifest), built for aarch64. build-flatpak.sh builds the executable against it for generic armv8-a and assembles it on the Platform 26.08 with that libc++, libc++abi and LLVM's libunwind in /app/lib: the Platform has no libc++, and its libunwind is libunwind 8. It fails when the executable or a bundled library needs a library neither the Platform nor /app/lib has, and when one of them links libunwind 8, which libc++'s -lunwind found first until the sysroot dropped its link name. The executable it packages is the build it just ran: the output directory's name ends in a hash of the configuration, so an older variant (another sysroot, --debug, --local) left in bin/ is removed first. make-flatpak-sysroot.sh tries each download five times, 30 s apart: Flathub's CDN answers 502 now and then. The sandbox gets Wayland, the GPU, net.catcrafts.IMS1 on the system bus and org.freedesktop.Notifications on the session bus. The metainfo's content rating declares the app's chat (OARS social-chat intense: uncontrolled texting between users), as the baseline Chatty's does, for the software centres and parental controls that read it, and recommends a display of 360 logical pixels or more — the phone screen the window is drawn for; a recommendation, not a requirement. The metainfo's one release is 0.0.0, and the app's version, 0.1.0 in the skeleton, is set to it: the version's comment in Model.cppm says a release moves the two together. AGENTS.md's SPDX rule says what the metainfo carries instead of the two SPDX lines: AppStream's single CC0-1.0 line. The flatpak carries the licences of what it ships under /app/share/licenses/net.catcrafts.ImsdMessages: the app's and the font's, those of the Crafter libraries it links statically and of the code they bring along (packaging/licenses/, with a NOTICE naming what each text covers), and LLVM's for its runtime libraries, which make-flatpak-sysroot.sh keeps beside libc++.
2026-10-21 23:59:17 +02:00
// The app's version, for --version. A release bumps it and adds its
// <release> to the metainfo, whose newest entry names this version.
inline constexpr std::string_view version = "0.0.0";
enum class Direction : std::uint8_t { Incoming, Outgoing };
// The life of a message as the UI shows it: a received text is Received;
// one of ours is Pending until imsd's StateChanged says sent or failed,
// or the app fails it, and a status report may move a sent one on to
// delivered, delivery-pending or delivery-failed.
enum class MessageState : std::uint8_t { Received, Pending, Sent, Failed, Delivered, DeliveryPending, DeliveryFailed };
// imsd's StateChanged `state` word; nullopt for one this version does
// not know, which the caller logs and ignores.
std::optional<MessageState> StateFromImsd(std::string_view state) {
if (state == "sent") return MessageState::Sent;
if (state == "failed") return MessageState::Failed;
if (state == "delivered") return MessageState::Delivered;
if (state == "delivery-pending") return MessageState::DeliveryPending;
if (state == "delivery-failed") return MessageState::DeliveryFailed;
return std::nullopt;
}
// The caption under an outgoing bubble. Words, not glyphs: the bundled
// font has no check marks.
std::string_view StateCaption(MessageState state) {
switch (state) {
case MessageState::Received: return "";
case MessageState::Pending: return "Sending…";
case MessageState::Sent: return "Sent";
case MessageState::Failed: return "Failed";
case MessageState::Delivered: return "Delivered";
case MessageState::DeliveryPending: return "Delivery pending";
case MessageState::DeliveryFailed: return "Delivery failed";
}
return "";
}
// A received text as imsd's Received signal and List reply describe it
// (imsd AGENTS.md §8.4), GLib-free.
struct ReceivedMessage {
std::string imsdId;
std::string from;
std::string text;
std::string timestamp; // the service centre's, ISO 8601 with its offset
std::int64_t received = 0; // arrival at imsd, epoch seconds
std::string sc;
std::string to; // the subscriber it arrived for: the registration's own number at receipt, "" when it gave none
std::string simOperator; // the operator of the SIM it arrived under (imsd's `operator`), "" when imsd gave none
std::int32_t smsClass = -1;
std::uint8_t pid = 0;
std::uint8_t dcs = 0;
std::int32_t segments = 1;
bool messageWaiting = false;
std::optional<std::uint32_t> portDst;
std::optional<std::uint32_t> portSrc;
std::vector<std::uint8_t> data;
std::vector<std::uint8_t> pdu;
friend bool operator==(const ReceivedMessage&, const ReceivedMessage&) = default;
};
// One message of a conversation as the app stores and shows it.
struct Message {
std::uint64_t id = 0; // the store's row id
std::string conversation; // the key (ImsdMessages:Number)
std::string peer; // the address as the network or the user gave it
SimPlan plan; // the SIM's plan when the row was written (Number's SimPlan): a non-international peer is dialled under that plan alone
Direction direction = Direction::Incoming;
std::string text;
std::int64_t sortTime = 0; // the SC's stamp of a received text (else its arrival); the send time of ours
std::int64_t received = 0; // arrival at imsd, or the send time
MessageState state = MessageState::Received;
std::string stateReason; // the reason of the last state change: imsd's, or why the app failed it
bool read = false;
std::string imsdId; // imsd's: ims-sms-in-<run>-<epoch>-<N>, or ims-sms-<run>-<start>-<N> once Send answered
std::int32_t segments = 1;
std::int32_t smsClass = -1;
bool messageWaiting = false;
std::optional<std::uint32_t> portDst;
std::optional<std::uint32_t> portSrc;
std::vector<std::uint8_t> data; // 8-bit payload (imsd's `data`), never shown raw
friend bool operator==(const Message&, const Message&) = default;
};
// The message of a received text. The conversation key comes from the
// sender's address completed with the code of the number the text
// arrived for (`to`, the subscriber's own number at receipt — the
// record's, since a status read later may be another SIM's) or,
// lacking one, of the service centre that delivered it. The row's plan
// is the own number's code — none when the centre's stood in — and the
// operator of the SIM it arrived under. The sort time is the service
// centre's stamp, else the arrival.
Message MessageFromReceived(const ReceivedMessage& r) {
Message m;
const std::string ownCode = CountryCodeOf(r.to);
const std::string code = !ownCode.empty() ? ownCode : CountryCodeOf(r.sc);
m.conversation = NormalizeNumber(r.from, code);
m.peer = r.from;
m.plan = { ownCode, r.simOperator };
m.direction = Direction::Incoming;
m.text = r.text;
const std::optional<ParsedTime> stamp = ParseIso8601(r.timestamp);
m.sortTime = stamp ? stamp->epoch : r.received;
m.received = r.received;
m.state = MessageState::Received;
m.imsdId = r.imsdId;
m.segments = r.segments;
m.smsClass = r.smsClass;
m.messageWaiting = r.messageWaiting;
m.portDst = r.portDst;
m.portSrc = r.portSrc;
m.data = r.data;
return m;
}
// A short message type 0 (TS 23.040 9.2.3.9, TP-PID 0x40): the phone
// acknowledges it and discards its content, neither stored nor shown.
bool IsType0(const ReceivedMessage& r) { return r.pid == 0x40; }
struct Conversation {
std::string key;
std::string lastText;
std::int64_t lastTime = 0;
Direction lastDirection = Direction::Incoming;
MessageState lastState = MessageState::Received;
std::uint64_t lastId = 0;
std::uint32_t unread = 0;
std::uint32_t count = 0;
friend bool operator==(const Conversation&, const Conversation&) = default;
};
// The conversations of a set of messages, newest first; the last message
// is the latest by sort time, then by id.
std::vector<Conversation> GroupConversations(std::span<const Message> messages) {
std::unordered_map<std::string, std::size_t> index;
std::vector<Conversation> out;
for (const Message& m : messages) {
auto [it, inserted] = index.try_emplace(m.conversation, out.size());
if (inserted) out.push_back({ .key = m.conversation });
Conversation& c = out[it->second];
++c.count;
if (m.direction == Direction::Incoming && !m.read) ++c.unread;
const bool later = m.sortTime > c.lastTime || (m.sortTime == c.lastTime && m.id > c.lastId);
if (c.count == 1 || later) {
c.lastText = m.text;
c.lastTime = m.sortTime;
c.lastDirection = m.direction;
c.lastState = m.state;
c.lastId = m.id;
}
}
std::ranges::sort(out, [](const Conversation& a, const Conversation& b) {
return a.lastTime != b.lastTime ? a.lastTime > b.lastTime : a.lastId > b.lastId;
});
return out;
}
Ui: the compose field and the send bar A text message needs several lines and UTF-8, and the library's InputField is one line edited by byte, so the field is the app's own. Its state and editing are the core's (ImsdMessages:Edit, tested without a window): a plain struct, insertion at the cursor, Backspace and Delete by code point, Home and End within the line, a newline. Ui:Compose turns the keys into those edits and draws the field one to five lines tall — as many as half the area under the header and the banner holds, and one at the least — with the canvas's word wrapper (a longer text shows the lines that end at the caret's, or the first ones while the caret is among them), a placeholder when empty, the caret at the cursor, and a tap placing the cursor at the nearest byte by the widths the glyphs are drawn at, in the text as it is when the tap lands (an edit since the last frame only asked for one; a field no frame has laid out yet takes a tap as one at its text's end; a tap at or past the last line's end asks for the text's end, where a space the wrapper hung off the line may be). The bar under a conversation holds the field and Send, enabled only with text, a sendable status and an address to send to; Send hands the text to Sync with that address and clears the field (a store that refuses the text keeps the draft) (Model's SendAddress: as a link gave it, else the latest message's — the network's form of a received text, the dialled form of ours — never the key, whose completed country code is a guess that groups; a conversation with neither has Send off, and so has one whose address is not international — a national number, a short code; typed, linked or the message's — and was typed or written under another SIM's plan than the one known now, which the plan each row and the view carry tells (the view's is that of the SIM the address was typed under, which Number's AfterStatus keeps; Number's AnotherPlan, its second caller)); Sync's StateChanged moves the bubble's caption. Keys reach the field while a conversation is open (Escape goes back, Ctrl+Enter sends), a held key repeats through a timer since frames are on demand, and the caret blinks on one. A text typed and not sent is its conversation's, not the view's: leaving the conversation (Back, another one opened by a notification or a link) keeps it by the conversation's key for the run, and opening the conversation again takes it up (Edit's Drafts: an empty field keeps nothing and drops nothing; the draft of a typed or linked address follows imsd's status as the open conversation's key does — Number's AfterStatus over the address and the plan kept with it — so one left before the status brought the country code is found under the key the address makes afterwards; and a second text kept under one key — two keys that became one — goes after the first on a line of its own). Tested: tests/Model, the address a text goes to (the typed or linked one, the latest message's, none for an emptied conversation, none under another SIM's plan than it was typed or written under — a national number with or without a trunk prefix under another country's SIM, a short code under another operator's too, though dialled under the same operator, the own number read when it was typed or not; a national number typed before the own number was read, none under another operator — an international one under any — and a typed address judged by its own plan, whatever the latest row's); tests/Edit (code points of one to four bytes, the moves within a line, the edits that change nothing, the first line shown as the caret moves down a long text; the drafts: kept and taken up by key with the cursor, taken once, an empty field keeping and dropping nothing, one per conversation, a second text under one key on a line of its own; a typed address's following the status — moved when the code comes, not while texts are stored under its key, not under another SIM's status, a list conversation's left alone and the store not asked, the learned plan kept, two keys that became one keeping both texts).
2026-10-18 00:35:39 +02:00
// The address a text from a conversation goes to: the one the user typed
// or a link gave (`dialled`), else the latest message's `peer` — the
// network's form of a received text, the dialled form of ours (the
// conversation oldest first, as the store gives it) — and "" when the
// conversation has neither, which turns Send off. Never the conversation
// key: a country code completed for it groups (ImsdMessages:Number) and
// must not be dialled. An address that is not international — a
// national number, a short code; typed, linked or a peer's — belongs
// to the plan it was typed or the row written under (`dialledPlan`,
// the message's `plan`); under another SIM's plan (`now`, the one
// known now: Number's AnotherPlan) it would reach another subscriber
// or another service — so no address, until the user types it again
// (the view keeps `dialled` across the change, so it is checked each
// time).
std::string SendAddress(std::string_view dialled, const SimPlan& dialledPlan, std::span<const Message> conversation, const SimPlan& now) {
const std::string address = !dialled.empty() ? std::string(dialled) : conversation.empty() ? std::string() : conversation.back().peer;
const SimPlan plan = !dialled.empty() ? dialledPlan : conversation.empty() ? SimPlan{} : conversation.back().plan;
if (AnotherPlan(address, plan, now)) return "";
return address;
}
// What the app knows about imsd, for the banner and the send button.
struct AppStatus {
bool imsdPresent = false; // net.catcrafts.IMS1 has an owner
bool statusKnown = false; // GetStatus has answered since imsd appeared
bool enabled = false; // GetStatus: SMS over IMS is on
bool registered = false; // GetStatus / RegistrationChanged
bool subscribed = false; // Subscribe succeeded on this connection
bool subscribeDenied = false; // Subscribe was refused by polkit: no live updates
bool subscribeFailed = false; // Subscribe failed otherwise: no live updates until it is tried again
std::string smsc; // GetStatus: the service centre's number
std::string ownNumber; // GetStatus: the subscriber's own number (imsd's ppi), E.164; "" when the network gave none
std::string simOperator; // GetStatus: the SIM's operator (imsd's `operator`: MCC, then MNC); "" when imsd gave none
std::uint32_t undeletable = 0; // messages imsd still holds because Delete was refused
bool storeFailed = false; // the store refused a write (its disk full): texts wait and the banner says so; a send still goes, and a write that gets room clears this
friend bool operator==(const AppStatus&, const AppStatus&) = default;
};
// The one line under the header; "" when nothing needs saying.
std::string BannerText(const AppStatus& s) {
if (!s.imsdPresent) return "imsd is not running";
if (!s.statusKnown) return "Connecting to imsd\u2026";
if (!s.enabled) return "SMS over IMS is off in imsd (SMS_OVER_IMS=0)";
if (s.subscribeDenied) return "No live updates: imsd refused this session (polkit)";
// What blocks sending comes first: the line is a refused send's
// reason too (Sync's Submit). The store's refusal blocks no send;
// it costs texts, which wait for room, before live updates.
if (!s.registered) return "Not registered with the IMS network";
if (s.storeFailed) return "Cannot save messages (storage full?): texts wait until there is room";
if (s.subscribeFailed) return "No live updates: imsd did not answer the subscription";
if (s.undeletable > 0) return std::format("imsd still holds {} message{} this session may not delete", s.undeletable, s.undeletable == 1 ? "" : "s");
return "";
}
bool CanSend(const AppStatus& s) {
return s.imsdPresent && s.statusKnown && s.enabled && s.registered && !s.subscribeDenied;
}
}