main: show the window; --screenshot and --quit-after

The executable shows the window at start unless --daemon (which
--headless and --send imply), on Activate and Open from a second launch
or a notification (of the URIs an Open carries, its first sms: link),
and on an sms: link, which opens the conversation of its first recipient
at once (Number's SmsUriRecipient: the scheme in any case, the fields
after '?' dropped, percent-escapes decoded; then ConversationKey with
the country code known at that moment — --country's, else the one imsd's
status gave once it is in, else what the number itself carries — which
takes NormalizeNumber's result as a phone number — E.164, or digits: a
short code, a national number no country code completed — and nothing
else), or just the window when it names no phone number; the
conversation remembers the address as dialled and the plan of the SIM it
was typed under, and that SIM's statuses move its key (Number's
AfterStatus, one step, applied in App::Status: another SIM's status —
another operator's, or without operators another own number's code,
Number's SameSim — changes nothing, so a SIM change leaves the key and
the plan the address was typed under; the same SIM's fills in what the
plan lacks, and the key follows from its digits to the centre's stand-in
and from any key to the own number's code once the plan has it, never
from one stand-in's key to another's and not while the code is lost, the
conversation it moves to shown at its latest message — and only while
nothing is stored under the key: a text stored before the code arrived
keeps the conversation on the key its rows carry). The shell forwards
Sync's events to the window and the notifier closes a conversation's
notification when it is opened (one closed while its Notify is on its
way goes when the answer comes). --screenshot renders one frame outside
the compositor's pacing 2.5 s after start — 600 ms later where it has to
make the window first — and saves it as a PNG before quitting, or ends
with exit 1 when no frame was captured — with a line when no window
could render it or another instance is running (a flag that acts on the
window finds none there: the run forwards nothing), and without one when
the run ended before the capture (the display gone, a close that quits);
a PNG the library cannot write is not noticed at this commit, and a
capture that throws ends the process — the verification path for a
machine without eyes, which must not depend on a desktop that repaints —
and --quit-after ends a bench on its own clock (a number of seconds its
timer can take: anything else is refused); a --send errand ended by
anything but its final state — that clock — exits 2, as it does on a
signal, its end latched before the loop stops; --screenshot beside
--send or --quit is refused, neither having a window. The window is torn
down in order before the bus client stops, and when the compositor's
connection breaks the process ends, so the next launch starts afresh. A
window the library cannot make (no display, no Vulkan driver) is logged
by Ui's Show and the start ends with exit 1, as a start without its
database does; a resident instance logs it and runs on without one, and
a later Activate or Open logs the same at once, the device's set-up
running only once.

Tested: tests/Number, the sms: links (a query, an escape, a list, the
scheme in capitals, no number), the keys of typed addresses, SameSim
(the same operator, another operator of one country, a status without
its operator, nothing known, own numbers' codes without operators) and
AfterStatus through the statuses a typed address meets: the stand-in
completing its digits while the plan learns the operator; another
stand-in, a lost code and another operator's status — its own number's
code the stand-in's or not — changing nothing; rows keeping the key
while the plan learns the code; the own number's code moving the
stand-in's key, at once or once nothing is stored; a key the own
number's code made, and its plan, staying under another SIM and under
its own SIM's stand-in; an own code that makes the stand-in's key; a
short code; --country before the operator; no operators; no address; an
international address, under another SIM and under its own; and the
address as dialled making the key the address as typed made.
This commit is contained in:
Jorijn van der Graaf 2026-10-18 00:26:09 +02:00
commit dd1108da58
Signed by: jorijnvdgraaf
GPG key ID: 2937E59CDCC1BCFB
6 changed files with 350 additions and 14 deletions

View file

@ -12,12 +12,12 @@ client to the Sync logic and the notifier, and runs the GLib main loop.
A --send errand takes no name and imports nothing.
Modes:
imsd-messages the app (the window arrives with the UI milestone)
imsd-messages the app, with its window
imsd-messages --daemon resident without a window: imports and notifies; beside a running instance it ends at once
imsd-messages --headless --daemon with a log line per event (the ssh smoke test)
imsd-messages --send N TEXT sends one text; exits once imsd has sent or failed it
imsd-messages --quit asks the running instance to exit
imsd-messages sms:+316... forwards a conversation to a running instance
imsd-messages sms:+316... opens (or forwards) a conversation
--session talks to `imsd --session` on the session bus; --data-dir and
--country override the database directory and the default country code.
@ -29,6 +29,7 @@ import std;
import Crafter.DB;
import ImsdMessages;
import ImsdMessages.Bus;
import ImsdMessages.Ui;
using namespace ImsdMessages;
namespace fs = std::filesystem;
@ -44,10 +45,28 @@ struct Options {
std::optional<std::pair<std::string, std::string>> send;
std::optional<std::string> uri;
std::optional<fs::path> dataDir;
std::optional<fs::path> screenshot;
std::optional<double> quitAfter; // seconds
std::string country;
std::string error;
};
// The flags that ask for an act on this process's own window: they go
// neither with an errand, which has no window, nor with --quit, nor beside
// a running instance, whose window is not this one. What configures a
// process (its store, its country code) is not among them: beside a
// running instance that instance's own stands.
bool WindowFlags(const Options& o) { return o.screenshot.has_value(); }
// A bench clock's seconds, which its timer takes as a guint of
// milliseconds: what is not such a number is the error.
double Seconds(std::string_view flag, const char* value, std::string& error) {
char* end = nullptr;
const double seconds = std::strtod(value, &end);
if (end == value || *end != '\0' || !(seconds >= 0 && seconds * 1000 <= G_MAXUINT)) error = std::format("{}: not a number of seconds: {}", flag, value); // a NaN fails both comparisons
return seconds;
}
Options Parse(std::span<const char* const> args) {
Options o;
for (std::size_t i = 0; i < args.size(); ++i) {
@ -63,8 +82,10 @@ Options Parse(std::span<const char* const> args) {
o.daemon = o.headless = true;
i += 2;
} else if (a == "--data-dir" && i + 1 < args.size()) o.dataDir = fs::path(args[++i]);
else if (a == "--screenshot" && i + 1 < args.size()) o.screenshot = fs::path(args[++i]);
else if (a == "--quit-after" && i + 1 < args.size()) o.quitAfter = Seconds(a, args[++i], o.error);
else if (a == "--country" && i + 1 < args.size()) o.country = args[++i];
else if (a.starts_with("sms:")) o.uri = std::string(a);
else if (IsSmsUri(a)) o.uri = std::string(a);
else o.error = std::format("unknown argument: {}", a);
}
if (o.send && DialledNumber(o.send->first).empty()) o.error = "--send: NUMBER is empty";
@ -80,6 +101,8 @@ Options Parse(std::span<const char* const> args) {
if (!o.country.empty() && (o.country.front() == '0' || CountryCodeOf(std::format("+{}0000000", o.country)) != o.country)) o.error = "--country: not a country code (one to three digits, without its +)";
if (o.send && o.quit) o.error = "--send and --quit do not go together";
if (o.send && o.uri) o.error = "--send and an sms: link do not go together";
if (o.send && WindowFlags(o)) o.error = "--send and a window do not go together";
if (o.quit && WindowFlags(o)) o.error = "--quit and a window do not go together";
return o;
}
@ -93,6 +116,21 @@ fs::path DefaultDataDir() {
return fs::path(xdg ? xdg : ".") / "imsd-messages";
}
fs::path CacheDir() {
const gchar* xdg = g_get_user_cache_dir();
return fs::path(xdg ? xdg : ".") / "imsd-messages";
}
// The font and the shaders sit beside the executable (Crafter.Build copies
// them there); IMSD_MESSAGES_ASSETS overrides.
fs::path AssetDir() {
const gchar* env = g_getenv("IMSD_MESSAGES_ASSETS");
if (env) return fs::path(env);
std::error_code ec;
const fs::path exe = fs::read_symlink("/proc/self/exe", ec);
return ec ? fs::current_path(ec) : exe.parent_path();
}
// What the daemon does with Sync's events: log, notify, and run the
// --send errand to its end.
class Shell : public SyncListener {
@ -105,11 +143,13 @@ public:
Shell& operator=(const Shell&) = delete;
Sync* sync = nullptr;
Ui::App* app = nullptr;
std::optional<std::pair<std::string, std::string>> send;
SendErrand errand; // the --send errand's rule (Sync's); the loop, the clock and the log are here
std::int32_t exitCode = 0;
void OnStatus(const AppStatus& s) override {
if (app) app->Status(s);
if (verbose) {
const std::string banner = BannerText(s);
Log(std::format("status: imsd {} enabled {} registered {} subscribed {}{}{}", s.imsdPresent ? "up" : "down", s.enabled, s.registered, s.subscribed, s.subscribeDenied ? " (subscribe refused)" : s.subscribeFailed ? " (subscribe failed)" : "", banner.empty() ? "" : std::format(" — {}", banner)));
@ -134,10 +174,12 @@ public:
void OnImported(const Message& m) override {
if (verbose) Log(std::format("received {} from {}: {} ({} byte(s), segments {})", m.imsdId, m.conversation, m.read ? "read" : "unread", m.text.size(), m.segments));
if (!m.read) notifier.Notify(m);
if (app) app->Changed();
}
void OnMessageChanged(const Message& m) override {
if (verbose) Log(std::format("message {} ({}): {}{}{}", m.id, m.imsdId.empty() ? "no imsd id yet" : m.imsdId, StateCaption(m.state), m.stateReason.empty() ? "" : " — ", m.stateReason));
if (app) app->Changed();
// The errand's message: imsd's word for the submission ends it — sent
// (0), or failed (1); a status report's word follows sent (imsd's
// order) — as does the app's own failure (imsd refused the Send, or
@ -160,6 +202,16 @@ public:
// and to take the text (SendErrand's TimedOut).
void OnTimeout() { End(errand.TimedOut("60 s")); }
// A bench's clock (--quit-after; the errand has no window to close or
// shoot): an errand without its final state reports none (2), its end
// latched before the loop stops — a status the loop dispatches after
// the clock in the same iteration makes no Send; a bench without an
// errand just stops.
void QuitAfter() {
if (send) End(errand.NoFinalState("ended before a final state"));
else g_main_loop_quit(loop);
}
private:
// The errand's end, once (the rule's): the exit code, the log line, the
// loop's end.
@ -212,7 +264,7 @@ int main(int argc, char** argv) {
return 0;
}
if (o.help) {
std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [sms:NUMBER] [--version]");
std::println("imsd-messages [--daemon|--headless] [--send NUMBER TEXT] [--quit] [--session] [--data-dir DIR] [--country CC] [--screenshot FILE.png] [--quit-after SECONDS] [sms:NUMBER] [--version]");
return 0;
}
@ -223,9 +275,21 @@ int main(int argc, char** argv) {
g_clear_error(&err);
}
GMainLoop* loop = g_main_loop_new(nullptr, FALSE);
std::optional<Ui::App> app;
Bus::Instance instance(session, {
.activate = [] { Log("activated (the window comes with the UI milestone)"); },
.open = [](std::vector<std::string> uris) { Log(std::format("open {} (the window comes with the UI milestone)", uris.empty() ? std::string_view("no link") : std::string_view(uris.front()))); },
.activate = [&app] {
if (app) app->Show();
},
.open = [&app](std::vector<std::string> uris) {
if (!app) return;
// One window, one conversation: the first sms: link of the
// call; without one, the window as it is.
const auto link = std::ranges::find_if(uris, [](const std::string& uri) { return IsSmsUri(uri); });
const std::string recipient = link == uris.end() ? std::string() : SmsUriRecipient(*link);
const std::string key = ConversationKey(recipient, app->sync ? app->sync->CountryCode() : "");
if (key.empty()) app->Show();
else app->Open(key, DialledNumber(recipient));
},
.quit = [loop] { g_main_loop_quit(loop); },
});
// A send errand is a client of its own: it neither owns the name nor
@ -240,6 +304,12 @@ int main(int argc, char** argv) {
}
if (owning == Bus::Instance::Owning::Taken) {
if (o.quit) return Bus::Instance::ForwardQuit(session) ? 0 : 1;
// A flag that acts on this process's own window finds none beside
// a running instance: the run says so, forwards nothing and fails.
if (WindowFlags(o)) {
Log("already running: a flag that acts on the window needs an instance of its own; nothing was done");
return 1;
}
// A second --daemon (a login entry beside the running instance) has
// nothing to add, and a forwarded Activate would ask for the window;
// the smoke test says it ran nothing.
@ -276,7 +346,6 @@ int main(int argc, char** argv) {
}
Bus::Notifier notifier(session);
notifier.onOpen = [](const std::string& conversation) { Log(std::format("notification tapped for {} (the window comes with the UI milestone)", conversation)); };
if (o.headless) notifier.onLog = Log;
Shell shell(o.headless, notifier, loop);
shell.send = o.send;
@ -286,17 +355,75 @@ int main(int argc, char** argv) {
// a --data-dir of its own): imsd's texts are that instance's to import.
if (o.send) sync.LeaveTexts();
shell.sync = &sync;
Log(std::format("{} {}; database {}; imsd on the {} bus; notifications {}", version, o.send ? "sending one text" : o.daemon ? "resident" : "starting", dataDir.string(), o.session ? "session" : "system", notifier.Enabled() ? "on" : "off"));
app.emplace(*store, AssetDir(), CacheDir());
if (o.screenshot) app->exitCode = 1; // an asked-for screenshot is a failure until the PNG is written: a run that ends first says so
app->sync = &sync;
app->onQuit = [loop] { g_main_loop_quit(loop); };
app->onConversationOpened = [&notifier](const std::string& conversation) { notifier.Close(conversation); };
app->onLog = Log;
// The compositor's connection broke, and the process cannot connect its
// display again: it ends (the store flushed, the name freed), so the next
// launch starts afresh.
app->onDisplayLost = [loop] {
Log("the Wayland display is gone: quitting");
g_main_loop_quit(loop);
};
shell.app = &*app;
notifier.onOpen = [&app](const std::string& conversation) { app->Open(conversation); };
Log(std::format("{} {}; database {}; imsd on the {} bus; notifications {}; assets {}", version, o.send ? "sending one text" : o.daemon ? "resident" : "starting", dataDir.string(), o.session ? "session" : "system", notifier.Enabled() ? "on" : "off", AssetDir().string()));
client.Start(sync);
if (o.uri) {
// The link's conversation opens at once, keyed with the country code
// known now — at a start --country's, else the number's own — and
// remembers the address as dialled: the status that brings the
// code re-keys it (Ui::App::Status, Number's AfterStatus).
app->Show();
const std::string recipient = SmsUriRecipient(*o.uri);
const std::string key = ConversationKey(recipient, sync.CountryCode());
if (!key.empty()) app->Open(key, DialledNumber(recipient));
} else if (!o.daemon) {
app->Show();
}
// A start that asked for the window and has none (Ui's log said why)
// ends with exit 1, as one without its database does; a resident
// instance runs on without a window, and the next Activate or Open
// asks for one again (a device whose set-up failed fails it at once).
if ((o.uri || !o.daemon) && !app->Visible()) {
client.Stop();
store->Flush();
g_main_loop_unref(loop);
return 1;
}
// The screenshot renders and saves without the compositor, 2.5 s after
// start (600 ms later where the window has to be made first).
struct ScreenshotJob {
Ui::App* app;
fs::path path;
};
std::optional<ScreenshotJob> screenshotJob;
if (o.screenshot) {
screenshotJob.emplace(&*app, *o.screenshot);
g_timeout_add(2500, [](gpointer data) -> gboolean {
ScreenshotJob& job = *static_cast<ScreenshotJob*>(data);
job.app->ScreenshotThenQuit(job.path);
return G_SOURCE_REMOVE;
}, &*screenshotJob);
}
g_unix_signal_add(SIGINT, OnQuitSignal, &shell);
g_unix_signal_add(SIGTERM, OnQuitSignal, &shell);
if (o.send) g_timeout_add_seconds(60, OnSendTimeout, &shell);
// A bench's clock: the smoke tests on the phone end on their own.
if (o.quitAfter) g_timeout_add(static_cast<guint>(*o.quitAfter * 1000), [](gpointer data) -> gboolean {
static_cast<Shell*>(data)->QuitAfter();
return G_SOURCE_REMOVE;
}, &shell);
g_main_loop_run(loop);
app->Shutdown();
client.Stop();
store->Flush();
if (session) g_dbus_connection_flush_sync(session, nullptr, nullptr); // a forwarded quit's reply, still queued, goes out before the exit
g_main_loop_unref(loop);
return shell.exitCode;
return shell.exitCode != 0 ? shell.exitCode : app->exitCode;
}

View file

@ -179,6 +179,88 @@ export namespace ImsdMessages {
return !codes || !IsE164(NormalizeNumber(address, now.code));
}
// An sms: link (RFC 5724), its scheme in any case.
bool IsSmsUri(std::string_view s) {
constexpr std::string_view scheme = "sms:";
return s.size() >= scheme.size() && std::ranges::equal(s.substr(0, scheme.size()), scheme, [](char a, char b) { return std::tolower(static_cast<std::uint8_t>(a)) == b; });
}
// The conversation key of a typed or linked address: NormalizeNumber's
// result when it is a phone number — E.164, or digits: a short code, a
// national number no country code completed — and empty for anything
// else.
std::string ConversationKey(std::string_view address, std::string_view defaultCountryCode) {
const std::string key = NormalizeNumber(address, defaultCountryCode);
return IsE164(key) || AllDigits(key) ? key : "";
}
// The key of a conversation opened with a typed or linked address, and
// the plan of the SIM the address was typed under.
struct TypedKey {
std::string key;
SimPlan plan;
friend bool operator==(const TypedKey&, const TypedKey&) = default;
};
// Whether a status's plan (`now`) can be that of the SIM `typed` is
// from. With its operator the plan tells: the same operator. Without
// one, two own numbers' codes that differ are two SIMs, and nothing
// else is known.
bool SameSim(const SimPlan& typed, const SimPlan& now) {
if (!typed.operatorId.empty()) return typed.operatorId == now.operatorId;
return typed.code.empty() || now.code.empty() || typed.code == now.code;
}
// What imsd's status makes of a typed address's key and plan: `now` is
// the SIM's plan as the status gives it, `code` the code a key is
// completed with meanwhile (the own number's, else the centre's
// stand-in, else none). Another SIM's status changes nothing: the key
// and the plan stay, and the plan is what an address typed under it is
// judged by under another SIM (AnotherPlan). The same SIM's fills in
// what the plan lacks, and while nothing is stored under the key
// (`nothingStored`: rows keep a conversation on the key they carry)
// the key follows: to the own number's code once the plan has it,
// whatever made the key before, and until then from its digits to the
// stand-in's — never from one stand-in's key to another's, and a lost
// code leaves it.
TypedKey AfterStatus(std::string_view dialled, TypedKey typed, const SimPlan& now, std::string_view code, bool nothingStored) {
if (!SameSim(typed.plan, now)) return typed;
if (typed.plan.operatorId.empty()) typed.plan.operatorId = now.operatorId;
if (typed.plan.code.empty()) typed.plan.code = now.code;
if (!nothingStored) return typed;
const std::string_view completing = !typed.plan.code.empty() ? std::string_view(typed.plan.code) : IsE164(typed.key) ? std::string_view() : code;
if (completing.empty()) return typed;
if (std::string key = ConversationKey(dialled, completing); !key.empty()) typed.key = std::move(key);
return typed;
}
// The first recipient of an sms: link, percent-decoded, without the
// fields after '?'; "" when the string is not an sms: link. Its key is
// ConversationKey's, its dialled form DialledNumber's.
std::string SmsUriRecipient(std::string_view uri) {
if (!IsSmsUri(uri)) return "";
std::string_view recipients = uri.substr(4);
if (recipients.starts_with("//")) recipients.remove_prefix(2);
recipients = recipients.substr(0, recipients.find('?'));
recipients = recipients.substr(0, recipients.find(','));
const auto hex = [](char c) -> std::int32_t {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
};
std::string decoded;
for (std::size_t i = 0; i < recipients.size(); ++i) {
if (recipients[i] == '%' && i + 2 < recipients.size() && hex(recipients[i + 1]) >= 0 && hex(recipients[i + 2]) >= 0) {
decoded.push_back(static_cast<char>(hex(recipients[i + 1]) * 16 + hex(recipients[i + 2])));
i += 2;
} else {
decoded.push_back(recipients[i]);
}
}
return decoded;
}
// The number as the UI shows it: "+31 612345678" for E.164, the key
// itself for everything else.
std::string DisplayNumber(std::string_view key) {

View file

@ -104,10 +104,23 @@ export namespace ImsdMessages::Bus {
const std::string body = bodyMarkup ? MarkupEscaped(Preview(m.text)) : Preview(m.text);
// GDBus's default timeout (25 s): a server still coming up at login
// answers late, and an answer that misses the timeout would leave a
// notification the app cannot route.
// notification the app cannot close or route.
g_dbus_connection_call(conn, notifyName, notifyPath, notifyName, "Notify", g_variant_new("(susssasa{sv}i)", "imsd-messages", replaces, std::string(appId).c_str(), summary.c_str(), body.c_str(), &actions, &hints, -1), G_VARIANT_TYPE("(u)"), G_DBUS_CALL_FLAGS_NONE, -1, nullptr, OnNotified, new std::pair<Notifier*, std::string>(this, m.conversation));
}
// The conversation was opened: its notification goes.
void Close(const std::string& conversation) {
if (!conn) return;
waiting.erase(conversation);
// A Notify still on its way has no id yet: closed when it comes.
if (inFlight.contains(conversation)) closeWhenShown.insert(conversation);
const auto it = byConversation.find(conversation);
if (it == byConversation.end()) return;
g_dbus_connection_call(conn, notifyName, notifyPath, notifyName, "CloseNotification", g_variant_new("(u)", it->second), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, nullptr, nullptr);
byId.erase(it->second);
byConversation.erase(it);
}
private:
static void OnCapabilities(GObject* source, GAsyncResult* result, gpointer data) {
GCancellable* cancellable = G_CANCELLABLE(data);
@ -144,7 +157,15 @@ export namespace ImsdMessages::Bus {
self.byConversation[p->second] = id;
self.byId[id] = p->second;
if (self.onLog) self.onLog(std::format("notification {} shown for {}", id, p->second));
if (self.closeWhenShown.contains(p->second)) {
// Closed while it was on its way: it goes now; a text that
// arrived meanwhile still gets its own below.
g_dbus_connection_call(self.conn, notifyName, notifyPath, notifyName, "CloseNotification", g_variant_new("(u)", id), nullptr, G_DBUS_CALL_FLAGS_NONE, 5000, nullptr, nullptr, nullptr);
self.byId.erase(id);
self.byConversation.erase(p->second);
}
}
self.closeWhenShown.erase(p->second);
self.inFlight.erase(p->second);
// A text that came while this one was on its way replaces it.
if (const auto w = self.waiting.find(p->second); w != self.waiting.end()) {
@ -189,6 +210,7 @@ export namespace ImsdMessages::Bus {
std::unordered_map<std::string, guint32> byConversation;
std::unordered_map<guint32, std::string> byId;
std::unordered_set<std::string> inFlight; // conversations with a Notify on its way
std::unordered_set<std::string> closeWhenShown; // closed while their Notify was on its way
std::unordered_map<std::string, Message> waiting; // the latest text that came meanwhile
};
}

View file

@ -58,6 +58,7 @@ export namespace ImsdMessages::Ui {
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
@ -138,8 +139,11 @@ export namespace ImsdMessages::Ui {
}
// 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) {
// 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 the
// status re-keys the conversation from (Status); "" from the list
// or a notification.
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.
@ -153,6 +157,8 @@ export namespace ImsdMessages::Ui {
view.emplace();
view->key = std::string(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 (store.MarkRead(key) > 0) Reload();
@ -186,6 +192,28 @@ export namespace ImsdMessages::Ui {
// ---- 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 (store.MarkRead(view->key) > 0) Reload();
if (sync) sync->SetOpenConversation(view->key);
if (onConversationOpened) onConversationOpened(view->key);
}
}
Dirty();
}

View file

@ -132,6 +132,8 @@ export namespace ImsdMessages::Ui {
class ViewScreen {
public:
std::string key;
std::string dialled; // the address as the user typed or a link gave it; "" from the list or a notification
SimPlan dialledPlan; // the plan of the SIM it was typed under, as far as that SIM's statuses have told it (Number's AfterStatus)
std::vector<Message> messages;
ScrollState scroll;
bool stickToBottom = true;

View file

@ -3,8 +3,10 @@
// Number normalisation: the raw address a user types or the network sends
// becomes the conversation key — E.164 for numbers, short codes and
// alphanumeric senders verbatim — the display form of a key, and the
// dialled form of an address (its separators gone, nothing added).
// alphanumeric senders verbatim — the display form of a key, the dialled
// form of an address (its separators gone, nothing added), an sms: link's
// recipient, and the key an open conversation moves to once the country
// code is known.
import std;
import ImsdMessages;
using namespace ImsdMessages;
@ -128,5 +130,78 @@ int main() {
CheckEqual(DisplayNumber("1234"), "1234", "display of a short code");
CheckEqual(DisplayNumber("KPN"), "KPN", "display of an alphanumeric sender");
// sms: links (RFC 5724): the first recipient, decoded, without the fields.
struct UriCase {
std::string_view uri;
std::string_view countryCode;
std::string_view key;
};
const std::array<UriCase, 11> uris = { {
{ "sms:+31612345678", "", "+31612345678" },
{ "SMS:+31612345678", "", "+31612345678" },
{ "sms:0612345678", "31", "+31612345678" },
{ "sms:+31612345678?body=Hi", "", "+31612345678" },
{ "sms:%2B31612345678", "", "+31612345678" },
{ "sms:+31612345678,+31687654321", "", "+31612345678" },
{ "sms://+31612345678", "", "+31612345678" },
{ "sms:1234", "", "1234" },
{ "sms:", "31", "" },
{ "sms:?body=Hi", "31", "" },
{ "sms:KPN", "31", "" },
} };
for (const UriCase& c : uris) CheckEqual(ConversationKey(SmsUriRecipient(c.uri), c.countryCode), c.key, std::format("ConversationKey(SmsUriRecipient(\"{}\"), \"{}\")", c.uri, c.countryCode));
CheckEqual(SmsUriRecipient("sms:06%2012345678?body=Hi"), "06 12345678", "the recipient as the link spelt it, decoded, for dialling");
CheckEqual(SmsUriRecipient("tel:+31612345678"), "", "no recipient from another scheme");
Check(IsSmsUri("Sms:1") && !IsSmsUri("smsto:1") && !IsSmsUri("sms"), "IsSmsUri takes the scheme in any case and nothing else");
struct KeyCase {
std::string_view address;
std::string_view countryCode;
std::string_view key;
};
constexpr std::array<KeyCase, 6> keys = { {
{ "0612345678", "31", "+31612345678" },
{ "+31 6 1234 5678", "", "+31612345678" },
{ "0612345678", "", "0612345678" },
{ "1234", "", "1234" },
{ "KPN", "31", "" },
{ "", "31", "" },
} };
for (const KeyCase& c : keys) CheckEqual(ConversationKey(c.address, c.countryCode), c.key, std::format("ConversationKey(\"{}\", \"{}\")", c.address, c.countryCode));
Check(SameSim({ "", "20408" }, kpn), "SameSim: the same operator, its own number's code read since");
Check(!SameSim(kpn, vodafoneNl), "SameSim: another operator of the same country is another SIM");
Check(!SameSim(kpn, { "31", "" }), "SameSim: a status without its operator is not known to be the typed SIM's");
Check(SameSim({}, telekomDe), "SameSim: typed before any status, nothing is known against it");
Check(SameSim({ "31", "" }, kpn) && !SameSim({ "31", "" }, telekomDe), "SameSim: typed under no known operator, the own numbers' codes tell");
{
const std::string_view typed = "0612345678";
const SimPlan unread{ "", "20408" }; // SIM A, its own number not read yet: the operator and no code
TypedKey t = AfterStatus(typed, { "0612345678", {} }, unread, "44", true);
Check(t == TypedKey{ "+44612345678", unread }, "AfterStatus: the centre's stand-in completes a key that is still its digits, and the plan learns the operator");
const TypedKey standIn = t;
Check(AfterStatus(typed, standIn, unread, "49", true) == standIn, "AfterStatus: one stand-in's key does not move to another's");
Check(AfterStatus(typed, standIn, unread, "", true) == standIn, "AfterStatus: a lost code leaves the key alone");
Check(AfterStatus(typed, standIn, { "44", "23410" }, "44", true) == standIn && AfterStatus(typed, standIn, telekomDe, "49", true) == standIn, "AfterStatus: another operator's status changes nothing, its own number's code the stand-in's or not");
Check(AfterStatus(typed, standIn, kpn, "31", false) == TypedKey{ "+44612345678", kpn }, "AfterStatus: rows under the key keep it there, and the plan still learns the code");
t = AfterStatus(typed, standIn, kpn, "31", true);
Check(t == TypedKey{ "+31612345678", kpn }, "AfterStatus: back on its SIM, the own number's code moves the key the stand-in made");
Check(AfterStatus(typed, AfterStatus(typed, standIn, kpn, "31", false), kpn, "31", true) == t, "AfterStatus: and moves it later, once nothing is stored under it");
Check(AfterStatus(typed, t, telekomDe, "49", true) == t && AfterStatus(typed, t, vodafoneNl, "31", true) == t, "AfterStatus: a key the own number's code made stays under another SIM, another country's or another operator's, and so does the plan it was typed under");
Check(AfterStatus(typed, t, unread, "44", true) == t, "AfterStatus: nor does its own SIM's stand-in move it back, the own number unread again");
Check(AfterStatus(typed, standIn, { "44", "20408" }, "44", true) == TypedKey{ "+44612345678", { "44", "20408" } }, "AfterStatus: an own number's code that makes the stand-in's key keeps it");
Check(AfterStatus("1234", { "1234", {} }, kpn, "31", true) == TypedKey{ "1234", kpn }, "AfterStatus: a short code keeps its key and learns its plan");
Check(AfterStatus(typed, { "+31612345678", { "31", "" } }, kpn, "31", true) == t, "AfterStatus: a code known before the operator (--country): the status completes the plan");
Check(AfterStatus(typed, { "+31612345678", { "31", "" } }, telekomDe, "49", true) == TypedKey{ "+31612345678", { "31", "" } }, "AfterStatus: and another own number's code is another SIM");
Check(AfterStatus(typed, { "+44612345678", {} }, { "31", "" }, "31", true) == TypedKey{ "+31612345678", { "31", "" } }, "AfterStatus: without operators the own number's code moves the stand-in's key all the same");
Check(AfterStatus("", { "+31612345678", {} }, kpn, "31", true).key == "+31612345678", "AfterStatus: no address, no other key (a conversation from the list or a notification)");
Check(AfterStatus("+31612345678", { "+31612345678", kpn }, telekomDe, "49", true) == TypedKey{ "+31612345678", kpn }, "AfterStatus: an international address never changes key");
Check(AfterStatus("+31612345678", { "+31612345678", { "", "20408" } }, { "44", "20408" }, "44", true).key == "+31612345678", "AfterStatus: nor under its own SIM's code, another country's");
// AfterStatus makes a key from the address as dialled; Open's is made from the address as typed.
bool sameKey = true;
for (const Case& c : cases) sameKey = sameKey && ConversationKey(DialledNumber(c.raw), c.countryCode) == ConversationKey(c.raw, c.countryCode);
for (const std::string_view raw : { "+31 (0)6 1234 5678", "0031 (0)6 1234 5678", "(06) 1234 5678", "(+44) (0)20 7946 0018" }) sameKey = sameKey && ConversationKey(DialledNumber(raw), "31") == ConversationKey(raw, "31");
Check(sameKey, "AfterStatus: the address as dialled makes the key the address as typed made, under every case's code");
}
return failures == 0 ? 0 : 1;
}