diff --git a/palm-client/Makefile b/palm-client/Makefile index 73a1148..4eadc44 100644 --- a/palm-client/Makefile +++ b/palm-client/Makefile @@ -11,7 +11,7 @@ APP = visormesh NAME = VisorMesh CREATOR = VMsh -SRCS = src/main.c src/app.c src/home_form.c src/convo_form.c src/node_form.c src/channel_form.c src/convos.c src/protocol.c src/sha256.c src/transport_srm.c src/transport_sb.c src/sb_spi.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_form.c src/contact_form.c src/heard.c src/remote_fmt.c src/remote.c src/remote_form.c src/messages.c src/channels.c src/preview_form.c src/ui/draw.c src/ui/text.c src/ui/rowlist.c src/ui/title.c src/ui/fontmetrics.c src/ports.c src/sounds.c src/mutes.c src/scopes.c src/scope_proto.c src/map_geo.c src/map_form.c src/ui/emoji.c src/bgcheck.c src/pins.c src/shots.c src/db.c +SRCS = src/main.c src/app.c src/home_form.c src/convo_form.c src/node_form.c src/channel_form.c src/convos.c src/protocol.c src/sha256.c src/transport_srm.c src/transport_sb.c src/sb_spi.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_form.c src/contact_form.c src/heard.c src/remote_fmt.c src/remote.c src/remote_form.c src/messages.c src/channels.c src/preview_form.c src/ui/draw.c src/ui/text.c src/ui/rowlist.c src/ui/title.c src/ui/fontmetrics.c src/ports.c src/sounds.c src/mutes.c src/scopes.c src/scope_proto.c src/map_geo.c src/map_form.c src/ui/emoji.c src/bgcheck.c src/pins.c src/shots.c src/db.c src/reaction_fmt.c src/reactions.c src/rxpath.c src/msg_menu.c OBJS = $(SRCS:src/%.c=build/%.o) CC = m68k-palmos-gcc @@ -81,6 +81,8 @@ test: | build build/test_scopes gcc -std=c99 -Wall -Wextra -D_DEFAULT_SOURCE -o build/test_map tests/test_map.c src/map_geo.c -lm build/test_map + gcc -std=c99 -Wall -Wextra -o build/test_reactions tests/test_reactions.c src/reaction_fmt.c src/rxpath.c src/sha256.c + build/test_reactions build: mkdir -p build diff --git a/palm-client/resources/visormesh.rcp b/palm-client/resources/visormesh.rcp index 4b2f8c2..0a0428f 100644 --- a/palm-client/resources/visormesh.rcp +++ b/palm-client/resources/visormesh.rcp @@ -66,6 +66,8 @@ BEGIN END PULLDOWN "Options" BEGIN + MENUITEM "Message Actions..." ID MainMenuMessage "Y" + MENUITEM "-" AUTOID MENUITEM "Connect" ID MainMenuConnect MENUITEM "Flood Scopes..." ID MainMenuScopes "O" MENUITEM "Preferences..." ID MainMenuSounds "R" @@ -153,6 +155,8 @@ BEGIN END PULLDOWN "Options" BEGIN + MENUITEM "Message Actions..." ID MainMenuMessage "Y" + MENUITEM "-" AUTOID MENUITEM "Connect" ID MainMenuConnect MENUITEM "Flood Scopes..." ID MainMenuScopes "O" MENUITEM "Preferences..." ID MainMenuSounds "R" @@ -193,6 +197,7 @@ BEGIN BUTTON "Send" ID ConvoSendButton AT (1 147 AUTO AUTO) BUTTON "Back" ID ConvoBackButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) GRAFFITISTATEINDICATOR AT (150 148) + LIST "" ID ConvoActionList AT (28 16 80 AUTO) NONUSABLE VISIBLEITEMS 5 END /* Node: this radio's details, connection and settings */ @@ -333,6 +338,22 @@ BEGIN BUTTONS "Zero-hop" "Flood" "Cancel" END +ALERT ID PathAlert +INFORMATION +BEGIN + TITLE "Message Path" + MESSAGE "^1" + BUTTONS "OK" +END + +ALERT ID ReactionsAlert +INFORMATION +BEGIN + TITLE "Reactions" + MESSAGE "^1" + BUTTONS "OK" +END + ALERT ID RetryAlert CONFIRMATION DEFAULTBUTTON 1 diff --git a/palm-client/src/bgcheck.c b/palm-client/src/bgcheck.c index 88e0122..3a39dd0 100644 --- a/palm-client/src/bgcheck.c +++ b/palm-client/src/bgcheck.c @@ -5,6 +5,7 @@ #include "contacts.h" #include "channels.h" #include "messages.h" +#include "reactions.h" #include "mutes.h" #include "convos.h" #include "resources.h" @@ -333,6 +334,7 @@ UInt16 BgCheckRun(void) ContactsClose(); ChannelsClose(); MessagesClose(); + ReactionsClose(); return kinds; } diff --git a/palm-client/src/contacts.c b/palm-client/src/contacts.c index 2019695..2d76d88 100644 --- a/palm-client/src/contacts.c +++ b/palm-client/src/contacts.c @@ -175,3 +175,16 @@ Err ContactsUpdate(void) gLastMod = lastMod; return err; } + +Boolean ContactsFindByName(const Char *name, VmContact *out) +{ + UInt16 i, n; + + if (ContactsOpen() != errNone) + return false; + n = DmNumRecords(gDb); + for (i = 0; i < n; i++) + if (ContactsGet(i, out) && out->type == VM_ADV_TYPE_CHAT && StrCompare(out->name, name) == 0) + return true; + return false; +} diff --git a/palm-client/src/contacts.h b/palm-client/src/contacts.h index decfe6b..a330182 100644 --- a/palm-client/src/contacts.h +++ b/palm-client/src/contacts.h @@ -30,5 +30,7 @@ Err ContactsRefresh(UInt32 *count) VM_SECT2; * refresh. Removals on the radio only show at the next full refresh. */ Err ContactsUpdate(void) VM_SECT4; +/* A companion by its exact name (a channel message names its sender only that way). */ +Boolean ContactsFindByName(const Char *name, VmContact *out) VM_SECT4; #endif diff --git a/palm-client/src/convo_form.c b/palm-client/src/convo_form.c index 16cef90..ade0ce2 100644 --- a/palm-client/src/convo_form.c +++ b/palm-client/src/convo_form.c @@ -16,6 +16,7 @@ #include "ui/text.h" #include "ui/rowlist.h" #include "ui/emoji.h" +#include "msg_menu.h" #include "convo_form.h" /* In the second code segment: see sections.h for the rules. */ @@ -39,6 +40,8 @@ static void Tapped(UInt16 row, Coord penX) VM_SECT2; static Boolean AllocLines(void) VM_SECT2; static void ShowEarlier(void) VM_SECT2; static Boolean TappedEmoji(UInt16 row, Coord penX) VM_SECT2; +static void MessageMenu(UInt16 msg, const RectangleType *b) VM_SECT2; +static Boolean Hold(UInt16 row, const RectangleType *b, void *ctx) VM_SECT2; #define MAX_MSGS 40 /* newest messages shown; "Earlier messages" adds as many again */ #define LINES_PER 5 /* lines allowed per message shown, on average */ @@ -51,6 +54,7 @@ static Boolean TappedEmoji(UInt16 row, Coord penX) VM_SECT2; #define L_TEXT 2 #define L_NEW 3 /* "── new ──" before the first message unread when the screen opened */ #define L_MORE 4 /* at the top when older messages aren't shown: tap for more */ +#define L_REACT 5 /* under a message: its reactions (off, len: in msg_menu's summaries) */ #define NO_NEW 0 typedef struct { @@ -142,12 +146,14 @@ static void Build(void) UInt16 *idx = MemPtrNew(gShow * sizeof(UInt16)); UInt16 nIdx = 0, i, n = MessagesCount(), width = TextWidth(); Boolean more = false; + Int16 react; UInt32 day, lastDay = 0; Char sender[VM_NAME_SIZE + 2], lastSender[VM_NAME_SIZE + 2], suffix[8]; FontID old = FntSetFont(vmSmallFont); gCount = 0; lastSender[0] = 0; + MsgReactLoad(); if (!idx) { FntSetFont(old); return; @@ -214,6 +220,9 @@ static void Build(void) if (gCount > 0) gLines[gCount - 1].last = true; MessagesRelease(m); + react = MsgReactSummary(m, &len); + if (react >= 0) + AddLine(L_REACT, m, (UInt16)react, len, false, false, 0); } MemPtrFree(idx); FntSetFont(old); @@ -297,6 +306,8 @@ static void DrawLine(UInt16 row, const RectangleType *b, void *ctx) } else if (l->kind == L_CHIP) { SenderOf(h, buf, sizeof(buf)); DrawChip(buf, x + 1, b->topLeft.y); + } else if (l->kind == L_REACT) { + WinDrawChars(MsgReactText(l->off), l->len, x + TEXT_X, y); } else { const Char *text = (const Char *)(h + 1) + l->off; @@ -520,6 +531,10 @@ static void Tapped(UInt16 row, Coord penX) ShowEarlier(); return; } + if (gLines[row].kind == L_REACT) { + MsgReactWho(gLines[row].msg); + return; + } if (TappedEmoji(row, penX)) return; h = MessagesLock(gLines[row].msg); @@ -538,6 +553,29 @@ static void Tapped(UInt16 row, Coord penX) } } +/* The actions popup for a message (b: its row; NULL from the menu), then what it changed. */ +static void MessageMenu(UInt16 msg, const RectangleType *b) +{ + UInt16 r = MsgMenuOpen(msg, b, ConvoActionList, ConvoGadget, ConvoField); + + if (r == MSG_MENU_REFRESH) { + Refresh(false); + DrawStatus(); + } else if (r == MSG_MENU_TEXT) { + DrawCounter(); + } +} + +static Boolean Hold(UInt16 row, const RectangleType *b, void *ctx) +{ + UInt8 kind = gLines[row].kind; + + if (kind != L_TEXT && kind != L_CHIP && kind != L_REACT) + return false; + MessageMenu(gLines[row].msg, b); + return true; +} + Boolean ConvoFormHandleEvent(EventType *event) { FormType *form = FrmGetActiveForm(); @@ -553,6 +591,7 @@ Boolean ConvoFormHandleEvent(EventType *event) FrmCopyTitle(form, gTitle); TitleStatusReset(); RowListInit(&gList, ConvoGadget, ConvoScroll, LINE_H, DrawLine, NULL, NULL); + gList.hold = Hold; gNewFrom = FirstUnread(); Build(); MessagesMarkRead(&gAppConv); @@ -570,6 +609,7 @@ Boolean ConvoFormHandleEvent(EventType *event) MemPtrFree(gLines); gLines = NULL; } + MsgReactFree(); return false; case frmUpdateEvent: @@ -608,6 +648,16 @@ Boolean ConvoFormHandleEvent(EventType *event) return true; break; + case menuEvent: + if (event->data.menu.itemID == MainMenuMessage) { + UInt16 msg; + + if (gLines && MsgMenuNewest(&msg)) + MessageMenu(msg, NULL); + return true; + } + break; + case keyDownEvent: if (event->data.keyDown.chr == linefeedChr) { /* Graffiti return sends */ Send(form); diff --git a/palm-client/src/main.c b/palm-client/src/main.c index 4c123d2..64e224f 100644 --- a/palm-client/src/main.c +++ b/palm-client/src/main.c @@ -4,6 +4,7 @@ #include "contacts.h" #include "channels.h" #include "messages.h" +#include "reactions.h" #include "app.h" #include "home_form.h" #include "convo_form.h" @@ -304,6 +305,7 @@ UInt32 PilotMain(UInt16 cmd, MemPtr cmdPBP, UInt16 launchFlags) ContactsClose(); ChannelsClose(); MessagesClose(); + ReactionsClose(); UiFontRelease(); ShotCancel(); BgSetAppOpen(false); diff --git a/palm-client/src/messages.c b/palm-client/src/messages.c index db6535d..bb865be 100644 --- a/palm-client/src/messages.c +++ b/palm-client/src/messages.c @@ -7,7 +7,7 @@ #include "channels.h" /* In the second code segment: see sections.h for the rules. */ -static Err Append(const VmMsgHeader *hdr, const Char *text, UInt16 *index) VM_SECT2; +static Err Append(const VmMsgHeader *hdr, const Char *text, const VmMsgExtra *ex, UInt16 *index) VM_SECT2; static void WriteHeader(UInt16 i, const VmMsgHeader *hdr) VM_SECT2; static Boolean ReadHeader(UInt16 i, VmMsgHeader *hdr) VM_SECT2; static void TagChannel(VmConv *conv) VM_SECT2; @@ -58,6 +58,23 @@ void MessagesRelease(UInt16 i) MemHandleUnlock(h); } +Boolean MessagesExtra(UInt16 i, VmMsgExtra *ex) +{ + MemHandle h = gDb ? DmQueryRecord(gDb, i) : NULL; + const VmMsgHeader *p; + Boolean has = false; + + if (!h) + return false; + p = MemHandleLock(h); + if (MemHandleSize(h) >= sizeof(VmMsgHeader) + p->textLen + 1 + sizeof(VmMsgExtra)) { + MemMove(ex, (const UInt8 *)(p + 1) + p->textLen + 1, sizeof(VmMsgExtra)); + has = true; + } + MemHandleUnlock(h); + return has; +} + UInt32 MessagesUniqueId(UInt16 i) { UInt32 id; @@ -86,10 +103,10 @@ static void TagChannel(VmConv *conv) MemMove(conv->key, c.secret, sizeof(conv->key)); } -static Err Append(const VmMsgHeader *hdr, const Char *text, UInt16 *index) +static Err Append(const VmMsgHeader *hdr, const Char *text, const VmMsgExtra *ex, UInt16 *index) { UInt16 i = dmMaxRecordIndex; - UInt32 size = sizeof(VmMsgHeader) + hdr->textLen + 1; + UInt32 size = sizeof(VmMsgHeader) + hdr->textLen + 1 + (ex ? sizeof(VmMsgExtra) : 0); MemHandle h; UInt8 *p; @@ -102,6 +119,8 @@ static Err Append(const VmMsgHeader *hdr, const Char *text, UInt16 *index) DmWrite(p, 0, hdr, sizeof(VmMsgHeader)); DmWrite(p, sizeof(VmMsgHeader), text, hdr->textLen); DmSet(p, sizeof(VmMsgHeader) + hdr->textLen, 1, 0); + if (ex) + DmWrite(p, sizeof(VmMsgHeader) + hdr->textLen + 1, ex, sizeof(VmMsgExtra)); MemHandleUnlock(h); DmReleaseRecord(gDb, i, true); if (index) @@ -109,7 +128,7 @@ static Err Append(const VmMsgHeader *hdr, const Char *text, UInt16 *index) return errNone; } -Err MessagesAddIncoming(const VmMessage *m, UInt32 now) +Err MessagesAddIncoming(const VmMessage *m, const VmMsgExtra *ex, UInt32 now) { VmMsgHeader hdr; Char text[TEXT_MAX]; @@ -150,7 +169,7 @@ Err MessagesAddIncoming(const VmMessage *m, UInt32 now) hdr.timestamp = m->timestamp; hdr.received = now; hdr.textLen = len - skip; - return Append(&hdr, text + skip, NULL); + return Append(&hdr, text + skip, ex, NULL); } Err MessagesAddOutgoing(const VmConv *conv, const Char *text, UInt32 now, UInt16 *index) @@ -169,7 +188,7 @@ Err MessagesAddOutgoing(const VmConv *conv, const Char *text, UInt32 now, UInt16 hdr.timestamp = now; hdr.received = now; hdr.textLen = StrLen(text); - return Append(&hdr, text, index); + return Append(&hdr, text, NULL, index); } /* Rewrites part of a record's header in place. */ diff --git a/palm-client/src/messages.h b/palm-client/src/messages.h index bc16fba..df07e2d 100644 --- a/palm-client/src/messages.h +++ b/palm-client/src/messages.h @@ -53,19 +53,36 @@ typedef struct { /* text follows, textLen bytes plus a NUL */ } VmMsgHeader; +/* + * Kept after a received message's text (records from before it have none): + * its reaction hash, worked out from the UTF-8 as received, and the + * repeaters it came through when the radio's RX log showed them (rxpath.h). + */ +typedef struct { + UInt8 hasHash; + UInt8 hash[5]; /* VM_REACT_HASH_BYTES */ + UInt8 hasPath; + UInt8 hashSize; /* bytes per repeater hash */ + UInt8 pathBytes; /* in path: the first VM_RX_PATH_MAX */ + UInt8 hops; + UInt8 path[VM_RX_PATH_MAX]; +} VmMsgExtra; + Err MessagesOpen(void) VM_SECT2; void MessagesClose(void) VM_SECT2; UInt16 MessagesCount(void) VM_SECT2; /* Locks record i; returns its header (text right after it). Call MessagesRelease(i) when done. */ const VmMsgHeader *MessagesLock(UInt16 i) VM_SECT2; void MessagesRelease(UInt16 i) VM_SECT2; +/* Record i's trailer; false if it has none. */ +Boolean MessagesExtra(UInt16 i, VmMsgExtra *ex) VM_SECT2; /* Record i's unique ID (0 if none): unlike the index, it stays put when old messages drop off. */ UInt32 MessagesUniqueId(UInt16 i) VM_SECT2; Boolean ConvEqual(const VmConv *a, const VmConv *b) VM_SECT2; -/* Stores a received message (converting its UTF-8 text). Returns its index. */ -Err MessagesAddIncoming(const VmMessage *m, UInt32 now) VM_SECT2; +/* Stores a received message (converting its UTF-8 text), with ex after it if given. */ +Err MessagesAddIncoming(const VmMessage *m, const VmMsgExtra *ex, UInt32 now) VM_SECT2; /* Stores an outgoing message as pending; *index is its record. */ Err MessagesAddOutgoing(const VmConv *conv, const Char *text, UInt32 now, UInt16 *index) VM_SECT2; void MessagesSetStatus(UInt16 index, UInt8 status, UInt32 ack, UInt32 ackDeadline) VM_SECT2; diff --git a/palm-client/src/msg_menu.c b/palm-client/src/msg_menu.c new file mode 100644 index 0000000..6020f2f --- /dev/null +++ b/palm-client/src/msg_menu.c @@ -0,0 +1,427 @@ +#include +#include "resources.h" +#include "protocol.h" +#include "session.h" +#include "messages.h" +#include "contacts.h" +#include "reactions.h" +#include "app.h" +#include "ui/text.h" +#include "ui/emoji.h" +#include "msg_menu.h" + +static Int16 Popup(const RectangleType *b, UInt16 listId, UInt16 areaId, Char **items, UInt16 n) VM_SECT3; +static void NameOf(const VmMsgHeader *h, Char *out) VM_SECT3; +static UInt16 React(UInt16 msg) VM_SECT3; +static UInt16 Reply(UInt16 msg, UInt16 fieldId) VM_SECT3; +static void SendDm(const Char *name) VM_SECT3; +static void PathDetails(UInt16 msg) VM_SECT3; +static void AppendClock(Char *out, const Char *label, UInt32 utc) VM_SECT3; +static Boolean Matches(const VmReact *r, const UInt8 *hash, const Char *name, Boolean channel) VM_SECT3; + +#define ACT_REACT 0 +#define ACT_REPLY 1 +#define ACT_DM 2 +#define ACT_PATH 3 +#define ACT_RETRY 4 +#define ACT_MAX 5 +#define LIST_X 28 +#define LIST_H(n) ((n) * 11 + 2) /* stdFont rows and the frame */ +#define QUOTE_CHARS 10 +#define REACT_MAX 60 /* reactions held for one conversation */ +#define POOL_SIZE 400 /* their summaries for the messages shown */ +#define KINDS_MAX 6 /* different emoji in one summary */ + +static VmReact *gReacts = NULL; +static UInt16 gReactCount; +static Char gPool[POOL_SIZE]; +static UInt16 gPoolUsed; + +/* Beside the row (below it, or above near the bottom of the transcript), like Home's. */ +static Int16 Popup(const RectangleType *b, UInt16 listId, UInt16 areaId, Char **items, UInt16 n) +{ + FormType *form = FrmGetActiveForm(); + ListType *list = FrmGetObjectPtr(form, FrmGetObjectIndex(form, listId)); + RectangleType area; + Coord y; + + FrmGetObjectBounds(form, FrmGetObjectIndex(form, areaId), &area); + y = b ? b->topLeft.y + b->extent.y : area.topLeft.y + area.extent.y; + if (y + LIST_H(n) > area.topLeft.y + area.extent.y) + y = (b ? b->topLeft.y : area.topLeft.y + area.extent.y) - LIST_H(n); + LstSetListChoices(list, items, n); + LstSetHeight(list, n); + LstSetPosition(list, LIST_X, y); + LstSetSelection(list, noListSelection); + return LstPopupList(list); +} + +/* The sender a channel reaction names: theirs, or ours for our own message. */ +static void NameOf(const VmMsgHeader *h, Char *out) +{ + if (h->dir == VM_DIR_OUT) + StrNCopy(out, SessionSelf()->name, VM_NAME_SIZE - 1); + else + StrNCopy(out, h->sender, VM_NAME_SIZE - 1); + out[VM_NAME_SIZE - 1] = 0; +} + +UInt16 MsgMenuOpen(UInt16 msg, const RectangleType *b, UInt16 listId, UInt16 areaId, UInt16 fieldId) +{ + const VmMsgHeader *h = MessagesLock(msg); + Char *items[ACT_MAX]; + UInt8 acts[ACT_MAX]; + UInt16 n = 0; + Int16 pick; + Boolean mine, channel, room, failed; + Char name[VM_NAME_SIZE]; + + if (!h) + return MSG_MENU_NONE; + mine = h->dir == VM_DIR_OUT; + channel = h->conv.type == VM_CONV_CHANNEL; + room = !channel && !mine && h->sender[0]; /* a room post: rooms have no reactions */ + failed = mine && h->status == VM_ST_FAILED; + NameOf(h, name); + MessagesRelease(msg); + + if (!mine && !room) { + items[n] = "React..."; + acts[n++] = ACT_REACT; + } + if (!mine) { + items[n] = "Reply"; + acts[n++] = ACT_REPLY; + } + if (!mine && channel && name[0]) { + items[n] = "Send DM"; + acts[n++] = ACT_DM; + } + items[n] = "Path Details"; + acts[n++] = ACT_PATH; + if (failed) { + items[n] = "Retry"; + acts[n++] = ACT_RETRY; + } + pick = Popup(b, listId, areaId, items, n); + if (pick < 0 || pick >= (Int16)n) + return MSG_MENU_NONE; + switch (acts[pick]) { + case ACT_REACT: return React(msg); + case ACT_REPLY: return Reply(msg, fieldId); + case ACT_DM: SendDm(name); break; + case ACT_PATH: PathDetails(msg); break; + case ACT_RETRY: + SessionRetry(msg); + return MSG_MENU_REFRESH; + } + return MSG_MENU_NONE; +} + +Boolean MsgMenuNewest(UInt16 *msg) +{ + UInt16 i; + const VmMsgHeader *h; + Boolean found = false; + + for (i = MessagesCount(); i > 0 && !found; i--) { + h = MessagesLock(i - 1); + if (!h) + continue; + if (h->dir == VM_DIR_IN && ConvEqual(&h->conv, &gAppConv)) { + *msg = i - 1; + found = true; + } + MessagesRelease(i - 1); + } + return found; +} + +static UInt16 React(UInt16 msg) +{ + const VmMsgHeader *h; + UInt8 hash[5]; + Char name[VM_NAME_SIZE], glyph, text[48]; + VmConv conv; + Err err; + + if (!SessionIsConnected()) { + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first.", "", ""); + return MSG_MENU_NONE; + } + if (!MessageHash(msg, hash)) { + FrmCustomAlert(SettingsErrorAlert, "Can't react to this message.", "", ""); + return MSG_MENU_NONE; + } + glyph = EmojiPick(); + if (!glyph) + return MSG_MENU_NONE; + h = MessagesLock(msg); + if (!h) + return MSG_MENU_NONE; + conv = h->conv; + NameOf(h, name); + MessagesRelease(msg); + err = SessionSendReaction(&conv, hash, conv.type == VM_CONV_CHANNEL ? name : "", glyph); + if (err != errNone) { + AppErrorText(err, text); + FrmCustomAlert(SettingsErrorAlert, text, "", ""); + } + return MSG_MENU_REFRESH; +} + +/* '@[Name] "first ten..' at the cursor; no mention in a DM, where it's clear who it's for. */ +static UInt16 Reply(UInt16 msg, UInt16 fieldId) +{ + FormType *form = FrmGetActiveForm(); + FieldType *field = FrmGetObjectPtr(form, FrmGetObjectIndex(form, fieldId)); + const VmMsgHeader *h = MessagesLock(msg); + const Char *t; + Char buf[VM_NAME_SIZE + QUOTE_CHARS + 12]; + UInt16 n = 0, i; + + if (!h) + return MSG_MENU_NONE; + t = (const Char *)(h + 1); + if (h->conv.type == VM_CONV_CHANNEL && h->sender[0]) { + StrPrintF(buf, "@[%s] ", h->sender); + n = StrLen(buf); + } + buf[n++] = '"'; + for (i = 0; i < h->textLen && i < QUOTE_CHARS; i++) + buf[n++] = (t[i] == '\n' || t[i] == '\t') ? ' ' : t[i]; + if (h->textLen > QUOTE_CHARS) { + buf[n++] = '.'; + buf[n++] = '.'; + } + buf[n++] = '"'; + buf[n++] = ' '; + buf[n] = 0; + MessagesRelease(msg); + FrmSetFocus(form, FrmGetObjectIndex(form, fieldId)); + FldInsert(field, buf, n); + return MSG_MENU_TEXT; +} + +static void SendDm(const Char *name) +{ + VmContact c; + VmConv conv; + Char msg[VM_NAME_SIZE + 48]; + + if (!ContactsFindByName(name, &c)) { + StrPrintF(msg, "No contact named %s yet. It's added once their advert is heard.", name); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + return; + } + MemSet(&conv, sizeof(conv), 0); + conv.type = VM_CONV_DIRECT; + MemMove(conv.key, c.pubKey, sizeof(conv.key)); + AppOpenConversation(&conv); +} + +/* "label HH:MM:SS" in local time, and the date if it isn't today. */ +static void AppendClock(Char *out, const Char *label, UInt32 utc) +{ + DateTimeType dt, now; + + TimSecondsToDateTime(SessionLocalPalm(utc), &dt); + TimSecondsToDateTime(SessionLocalPalm(SessionNow()), &now); + out += StrLen(out); + if (dt.year != now.year || dt.month != now.month || dt.day != now.day) + StrPrintF(out, "%s %u/%u %02u:%02u:%02u", label, dt.month, dt.day, dt.hour, dt.minute, dt.second); + else + StrPrintF(out, "%s %02u:%02u:%02u", label, dt.hour, dt.minute, dt.second); +} + +static void PathDetails(UInt16 msg) +{ + const VmMsgHeader *h = MessagesLock(msg); + VmMsgHeader hdr; + VmMsgExtra ex; + VmContact c; + Boolean hasEx; + Char text[300], hex[8], snr[8]; + UInt16 i, hops, len; + + if (!h) + return; + hdr = *h; + MessagesRelease(msg); + hasEx = MessagesExtra(msg, &ex); + text[0] = 0; + if (hdr.dir == VM_DIR_OUT) { + AppendClock(text, "Sent", hdr.timestamp); + StrCat(text, "\n"); + switch (hdr.status) { + case VM_ST_PENDING: StrCat(text, "Waiting for the radio"); break; + case VM_ST_SENT: StrCat(text, hdr.conv.type == VM_CONV_CHANNEL ? "Sent (channels report no delivery)" : "Sent, not confirmed yet"); break; + case VM_ST_ACKED: StrCat(text, "Delivered"); break; + case VM_ST_FAILED: StrCat(text, "Not delivered"); break; + } + FrmCustomAlert(PathAlert, text, "", ""); + return; + } + AppendClock(text, "Sent", hdr.timestamp); /* the sender's clock */ + StrCat(text, "\n"); + AppendClock(text, "Got", hdr.received); + StrCat(text, "\n"); + hops = VM_PATH_HOPS(hdr.pathLen); + if (hdr.pathLen == VM_PATH_UNKNOWN) + StrCat(text, "Direct route"); + else if (hops == 0) + StrCat(text, "Heard directly (no repeaters)"); + else + StrPrintF(text + StrLen(text), "Flood, %u hop%s", hops, hops == 1 ? "" : "s"); + TxtFormatSnr(snr, hdr.snrQuarterDb); + StrPrintF(text + StrLen(text), ", SNR %s\n", snr); + if (hdr.pathLen == VM_PATH_UNKNOWN || hops == 0) { + /* nothing more to show */ + } else if (!hasEx || !ex.hasPath || ex.hashSize == 0 || ex.hashSize > 3) { + StrCat(text, "Repeaters not recorded"); + } else { + StrCat(text, "Via"); + for (i = 0; i + ex.hashSize <= ex.pathBytes; i += ex.hashSize) { + if (StrLen(text) > sizeof(text) - 80) { /* room for one more entry and the end */ + StrCat(text, ", ..."); + break; + } + TxtHex(ex.path + i, ex.hashSize, hex); + StrCat(text, i ? ", " : " "); + StrCat(text, hex); + if (ContactsFindByPrefixN(ex.path + i, ex.hashSize, &c)) { + len = StrLen(text); + StrCat(text, " "); + StrNCat(text, c.name, len + 1 + 12 + 1); /* up to 12 of the name */ + } + } + if (ex.hops * ex.hashSize > ex.pathBytes) + StrPrintF(text + StrLen(text), " +%u more", ex.hops - ex.pathBytes / ex.hashSize); + } + FrmCustomAlert(PathAlert, text, "", ""); +} + +void MsgReactLoad(void) +{ + if (!gReacts) + gReacts = MemPtrNew(sizeof(VmReact) * REACT_MAX); + gReactCount = gReacts ? ReactionsFor(&gAppConv, gReacts, REACT_MAX) : 0; + gPoolUsed = 0; +} + +void MsgReactFree(void) +{ + if (gReacts) { + MemPtrFree(gReacts); + gReacts = NULL; + } + gReactCount = 0; +} + +static Boolean Matches(const VmReact *r, const UInt8 *hash, const Char *name, Boolean channel) +{ + return MemCmp(r->hash, hash, sizeof(r->hash)) == 0 && (!channel || StrCompare(r->target, name) == 0); +} + +Int16 MsgReactSummary(UInt16 msg, UInt16 *len) +{ + const VmMsgHeader *h; + UInt8 hash[5]; + Char name[VM_NAME_SIZE], kinds[KINDS_MAX], buf[KINDS_MAX * 5]; + UInt16 counts[KINDS_MAX], nKinds = 0, i, k, n = 0; + Boolean channel; + + *len = 0; + if (gReactCount == 0 || !MessageHash(msg, hash)) + return -1; + h = MessagesLock(msg); + if (!h) + return -1; + channel = h->conv.type == VM_CONV_CHANNEL; + NameOf(h, name); + MessagesRelease(msg); + for (i = 0; i < gReactCount; i++) { + if (!Matches(&gReacts[i], hash, name, channel)) + continue; + for (k = 0; k < nKinds && kinds[k] != gReacts[i].glyph; k++) + ; + if (k == nKinds) { + if (nKinds == KINDS_MAX) + continue; + kinds[nKinds] = gReacts[i].glyph; + counts[nKinds++] = 0; + } + counts[k]++; + } + for (k = 0; k < nKinds; k++) { + if (k) + buf[n++] = ' '; + buf[n++] = kinds[k]; + if (counts[k] > 1) { + StrPrintF(buf + n, "%u", counts[k]); + n += StrLen(buf + n); + } + } + if (n == 0 || gPoolUsed + n > POOL_SIZE) + return -1; + MemMove(gPool + gPoolUsed, buf, n); + gPoolUsed += n; + *len = n; + return (Int16)(gPoolUsed - n); +} + +const Char *MsgReactText(UInt16 off) +{ + return gPool + off; +} + +/* "Thumbs up: Bob, you" per emoji. */ +void MsgReactWho(UInt16 msg) +{ + const VmMsgHeader *h; + UInt8 hash[5]; + Char name[VM_NAME_SIZE], text[300], label[EMOJI_NAME_SIZE], done[KINDS_MAX]; + UInt16 i, j, nDone = 0, k; + Boolean channel, first; + Char glyph; + + if (!MessageHash(msg, hash)) + return; + h = MessagesLock(msg); + if (!h) + return; + channel = h->conv.type == VM_CONV_CHANNEL; + NameOf(h, name); + MessagesRelease(msg); + text[0] = 0; + for (i = 0; i < gReactCount && nDone < KINDS_MAX; i++) { + if (!Matches(&gReacts[i], hash, name, channel)) + continue; + glyph = gReacts[i].glyph; + for (k = 0; k < nDone && done[k] != glyph; k++) + ; + if (k < nDone) + continue; + done[nDone++] = glyph; + if (!EmojiName(glyph, label)) + StrCopy(label, "Emoji"); + if (text[0]) + StrCat(text, "\n"); + StrCat(text, label); + StrCat(text, ":"); + first = true; + for (j = i; j < gReactCount; j++) { + const VmReact *r = &gReacts[j]; + + if (r->glyph != glyph || !Matches(r, hash, name, channel)) + continue; + if (StrLen(text) + VM_NAME_SIZE + 3 >= sizeof(text)) + break; + StrCat(text, first ? " " : ", "); + StrCat(text, r->mine ? "you" : r->from[0] ? r->from : "them"); + first = false; + } + } + if (text[0]) + FrmCustomAlert(ReactionsAlert, text, "", ""); +} diff --git a/palm-client/src/msg_menu.h b/palm-client/src/msg_menu.h new file mode 100644 index 0000000..fbc2e80 --- /dev/null +++ b/palm-client/src/msg_menu.h @@ -0,0 +1,37 @@ +/* + * What can be done with one message in a conversation (tap and hold it, or + * Options > Message Actions): react with an emoji, reply quoting it, send + * its sender a DM, see the path it came by. Also the reactions shown under + * messages: load a conversation's once per rebuild (MsgReactLoad), then ask + * for each message's summary. + */ +#ifndef VM_MSG_MENU_H +#define VM_MSG_MENU_H + +#include +#include "sections.h" /* this module is in the third code segment */ + +#define MSG_MENU_NONE 0 +#define MSG_MENU_REFRESH 1 /* the transcript changed (a reaction, a retry): rebuild it */ +#define MSG_MENU_TEXT 2 /* the compose field changed */ + +/* + * The actions popup for message msg, beside its row b (b NULL: over the + * transcript's bottom); list and area are the form's popup list and transcript gadget. + */ +UInt16 MsgMenuOpen(UInt16 msg, const RectangleType *b, UInt16 listId, UInt16 areaId, UInt16 fieldId) VM_SECT3; +/* The newest message in the conversation from someone else, for the menu command; false if none. */ +Boolean MsgMenuNewest(UInt16 *msg) VM_SECT3; + +void MsgReactLoad(void) VM_SECT3; +void MsgReactFree(void) VM_SECT3; +/* + * Message msg's reactions as glyphs and counts ("2 "), kept + * until the next MsgReactLoad: returns where it is for MsgReactText, -1 if none. + */ +Int16 MsgReactSummary(UInt16 msg, UInt16 *len) VM_SECT3; +const Char *MsgReactText(UInt16 off) VM_SECT3; +/* Who reacted to msg, in an alert. */ +void MsgReactWho(UInt16 msg) VM_SECT3; + +#endif diff --git a/palm-client/src/protocol.c b/palm-client/src/protocol.c index 961a51a..6739487 100644 --- a/palm-client/src/protocol.c +++ b/palm-client/src/protocol.c @@ -658,11 +658,17 @@ Boolean VmParseRxLog(const UInt8 *p, UInt16 len, VmRxLog *out) return 0; out->isAdvert = 0; out->fromLen = 0; + out->flood = route == 1 || route == 0; + out->hashSize = size; + out->pathBytes = (UInt8)(pathBytes > VM_RX_PATH_MAX ? VM_RX_PATH_MAX : pathBytes); + CopyBytes(out->path, p + i, out->pathBytes); + out->payloadLen = (UInt8)(len - i - pathBytes > 8 ? 8 : len - i - pathBytes); + CopyBytes(out->payload, p + i + pathBytes, out->payloadLen); if (out->payloadType == VM_PAYLOAD_ADVERT && len >= i + pathBytes + 6) { out->isAdvert = 1; CopyBytes(out->advertKey, p + i + pathBytes, 6); } - if (route == 1 || route == 0) { /* flood: the path is who relayed it, in order */ + if (out->flood) { /* the path is who relayed it, in order */ if (out->hops > 0) { out->fromLen = size; CopyBytes(out->from, p + i + pathBytes - size, size); diff --git a/palm-client/src/protocol.h b/palm-client/src/protocol.h index d8de9fe..fe2f718 100644 --- a/palm-client/src/protocol.h +++ b/palm-client/src/protocol.h @@ -274,8 +274,17 @@ typedef struct { UInt8 advertKey[6]; /* the advertiser (any hop count), if isAdvert */ UInt8 fromLen; /* 0 = not known */ UInt8 from[6]; + Boolean flood; + UInt8 hashSize; /* bytes per path hash */ + UInt8 pathBytes; /* kept in path: the first VM_RX_PATH_MAX */ + UInt8 path[16]; /* flood: the repeaters it came through, first to last */ + UInt8 payloadLen; /* kept in payload, up to 8: tells copies of one packet apart */ + UInt8 payload[8]; } VmRxLog; -#define VM_PAYLOAD_ADVERT 4 +#define VM_RX_PATH_MAX 16 +#define VM_PAYLOAD_TXT 2 +#define VM_PAYLOAD_ADVERT 4 +#define VM_PAYLOAD_GRP_TXT 5 Boolean VmParseRxLog(const UInt8 *p, UInt16 len, VmRxLog *out) VM_SECT2; /* PUSH_LOGIN_SUCCESS / PUSH_LOGIN_FAIL: which node (key prefix) and, on success, whether we're admin. */ diff --git a/palm-client/src/reaction_fmt.c b/palm-client/src/reaction_fmt.c new file mode 100644 index 0000000..6dcace0 --- /dev/null +++ b/palm-client/src/reaction_fmt.c @@ -0,0 +1,279 @@ +#include "reaction_fmt.h" +#include "sha256.h" + +static Char B32Char(UInt8 v) VM_SECT4; +static Int16 B32Value(Char c) VM_SECT4; +static UInt16 Utf8Next(const UInt8 *s, UInt16 len, UInt16 i, UInt32 *cp) VM_SECT4; +static Boolean EmojiBase(UInt32 cp) VM_SECT4; +static Boolean OneEmoji(const UInt8 *s, UInt16 len) VM_SECT4; +static Boolean HasMention(const UInt8 *s, UInt16 len) VM_SECT4; + +/* Crockford's alphabet, 0-9 then a-z without i, l, o, u: worked out, not a table (sections.h). */ +static Char B32Char(UInt8 v) +{ + Char c; + + if (v < 10) + return (Char)('0' + v); + for (c = 'a', v -= 10; ; c++) { + if (c == 'i' || c == 'l' || c == 'o' || c == 'u') + continue; + if (v-- == 0) + return c; + } +} + +/* Either case; o reads as 0 and i, l as 1. -1 if it isn't one. */ +static Int16 B32Value(Char c) +{ + Int16 v = 10; + Char k; + + if (c >= '0' && c <= '9') + return c - '0'; + if (c >= 'A' && c <= 'Z') + c = (Char)(c - 'A' + 'a'); + if (c == 'o') + return 0; + if (c == 'i' || c == 'l') + return 1; + if (c < 'a' || c > 'z' || c == 'u') + return -1; + for (k = 'a'; k < c; k++) + if (k != 'i' && k != 'l' && k != 'o' && k != 'u') + v++; + return v; +} + +void VmReactHash(const UInt8 *text, UInt16 len, UInt32 timestamp, UInt8 hash[VM_REACT_HASH_BYTES]) +{ + UInt8 buf[VM_MAX_FRAME + 4], digest[32]; + UInt16 i; + + if (len > VM_MAX_FRAME) + len = VM_MAX_FRAME; + for (i = 0; i < len; i++) + buf[i] = text[i]; + buf[len] = (UInt8)timestamp; + buf[len + 1] = (UInt8)(timestamp >> 8); + buf[len + 2] = (UInt8)(timestamp >> 16); + buf[len + 3] = (UInt8)(timestamp >> 24); + VmSha256(buf, (UInt32)len + 4, digest); + for (i = 0; i < VM_REACT_HASH_BYTES; i++) + hash[i] = digest[i]; +} + +/* 40 bits, 5 at a time from the top. */ +void VmReactHashText(const UInt8 hash[VM_REACT_HASH_BYTES], Char out[VM_REACT_HASH_LEN + 1]) +{ + UInt16 i, bit, v, b; + + for (i = 0; i < VM_REACT_HASH_LEN; i++) { + v = 0; + for (b = 0; b < 5; b++) { + bit = i * 5 + b; + v = (UInt16)((v << 1) | ((hash[bit / 8] >> (7 - bit % 8)) & 1)); + } + out[i] = B32Char((UInt8)v); + } + out[VM_REACT_HASH_LEN] = 0; +} + +const UInt8 *VmReactChannelBody(const UInt8 *text, UInt16 len, UInt16 *bodyLen) +{ + UInt16 i, start = 0, end = len; + + for (i = 0; i < len; i++) { + if (text[i] == ':') { + start = i + 1; + break; + } + } + while (start < end && (text[start] == ' ' || text[start] == '\t')) + start++; + while (end > start && (text[end - 1] == ' ' || text[end - 1] == '\t')) + end--; + *bodyLen = end - start; + return text + start; +} + +UInt16 VmReactBuild(Boolean isChannel, const UInt8 *target, UInt16 targetLen, + const UInt8 *emoji, UInt16 emojiLen, const UInt8 hash[VM_REACT_HASH_BYTES], + UInt8 *out, UInt16 outSize) +{ + Char h[VM_REACT_HASH_LEN + 1]; + UInt16 n = 0, i; + + if ((isChannel ? targetLen + 3 : 0) + emojiLen + 1 + VM_REACT_HASH_LEN > outSize) + return 0; + if (isChannel) { + out[n++] = '@'; + out[n++] = '['; + for (i = 0; i < targetLen; i++) + out[n++] = target[i]; + out[n++] = ']'; + } + for (i = 0; i < emojiLen; i++) + out[n++] = emoji[i]; + out[n++] = '\n'; + VmReactHashText(hash, h); + for (i = 0; i < VM_REACT_HASH_LEN; i++) + out[n++] = (UInt8)h[i]; + return n; +} + +/* Decodes the code point at i; returns the index after it, or 0 if it's malformed. */ +static UInt16 Utf8Next(const UInt8 *s, UInt16 len, UInt16 i, UInt32 *cp) +{ + UInt8 c = s[i]; + UInt16 n, k; + + if (c < 0x80) { + *cp = c; + return i + 1; + } + if ((c & 0xE0) == 0xC0) { + n = 1; + *cp = c & 0x1F; + } else if ((c & 0xF0) == 0xE0) { + n = 2; + *cp = c & 0x0F; + } else if ((c & 0xF8) == 0xF0) { + n = 3; + *cp = c & 0x07; + } else { + return 0; + } + for (k = 1; k <= n; k++) { + if (i + k >= len || (s[i + k] & 0xC0) != 0x80) + return 0; + *cp = (*cp << 6) | (s[i + k] & 0x3F); + } + return i + n + 1; +} + +/* A code point that's an emoji on its own: pictographs, symbols, dingbats, arrows. */ +static Boolean EmojiBase(UInt32 cp) +{ + return (cp >= 0x1F000 && cp <= 0x1FAFF) || (cp >= 0x2190 && cp <= 0x2BFF) || + cp == 0x3030 || cp == 0x303D || cp == 0x3297 || cp == 0x3299; +} + +/* + * One emoji grapheme, near enough: an emoji code point, then only variation + * selectors, skin tones, a keycap mark, tags, a second flag letter, or a + * joiner and another emoji. A keycap (1, #, *) or (c) / (r) only counts with + * the selector or keycap mark after it. Text that merely starts with an emoji + * isn't one. + */ +static Boolean OneEmoji(const UInt8 *s, UInt16 len) +{ + UInt32 cp, first; + UInt16 i, next, n = 0; + Boolean flag, joined = 0, plainBase; + + if (len == 0 || len > VM_REACT_EMOJI_MAX) + return 0; + i = Utf8Next(s, len, 0, &first); + if (i == 0) + return 0; + flag = first >= 0x1F1E6 && first <= 0x1F1FF; + plainBase = (first >= '0' && first <= '9') || first == '#' || first == '*' || + first == 0xA9 || first == 0xAE; + if (!EmojiBase(first) && !plainBase) + return 0; + while (i < len) { + next = Utf8Next(s, len, i, &cp); + if (next == 0) + return 0; + n++; + if (joined) { + if (!EmojiBase(cp)) + return 0; + joined = 0; + } else if (cp == 0x200D) { + joined = 1; + } else if (flag && n == 1 && cp >= 0x1F1E6 && cp <= 0x1F1FF) { + /* the flag's second letter */ + } else if (!(cp == 0xFE0F || cp == 0xFE0E || cp == 0x20E3 || + (cp >= 0x1F3FB && cp <= 0x1F3FF) || (cp >= 0xE0020 && cp <= 0xE007F))) { + return 0; + } + i = next; + } + if (joined) + return 0; + return !plainBase || n > 0; +} + +static Boolean HasMention(const UInt8 *s, UInt16 len) +{ + UInt16 i; + + for (i = 0; i + 1 < len; i++) + if (s[i] == '@' && s[i + 1] == '[') + return 1; + return 0; +} + +Boolean VmReactParse(Boolean isChannel, const UInt8 *text, UInt16 len, VmReaction *r) +{ + UInt16 nl, i, head; + UInt32 bits; + Int16 v; + UInt16 bit; + + /* the hash after the last line break: exactly 8 characters */ + for (nl = len; nl > 0 && text[nl - 1] != '\n'; nl--) + ; + if (nl == 0 || len - nl != VM_REACT_HASH_LEN) + return 0; + head = nl - 1; + for (i = 0; i < VM_REACT_HASH_BYTES; i++) + r->hash[i] = 0; + for (i = 0; i < VM_REACT_HASH_LEN; i++) { + v = B32Value((Char)text[nl + i]); + if (v < 0) + return 0; + for (bits = 0; bits < 5; bits++) { + bit = (UInt16)(i * 5 + bits); + if (v & (0x10 >> bits)) + r->hash[bit / 8] |= (UInt8)(0x80 >> (bit % 8)); + } + } + r->target = 0; + r->targetLen = 0; + if (!isChannel) { + if (HasMention(text, head)) + return 0; + r->emoji = text; + r->emojiLen = head; + return OneEmoji(r->emoji, r->emojiLen); + } + if (head >= 2 && text[0] == '@' && text[1] == '[') { + for (i = 2; i < head && text[i] != ']'; i++) + ; + if (i >= head) + return 0; + r->target = text + 2; + r->targetLen = i - 2; + r->emoji = text + i + 1; + r->emojiLen = head - (i + 1); + } else { + /* before MC1 1.4.1: the emoji, then the mention ending the line */ + for (i = 0; i + 1 < head && !(text[i] == '@' && text[i + 1] == '['); i++) + ; + if (i + 1 >= head || text[head - 1] != ']') + return 0; + r->emoji = text; + r->emojiLen = i; + r->target = text + i + 2; + r->targetLen = head - 1 - (i + 2); + } + if (r->targetLen == 0) + return 0; + for (i = 0; i < r->targetLen; i++) + if (r->target[i] == ']' || r->target[i] == '\n') + return 0; + return OneEmoji(r->emoji, r->emojiLen); +} diff --git a/palm-client/src/reaction_fmt.h b/palm-client/src/reaction_fmt.h new file mode 100644 index 0000000..2d86bfc --- /dev/null +++ b/palm-client/src/reaction_fmt.h @@ -0,0 +1,52 @@ +/* + * Emoji reactions (tapbacks) in MeshCore One's format, so MC1 and the apps + * that follow it (MeshMonitor, ...) show ours and we show theirs. MeshCore + * has no reaction packet: a reaction is an ordinary text message + * + * channel @[TargetSender]\n (before MC1 1.4.1: @[TargetSender]\n) + * DM \n + * + * where is one emoji (one grapheme) and names the message + * reacted to: Crockford Base32 (lowercase) of the first 5 bytes of + * SHA-256(UTF-8 text || sender's timestamp as a little-endian UInt32). A + * channel message's text is its body after the "Name:" prefix, spaces and + * tabs trimmed; a DM's is as sent. Spec: MeshCoreOne docs/Reactions.md. + * + * Works on the UTF-8 text as it is on the air: the Visor's character set + * loses emoji detail, so hash and parse before converting. + * Plain C with no Palm OS calls, so it also builds on the host for tests. + */ +#ifndef VM_REACTION_FMT_H +#define VM_REACTION_FMT_H + +#include "protocol.h" /* this module is in the fourth code segment */ + +#define VM_REACT_HASH_LEN 8 +#define VM_REACT_HASH_BYTES 5 +#define VM_REACT_EMOJI_MAX 32 /* UTF-8 bytes */ + +typedef struct { + const UInt8 *target; /* channel: the sender reacted to (not NUL-terminated) */ + UInt16 targetLen; + const UInt8 *emoji; + UInt16 emojiLen; + UInt8 hash[VM_REACT_HASH_BYTES]; +} VmReaction; + +/* The message's hash, as the 5 bytes the Base32 text encodes. */ +void VmReactHash(const UInt8 *text, UInt16 len, UInt32 timestamp, UInt8 hash[VM_REACT_HASH_BYTES]) VM_SECT4; +/* The 8 lowercase characters for a hash, NUL-terminated. */ +void VmReactHashText(const UInt8 hash[VM_REACT_HASH_BYTES], Char out[VM_REACT_HASH_LEN + 1]) VM_SECT4; +/* A channel message's hashed body: after the first ':', spaces and tabs trimmed (all of it without a ':'). */ +const UInt8 *VmReactChannelBody(const UInt8 *text, UInt16 len, UInt16 *bodyLen) VM_SECT4; +/* Builds a reaction's text (target is ignored for a DM). Returns its length, 0 if it doesn't fit. */ +UInt16 VmReactBuild(Boolean isChannel, const UInt8 *target, UInt16 targetLen, + const UInt8 *emoji, UInt16 emojiLen, const UInt8 hash[VM_REACT_HASH_BYTES], + UInt8 *out, UInt16 outSize) VM_SECT4; +/* + * Whether text is a reaction; a channel message's text is its body (after + * "Name: "). Fills r with pointers into text. + */ +Boolean VmReactParse(Boolean isChannel, const UInt8 *text, UInt16 len, VmReaction *r) VM_SECT4; + +#endif diff --git a/palm-client/src/reactions.c b/palm-client/src/reactions.c new file mode 100644 index 0000000..60f1c75 --- /dev/null +++ b/palm-client/src/reactions.c @@ -0,0 +1,227 @@ +#include +#include "db.h" +#include "channels.h" +#include "reaction_fmt.h" +#include "rxpath.h" +#include "ui/text.h" +#include "ui/glyphs.h" +#include "reactions.h" + +static Err Open(void) VM_SECT4; +static void ChannelKey(VmConv *conv) VM_SECT4; +static Boolean SameConv(const VmConv *a, const VmConv *b) VM_SECT4; +static void Store(const VmReact *r) VM_SECT4; +static Char GlyphOf(const UInt8 *emoji, UInt16 len) VM_SECT4; + +static Char DB_NAME[] = "VisorMeshReactions"; +#define DB_TYPE 'reac' + +static DmOpenRef gDb = 0; + +static Err Open(void) +{ + return gDb ? errNone : DbOpen(DB_NAME, DB_TYPE, &gDb); +} + +void ReactionsClose(void) +{ + if (gDb) { + DmCloseDatabase(gDb); + gDb = 0; + } +} + +/* A channel conversation's secret prefix, so reactions follow the channel when its slot changes. */ +static void ChannelKey(VmConv *conv) +{ + VmChannel c; + + MemSet(conv->key, sizeof(conv->key), 0); + if (ChannelsFindSlot(conv->channel, &c)) + MemMove(conv->key, c.secret, sizeof(conv->key)); +} + +static Boolean SameConv(const VmConv *a, const VmConv *b) +{ + return a->type == b->type && MemCmp(a->key, b->key, sizeof(a->key)) == 0; +} + +/* Adds r unless it's already there (a reaction can be heard more than once). */ +static void Store(const VmReact *r) +{ + UInt16 i, n, at = dmMaxRecordIndex; + MemHandle h; + const VmReact *p; + Boolean dup = false; + + if (Open() != errNone) + return; + n = DmNumRecords(gDb); + for (i = 0; i < n && !dup; i++) { + h = DmQueryRecord(gDb, i); + if (!h) + continue; + p = MemHandleLock(h); + dup = SameConv(&p->conv, &r->conv) && MemCmp(p->hash, r->hash, sizeof(r->hash)) == 0 && + p->glyph == r->glyph && p->mine == r->mine && StrCompare(p->from, r->from) == 0; + MemHandleUnlock(h); + } + if (dup) + return; + while (DmNumRecords(gDb) >= VM_MAX_REACTIONS) + DmRemoveRecord(gDb, 0); + h = DmNewRecord(gDb, &at, sizeof(VmReact)); + if (!h) + return; + DmWrite(MemHandleLock(h), 0, r, sizeof(VmReact)); + MemHandleUnlock(h); + DmReleaseRecord(gDb, at, true); +} + +/* The emoji as the Visor shows it: one glyph, the generic smiley for ones the font lacks. */ +static Char GlyphOf(const UInt8 *emoji, UInt16 len) +{ + Char buf[8]; + UInt16 n = TxtUtf8ToPalm(emoji, len, buf, sizeof(buf)); + + return n ? buf[0] : GLYPH_EMOJI; +} + +Boolean ReactionsTake(const VmMessage *m, UInt32 now) +{ + VmReaction rx; + VmReact r; + const UInt8 *body = m->text; + UInt16 bodyLen = m->textLen, n; + + if (m->txtType != VM_TXT_TYPE_PLAIN || m->hasSigner) /* rooms have no reactions */ + return false; + if (m->isChannel) + body = VmReactChannelBody(m->text, m->textLen, &bodyLen); + if (!VmReactParse(m->isChannel, body, bodyLen, &rx)) + return false; + MemSet(&r, sizeof(r), 0); + if (m->isChannel) { + r.conv.type = VM_CONV_CHANNEL; + r.conv.channel = m->channelIdx; + ChannelKey(&r.conv); + n = TxtUtf8ToPalm(rx.target, rx.targetLen, r.target, sizeof(r.target) - 1); + r.target[n] = 0; + /* the reactor: the "Name" before the ':' */ + for (n = 0; n < m->textLen && m->text[n] != ':'; n++) + ; + n = TxtUtf8ToPalm(m->text, n, r.from, sizeof(r.from) - 1); + r.from[n] = 0; + } else { + r.conv.type = VM_CONV_DIRECT; + MemMove(r.conv.key, m->senderPrefix, sizeof(r.conv.key)); + } + MemMove(r.hash, rx.hash, sizeof(r.hash)); + r.glyph = GlyphOf(rx.emoji, rx.emojiLen); + r.time = now; + Store(&r); + return true; +} + +void ReactionsAddMine(const VmConv *conv, const UInt8 *hash, const Char *target, Char glyph, UInt32 now) +{ + VmReact r; + + MemSet(&r, sizeof(r), 0); + r.conv = *conv; + if (conv->type == VM_CONV_CHANNEL) + ChannelKey(&r.conv); + MemMove(r.hash, hash, sizeof(r.hash)); + r.mine = 1; + r.glyph = glyph; + StrNCopy(r.target, target, sizeof(r.target) - 1); + r.time = now; + Store(&r); +} + +UInt16 ReactionsFor(const VmConv *conv, VmReact *out, UInt16 max) +{ + VmConv want = *conv; + UInt16 i, n, found = 0; + MemHandle h; + const VmReact *p; + + if (Open() != errNone) + return 0; + if (want.type == VM_CONV_CHANNEL) + ChannelKey(&want); + n = DmNumRecords(gDb); + /* the newest max, oldest first */ + for (i = n; i > 0 && found < max; i--) { + h = DmQueryRecord(gDb, i - 1); + if (!h) + continue; + p = MemHandleLock(h); + if (SameConv(&p->conv, &want)) + out[found++] = *p; + MemHandleUnlock(h); + } + for (i = 0; i < found / 2; i++) { + VmReact t = out[i]; + + out[i] = out[found - 1 - i]; + out[found - 1 - i] = t; + } + return found; +} + +Boolean MessageHash(UInt16 index, UInt8 *hash) +{ + VmMsgExtra ex; + const VmMsgHeader *h; + UInt8 utf8[VM_MAX_FRAME]; + UInt16 n, len, start = 0; + Boolean channel; + UInt32 ts; + + if (MessagesExtra(index, &ex)) { + if (!ex.hasHash) + return false; + MemMove(hash, ex.hash, sizeof(ex.hash)); + return true; + } + h = MessagesLock(index); + if (!h) + return false; + len = h->textLen; + n = TxtPalmToUtf8((const Char *)(h + 1), len, utf8, sizeof(utf8)); + channel = h->conv.type == VM_CONV_CHANNEL; + ts = h->timestamp; + MessagesRelease(index); + if (n == 0 && len) + return false; + /* a channel message is stored without its "Name: ", so the hashed body is the text, trimmed */ + if (channel) { + while (start < n && (utf8[start] == ' ' || utf8[start] == '\t')) + start++; + while (n > start && (utf8[n - 1] == ' ' || utf8[n - 1] == '\t')) + n--; + } + VmReactHash(utf8 + start, n - start, ts, hash); + return true; +} + +void MessageExtraFor(const VmMessage *m, UInt32 now, VmMsgExtra *ex) +{ + const UInt8 *body = m->text; + UInt16 bodyLen = m->textLen; + VmRxLog rx; + + MemSet(ex, sizeof(*ex), 0); + if (m->isChannel) + body = VmReactChannelBody(m->text, m->textLen, &bodyLen); + VmReactHash(body, bodyLen, m->timestamp, ex->hash); + ex->hasHash = 1; + if (RxPathTake(m->isChannel, m->pathLen, m->isChannel ? NULL : m->senderPrefix, now, &rx)) { + ex->hasPath = 1; + ex->hashSize = rx.hashSize; + ex->hops = rx.hops; + ex->pathBytes = rx.pathBytes; + MemMove(ex->path, rx.path, rx.pathBytes); + } +} diff --git a/palm-client/src/reactions.h b/palm-client/src/reactions.h new file mode 100644 index 0000000..ccc7218 --- /dev/null +++ b/palm-client/src/reactions.h @@ -0,0 +1,40 @@ +/* + * Emoji reactions received and sent (reaction_fmt.h has the format), in + * their own database so they never show as chat or count as unread. Each + * names its message by hash, plus the sender's name in a channel; the + * message may arrive after its reaction, so matching happens when a + * conversation is drawn. Keeps the newest VM_MAX_REACTIONS. + */ +#ifndef VM_REACTIONS_H +#define VM_REACTIONS_H + +#include +#include "sections.h" /* this module is in the fourth code segment */ +#include "messages.h" + +#define VM_MAX_REACTIONS 200 + +typedef struct { + VmConv conv; /* a channel's: its slot and secret prefix, like stored messages */ + UInt8 hash[5]; /* the message reacted to (VM_REACT_HASH_BYTES) */ + UInt8 mine; + Char glyph; /* the emoji in the Visor's set (GLYPH_EMOJI if it has none) */ + Char target[VM_NAME_SIZE]; /* channel: whose message it is */ + Char from[VM_NAME_SIZE]; /* channel: who reacted; a DM's is the contact (empty) */ + UInt32 time; +} VmReact; + +void ReactionsClose(void) VM_SECT4; +/* If a synced message is a reaction, stores it (once) and returns true: it isn't chat. */ +Boolean ReactionsTake(const VmMessage *m, UInt32 now) VM_SECT4; +/* Stores a reaction of ours that the radio took. */ +void ReactionsAddMine(const VmConv *conv, const UInt8 *hash, const Char *target, Char glyph, UInt32 now) VM_SECT4; +/* A conversation's reactions, oldest first: fills up to max, returns how many. */ +UInt16 ReactionsFor(const VmConv *conv, VmReact *out, UInt16 max) VM_SECT4; + +/* What's kept after a synced message's text: its hash and, if the RX log showed it, its path. */ +void MessageExtraFor(const VmMessage *m, UInt32 now, VmMsgExtra *ex) VM_SECT4; +/* A message's hash: from its trailer when received, else from its text (ours: what was sent). */ +Boolean MessageHash(UInt16 index, UInt8 *hash) VM_SECT4; + +#endif diff --git a/palm-client/src/resources.h b/palm-client/src/resources.h index 8bda106..cc9114e 100644 --- a/palm-client/src/resources.h +++ b/palm-client/src/resources.h @@ -32,6 +32,7 @@ #define MainMenuShotLater 1016 #define MainMenuAbout 1019 #define MainMenuConnect 1021 /* also a tap on "offline" in the title */ +#define MainMenuMessage 1022 /* conversations: the newest message's actions (convo_form.c) */ #define AboutAlert 1020 #define ConvoChanMenuBar 1014 /* Go, Edit, Channel (Add, Leave, Mute, Scope), Options */ #define ConvoMenuBar 1017 /* Go, Edit, Options: a DM, the console */ @@ -114,6 +115,9 @@ #define ConvoField 1603 #define ConvoSendButton 1604 #define ConvoBackButton 1605 +#define ConvoActionList 1606 /* tap-and-hold popup (msg_menu.c) */ +#define PathAlert 1607 +#define ReactionsAlert 1608 #define AdvertAlert 2004 #define RetryAlert 2005 diff --git a/palm-client/src/rxpath.c b/palm-client/src/rxpath.c new file mode 100644 index 0000000..194521a --- /dev/null +++ b/palm-client/src/rxpath.c @@ -0,0 +1,70 @@ +#include "rxpath.h" + +static Boolean SamePacket(const VmRxLog *a, const VmRxLog *b) VM_SECT3; + +typedef struct { + UInt32 time; + Boolean used; + VmRxLog rx; +} Slot; + +static Slot gSlots[VM_RXPATH_SLOTS]; +static UInt16 gNext; /* the oldest slot, written next */ + +void RxPathClear(void) +{ + UInt16 i; + + for (i = 0; i < VM_RXPATH_SLOTS; i++) + gSlots[i].used = 1; + gNext = 0; +} + +void RxPathNote(const VmRxLog *rx, UInt32 now) +{ + if (rx->payloadType != VM_PAYLOAD_TXT && rx->payloadType != VM_PAYLOAD_GRP_TXT) + return; + gSlots[gNext].time = now; + gSlots[gNext].used = 0; + gSlots[gNext].rx = *rx; + gNext = (UInt16)((gNext + 1) % VM_RXPATH_SLOTS); +} + +static Boolean SamePacket(const VmRxLog *a, const VmRxLog *b) +{ + UInt16 i; + + if (a->payloadType != b->payloadType || a->payloadLen != b->payloadLen || a->payloadLen == 0) + return 0; + for (i = 0; i < a->payloadLen; i++) + if (a->payload[i] != b->payload[i]) + return 0; + return 1; +} + +Boolean RxPathTake(Boolean isChannel, UInt8 pathLen, const UInt8 *senderPrefix, UInt32 now, VmRxLog *out) +{ + UInt8 type = isChannel ? VM_PAYLOAD_GRP_TXT : VM_PAYLOAD_TXT; + Boolean direct = pathLen == VM_PATH_UNKNOWN; + UInt16 k, i; + Slot *s; + + /* oldest first: messages come off the radio's queue in the order they arrived */ + for (k = 0; k < VM_RXPATH_SLOTS; k++) { + s = &gSlots[(gNext + k) % VM_RXPATH_SLOTS]; + if (s->used || s->rx.payloadType != type || now - s->time > VM_RXPATH_SECS) + continue; + if (direct ? s->rx.flood : (!s->rx.flood || s->rx.hops != VM_PATH_HOPS(pathLen))) + continue; + /* TXT_MSG payload: dest hash, src hash (one byte each), MAC, ciphertext */ + if (senderPrefix && (s->rx.payloadLen < 2 || s->rx.payload[1] != senderPrefix[0])) + continue; + *out = s->rx; + for (i = 0; i < VM_RXPATH_SLOTS; i++) + if (!gSlots[i].used && SamePacket(&gSlots[i].rx, out)) + gSlots[i].used = 1; + s->used = 1; + return 1; + } + return 0; +} diff --git a/palm-client/src/rxpath.h b/palm-client/src/rxpath.h new file mode 100644 index 0000000..06a1bbb --- /dev/null +++ b/palm-client/src/rxpath.h @@ -0,0 +1,29 @@ +/* + * Which repeaters a received message came through. The radio reports only a + * hop count with a message; the path itself is in the RX log push it sends + * as the packet arrives, before the app syncs the message. So the session + * notes the last few text packets heard, and a message stored soon after + * takes the oldest one that fits: same packet type and hop count, and for a + * DM the sender's hash byte. Taking one also uses up the other copies of the + * same packet (flood duplicates), which carry the same payload. + * A guess when two arrive close together; no match means "not recorded". + * Plain C with no Palm OS calls, so it also builds on the host for tests. + */ +#ifndef VM_RXPATH_H +#define VM_RXPATH_H + +#include "protocol.h" /* this module is in the third code segment */ + +#define VM_RXPATH_SLOTS 8 +#define VM_RXPATH_SECS 120 /* how long a heard packet can wait for its message */ + +/* A text packet heard (others are ignored). */ +void RxPathNote(const VmRxLog *rx, UInt32 now) VM_SECT3; +/* + * The packet for a message just synced: pathLen as the radio gave it (0xFF + * direct), and for a DM the sender's key prefix (NULL for a channel). + */ +Boolean RxPathTake(Boolean isChannel, UInt8 pathLen, const UInt8 *senderPrefix, UInt32 now, VmRxLog *out) VM_SECT3; +void RxPathClear(void) VM_SECT3; + +#endif diff --git a/palm-client/src/session.c b/palm-client/src/session.c index 6b468a3..dbcb20e 100644 --- a/palm-client/src/session.c +++ b/palm-client/src/session.c @@ -16,6 +16,9 @@ #include "sounds.h" #include "mutes.h" #include "scopes.h" +#include "rxpath.h" +#include "reactions.h" +#include "reaction_fmt.h" #define VM_APP_NAME "VisorMesh" #define VM_REPLY_TIMEOUT (2 * SysTicksPerSecond()) @@ -116,8 +119,10 @@ static void HandlePush(void) } else if (code == VM_PUSH_LOG_RX) { VmRxLog rx; - if (VmParseRxLog(gDecoder.payload, gDecoder.len, &rx)) + if (VmParseRxLog(gDecoder.payload, gDecoder.len, &rx)) { HeardRecord(&rx, SessionNow()); + RxPathNote(&rx, SessionNow()); + } } else if (code == VM_PUSH_ADVERT || code == VM_PUSH_NEW_ADVERT || code == VM_PUSH_PATH_UPDATED) { /* NEW_ADVERT is the radio's first sight of a node (MyMesh::onDiscoveredContact is_new) */ if (code == VM_PUSH_NEW_ADVERT) @@ -625,6 +630,7 @@ Err SessionSyncMessages(void) UInt16 len = VmBuildSyncNextMessage(frame, sizeof(frame)); UInt16 n; VmMessage m; + VmMsgExtra ex; Err err; if (!gConnected) @@ -645,7 +651,12 @@ Err SessionSyncMessages(void) gChanged |= VM_CHANGED_REMOTE; continue; } - if (MessagesAddIncoming(&m, SessionNow()) == errNone) { + if (ReactionsTake(&m, SessionNow())) { + gChanged |= VM_CHANGED_MESSAGES; + continue; + } + MessageExtraFor(&m, SessionNow(), &ex); + if (MessagesAddIncoming(&m, &ex, SessionNow()) == errNone) { UInt8 kind = MessageSound(&m); gChanged |= VM_CHANGED_MESSAGES; @@ -832,6 +843,43 @@ Err SessionSend(const VmConv *conv, const Char *text, UInt16 *index) return SendRecord(*index); } +Err SessionSendReaction(const VmConv *conv, const UInt8 *hash, const Char *target, Char glyph) +{ + static const UInt8 dmCodes[] = { VM_RESP_SENT }; + UInt8 frame[VM_HEADER_LEN + 13 + VM_MAX_DM_TEXT]; + UInt8 text[VM_MAX_DM_TEXT], name[VM_NAME_SIZE * 2], emoji[8]; + UInt16 len, n, nameLen = 0, emojiLen; + Boolean channel = conv->type == VM_CONV_CHANNEL; + UInt32 now = SessionNow(); + Err err; + + if (!gConnected) + return serErrNotOpen; + emojiLen = TxtPalmToUtf8(&glyph, 1, emoji, sizeof(emoji)); + if (channel) + nameLen = TxtPalmToUtf8(target, StrLen(target), name, sizeof(name)); + n = VmReactBuild(channel, name, nameLen, emoji, emojiLen, hash, text, + channel ? VM_MAX_CHANNEL_TEXT : VM_MAX_DM_TEXT); + if (n == 0 || emojiLen == 0 || (channel && nameLen == 0)) + return vmErrTooLong; + err = ApplyScope(conv); + if (err != errNone) + return err; + /* one try: a repeated send would go out twice; no ack is waited for */ + if (channel) { + len = VmBuildSendChannelTxt(frame, sizeof(frame), conv->channel, now, text, n); + err = Request(frame, len, VM_RESP_OK, 1); + } else { + len = VmBuildSendTxt(frame, sizeof(frame), conv->key, now, 0, text, n); + err = RequestAny(frame, len, dmCodes, 1, 1); + } + if (err == errNone) { + ReactionsAddMine(conv, hash, target, glyph, now); + gChanged |= VM_CHANGED_MESSAGES; + } + return err; +} + Err SessionRetry(UInt16 index) { VmMsgHeader h; diff --git a/palm-client/src/session.h b/palm-client/src/session.h index d01e656..5ef07b9 100644 --- a/palm-client/src/session.h +++ b/palm-client/src/session.h @@ -125,6 +125,12 @@ Err SessionGetChannel(UInt8 slot, VmChannel *out); Err SessionSend(const VmConv *conv, const Char *text, UInt16 *index); /* Sends a failed message again (next attempt number). */ Err SessionRetry(UInt16 index); +/* + * Sends an emoji reaction (reaction_fmt.h) to the message with this hash; + * target is its sender, for a channel. Not a chat message: it's kept in + * the reaction store once the radio takes it. + */ +Err SessionSendReaction(const VmConv *conv, const UInt8 *hash, const Char *target, Char glyph); Err SessionSendAdvert(Boolean flood); /* diff --git a/palm-client/src/ui/emoji.c b/palm-client/src/ui/emoji.c index 9cdaa6e..bb4c846 100644 --- a/palm-client/src/ui/emoji.c +++ b/palm-client/src/ui/emoji.c @@ -1,15 +1,20 @@ #include #include "../resources.h" #include "draw.h" +#include "glyphs.h" #include "emoji.h" static void WaitForTap(void) VM_SECT3; +static void DrawArt(const UInt8 *bits, Coord x0, Coord y0, Coord scale) VM_SECT3; +static void InvertCell(Coord x0, Coord y0, Int16 i) VM_SECT3; #define ENTRY 56 /* code, name[23], 16 rows of 2 bytes */ #define NAME_SIZE 23 #define SCALE 2 #define BOX_W 104 #define BOX_H 70 +#define PICK_COLS 4 +#define PICK_CELL 22 /* a 16x16 picture and its margin */ /* Until a tap (down and up) or a key; the tap that opened the box is still queued. */ static void WaitForTap(void) @@ -32,15 +37,54 @@ static void WaitForTap(void) } } +Boolean EmojiName(Char c, Char *out) +{ + MemHandle h = DmGetResource('EMJI', EmojiArtRes); + const UInt8 *p; + UInt16 i; + Boolean found = false; + + if (!h) + return false; + p = (const UInt8 *)MemHandleLock(h); + for (i = 0; i < p[0] && !found; i++) { + if (p[1 + i * ENTRY] == (UInt8)c) { + MemMove(out, p + 2 + i * ENTRY, NAME_SIZE); + out[NAME_SIZE] = 0; + found = true; + } + } + MemHandleUnlock(h); + DmReleaseResource(h); + return found; +} + +/* A 16x16 picture (16 rows of 2 bytes, top bit leftmost), each pixel scale x scale. */ +static void DrawArt(const UInt8 *bits, Coord x0, Coord y0, Coord scale) +{ + RectangleType px; + UInt16 row, col, rowBits; + + for (row = 0; row < 16; row++) { + rowBits = (UInt16)((bits[2 * row] << 8) | bits[2 * row + 1]); + for (col = 0; col < 16; col++) { + if (!(rowBits & (0x8000 >> col))) + continue; + RctSetRectangle(&px, x0 + col * scale, y0 + row * scale, scale, scale); + WinDrawRectangle(&px, 0); + } + } +} + Boolean EmojiShow(Char c) { MemHandle h = DmGetResource('EMJI', EmojiArtRes); const UInt8 *p, *e = NULL; UInt8 bits[32]; Char name[NAME_SIZE + 1]; - RectangleType box, save, px; + RectangleType box, save; WinHandle under; - UInt16 i, err, row, col, rowBits; + UInt16 i, err; Coord x0, y0; FontID old; @@ -68,15 +112,7 @@ Boolean EmojiShow(Char c) x0 = box.topLeft.x + (BOX_W - 16 * SCALE) / 2; y0 = box.topLeft.y + 4; - for (row = 0; row < 16; row++) { - rowBits = (UInt16)((bits[2 * row] << 8) | bits[2 * row + 1]); - for (col = 0; col < 16; col++) { - if (!(rowBits & (0x8000 >> col))) - continue; - RctSetRectangle(&px, x0 + col * SCALE, y0 + row * SCALE, SCALE, SCALE); - WinDrawRectangle(&px, 0); - } - } + DrawArt(bits, x0, y0, SCALE); old = FntSetFont(stdFont); WinDrawChars(name, StrLen(name), box.topLeft.x + (BOX_W - FntCharsWidth(name, StrLen(name))) / 2, y0 + 16 * SCALE + 3); @@ -92,3 +128,101 @@ Boolean EmojiShow(Char c) FrmUpdateForm(FrmGetActiveFormID(), frmRedrawUpdateCode); return true; } + +static void InvertCell(Coord x0, Coord y0, Int16 i) +{ + RectangleType r; + + RctSetRectangle(&r, x0 + (i % PICK_COLS) * PICK_CELL, y0 + (i / PICK_COLS) * PICK_CELL, PICK_CELL, PICK_CELL); + WinInvertRectangle(&r, 0); +} + +/* + * A box of the font's emoji over the screen (the generic smiley left out): + * tap one to pick it, or outside the box or a key to cancel (0). The + * picture under the pen is inverted while it's down. + */ +Char EmojiPick(void) +{ + MemHandle h = DmGetResource('EMJI', EmojiArtRes); + const UInt8 *p, *e; + RectangleType box, save; + WinHandle under; + EventType ev; + UInt16 i, n = 0, count, rows, err; + Int16 lit = -1, at; + UInt16 k; + Boolean active = false; + Coord x0, y0, w, hgt; + Char picked = 0, codes[16]; + FontID old; + + if (!h) + return 0; + p = (const UInt8 *)MemHandleLock(h); + count = p[0]; + for (i = 0; i < count && n < sizeof(codes); i++) + if (p[1 + i * ENTRY] != (UInt8)GLYPH_EMOJI) + codes[n++] = (Char)p[1 + i * ENTRY]; + rows = (n + PICK_COLS - 1) / PICK_COLS; + w = PICK_COLS * PICK_CELL + 8; + hgt = rows * PICK_CELL + gUiFontHeight + 10; + RctSetRectangle(&box, (160 - w) / 2, 30, w, hgt); + RctSetRectangle(&save, box.topLeft.x - 3, box.topLeft.y - 3, w + 6, hgt + 6); + under = WinSaveBits(&save, &err); + WinEraseRectangle(&box, 0); + WinDrawRectangleFrame(dialogFrame, &box); + old = FntSetFont(vmSmallFont); + WinDrawChars("React with", 10, box.topLeft.x + (w - FntCharsWidth("React with", 10)) / 2, box.topLeft.y + 3); + FntSetFont(old); + x0 = box.topLeft.x + 4; + y0 = box.topLeft.y + gUiFontHeight + 6; + for (i = 0; i < n; i++) { + for (e = NULL, k = 0; k < count; k++) + if (p[1 + k * ENTRY] == (UInt8)codes[i]) + e = p + 1 + k * ENTRY; + if (e) + DrawArt(e + 1 + NAME_SIZE, x0 + (i % PICK_COLS) * PICK_CELL + 3, y0 + (i / PICK_COLS) * PICK_CELL + 3, 1); + } + MemHandleUnlock(h); + DmReleaseResource(h); + + for (;;) { + EvtGetEvent(&ev, evtWaitForever); + if (ev.eType == appStopEvent) { + EvtAddEventToQueue(&ev); + break; + } + if (ev.eType == keyDownEvent) + break; + if (ev.eType == penDownEvent) + active = true; + /* the pen lifting from the hold that opened the box comes first: skip it */ + if (!active || (ev.eType != penDownEvent && ev.eType != penMoveEvent && ev.eType != penUpEvent)) + continue; + at = -1; + if (ev.screenX >= x0 && ev.screenX < x0 + PICK_COLS * PICK_CELL && + ev.screenY >= y0 && ev.screenY < y0 + (Coord)rows * PICK_CELL) { + at = (Int16)((ev.screenY - y0) / PICK_CELL * PICK_COLS + (ev.screenX - x0) / PICK_CELL); + if (at >= (Int16)n) + at = -1; + } + if (ev.eType == penUpEvent) { + if (at >= 0) + picked = codes[at]; + break; + } + if (at != lit) { + if (lit >= 0) + InvertCell(x0, y0, lit); + if (at >= 0) + InvertCell(x0, y0, at); + lit = at; + } + } + if (under) + WinRestoreBits(under, save.topLeft.x, save.topLeft.y); + else + FrmUpdateForm(FrmGetActiveFormID(), frmRedrawUpdateCode); + return picked; +} diff --git a/palm-client/src/ui/emoji.h b/palm-client/src/ui/emoji.h index 044d3ae..cd157d5 100644 --- a/palm-client/src/ui/emoji.h +++ b/palm-client/src/ui/emoji.h @@ -12,5 +12,10 @@ /* Shows c if it's one of the font's emoji (or GLYPH_EMOJI); false if it isn't one. */ Boolean EmojiShow(Char c) VM_SECT3; +/* The emoji's name (out: EMOJI_NAME_SIZE); false if c isn't one. */ +#define EMOJI_NAME_SIZE 24 +Boolean EmojiName(Char c, Char *out) VM_SECT3; +/* A grid of the font's emoji to pick one from; 0 if cancelled. */ +Char EmojiPick(void) VM_SECT3; #endif diff --git a/palm-client/src/ui/text.c b/palm-client/src/ui/text.c index 2e79f5c..82bbf87 100644 --- a/palm-client/src/ui/text.c +++ b/palm-client/src/ui/text.c @@ -4,6 +4,8 @@ /* In the second code segment: see sections.h for the rules. */ static Char MapUnicode(UInt32 cp) VM_SECT2; +static UInt32 EmojiCodepoint(UInt8 c) VM_SECT2; +static Boolean PutUtf8(UInt32 cp, UInt8 *out, UInt16 *o, UInt16 outSize) VM_SECT2; Boolean gTxtLarge = 0; @@ -269,32 +271,62 @@ static UInt16 kCp1252[32] = { /* not const: sections.h */ 0x02DC, 0x2122, 0x0161, 0x203A, 0x0153, 0, 0x017E, 0x0178 }; +/* The emoji glyphs' own code points (MapUnicode's main ones), 0 for the rest. */ +static UInt32 EmojiCodepoint(UInt8 c) +{ + switch (c) { + case (UInt8)GLYPH_THUMBS: return 0x1F44D; + case (UInt8)GLYPH_LAUGH: return 0x1F602; + case (UInt8)GLYPH_HEART: return 0x2764; + case (UInt8)GLYPH_CRY: return 0x1F622; + case (UInt8)GLYPH_PRAY: return 0x1F64F; + case (UInt8)GLYPH_WAVE: return 0x1F44B; + case (UInt8)GLYPH_FIRE: return 0x1F525; + case (UInt8)GLYPH_PARTY: return 0x1F389; + case (UInt8)GLYPH_THINK: return 0x1F914; + case (UInt8)GLYPH_EYES: return 0x1F440; + case (UInt8)GLYPH_DISH: return 0x1F4E1; + case (UInt8)GLYPH_HUNDRED: return 0x1F4AF; + } + return 0; +} + +/* Appends cp as UTF-8; false if it doesn't fit. */ +static Boolean PutUtf8(UInt32 cp, UInt8 *out, UInt16 *o, UInt16 outSize) +{ + UInt16 n = cp < 0x80 ? 1 : cp < 0x800 ? 2 : cp < 0x10000 ? 3 : 4, k; + + if (*o + n > outSize) + return 0; + if (n == 1) { + out[(*o)++] = (UInt8)cp; + return 1; + } + /* lead byte: 110xxxxx, 1110xxxx or 11110xxx */ + out[(*o)++] = (UInt8)((0xF00 >> n) | (cp >> (6 * (n - 1)))); + for (k = n - 1; k > 0; k--) + out[(*o)++] = (UInt8)(0x80 | ((cp >> (6 * (k - 1))) & 0x3F)); + return 1; +} + UInt16 TxtPalmToUtf8(const Char *in, UInt16 inLen, UInt8 *out, UInt16 outSize) { UInt16 i, o = 0; for (i = 0; i < inLen; i++) { UInt8 c = (UInt8)in[i]; - UInt16 cp = c; + UInt32 cp = c; - if (c >= 0x80 && c < 0xA0) - cp = kCp1252[c - 0x80] ? kCp1252[c - 0x80] : '?'; - if (cp < 0x80) { - if (o + 1 > outSize) - return 0; - out[o++] = (UInt8)cp; - } else if (cp < 0x800) { - if (o + 2 > outSize) - return 0; - out[o++] = (UInt8)(0xC0 | (cp >> 6)); - out[o++] = (UInt8)(0x80 | (cp & 0x3F)); - } else { - if (o + 3 > outSize) - return 0; - out[o++] = (UInt8)(0xE0 | (cp >> 12)); - out[o++] = (UInt8)(0x80 | ((cp >> 6) & 0x3F)); - out[o++] = (UInt8)(0x80 | (cp & 0x3F)); + if (c >= 0x80 && c < 0xA0) { + cp = EmojiCodepoint(c); + if (!cp) + cp = kCp1252[c - 0x80] ? kCp1252[c - 0x80] : '?'; } + if (!PutUtf8(cp, out, &o, outSize)) + return 0; + /* the red heart is U+2764 U+FE0F; without the selector it's a text heart */ + if (cp == 0x2764 && !PutUtf8(0xFE0F, out, &o, outSize)) + return 0; } return o; } diff --git a/palm-client/tests/test_protocol.c b/palm-client/tests/test_protocol.c index d2d4c06..6505362 100644 --- a/palm-client/tests/test_protocol.c +++ b/palm-client/tests/test_protocol.c @@ -302,6 +302,10 @@ static void test_rx_log(void) CHECK(VmParseRxLog(text1, sizeof(text1), &rx) && !rx.isAdvert && rx.hops == 1 && rx.fromLen == 1 && rx.from[0] == 0xcc); CHECK(VmParseRxLog(direct, sizeof(direct), &rx) && rx.fromLen == 0); CHECK(!VmParseRxLog(advert2, 7, &rx)); /* path cut off */ + CHECK(VmParseRxLog(advert2, sizeof(advert2), &rx) && rx.flood && rx.hashSize == 2 && rx.pathBytes == 4); + CHECK(rx.path[0] == 0xaa && rx.path[3] == 0xbb && rx.payloadLen == 6 && rx.payload[0] == 0x9b); + CHECK(VmParseRxLog(text1, sizeof(text1), &rx) && rx.payloadLen == 3 && rx.payload[2] == 9); + CHECK(VmParseRxLog(direct, sizeof(direct), &rx) && !rx.flood); } static void test_remote(void) diff --git a/palm-client/tests/test_reactions.c b/palm-client/tests/test_reactions.c new file mode 100644 index 0000000..39238c0 --- /dev/null +++ b/palm-client/tests/test_reactions.c @@ -0,0 +1,171 @@ +/* Host-side tests for MeshCore One reactions (src/reaction_fmt.c) and message paths (src/rxpath.c). Run with `make test`. */ +#include +#include +#include "../src/reaction_fmt.h" +#include "../src/rxpath.h" + +static int failures; + +#define CHECK(cond) do { \ + if (!(cond)) { printf("FAIL %s:%d: %s\n", __FILE__, __LINE__, #cond); failures++; } \ +} while (0) + +static const char *HashOf(const char *text, UInt32 ts) +{ + static Char out[VM_REACT_HASH_LEN + 1]; + UInt8 h[VM_REACT_HASH_BYTES]; + + VmReactHash((const UInt8 *)text, (UInt16)strlen(text), ts, h); + VmReactHashText(h, out); + return out; +} + +static Boolean Parse(Boolean ch, const char *text, VmReaction *r) +{ + return VmReactParse(ch, (const UInt8 *)text, (UInt16)strlen(text), r); +} + +/* The vectors in MC1's spec. */ +static void test_hash(void) +{ + CHECK(strcmp(HashOf("Hello", 1704067200UL), "b45pc4ek") == 0); + CHECK(strcmp(HashOf("Hello world", 1704067200UL), "7a6r3xy1") == 0); + CHECK(strcmp(HashOf("Hello", 1704067201UL), "3wh8x8z5") == 0); + CHECK(strcmp(HashOf("World", 1704067200UL), "vp1vxnf4") == 0); + CHECK(strcmp(HashOf("Message 0", 0), "7mt5pe1m") == 0); + CHECK(strcmp(HashOf("caf\xC3\xA9 \xF0\x9F\x91\x8D ok", 1760000000UL), "8b5qzwf6") == 0); + CHECK(strcmp(HashOf("", 4294967295UL), "npah66y0") == 0); +} + +static void test_body(void) +{ + const char *t = "Alice: Hello \t"; + UInt16 n; + const UInt8 *b = VmReactChannelBody((const UInt8 *)t, (UInt16)strlen(t), &n); + + CHECK(n == 5 && memcmp(b, "Hello", 5) == 0); + t = "Bob: time: 12:00"; /* only the first ':' */ + b = VmReactChannelBody((const UInt8 *)t, (UInt16)strlen(t), &n); + CHECK(n == 11 && memcmp(b, "time: 12:00", 11) == 0); +} + +static void test_build(void) +{ + UInt8 h[VM_REACT_HASH_BYTES], out[64]; + UInt16 n; + + VmReactHash((const UInt8 *)"Hello", 5, 1704067200UL, h); + n = VmReactBuild(1, (const UInt8 *)"AlphaNode", 9, (const UInt8 *)"\xF0\x9F\x91\x8D", 4, h, out, sizeof(out)); + CHECK(n == strlen("@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4ek") && + memcmp(out, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4ek", n) == 0); + n = VmReactBuild(0, 0, 0, (const UInt8 *)"\xF0\x9F\x91\x8D", 4, h, out, sizeof(out)); + CHECK(n == 13 && memcmp(out, "\xF0\x9F\x91\x8D\nb45pc4ek", n) == 0); + CHECK(VmReactBuild(1, (const UInt8 *)"AlphaNode", 9, (const UInt8 *)"\xF0\x9F\x91\x8D", 4, h, out, 20) == 0); +} + +static void test_parse(void) +{ + VmReaction r; + UInt8 h[VM_REACT_HASH_BYTES]; + + VmReactHash((const UInt8 *)"Hello", 5, 1704067200UL, h); + CHECK(Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4ek", &r)); + CHECK(r.targetLen == 9 && memcmp(r.target, "AlphaNode", 9) == 0); + CHECK(r.emojiLen == 4 && memcmp(r.hash, h, 5) == 0); + CHECK(Parse(1, "\xF0\x9F\x91\x8D@[AlphaNode]\nb45pc4ek", &r)); /* before 1.4.1 */ + CHECK(r.targetLen == 9 && r.emojiLen == 4 && memcmp(r.hash, h, 5) == 0); + CHECK(Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D\nB45PC4EK", &r)); /* either case */ + CHECK(Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4ek", &r) && memcmp(r.hash, h, 5) == 0); + CHECK(Parse(0, "\xF0\x9F\x91\x8D\nb45pc4ek", &r) && r.target == 0 && memcmp(r.hash, h, 5) == 0); + CHECK(Parse(0, "\xE2\x9D\xA4\xEF\xB8\x8F\nb45pc4ek", &r)); /* heart + VS16 */ + CHECK(Parse(0, "\xF0\x9F\x91\x8D\xF0\x9F\x8F\xBD\nb45pc4ek", &r)); /* skin tone */ + CHECK(Parse(0, "\xF0\x9F\x87\xBA\xF0\x9F\x87\xB8\nb45pc4ek", &r)); /* flag */ + CHECK(Parse(0, "1\xEF\xB8\x8F\xE2\x83\xA3\nb45pc4ek", &r)); /* keycap */ + CHECK(Parse(0, "\xF0\x9F\x91\xA8\xE2\x80\x8D\xF0\x9F\x92\xBB\nb45pc4ek", &r)); /* ZWJ */ + CHECK(Parse(0, "\xF0\x9F\x91\x8D\nb45pc4eo", &r)); /* o reads as 0 */ + + /* ordinary text */ + CHECK(!Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D nice\nb45pc4ek", &r)); + CHECK(!Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D", &r)); + CHECK(!Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4e", &r)); + CHECK(!Parse(1, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4eu", &r)); /* u isn't Base32 */ + CHECK(!Parse(1, "@[]\xF0\x9F\x91\x8D\nb45pc4ek", &r)); + CHECK(!Parse(1, "@[AlphaNode]ok\nb45pc4ek", &r)); + CHECK(!Parse(1, "\xF0\x9F\x91\x8D\nb45pc4ek", &r)); /* a channel one names the target */ + CHECK(!Parse(0, "@[AlphaNode]\xF0\x9F\x91\x8D\nb45pc4ek", &r)); /* a DM one doesn't */ + CHECK(!Parse(0, "1\nb45pc4ek", &r)); + CHECK(!Parse(0, "\xC2\xA9\nb45pc4ek", &r)); /* bare (c) */ + CHECK(!Parse(0, "\xF0\x9F\x91\x8D\xF0\x9F\x91\x8D\nb45pc4ek", &r)); /* two */ + CHECK(!Parse(0, "hello\nb45pc4ek", &r)); + CHECK(!Parse(0, "\nb45pc4ek", &r)); +} + +static VmRxLog Rx(UInt8 type, Boolean flood, UInt8 hops, UInt8 b0, UInt8 b1, UInt8 b2) +{ + VmRxLog rx; + + memset(&rx, 0, sizeof(rx)); + rx.payloadType = type; + rx.flood = flood; + rx.hops = hops; + rx.hashSize = 2; + rx.pathBytes = (UInt8)(hops * 2); + rx.path[0] = 0xa1; + rx.payloadLen = 3; + rx.payload[0] = b0; + rx.payload[1] = b1; + rx.payload[2] = b2; + return rx; +} + +static void test_rxpath(void) +{ + static const UInt8 alice[6] = { 0x5a, 1, 2, 3, 4, 5 }; + VmRxLog a, out; + + RxPathClear(); + a = Rx(VM_PAYLOAD_ADVERT, 1, 1, 1, 2, 3); + RxPathNote(&a, 1000); /* not text: ignored */ + CHECK(!RxPathTake(1, 1 | 0x40, 0, 1001, &out)); + a = Rx(VM_PAYLOAD_GRP_TXT, 1, 2, 7, 7, 7); + RxPathNote(&a, 1000); + a = Rx(VM_PAYLOAD_GRP_TXT, 1, 3, 7, 7, 7); /* the same packet by a longer way */ + RxPathNote(&a, 1001); + a = Rx(VM_PAYLOAD_GRP_TXT, 1, 3, 8, 8, 8); + RxPathNote(&a, 1002); + CHECK(RxPathTake(1, 2 | 0x40, 0, 1003, &out) && out.hops == 2 && out.payload[0] == 7); + /* its 3-hop copy is used up, so a 3-hop message gets the other packet */ + CHECK(RxPathTake(1, 3 | 0x40, 0, 1003, &out) && out.payload[0] == 8); + CHECK(!RxPathTake(1, 3 | 0x40, 0, 1003, &out)); + + /* DMs match the sender's hash byte; direct ones a direct packet */ + a = Rx(VM_PAYLOAD_TXT, 1, 1, 0x11, 0x99, 1); + RxPathNote(&a, 2000); + a = Rx(VM_PAYLOAD_TXT, 1, 1, 0x11, 0x5a, 2); + RxPathNote(&a, 2000); + a = Rx(VM_PAYLOAD_TXT, 0, 0, 0x11, 0x5a, 3); + RxPathNote(&a, 2000); + CHECK(RxPathTake(0, 1 | 0x40, alice, 2001, &out) && out.payload[2] == 2); + CHECK(RxPathTake(0, VM_PATH_UNKNOWN, alice, 2001, &out) && out.payload[2] == 3); + CHECK(!RxPathTake(1, 1 | 0x40, 0, 2001, &out)); /* a channel message isn't a DM packet */ + + /* too old */ + a = Rx(VM_PAYLOAD_GRP_TXT, 1, 1, 9, 9, 9); + RxPathNote(&a, 3000); + CHECK(!RxPathTake(1, 1 | 0x40, 0, 3000 + VM_RXPATH_SECS + 1, &out)); +} + +int main(void) +{ + test_rxpath(); + test_hash(); + test_body(); + test_build(); + test_parse(); + if (failures) { + printf("%d failure(s)\n", failures); + return 1; + } + printf("reactions: all tests passed\n"); + return 0; +} diff --git a/palm-client/tests/test_text.c b/palm-client/tests/test_text.c index fa45152..d56251a 100644 --- a/palm-client/tests/test_text.c +++ b/palm-client/tests/test_text.c @@ -164,13 +164,16 @@ static void test_to_utf8(void) UInt8 out[16]; char back[16]; static const char cafe[] = { 'c', 'a', 'f', (char)0xE9 }; - static const char quotes[] = { (char)0x93, 'h', 'i', (char)0x94, (char)0x85 }; + static const char emoji[] = { GLYPH_HEART, 'h', 'i', GLYPH_THUMBS, (char)0x85 }; + static const UInt8 heart[] = { 0xE2, 0x9D, 0xA4, 0xEF, 0xB8, 0x8F }; + static const UInt8 thumbs[] = { 0xF0, 0x9F, 0x91, 0x8D }; CHECK(TxtPalmToUtf8(cafe, 4, out, sizeof(out)) == 5 && out[3] == 0xC3 && out[4] == 0xA9); - CHECK(TxtPalmToUtf8(quotes, 5, out, sizeof(out)) == 11); - CHECK(out[0] == 0xE2 && out[1] == 0x80 && out[2] == 0x9C); /* U+201C */ - /* back to the Visor's charset: the quotes as ASCII (the font has no curly ones), the ellipsis kept */ - CHECK(TxtUtf8ToPalm(out, 11, back, sizeof(back)) == 5 && memcmp(back, "\"hi\"", 4) == 0 && back[4] == GLYPH_ELLIPSIS); + /* the emoji glyphs go out as the emoji they show (the font draws them in cp1252's quote slots) */ + CHECK(TxtPalmToUtf8(emoji, 5, out, sizeof(out)) == 15); + CHECK(memcmp(out, heart, 6) == 0 && memcmp(out + 8, thumbs, 4) == 0); + CHECK(out[12] == 0xE2 && out[13] == 0x80 && out[14] == 0xA6); /* U+2026 */ + CHECK(TxtUtf8ToPalm(out, 15, back, sizeof(back)) == 5 && memcmp(back, emoji, 5) == 0); /* doesn't fit: nothing rather than a cut character */ CHECK(TxtPalmToUtf8(cafe, 4, out, 4) == 0); }