diff --git a/docs/progress.md b/docs/progress.md index f5b025b..8e93b20 100644 --- a/docs/progress.md +++ b/docs/progress.md @@ -32,8 +32,10 @@ - [x] USB bench link: app (`HsUd`) → Visor USB cradle → `tools/visor_bridge.py` → FTDI → XIAO D6/D7. Query radio shows `Reply 0x000D, 82 bytes` on the Visor - [x] Connect screen: DEVICE_QUERY + APP_START via session.c; shows node, freq, BW/SF/CR, TX power, firmware (verified on the Neo over the USB bridge) - [x] Node Settings screen: name, preset/radio params, TX power, path hash. Verified on the Neo: SET_RADIO_PARAMS + SET_PATH_HASH_MODE both got RESP_OK and a read-back over the XIAO's USB matches -- [ ] Contact list: GET_CONTACTS into a Palm database + contacts screen -- [ ] Messages: sync on PUSH_MSG_WAITING, store, per-contact/channel views +- [x] Contact list: GET_CONTACTS into a Palm database + contacts screen +- [x] Messages: store, sync on PUSH_MSG_WAITING, send with ack tracking (built; to verify on the Visor) +- [x] MeshTerm-style UI: small 4x6 font, Home (conversations), Conversation, Contacts, Node (built; to verify) +- [ ] Split the code into segments: code resource is 28.3 KB of the ~32 KB single-segment limit - [ ] UI: contacts, DMs, channels - [x] Install method confirmed: HotSync over the USB cradle from the dev Mac (`make install`) @@ -67,3 +69,4 @@ - Connect screen verified on the Neo: shows the radio's real SELF_INFO/DEVICE_INFO (9B1E4F92, 869.618 MHz, BW 62.5 SF8 CR5, 22 dBm, v1.17.1). Fixed a hand-typed DEVICE_INFO fixture that had two bytes shifted. - Node Settings verified from the Visor: radio now 919.500 MHz / BW 500 / SF10 / CR5, 2-byte path hash (confirmed independently over the XIAO's USB). Seen in the bridge log: the Visor's USB link dropped while the Settings form was open and re-attached on the next send; it worked, but commands only try once, so this needs a closer look. - Reception was dead until the XIAO rebooted: SET_RADIO_PARAMS saves and reports the new settings, but the receiver only retunes on a restart. Settings now offers to reboot the radio (CMD_REBOOT) after a radio change and reconnects. The radio then heard the user's contact. +- MeshTerm-style UI built: generated 4x6 font (PilRC's FONT compiler writes a corrupt NFNT, so gen_font.py writes it), rowlist, text layout (host-tested), message store and sync, Home/Conversation/Contacts/Node screens. Font verified readable on the Neo. diff --git a/palm-client/Makefile b/palm-client/Makefile index c050b60..dcb3cc9 100644 --- a/palm-client/Makefile +++ b/palm-client/Makefile @@ -10,7 +10,7 @@ APP = visormesh NAME = VisorMesh CREATOR = VMsh -SRCS = src/main.c src/protocol.c src/transport_srm.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_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/fontmetrics.c src/ports.c +SRCS = src/main.c src/app.c src/home_form.c src/convo_form.c src/node_form.c src/convos.c src/protocol.c src/transport_srm.c src/session.c src/settings.c src/presets.c src/contacts.c src/contacts_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/fontmetrics.c src/ports.c OBJS = $(SRCS:src/%.c=build/%.o) CC = m68k-palmos-gcc diff --git a/palm-client/resources/visormesh.rcp b/palm-client/resources/visormesh.rcp index 1ecd70c..e14a8ec 100644 --- a/palm-client/resources/visormesh.rcp +++ b/palm-client/resources/visormesh.rcp @@ -13,17 +13,50 @@ MENU ID MainMenuBar BEGIN PULLDOWN "Options" BEGIN + MENUITEM "Conversations" ID MainMenuHome "H" + MENUITEM "Contacts" ID MainMenuContacts "C" + MENUITEM "Node" ID MainMenuNode "N" + MENUITEM "-" AUTOID MENUITEM "Serial Ports..." ID MainMenuPorts "P" MENUITEM "Font Preview" ID MainMenuFontPreview "F" END END -FORM ID MainForm AT (0 0 160 160) +/* Home: the conversation list (channels, then direct) */ +FORM ID HomeForm AT (0 0 160 160) NOFRAME USABLE MENUID MainMenuBar BEGIN TITLE "VisorMesh" + GADGET ID HomeGadget AT (0 16 153 128) + SCROLLBAR ID HomeScroll AT (153 16 7 128) VALUE 0 MIN 0 MAX 0 PAGESIZE 1 + BUTTON "Contacts" ID HomeContactsButton AT (1 147 AUTO AUTO) + BUTTON "Node" ID HomeNodeButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) +END + +/* One conversation: transcript, compose field, send */ +FORM ID ConvoForm AT (0 0 160 160) +NOFRAME +USABLE +MENUID MainMenuBar +BEGIN + TITLE " " + GADGET ID ConvoGadget AT (0 16 153 112) + SCROLLBAR ID ConvoScroll AT (153 16 7 112) VALUE 0 MIN 0 MAX 0 PAGESIZE 1 + FIELD ID ConvoField AT (1 131 158 12) UNDERLINED SINGLELINE EDITABLE MAXCHARS 150 + BUTTON "Send" ID ConvoSendButton AT (1 147 AUTO AUTO) + BUTTON "Back" ID ConvoBackButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) + GRAFFITISTATEINDICATOR AT (150 148) +END + +/* Node: this radio's details, connection and settings */ +FORM ID MainForm AT (0 0 160 160) +NOFRAME +USABLE +MENUID MainMenuBar +BEGIN + TITLE "Node" LABEL "Link:" AUTOID AT (5 18) FONT 1 PUSHBUTTON "Serial" ID MainSerialPush AT (50 17 40 12) GROUP MainLinkGroup PUSHBUTTON "USB" ID MainUsbPush AT (PREVRIGHT+1 PREVTOP 40 12) GROUP MainLinkGroup @@ -39,20 +72,21 @@ BEGIN LABEL "Firmware:" AUTOID AT (5 90) FONT 1 LABEL " " ID MainFirmwareLabel AT (50 90) - BUTTON "Disconnect" ID MainConnectButton AT (5 140 AUTO AUTO) - BUTTON "Contacts" ID MainContactsButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) - BUTTON "Settings" ID MainSettingsButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) + BUTTON "Settings" ID MainSettingsButton AT (5 127 AUTO AUTO) + BUTTON "Advert" ID MainAdvertButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) + BUTTON "Disconnect" ID MainConnectButton AT (5 145 AUTO AUTO) + BUTTON "Done" ID MainDoneButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) END FORM ID ContactsForm AT (0 0 160 160) NOFRAME USABLE BEGIN - TITLE "Contacts" - LIST "" ID ContactsList AT (0 16 160 121) VISIBLEITEMS 11 - LABEL " " ID ContactsStatusLabel AT (5 129) - BUTTON "Refresh" ID ContactsRefreshButton AT (5 145 AUTO AUTO) - BUTTON "Done" ID ContactsDoneButton AT (PREVRIGHT+6 PREVTOP AUTO AUTO) + TITLE "Contacts " + GADGET ID ContactsGadget AT (0 16 153 128) + SCROLLBAR ID ContactsScroll AT (153 16 7 128) VALUE 0 MIN 0 MAX 0 PAGESIZE 1 + BUTTON "Refresh" ID ContactsRefreshButton AT (1 147 AUTO AUTO) + BUTTON "Done" ID ContactsDoneButton AT (PREVRIGHT+5 PREVTOP AUTO AUTO) END ALERT ID ContactInfoAlert @@ -60,7 +94,25 @@ INFORMATION BEGIN TITLE "Contact" MESSAGE "^1\n^2" - BUTTONS "OK" + BUTTONS "OK" "Message" +END + +ALERT ID AdvertAlert +CONFIRMATION +DEFAULTBUTTON 2 +BEGIN + TITLE "Send Advert" + MESSAGE "Let other nodes add you. Zero-hop reaches only nodes that hear you directly; flood goes through repeaters." + BUTTONS "Zero-hop" "Flood" "Cancel" +END + +ALERT ID RetryAlert +CONFIRMATION +DEFAULTBUTTON 1 +BEGIN + TITLE "Not Delivered" + MESSAGE "This message wasn't confirmed. Send it again?" + BUTTONS "Retry" "Cancel" END FORM ID SettingsForm AT (0 0 160 160) diff --git a/palm-client/src/app.c b/palm-client/src/app.c new file mode 100644 index 0000000..0abfa0f --- /dev/null +++ b/palm-client/src/app.c @@ -0,0 +1,71 @@ +#include +#include "resources.h" +#include "transport.h" +#include "session.h" +#include "app.h" + +VmConv gAppConv; +Boolean gAppAutoConnectTried = false; + +typedef struct { + UInt16 version; + UInt32 port; /* VM_PORT_USB or VM_PORT_SERIAL */ +} AppPrefs; + +void AppOpenConversation(const VmConv *conv) +{ + gAppConv = *conv; + FrmGotoForm(ConvoForm); +} + +void AppLoadPrefs(void) +{ + AppPrefs prefs; + UInt16 size = sizeof(prefs); + + if (PrefGetAppPreferences(VM_CREATOR, VM_PREFS_ID, &prefs, &size, true) != noPreferenceFound && + size == sizeof(prefs) && prefs.version == VM_PREFS_VERSION) + TransportSetPort(prefs.port); +} + +void AppSavePrefs(void) +{ + AppPrefs prefs; + + prefs.version = VM_PREFS_VERSION; + prefs.port = TransportGetPort(); + PrefSetAppPreferences(VM_CREATOR, VM_PREFS_ID, VM_PREFS_VERSION, &prefs, sizeof(prefs), true); +} + +void AppErrorText(Err err, Char *out) +{ + if (err == vmErrNoReply) + StrCopy(out, "No reply from the radio."); + else if (err == vmErrRadio) + StrCopy(out, "The radio returned an error."); + else if (err == vmErrBadReply) + StrCopy(out, "Unexpected reply from the radio."); + else if (err == vmErrTooLong) + StrCopy(out, "Message too long."); + else if (err == serErrNotOpen) + StrCopy(out, "Not connected."); + else + StrPrintF(out, "Error 0x%x.", err); +} + +Err AppConnect(AppStatusFn status, Boolean quiet) +{ + Char msg[40]; + Err err; + + if (SessionIsConnected()) + return errNone; + if (status) + status("Connecting..."); + err = SessionConnect(); + if (err != errNone && !quiet) { + AppErrorText(err, msg); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + } + return err; +} diff --git a/palm-client/src/app.h b/palm-client/src/app.h new file mode 100644 index 0000000..a8d37d5 --- /dev/null +++ b/palm-client/src/app.h @@ -0,0 +1,36 @@ +/* + * App-wide state shared by the screens: which conversation is open, the + * saved link choice, and connecting with progress on screen. + */ +#ifndef VM_APP_H +#define VM_APP_H + +#include +#include "messages.h" + +#define VM_CREATOR 'VMsh' +#define VM_PREFS_ID 0 +#define VM_PREFS_VERSION 1 + +/* The conversation ConvoForm shows. */ +extern VmConv gAppConv; + +void AppOpenConversation(const VmConv *conv); + +/* Loads/saves the link choice (USB or serial) so the app reconnects the same way. */ +void AppLoadPrefs(void); +void AppSavePrefs(void); + +/* + * Connects (if not already), drawing progress with the given status callback, + * and reports a failure in an alert unless quiet. Returns the error. + */ +typedef void (*AppStatusFn)(const Char *text); +Err AppConnect(AppStatusFn status, Boolean quiet); +/* True once the launch-time automatic connect has been tried. */ +extern Boolean gAppAutoConnectTried; + +/* Short human text for a connect/send error. */ +void AppErrorText(Err err, Char *out); + +#endif diff --git a/palm-client/src/contacts.c b/palm-client/src/contacts.c index 3fa2434..1b85a9f 100644 --- a/palm-client/src/contacts.c +++ b/palm-client/src/contacts.c @@ -60,6 +60,31 @@ Boolean ContactsGet(UInt16 index, VmContact *out) return true; } +Boolean ContactsFindByPrefix(const UInt8 *prefix6, VmContact *out) +{ + UInt16 i, n; + MemHandle h; + Boolean found = false; + + if (ContactsOpen() != errNone) + return false; + n = DmNumRecords(gDb); + for (i = 0; i < n && !found; i++) { + const VmContact *c; + + h = DmQueryRecord(gDb, i); + if (!h) + continue; + c = MemHandleLock(h); + if (MemCmp(c->pubKey, prefix6, 6) == 0) { + MemMove(out, c, sizeof(VmContact)); + found = true; + } + MemHandleUnlock(h); + } + return found; +} + static Int16 CompareByName(void *a, void *b, Int16 other, SortRecordInfoPtr ia, SortRecordInfoPtr ib, MemHandle appInfo) { diff --git a/palm-client/src/contacts.h b/palm-client/src/contacts.h index acfc30f..057d1af 100644 --- a/palm-client/src/contacts.h +++ b/palm-client/src/contacts.h @@ -12,6 +12,8 @@ Err ContactsOpen(void); void ContactsClose(void); UInt16 ContactsCount(void); Boolean ContactsGet(UInt16 index, VmContact *out); +/* Finds a contact by the first 6 bytes of its key (how DMs name their sender). */ +Boolean ContactsFindByPrefix(const UInt8 *prefix6, VmContact *out); /* * Downloads the radio's whole contact list and replaces the stored one. The diff --git a/palm-client/src/contacts_form.c b/palm-client/src/contacts_form.c index f74e945..b3f684c 100644 --- a/palm-client/src/contacts_form.c +++ b/palm-client/src/contacts_form.c @@ -1,28 +1,52 @@ /* - * Contacts screen: the stored list (works offline), Refresh to download it - * from the radio, tap a contact for its details. + * Contacts, MeshTerm style: our node pinned first (star), then the stored + * contacts by name, each with its type mark, name, when it was last heard and + * its route. Refresh downloads the list; tap a contact for its details and + * Message to open a direct conversation. */ #include #include "resources.h" #include "protocol.h" #include "session.h" #include "contacts.h" +#include "convos.h" +#include "app.h" +#include "ui/draw.h" +#include "ui/text.h" +#include "ui/rowlist.h" #include "contacts_form.h" #define PALM_EPOCH_OFFSET 2082844800UL /* seconds from 1904-01-01 (Palm) to 1970-01-01 (Unix) */ +#define NAME_X 8 +#define NAME_W 82 +#define HEARD_R 110 + +static RowList gList; + +static Char TypeGlyph(UInt8 type) +{ + switch (type) { + case VM_ADV_TYPE_CHAT: return GLYPH_COMPANION; + case VM_ADV_TYPE_REPEATER: return GLYPH_REPEATER; + case VM_ADV_TYPE_ROOM: return GLYPH_ROOM; + case VM_ADV_TYPE_SENSOR: return GLYPH_SENSOR; + default: return GLYPH_UNKNOWN; + } +} static const Char *TypeName(UInt8 type) { switch (type) { - case VM_ADV_TYPE_CHAT: return "Chat"; + case VM_ADV_TYPE_CHAT: return "Companion"; case VM_ADV_TYPE_REPEATER: return "Repeater"; - case VM_ADV_TYPE_ROOM: return "Room"; + case VM_ADV_TYPE_ROOM: return "Room server"; case VM_ADV_TYPE_SENSOR: return "Sensor"; - default: return "?"; + default: return "Unknown"; } } -static void FormatHops(Char *out, UInt8 pathLen) +/* "direct", "2 hops", or "flood" (no known path). */ +static void FormatRoute(Char *out, UInt8 pathLen) { UInt8 hops = VM_PATH_HOPS(pathLen); @@ -34,131 +58,145 @@ static void FormatHops(Char *out, UInt8 pathLen) StrPrintF(out, "%u hop%s", hops, hops == 1 ? "" : "s"); } -/* List draw callback: name on the left, type and route on the right. */ -static void DrawContact(Int16 itemNum, RectangleType *bounds, Char **itemsText) +/* Row 0 is our own node when connected; the stored contacts follow. */ +static UInt16 SelfRows(void) { + return SessionIsConnected() ? 1 : 0; +} + +static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) +{ + FontID old = FntSetFont(vmSmallFont); + Coord x = b->topLeft.x, y = b->topLeft.y, right = x + b->extent.x; + Char mark, buf[16]; VmContact c; - Char right[24], hops[12]; - Int16 rightW, nameW; - UInt16 nameLen; - Boolean fits; - if (!ContactsGet((UInt16)itemNum, &c)) + if (row < SelfRows()) { + mark = GLYPH_SELF; + WinDrawChars(&mark, 1, x + 1, y); + DrawCut(SessionSelf()->name, x + NAME_X, y, NAME_W); + DrawRight("you", right - 1, y); + FntSetFont(old); return; - FormatHops(hops, c.outPathLen); - StrPrintF(right, "%s, %s", TypeName(c.type), hops); - rightW = FntCharsWidth(right, StrLen(right)); - WinDrawChars(right, StrLen(right), bounds->topLeft.x + bounds->extent.x - rightW - 2, bounds->topLeft.y); - - nameLen = StrLen(c.name); - nameW = bounds->extent.x - rightW - 8; - FntCharsInWidth(c.name, &nameW, &nameLen, &fits); - WinDrawChars(c.name, nameLen, bounds->topLeft.x + 1, bounds->topLeft.y); -} - -static void SetStatus(FormType *form, const Char *text) -{ - UInt16 index = FrmGetObjectIndex(form, ContactsStatusLabel); - - FrmHideObject(form, index); - FrmCopyLabel(form, ContactsStatusLabel, text); - FrmShowObject(form, index); -} - -static void LoadList(FormType *form, Boolean redraw) -{ - ListType *list = FrmGetObjectPtr(form, FrmGetObjectIndex(form, ContactsList)); - Char status[32]; - UInt16 n = ContactsCount(); - - LstSetListChoices(list, NULL, n); - LstSetDrawFunction(list, DrawContact); - LstSetSelection(list, noListSelection); - if (n == 0) - StrCopy(status, SessionIsConnected() ? "No contacts. Tap Refresh." : "No contacts stored."); - else - StrPrintF(status, "%u contact%s", n, n == 1 ? "" : "s"); - if (redraw) { - LstDrawList(list); - SetStatus(form, status); - } else { - FrmCopyLabel(form, ContactsStatusLabel, status); } + if (!ContactsGet(row - SelfRows(), &c)) { + FntSetFont(old); + return; + } + mark = TypeGlyph(c.type); + WinDrawChars(&mark, 1, x + 1, y); + DrawCut(c.name, x + NAME_X, y, NAME_W); + if (c.lastAdvert) { + UInt32 now = SessionNow(); + + TxtFormatAge(buf, now > c.lastAdvert ? now - c.lastAdvert : 0); + DrawRight(buf, x + HEARD_R, y); + } + FormatRoute(buf, c.outPathLen); + DrawRight(buf, right - 1, y); + FntSetFont(old); +} + +static void Load(Boolean draw) +{ + ContactsOpen(); + RowListSetCount(&gList, (UInt16)(ContactsCount() + SelfRows())); + if (draw) + RowListDraw(&gList); +} + +/* Title: "Contacts (n)". */ +static void SetTitle(FormType *form) +{ + static Char title[20]; + + StrPrintF(title, "Contacts (%u)", ContactsCount()); + FrmCopyTitle(form, title); } static void Refresh(FormType *form) { - UInt32 total = 0; - Char msg[40]; + Char msg[48]; Err err; if (!SessionIsConnected()) { - FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first.", "", ""); + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first (Node).", "", ""); return; } - SetStatus(form, "Downloading..."); - err = ContactsRefresh(&total); - LoadList(form, true); - if (err == errNone) - return; - if (err == vmErrNoReply) - StrCopy(msg, "No reply from the radio."); - else if (err == vmErrRadio) - StrCopy(msg, "The radio returned an error."); - else - StrPrintF(msg, "Refresh failed (0x%x).", err); - FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + err = ContactsRefresh(NULL); + SetTitle(form); + Load(true); + if (err != errNone) { + AppErrorText(err, msg); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + } } -static void ShowDetails(UInt16 index) +static void ShowDetails(UInt16 row) { VmContact c; DateTimeType dt; - Char line[96], hops[12], key[16]; + VmConv conv; + Char line[96], route[12]; - if (!ContactsGet(index, &c)) + if (row < SelfRows() || !ContactsGet(row - SelfRows(), &c)) return; - FormatHops(hops, c.outPathLen); - StrPrintF(key, "%02x%02x%02x%02x%02x%02x", c.pubKey[0], c.pubKey[1], c.pubKey[2], c.pubKey[3], - c.pubKey[4], c.pubKey[5]); + FormatRoute(route, c.outPathLen); if (c.lastAdvert) { TimSecondsToDateTime(c.lastAdvert + PALM_EPOCH_OFFSET, &dt); - StrPrintF(line, "%s, %s\nKey %s...\nLast advert %u-%02u-%02u %02u:%02u", TypeName(c.type), hops, key, - dt.year, dt.month, dt.day, dt.hour, dt.minute); + StrPrintF(line, "%s, %s\nKey %02x%02x%02x%02x%02x%02x...\nHeard %u-%02u-%02u %02u:%02u", + TypeName(c.type), route, c.pubKey[0], c.pubKey[1], c.pubKey[2], c.pubKey[3], c.pubKey[4], + c.pubKey[5], dt.year, dt.month, dt.day, dt.hour, dt.minute); } else { - StrPrintF(line, "%s, %s\nKey %s...", TypeName(c.type), hops, key); + StrPrintF(line, "%s, %s\nKey %02x%02x%02x%02x%02x%02x...", TypeName(c.type), route, + c.pubKey[0], c.pubKey[1], c.pubKey[2], c.pubKey[3], c.pubKey[4], c.pubKey[5]); + } + if (FrmCustomAlert(ContactInfoAlert, c.name, line, "") == 1) { /* Message */ + MemSet(&conv, sizeof(conv), 0); + conv.type = VM_CONV_DIRECT; + MemMove(conv.key, c.pubKey, 6); + AppOpenConversation(&conv); } - FrmCustomAlert(ContactInfoAlert, c.name, line, ""); } Boolean ContactsFormHandleEvent(EventType *event) { FormType *form = FrmGetActiveForm(); + Int16 tapped = -1; switch (event->eType) { case frmOpenEvent: - ContactsOpen(); - LoadList(form, false); + RowListInit(&gList, ContactsGadget, ContactsScroll, VM_ROW_H, DrawRow, NULL, NULL); + Load(false); + SetTitle(form); FrmDrawForm(form); + RowListDraw(&gList); return true; - case lstSelectEvent: - if (event->data.lstSelect.listID == ContactsList) { - ShowDetails((UInt16)event->data.lstSelect.selection); - return true; - } - break; + + case frmUpdateEvent: + SetTitle(form); + Load(true); + return true; + case ctlSelectEvent: switch (event->data.ctlSelect.controlID) { case ContactsRefreshButton: Refresh(form); return true; case ContactsDoneButton: - FrmGotoForm(MainForm); + FrmGotoForm(HomeForm); return true; } break; + default: break; } + + if (RowListHandleEvent(&gList, event, &tapped)) { + if (tapped >= 0) + ShowDetails((UInt16)tapped); + return true; + } return false; } diff --git a/palm-client/src/convo_form.c b/palm-client/src/convo_form.c new file mode 100644 index 0000000..c660c00 --- /dev/null +++ b/palm-client/src/convo_form.c @@ -0,0 +1,359 @@ +/* + * One conversation, MeshTerm's chat screen: day dividers, a name chip when + * the sender changes (ours is "* Name"), then the time and wrapped text, with + * SNR after received messages and the delivery mark after ours. Compose field + * with a byte counter at the bottom; tap a failed message to retry it. + */ +#include +#include "resources.h" +#include "protocol.h" +#include "session.h" +#include "messages.h" +#include "convos.h" +#include "app.h" +#include "ui/draw.h" +#include "ui/text.h" +#include "ui/rowlist.h" +#include "convo_form.h" + +#define MAX_MSGS 40 /* newest messages shown */ +#define MAX_LINES 200 +#define LINE_H VM_CHIP_H /* chips need the extra 2 px */ +#define TIME_X 2 +#define TEXT_X 26 +#define PALM_EPOCH 2082844800UL + +#define L_DAY 0 +#define L_CHIP 1 +#define L_TEXT 2 + +typedef struct { + UInt8 kind; + UInt8 first; /* first text line of a message: draw its time */ + UInt8 last; /* last line of a message: draw its SNR / delivery mark */ + UInt16 msg; /* message record */ + UInt16 off, len; /* the text on this line */ + UInt32 day; /* L_DAY: local day number */ +} Line; + +static Line *gLines = NULL; +static UInt16 gCount = 0; +static RowList gList; +static Char gTitle[VM_NAME_SIZE + 2]; + +static const Char *kDays[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; +static const Char *kMonths[] = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" }; + +static UInt16 TextWidth(void) +{ + RectangleType r; + FormType *form = FrmGetActiveForm(); + + FrmGetObjectBounds(form, FrmGetObjectIndex(form, ConvoGadget), &r); + return (UInt16)(r.extent.x - TEXT_X - 1); +} + +/* The sender name a message is filed under (for chips and grouping). */ +static void SenderOf(const VmMsgHeader *h, Char *out, UInt16 size) +{ + if (h->dir == VM_DIR_OUT) + StrPrintF(out, "%c %s", GLYPH_SELF, SessionSelf()->name[0] ? SessionSelf()->name : "you"); + else if (h->conv.type == VM_CONV_CHANNEL) + StrNCopy(out, h->sender[0] ? h->sender : "?", size - 1); + else + ContactNameForPrefix(h->conv.key, out, size); + out[size - 1] = 0; +} + +/* SNR after a received message, the delivery mark after ours (none for a sent channel message). */ +static void SuffixOf(const VmMsgHeader *h, Char *out) +{ + out[0] = 0; + if (h->dir == VM_DIR_IN) { + TxtFormatSnr(out, h->snrQuarterDb); + return; + } + switch (h->status) { + case VM_ST_PENDING: out[0] = GLYPH_ELLIPSIS; out[1] = 0; break; + case VM_ST_SENT: if (h->conv.type == VM_CONV_DIRECT) { out[0] = GLYPH_PENDING; out[1] = 0; } break; + case VM_ST_ACKED: out[0] = GLYPH_ACKED; out[1] = 0; break; + case VM_ST_FAILED: out[0] = GLYPH_FAILED; out[1] = 0; break; + } +} + +static UInt32 LocalDay(UInt32 unix) +{ + return (unix + PALM_EPOCH) / 86400UL; /* the Visor's clock is local time */ +} + +static void AddLine(UInt8 kind, UInt16 msg, UInt16 off, UInt16 len, Boolean first, Boolean last, UInt32 day) +{ + Line *l; + + if (gCount >= MAX_LINES) + return; + l = &gLines[gCount++]; + l->kind = kind; + l->msg = msg; + l->off = off; + l->len = len; + l->first = first; + l->last = last; + l->day = day; +} + +static void Build(void) +{ + UInt16 idx[MAX_MSGS]; + UInt16 nIdx = 0, i, n = MessagesCount(), width = TextWidth(); + 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; + /* the newest MAX_MSGS of this conversation, oldest first */ + for (i = n; i > 0 && nIdx < MAX_MSGS; i--) { + const VmMsgHeader *h = MessagesLock(i - 1); + + if (h) { + if (ConvEqual(&h->conv, &gAppConv)) + idx[nIdx++] = i - 1; + MessagesRelease(i - 1); + } + } + while (nIdx > 0) { + UInt16 m = idx[--nIdx], off = 0, len, used; + Boolean firstText = true; + const VmMsgHeader *h = MessagesLock(m); + const Char *text; + + if (!h) + continue; + text = (const Char *)(h + 1); + day = LocalDay(h->received); + if (day != lastDay) { + AddLine(L_DAY, m, 0, 0, false, false, day); + lastDay = day; + lastSender[0] = 0; + } + SenderOf(h, sender, sizeof(sender)); + if (StrCompare(sender, lastSender) != 0) { + AddLine(L_CHIP, m, 0, 0, false, false, 0); + StrCopy(lastSender, sender); + } + do { + len = TxtWrap(text + off, h->textLen - off, width, TxtSmallWidth, &used); + AddLine(L_TEXT, m, off, len, firstText, false, 0); + firstText = false; + off += used; + } while (off < h->textLen && used > 0); + /* the SNR / mark goes after the last line if it fits, else on a line of its own */ + SuffixOf(h, suffix); + if (suffix[0] && gCount > 0) { + Line *l = &gLines[gCount - 1]; + Int16 lineW = TxtWidth(text + l->off, l->len, TxtSmallWidth); + + if (lineW + 4 + TxtWidth(suffix, StrLen(suffix), TxtSmallWidth) > (Int16)width) + AddLine(L_TEXT, m, h->textLen, 0, false, false, 0); + } + if (gCount > 0) + gLines[gCount - 1].last = true; + MessagesRelease(m); + } + FntSetFont(old); +} + +static void DrawLine(UInt16 row, const RectangleType *b, void *ctx) +{ + const Line *l = &gLines[row]; + const VmMsgHeader *h = MessagesLock(l->msg); + FontID old = FntSetFont(vmSmallFont); + Coord x = b->topLeft.x, y = b->topLeft.y + 1; + Char buf[VM_NAME_SIZE + 4]; + DateTimeType dt; + + if (!h) { + FntSetFont(old); + return; + } + if (l->kind == L_DAY) { + TimSecondsToDateTime(l->day * 86400UL, &dt); + StrPrintF(buf, "%s %s %u", kDays[DayOfWeek(dt.month, dt.day, dt.year)], kMonths[dt.month - 1], dt.day); + DrawSection(buf, x, y, b->extent.x); + } else if (l->kind == L_CHIP) { + SenderOf(h, buf, sizeof(buf)); + DrawChip(buf, x + 1, b->topLeft.y); + } else { + const Char *text = (const Char *)(h + 1) + l->off; + + if (l->first) { + TimSecondsToDateTime(h->received + PALM_EPOCH, &dt); + StrPrintF(buf, "%02u:%02u", dt.hour, dt.minute); + WinDrawChars(buf, StrLen(buf), x + TIME_X, y); + } + WinDrawChars(text, l->len, x + TEXT_X, y); + if (l->last) { + SuffixOf(h, buf); + if (buf[0]) + WinDrawChars(buf, StrLen(buf), x + TEXT_X + FntCharsWidth(text, l->len) + (l->len ? 4 : 0), y); + } + } + MessagesRelease(l->msg); + FntSetFont(old); +} + +/* "12/130" bytes used, bottom right. */ +static void DrawCounter(void) +{ + FormType *form = FrmGetActiveForm(); + FieldType *field = FrmGetObjectPtr(form, FrmGetObjectIndex(form, ConvoField)); + const Char *t = FldGetTextPtr(field); + UInt16 limit = gAppConv.type == VM_CONV_CHANNEL ? VM_MAX_CHANNEL_TEXT : VM_MAX_DM_TEXT; + UInt8 utf8[VM_MAX_DM_TEXT + 4]; + UInt16 used = t ? TxtPalmToUtf8(t, StrLen(t), utf8, sizeof(utf8)) : 0; + RectangleType r; + Char buf[12]; + FontID old = FntSetFont(vmSmallFont); + + if (t && *t && used == 0) + used = sizeof(utf8); /* over even our buffer */ + StrPrintF(buf, "%u/%u", used, limit); + RctSetRectangle(&r, 100, 148, 46, 8); + WinEraseRectangle(&r, 0); + DrawRight(buf, 146, 149); + FntSetFont(old); +} + +static void Refresh(Boolean toEnd) +{ + MessagesMarkRead(&gAppConv); + Build(); + RowListSetCount(&gList, gCount); + if (toEnd) + RowListScrollToEnd(&gList); + RowListDraw(&gList); +} + +static void Send(FormType *form) +{ + FieldType *field = FrmGetObjectPtr(form, FrmGetObjectIndex(form, ConvoField)); + const Char *t = FldGetTextPtr(field); + UInt16 limit = gAppConv.type == VM_CONV_CHANNEL ? VM_MAX_CHANNEL_TEXT : VM_MAX_DM_TEXT; + UInt8 utf8[VM_MAX_DM_TEXT]; + UInt16 index; + Char msg[48]; + Err err; + + if (!t || !*t) + return; + if (TxtPalmToUtf8(t, StrLen(t), utf8, limit) == 0) { + StrPrintF(msg, "That's over the %u-byte limit.", limit); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + return; + } + if (!SessionIsConnected()) { + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first (Node).", "", ""); + return; + } + err = SessionSend(&gAppConv, t, &index); + FldDelete(field, 0, FldGetTextLength(field)); + DrawCounter(); + Refresh(true); + if (err == vmErrNoReply || (err != errNone && err != vmErrRadio)) { + AppErrorText(err, msg); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + } +} + +static void Tapped(UInt16 row) +{ + const VmMsgHeader *h = MessagesLock(gLines[row].msg); + Boolean failed; + + if (!h) + return; + failed = h->dir == VM_DIR_OUT && h->status == VM_ST_FAILED; + MessagesRelease(gLines[row].msg); + if (failed && FrmAlert(RetryAlert) == 0) { + SessionRetry(gLines[row].msg); + Refresh(false); + } +} + +Boolean ConvoFormHandleEvent(EventType *event) +{ + FormType *form = FrmGetActiveForm(); + Int16 tapped = -1; + + switch (event->eType) { + case frmOpenEvent: + if (!gLines) + gLines = MemPtrNew(sizeof(Line) * MAX_LINES); + if (!gLines) + return false; + ConvName(&gAppConv, gTitle, VM_NAME_SIZE); + FrmCopyTitle(form, gTitle); + RowListInit(&gList, ConvoGadget, ConvoScroll, LINE_H, DrawLine, NULL, NULL); + MessagesMarkRead(&gAppConv); + Build(); + RowListSetCount(&gList, gCount); + RowListScrollToEnd(&gList); + FrmDrawForm(form); + RowListDraw(&gList); + DrawCounter(); + FrmSetFocus(form, FrmGetObjectIndex(form, ConvoField)); + return true; + + case frmCloseEvent: + if (gLines) { + MemPtrFree(gLines); + gLines = NULL; + } + return false; + + case frmUpdateEvent: + if (gLines) + Refresh(gList.top + RowListVisibleRows(&gList) >= gCount); /* follow new messages if at the end */ + return true; + + case fldChangedEvent: + DrawCounter(); + return false; + + case ctlSelectEvent: + switch (event->data.ctlSelect.controlID) { + case ConvoSendButton: + Send(form); + return true; + case ConvoBackButton: + FrmGotoForm(HomeForm); + return true; + } + break; + + case keyDownEvent: + if (event->data.keyDown.chr == linefeedChr) { /* Graffiti return sends */ + Send(form); + return true; + } + break; + + default: + break; + } + + if (gLines && RowListHandleEvent(&gList, event, &tapped)) { + if (tapped >= 0) + Tapped((UInt16)tapped); + return true; + } + return false; +} + +void ConvoFormIdle(void) +{ + if (gLines) + DrawCounter(); +} diff --git a/palm-client/src/convo_form.h b/palm-client/src/convo_form.h new file mode 100644 index 0000000..4869283 --- /dev/null +++ b/palm-client/src/convo_form.h @@ -0,0 +1,10 @@ +#ifndef VM_CONVO_FORM_H +#define VM_CONVO_FORM_H + +#include + +Boolean ConvoFormHandleEvent(EventType *event); +/* Called on idle while the form is up (keeps the byte counter current). */ +void ConvoFormIdle(void); + +#endif diff --git a/palm-client/src/convos.c b/palm-client/src/convos.c new file mode 100644 index 0000000..e9e19f7 --- /dev/null +++ b/palm-client/src/convos.c @@ -0,0 +1,199 @@ +#include +#include "protocol.h" +#include "ui/glyphs.h" +#include "channels.h" +#include "contacts.h" +#include "messages.h" +#include "convos.h" + +static void HexPrefix(const UInt8 *p, Char *out) +{ + StrPrintF(out, "%02x%02x%02x%02x", p[0], p[1], p[2], p[3]); +} + +void ContactNameForPrefix(const UInt8 *prefix, Char *out, UInt16 size) +{ + VmContact c; + + if (ContactsFindByPrefix(prefix, &c)) { + StrNCopy(out, c.name, size - 1); + out[size - 1] = 0; + } else if (size > 8) { + HexPrefix(prefix, out); + } else { + out[0] = 0; + } +} + +/* Channel names: "#foo" shows as marker '#' + "foo"; slot 0 / Public as '@'; others are private. */ +static Char ChannelMarker(const VmChannel *c) +{ + if (c->name[0] == '#') + return '#'; + if (c->idx == 0 || StrCaselessCompare(c->name, "Public") == 0) + return '@'; + return GLYPH_LOCK; +} + +static void ChannelDisplayName(const VmChannel *c, Char *out, UInt16 size) +{ + const Char *n = c->name[0] == '#' ? c->name + 1 : c->name; + + if (!*n) + StrPrintF(out, "Channel %u", c->idx); + else { + StrNCopy(out, n, size - 1); + out[size - 1] = 0; + } +} + +void ConvName(const VmConv *conv, Char *out, UInt16 size) +{ + VmChannel c; + + if (conv->type == VM_CONV_DIRECT) { + ContactNameForPrefix(conv->key, out, size); + } else if (ChannelsFindSlot(conv->channel, &c)) { + ChannelDisplayName(&c, out, size); + } else { + StrPrintF(out, "Channel %u", conv->channel); + } +} + +static void AddSection(VmConvRow *rows, UInt16 *n, UInt16 max, const Char *label) +{ + if (*n >= max) + return; + MemSet(&rows[*n], sizeof(VmConvRow), 0); + rows[*n].kind = VM_ROW_SECTION; + StrCopy(rows[*n].name, label); + (*n)++; +} + +static VmConvRow *AddConv(VmConvRow *rows, UInt16 *n, UInt16 max, const VmConv *conv, Char marker, + const Char *name) +{ + VmConvRow *r; + + if (*n >= max) + return NULL; + r = &rows[(*n)++]; + MemSet(r, sizeof(VmConvRow), 0); + r->kind = VM_ROW_CONV; + r->conv = *conv; + r->marker = marker; + StrNCopy(r->name, name, VM_NAME_SIZE - 1); + return r; +} + +static VmConvRow *FindRow(VmConvRow *rows, UInt16 n, const VmConv *conv) +{ + UInt16 i; + + for (i = 0; i < n; i++) + if (rows[i].kind == VM_ROW_CONV && ConvEqual(&rows[i].conv, conv)) + return &rows[i]; + return NULL; +} + +static void SetPreview(VmConvRow *r, const VmMsgHeader *h) +{ + const Char *text = (const Char *)(h + 1); + UInt16 len = 0; + + if (h->dir == VM_DIR_OUT) { + StrCopy(r->preview, "you: "); + len = 5; + } else if (h->sender[0]) { + StrNCopy(r->preview, h->sender, 12); + r->preview[12] = 0; + len = StrLen(r->preview); + r->preview[len++] = ':'; + r->preview[len++] = ' '; + } + StrNCopy(r->preview + len, text, VM_PREVIEW_LEN - 1 - len); + r->preview[VM_PREVIEW_LEN - 1] = 0; +} + +UInt16 ConvosBuild(VmConvRow *rows, UInt16 max) +{ + VmChannel ch; + VmContact ct; + VmConv conv; + VmConvRow *r, tmp; + UInt16 n = 0, i, j, directStart, count; + Char name[VM_NAME_SIZE]; + + ChannelsOpen(); + ContactsOpen(); + MessagesOpen(); + + AddSection(rows, &n, max, "Channels"); + count = ChannelsCount(); + for (i = 0; i < count; i++) { + if (!ChannelsGet(i, &ch)) + continue; + MemSet(&conv, sizeof(conv), 0); + conv.type = VM_CONV_CHANNEL; + conv.channel = ch.idx; + ChannelDisplayName(&ch, name, sizeof(name)); + AddConv(rows, &n, max, &conv, ChannelMarker(&ch), name); + } + + AddSection(rows, &n, max, "Direct"); + directStart = n; + count = ContactsCount(); + for (i = 0; i < count; i++) { + if (!ContactsGet(i, &ct) || ct.type != VM_ADV_TYPE_CHAT) + continue; + MemSet(&conv, sizeof(conv), 0); + conv.type = VM_CONV_DIRECT; + MemMove(conv.key, ct.pubKey, 6); + AddConv(rows, &n, max, &conv, GLYPH_UNKNOWN, ct.name); + } + + /* one pass over the messages: newest wins the preview */ + count = MessagesCount(); + for (i = 0; i < count; i++) { + const VmMsgHeader *h = MessagesLock(i); + + if (!h) + continue; + r = FindRow(rows, n, &h->conv); + if (!r && h->conv.type == VM_CONV_DIRECT) { /* a DM from someone not in contacts */ + ContactNameForPrefix(h->conv.key, name, sizeof(name)); + r = AddConv(rows, &n, max, &h->conv, GLYPH_UNKNOWN, name); + } + if (r) { + if (h->received >= r->last) { + r->last = h->received; + SetPreview(r, h); + } + if (h->unread) + r->unread++; + if (h->dir == VM_DIR_OUT && h->status == VM_ST_FAILED) + r->failed = true; + if (r->conv.type == VM_CONV_DIRECT) + r->marker = GLYPH_COMPANION; /* has history */ + } + MessagesRelease(i); + } + + /* direct: most recent first; those without messages keep their (alphabetical) order */ + for (i = directStart + 1; i < n; i++) { + tmp = rows[i]; + for (j = i; j > directStart && rows[j - 1].last < tmp.last; j--) + rows[j] = rows[j - 1]; + rows[j] = tmp; + } + return n; +} + +UInt16 ConvosUnread(const VmConvRow *rows, UInt16 n) +{ + UInt16 i, total = 0; + + for (i = 0; i < n; i++) + total += rows[i].unread; + return total; +} diff --git a/palm-client/src/convos.h b/palm-client/src/convos.h new file mode 100644 index 0000000..0b44eb4 --- /dev/null +++ b/palm-client/src/convos.h @@ -0,0 +1,37 @@ +/* + * The conversation list: channels (slot order) then direct conversations + * (most recent first), with unread counts, last activity and a preview, + * built from the channel cache, the contacts and one pass over the messages. + */ +#ifndef VM_CONVOS_H +#define VM_CONVOS_H + +#include +#include "messages.h" + +#define VM_ROW_SECTION 0 +#define VM_ROW_CONV 1 +#define VM_PREVIEW_LEN 40 + +typedef struct { + UInt8 kind; /* VM_ROW_SECTION (name is the label) or VM_ROW_CONV */ + Char marker; /* glyph before the name */ + VmConv conv; + Char name[VM_NAME_SIZE]; + UInt16 unread; + UInt32 last; /* Unix seconds of the newest message, 0 = none */ + Boolean failed; /* an outgoing message here wasn't delivered */ + Char preview[VM_PREVIEW_LEN]; +} VmConvRow; + +/* Fills rows (sections included); returns how many. */ +UInt16 ConvosBuild(VmConvRow *rows, UInt16 max); +/* Total unread messages across conversations. */ +UInt16 ConvosUnread(const VmConvRow *rows, UInt16 n); + +/* Display name for a conversation (channel name, contact name, or key prefix in hex). */ +void ConvName(const VmConv *conv, Char *out, UInt16 size); +/* Display name for a DM sender / contact key prefix. */ +void ContactNameForPrefix(const UInt8 *prefix, Char *out, UInt16 size); + +#endif diff --git a/palm-client/src/home_form.c b/palm-client/src/home_form.c new file mode 100644 index 0000000..516c62a --- /dev/null +++ b/palm-client/src/home_form.c @@ -0,0 +1,158 @@ +/* + * Home: the conversation list, MeshTerm's chat picker. Channels in slot + * order, then direct conversations (most recent first). Each row: marker, + * name, unread badge or failed mark, age, preview. Tap to open. + */ +#include +#include "resources.h" +#include "session.h" +#include "convos.h" +#include "app.h" +#include "ui/draw.h" +#include "ui/text.h" +#include "ui/rowlist.h" +#include "home_form.h" + +#define HOME_MAX_ROWS 64 +#define NAME_X 8 +#define NAME_W 56 +#define BADGE_R 84 +#define AGE_R 100 +#define PREVIEW_X 103 + +static VmConvRow *gRows = NULL; +static UInt16 gCount = 0; +static RowList gList; + +static void DrawRow(UInt16 row, const RectangleType *b, void *ctx) +{ + const VmConvRow *r = &gRows[row]; + FontID old = FntSetFont(vmSmallFont); + Coord x = b->topLeft.x, y = b->topLeft.y, right = x + b->extent.x; + Char buf[12]; + + if (r->kind == VM_ROW_SECTION) { + FntSetFont(old); + DrawSection(r->name, x, y, b->extent.x); + return; + } + WinDrawChars(&r->marker, 1, x + 1, y); + DrawCut(r->name, x + NAME_X, y, NAME_W); + if (r->failed) { + buf[0] = GLYPH_FAILED; + buf[1] = 0; + DrawRight(buf, x + BADGE_R, y); + } else if (r->unread) { + StrPrintF(buf, "%c%u", GLYPH_COMPANION, r->unread); + DrawRight(buf, x + BADGE_R, y); + } + if (r->last) { + UInt32 now = SessionNow(); + + TxtFormatAge(buf, now > r->last ? now - r->last : 0); + DrawRight(buf, x + AGE_R, y); + DrawCut(r->preview, x + PREVIEW_X, y, right - (x + PREVIEW_X)); + } + FntSetFont(old); +} + +static Boolean Selectable(UInt16 row, void *ctx) +{ + return gRows[row].kind == VM_ROW_CONV; +} + +/* Right end of the title bar: unread total and connection state. */ +static void DrawTitleStatus(void) +{ + RectangleType r; + Char buf[24]; + FontID old = FntSetFont(vmSmallFont); + UInt16 unread = ConvosUnread(gRows, gCount); + + RctSetRectangle(&r, 100, 2, 60, 9); + WinEraseRectangle(&r, 0); + if (unread) + StrPrintF(buf, "%c%u %s", GLYPH_COMPANION, unread, SessionIsConnected() ? "online" : "offline"); + else + StrCopy(buf, SessionIsConnected() ? "online" : "offline"); + DrawRight(buf, 158, 4); + FntSetFont(old); +} + +static void ShowStatus(const Char *text) +{ + RectangleType r; + FontID old = FntSetFont(vmSmallFont); + + RctSetRectangle(&r, 100, 2, 60, 9); + WinEraseRectangle(&r, 0); + DrawRight(text, 158, 4); + FntSetFont(old); +} + +static void Rebuild(Boolean draw) +{ + gCount = ConvosBuild(gRows, HOME_MAX_ROWS); + RowListSetCount(&gList, gCount); + if (draw) { + RowListDraw(&gList); + DrawTitleStatus(); + } +} + +Boolean HomeFormHandleEvent(EventType *event) +{ + Int16 tapped = -1; + + switch (event->eType) { + case frmOpenEvent: + if (!gRows) + gRows = MemPtrNew(sizeof(VmConvRow) * HOME_MAX_ROWS); + if (!gRows) + return false; + RowListInit(&gList, HomeGadget, HomeScroll, VM_ROW_H, DrawRow, Selectable, NULL); + Rebuild(false); + FrmDrawForm(FrmGetActiveForm()); + RowListDraw(&gList); + DrawTitleStatus(); + if (!gAppAutoConnectTried && !SessionIsConnected()) { + gAppAutoConnectTried = true; + AppConnect(ShowStatus, true); + Rebuild(true); + } + return true; + + case frmCloseEvent: + if (gRows) { + MemPtrFree(gRows); + gRows = NULL; + } + return false; + + case frmUpdateEvent: + if (gRows) + Rebuild(true); + return true; + + case ctlSelectEvent: + switch (event->data.ctlSelect.controlID) { + case HomeContactsButton: + FrmGotoForm(ContactsForm); + return true; + case HomeNodeButton: + FrmGotoForm(MainForm); + return true; + } + break; + + default: + break; + } + + if (gRows && RowListHandleEvent(&gList, event, &tapped)) { + if (tapped >= 0) + AppOpenConversation(&gRows[tapped].conv); + return true; + } + return false; +} diff --git a/palm-client/src/home_form.h b/palm-client/src/home_form.h new file mode 100644 index 0000000..09ca2c5 --- /dev/null +++ b/palm-client/src/home_form.h @@ -0,0 +1,8 @@ +#ifndef VM_HOME_FORM_H +#define VM_HOME_FORM_H + +#include + +Boolean HomeFormHandleEvent(EventType *event); + +#endif diff --git a/palm-client/src/main.c b/palm-client/src/main.c index b83ba29..d61342d 100644 --- a/palm-client/src/main.c +++ b/palm-client/src/main.c @@ -1,17 +1,22 @@ #include #include "resources.h" -#include "protocol.h" -#include "transport.h" #include "session.h" -#include "ports.h" -#include "settings.h" #include "contacts.h" +#include "channels.h" +#include "messages.h" +#include "app.h" +#include "home_form.h" +#include "convo_form.h" #include "contacts_form.h" +#include "node_form.h" +#include "settings.h" +#include "ports.h" #include "preview_form.h" #include "ui/draw.h" #define VM_MIN_ROM_VERSION sysMakeROMVersion(3, 5, 0, sysROMStageRelease, 0) -#define VM_LABEL_CHARS 22 /* the info labels in the .rcp are padded to this width */ +#define VM_POLL_TICKS (SysTicksPerSecond() / 2) +#define VM_UPDATE_DATA 0x0100 /* frmUpdateEvent code: new messages / contacts */ static Err RomVersionCompatible(UInt32 required, UInt16 launchFlags) { @@ -26,143 +31,15 @@ static Err RomVersionCompatible(UInt32 required, UInt16 launchFlags) return sysErrRomIncompatible; } -/* Replaces a label's text, truncated to the width reserved for it in the .rcp. */ -static void SetLabel(FormType *form, UInt16 id, const Char *text) +/* The Options menu is the same on every screen. */ +static Boolean HandleMenu(UInt16 itemID) { - Char buf[VM_LABEL_CHARS + 1]; - UInt16 index = FrmGetObjectIndex(form, id); - Boolean visible = FrmVisible(form); - - StrNCopy(buf, text, VM_LABEL_CHARS); - buf[VM_LABEL_CHARS] = 0; - if (visible) - FrmHideObject(form, index); - FrmCopyLabel(form, id, buf); - if (visible) - FrmShowObject(form, index); -} - -/* Formats e.g. 869618 kHz as "869.618 MHz" and 62500 Hz as "62.5" (kHz), without floating point. */ -static void FormatFreq(Char *out, UInt32 kHz) -{ - StrPrintF(out, "%lu.%03lu MHz", kHz / 1000, kHz % 1000); -} - -static void FormatBandwidth(Char *out, UInt32 hz) -{ - if (hz % 1000) - StrPrintF(out, "%lu.%lu", hz / 1000, (hz % 1000) / 100); - else - StrPrintF(out, "%lu", hz / 1000); -} - -static void ShowRadioInfo(FormType *form) -{ - const VmDeviceInfo *dev = SessionDevice(); - const VmSelfInfo *self = SessionSelf(); - Char buf[40], bw[12]; - - if (!SessionIsConnected()) { - SetLabel(form, MainNameLabel, "Not connected"); - SetLabel(form, MainFreqLabel, "-"); - SetLabel(form, MainModeLabel, "-"); - SetLabel(form, MainPowerLabel, "-"); - SetLabel(form, MainFirmwareLabel, "-"); - CtlSetLabel(FrmGetObjectPtr(form, FrmGetObjectIndex(form, MainConnectButton)), "Connect"); - return; - } - SetLabel(form, MainNameLabel, self->name); - FormatFreq(buf, self->freqKHz); - SetLabel(form, MainFreqLabel, buf); - FormatBandwidth(bw, self->bwHz); - StrPrintF(buf, "BW %s SF%u CR%u", bw, self->sf, self->cr); - SetLabel(form, MainModeLabel, buf); - StrPrintF(buf, "%d dBm (max %u)", (Int16)(Int8)self->txPowerDbm, self->maxTxPowerDbm); - SetLabel(form, MainPowerLabel, buf); - StrPrintF(buf, "%s (%u)", dev->version, dev->fwVerCode); - SetLabel(form, MainFirmwareLabel, buf); - CtlSetLabel(FrmGetObjectPtr(form, FrmGetObjectIndex(form, MainConnectButton)), "Disconnect"); -} - -static void ConnectOrDisconnect(FormType *form) -{ - Char msg[32]; - Err err; - - if (SessionIsConnected()) { - SessionDisconnect(); - ShowRadioInfo(form); - return; - } - - SetLabel(form, MainNameLabel, "Connecting..."); - err = SessionConnect(); - if (err == errNone) { - ShowRadioInfo(form); - return; - } - ShowRadioInfo(form); - if (err == vmErrNoReply) - StrCopy(msg, "No reply from radio"); - else if (err == vmErrRadio) - StrCopy(msg, "Radio returned an error"); - else if (err == vmErrBadReply) - StrCopy(msg, "Unexpected reply"); - else - StrPrintF(msg, "Port error 0x%x", err); - SetLabel(form, MainNameLabel, msg); -} - -static Boolean MainFormHandleEvent(EventType *event) -{ - FormType *form = FrmGetActiveForm(); - - switch (event->eType) { - case frmOpenEvent: { - UInt16 link = (TransportGetPort() == VM_PORT_USB) ? MainUsbPush : MainSerialPush; - - FrmSetControlGroupSelection(form, MainLinkGroup, link); - ShowRadioInfo(form); - FrmDrawForm(form); - return true; - } - case ctlSelectEvent: - switch (event->data.ctlSelect.controlID) { - case MainSerialPush: - case MainUsbPush: - /* Changing the link drops any open connection; it applies on the next Connect. */ - if (SessionIsConnected()) { - SessionDisconnect(); - ShowRadioInfo(form); - } - TransportSetPort(event->data.ctlSelect.controlID == MainUsbPush ? VM_PORT_USB : VM_PORT_SERIAL); - return true; - case MainConnectButton: - ConnectOrDisconnect(form); - return true; - case MainContactsButton: - FrmGotoForm(ContactsForm); - return true; - case MainSettingsButton: - if (SessionIsConnected()) - FrmGotoForm(SettingsForm); - else - FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first.", "", ""); - return true; - } - break; - case menuEvent: - if (event->data.menu.itemID == MainMenuPorts) { - FrmGotoForm(PortsForm); - return true; - } - if (event->data.menu.itemID == MainMenuFontPreview) { - FrmGotoForm(FontPreviewForm); - return true; - } - break; - default: - break; + switch (itemID) { + case MainMenuHome: FrmGotoForm(HomeForm); return true; + case MainMenuContacts: FrmGotoForm(ContactsForm); return true; + case MainMenuNode: FrmGotoForm(MainForm); return true; + case MainMenuPorts: FrmGotoForm(PortsForm); return true; + case MainMenuFontPreview: FrmGotoForm(FontPreviewForm); return true; } return false; } @@ -172,31 +49,47 @@ static Boolean AppHandleEvent(EventType *event) FormType *form; UInt16 formId; + if (event->eType == menuEvent) + return HandleMenu(event->data.menu.itemID); if (event->eType != frmLoadEvent) return false; formId = event->data.frmLoad.formID; form = FrmInitForm(formId); FrmSetActiveForm(form); - if (formId == MainForm) - FrmSetEventHandler(form, MainFormHandleEvent); - else if (formId == PortsForm) - FrmSetEventHandler(form, PortsFormHandleEvent); - else if (formId == SettingsForm) - FrmSetEventHandler(form, SettingsFormHandleEvent); - else if (formId == ContactsForm) - FrmSetEventHandler(form, ContactsFormHandleEvent); - else if (formId == FontPreviewForm) - FrmSetEventHandler(form, FontPreviewFormHandleEvent); + switch (formId) { + case HomeForm: FrmSetEventHandler(form, HomeFormHandleEvent); break; + case ConvoForm: FrmSetEventHandler(form, ConvoFormHandleEvent); break; + case ContactsForm: FrmSetEventHandler(form, ContactsFormHandleEvent); break; + case MainForm: FrmSetEventHandler(form, NodeFormHandleEvent); break; + case SettingsForm: FrmSetEventHandler(form, SettingsFormHandleEvent); break; + case PortsForm: FrmSetEventHandler(form, PortsFormHandleEvent); break; + case FontPreviewForm: FrmSetEventHandler(form, FontPreviewFormHandleEvent); break; + } return true; } +/* While connected, wake regularly to handle what the radio sends and refresh the screen on show. */ +static void Poll(void) +{ + UInt16 formId = FrmGetActiveFormID(); + + if (SessionPoll()) + FrmUpdateForm(formId, VM_UPDATE_DATA); + if (formId == ConvoForm) + ConvoFormIdle(); +} + static void AppEventLoop(void) { EventType event; Err err; do { - EvtGetEvent(&event, evtWaitForever); + EvtGetEvent(&event, SessionIsConnected() ? VM_POLL_TICKS : evtWaitForever); + if (event.eType == nilEvent) { + Poll(); + continue; + } if (SysHandleEvent(&event)) continue; if (MenuHandleEvent(0, &event, &err)) @@ -215,12 +108,15 @@ UInt32 PilotMain(UInt16 cmd, MemPtr cmdPBP, UInt16 launchFlags) return err; if (cmd == sysAppLaunchCmdNormalLaunch) { UiFontInit(); - FrmGotoForm(MainForm); + AppLoadPrefs(); + FrmGotoForm(HomeForm); AppEventLoop(); SessionDisconnect(); - ContactsClose(); - UiFontRelease(); FrmCloseAllForms(); + ContactsClose(); + ChannelsClose(); + MessagesClose(); + UiFontRelease(); } return errNone; } diff --git a/palm-client/src/node_form.c b/palm-client/src/node_form.c new file mode 100644 index 0000000..16197d2 --- /dev/null +++ b/palm-client/src/node_form.c @@ -0,0 +1,169 @@ +/* + * Node: this radio's details, the link (USB / serial), connect/disconnect, + * settings and sending an advert. + */ +#include +#include "resources.h" +#include "protocol.h" +#include "transport.h" +#include "session.h" +#include "app.h" +#include "node_form.h" + +#define VM_LABEL_CHARS 22 /* the info labels in the .rcp are padded to this width */ + +/* Replaces a label's text, truncated to the width reserved for it in the .rcp. */ +static void SetLabel(FormType *form, UInt16 id, const Char *text) +{ + Char buf[VM_LABEL_CHARS + 1]; + UInt16 index = FrmGetObjectIndex(form, id); + Boolean visible = FrmVisible(form); + + StrNCopy(buf, text, VM_LABEL_CHARS); + buf[VM_LABEL_CHARS] = 0; + if (visible) + FrmHideObject(form, index); + FrmCopyLabel(form, id, buf); + if (visible) + FrmShowObject(form, index); +} + +/* Formats e.g. 869618 kHz as "869.618 MHz" and 62500 Hz as "62.5" (kHz), without floating point. */ +static void FormatFreq(Char *out, UInt32 kHz) +{ + StrPrintF(out, "%lu.%03lu MHz", kHz / 1000, kHz % 1000); +} + +static void FormatBandwidth(Char *out, UInt32 hz) +{ + if (hz % 1000) + StrPrintF(out, "%lu.%lu", hz / 1000, (hz % 1000) / 100); + else + StrPrintF(out, "%lu", hz / 1000); +} + +static void ShowRadioInfo(FormType *form) +{ + const VmDeviceInfo *dev = SessionDevice(); + const VmSelfInfo *self = SessionSelf(); + Char buf[40], bw[12]; + + if (!SessionIsConnected()) { + SetLabel(form, MainNameLabel, "Not connected"); + SetLabel(form, MainFreqLabel, "-"); + SetLabel(form, MainModeLabel, "-"); + SetLabel(form, MainPowerLabel, "-"); + SetLabel(form, MainFirmwareLabel, "-"); + CtlSetLabel(FrmGetObjectPtr(form, FrmGetObjectIndex(form, MainConnectButton)), "Connect"); + return; + } + SetLabel(form, MainNameLabel, self->name); + FormatFreq(buf, self->freqKHz); + SetLabel(form, MainFreqLabel, buf); + FormatBandwidth(bw, self->bwHz); + StrPrintF(buf, "BW %s SF%u CR%u", bw, self->sf, self->cr); + SetLabel(form, MainModeLabel, buf); + StrPrintF(buf, "%d dBm (max %u)", (Int16)self->txPowerDbm, self->maxTxPowerDbm); + SetLabel(form, MainPowerLabel, buf); + StrPrintF(buf, "%s (%u)", dev->version, dev->fwVerCode); + SetLabel(form, MainFirmwareLabel, buf); + CtlSetLabel(FrmGetObjectPtr(form, FrmGetObjectIndex(form, MainConnectButton)), "Disconnect"); +} + +static FormType *gStatusForm; + +static void ShowStatus(const Char *text) +{ + SetLabel(gStatusForm, MainNameLabel, text); +} + +static void ConnectOrDisconnect(FormType *form) +{ + Char msg[40]; + Err err; + + if (SessionIsConnected()) { + SessionDisconnect(); + ShowRadioInfo(form); + return; + } + gStatusForm = form; + err = AppConnect(ShowStatus, true); + ShowRadioInfo(form); + if (err != errNone) { + AppErrorText(err, msg); + SetLabel(form, MainNameLabel, msg); + } +} + +static void SendAdvert(void) +{ + UInt16 choice; + Char msg[40]; + Err err; + + if (!SessionIsConnected()) { + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first.", "", ""); + return; + } + choice = FrmAlert(AdvertAlert); /* 0 zero-hop, 1 flood, 2 cancel */ + if (choice > 1) + return; + err = SessionSendAdvert(choice == 1); + if (err != errNone) { + AppErrorText(err, msg); + FrmCustomAlert(SettingsErrorAlert, msg, "", ""); + } +} + +Boolean NodeFormHandleEvent(EventType *event) +{ + FormType *form = FrmGetActiveForm(); + + switch (event->eType) { + case frmOpenEvent: { + UInt16 link = (TransportGetPort() == VM_PORT_USB) ? MainUsbPush : MainSerialPush; + + FrmSetControlGroupSelection(form, MainLinkGroup, link); + ShowRadioInfo(form); + FrmDrawForm(form); + return true; + } + case frmUpdateEvent: + ShowRadioInfo(form); + return true; + + case ctlSelectEvent: + switch (event->data.ctlSelect.controlID) { + case MainSerialPush: + case MainUsbPush: + /* Changing the link drops any open connection; it applies on the next Connect. */ + if (SessionIsConnected()) { + SessionDisconnect(); + ShowRadioInfo(form); + } + TransportSetPort(event->data.ctlSelect.controlID == MainUsbPush ? VM_PORT_USB : VM_PORT_SERIAL); + AppSavePrefs(); + return true; + case MainConnectButton: + ConnectOrDisconnect(form); + return true; + case MainSettingsButton: + if (SessionIsConnected()) + FrmGotoForm(SettingsForm); + else + FrmCustomAlert(SettingsErrorAlert, "Connect to the radio first.", "", ""); + return true; + case MainAdvertButton: + SendAdvert(); + return true; + case MainDoneButton: + FrmGotoForm(HomeForm); + return true; + } + break; + default: + break; + } + return false; +} diff --git a/palm-client/src/node_form.h b/palm-client/src/node_form.h new file mode 100644 index 0000000..7162ed3 --- /dev/null +++ b/palm-client/src/node_form.h @@ -0,0 +1,8 @@ +#ifndef VM_NODE_FORM_H +#define VM_NODE_FORM_H + +#include + +Boolean NodeFormHandleEvent(EventType *event); + +#endif diff --git a/palm-client/src/preview_form.c b/palm-client/src/preview_form.c index 21c683f..4135fba 100644 --- a/palm-client/src/preview_form.c +++ b/palm-client/src/preview_form.c @@ -30,18 +30,18 @@ static void DrawPreview(void) Coord y = TOP; FontID old = FntSetFont(vmSmallFont); - DrawSection("Channels", y); y += VM_ROW_H; + DrawSection("Channels", 0, y, 160); y += VM_ROW_H; StrPrintF(line, "%c2", GLYPH_COMPANION); Row(y, '@', "Public", line, "5m", "Steve: spare antenna?"); y += VM_ROW_H; Row(y, '#', "phillymesh", NULL, "1h", "ok see you there"); y += VM_ROW_H; - DrawSection("Direct", y); y += VM_ROW_H; + DrawSection("Direct", 0, y, 160); y += VM_ROW_H; StrPrintF(line, "%c", GLYPH_FAILED); Row(y, GLYPH_COMPANION, "Rich K.", line, "23h", "test from the visor"); y += VM_ROW_H; Row(y, GLYPH_REPEATER, "Hilltop Repeater", NULL, "2d", NULL); y += VM_ROW_H; Row(y, GLYPH_ROOM, "Rittenhouse Room", NULL, "3d", NULL); y += VM_ROW_H; Row(y, GLYPH_SENSOR, "Weather Sensor", NULL, NULL, NULL); y += VM_ROW_H; - DrawSection("Thu Nov 1", y); y += VM_ROW_H + 1; + DrawSection("Thu Nov 1", 0, y, 160); y += VM_ROW_H + 1; DrawChip("Steve K.", 1, y); y += VM_CHIP_H + 1; WinDrawChars("11:30", 5, 4, y); WinDrawChars("I'll bring a spare antenna", 26, 26, y); y += VM_ROW_H; diff --git a/palm-client/src/resources.h b/palm-client/src/resources.h index 30e78a3..f37b37a 100644 --- a/palm-client/src/resources.h +++ b/palm-client/src/resources.h @@ -11,10 +11,14 @@ #define MainPowerLabel 1008 #define MainFirmwareLabel 1009 #define MainSettingsButton 1010 -#define MainContactsButton 1011 +#define MainAdvertButton 1011 +#define MainDoneButton 1012 #define MainMenuBar 1000 #define MainMenuPorts 1001 #define MainMenuFontPreview 1002 +#define MainMenuHome 1003 +#define MainMenuContacts 1004 +#define MainMenuNode 1005 #define MainLinkGroup 1 #define SettingsForm 1200 @@ -39,11 +43,27 @@ #define RebootRadioAlert 2003 #define ContactsForm 1300 -#define ContactsList 1301 -#define ContactsStatusLabel 1302 +#define ContactsGadget 1301 +#define ContactsScroll 1302 #define ContactsRefreshButton 1303 #define ContactsDoneButton 1304 +#define HomeForm 1500 +#define HomeGadget 1501 +#define HomeScroll 1502 +#define HomeContactsButton 1503 +#define HomeNodeButton 1504 + +#define ConvoForm 1600 +#define ConvoGadget 1601 +#define ConvoScroll 1602 +#define ConvoField 1603 +#define ConvoSendButton 1604 +#define ConvoBackButton 1605 + +#define AdvertAlert 2004 +#define RetryAlert 2005 + #define PortsForm 1100 #define PortsDoneButton 1101 diff --git a/palm-client/src/ui/draw.c b/palm-client/src/ui/draw.c index dbef57b..6130958 100644 --- a/palm-client/src/ui/draw.c +++ b/palm-client/src/ui/draw.c @@ -23,20 +23,20 @@ void UiFontRelease(void) } } -void DrawSection(const Char *label, Coord y) +void DrawSection(const Char *label, Coord x0, Coord y, Coord width) { Char rule = GLYPH_RULE; FontID old = FntSetFont(vmSmallFont); Coord ruleW = FntCharWidth(rule); Coord labelW = FntCharsWidth(label, StrLen(label)); - Coord x = 0; + Coord x = x0; UInt16 i; for (i = 0; i < 2; i++, x += ruleW) WinDrawChars(&rule, 1, x, y); x += 2; WinDrawChars(label, StrLen(label), x, y); - for (x += labelW + 2; x + ruleW <= 160; x += ruleW) + for (x += labelW + 2; x + ruleW <= x0 + width; x += ruleW) WinDrawChars(&rule, 1, x, y); FntSetFont(old); } diff --git a/palm-client/src/ui/draw.h b/palm-client/src/ui/draw.h index a460487..258e2bc 100644 --- a/palm-client/src/ui/draw.h +++ b/palm-client/src/ui/draw.h @@ -15,8 +15,8 @@ Err UiFontInit(void); void UiFontRelease(void); -/* "── Label ──" across the full width at y, in the small font. */ -void DrawSection(const Char *label, Coord y); +/* "── Label ──" from x to x + width at y, in the small font. */ +void DrawSection(const Char *label, Coord x, Coord y, Coord width); /* A name chip: text inverted (white on black), VM_CHIP_H tall. Returns its width. */ #define VM_CHIP_H (VM_SMALL_FONT_HEIGHT + 2)