ucmd_chat.c 65 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533
  1. /* chat: native client for Cloudron Chat on the ngui canvas toolkit.
  2. *
  3. * Login is the native Cloudron OIDC driver in chat_login.c (username,
  4. * password, optional TOTP) or a pasted session cookie. The session cookie is
  5. * kept in a uhttp cookie jar and saved with the server address in a small
  6. * config file: /data/CHAT.CFG on an installed disk, /share/chat.cfg when
  7. * there is no persistent /data mount, or the path given as argument.
  8. * The password is never stored.
  9. *
  10. * Everything else is the Chat REST API over uhttp: the channel and DM
  11. * directory, message pages (newest first, older paging with ?before=, live
  12. * updates with ?after=), sending, read markers, joining public channels and
  13. * opening DMs. There is no WebSocket: the open conversation is polled every
  14. * ~2 s and the directory every ~12 s, and polling waits while the user types.
  15. *
  16. * Network calls block the UI; the frame showing the "Loading" status is
  17. * presented first. TLS certificates are NOT verified (tls.c phase A), which
  18. * the login screen says. */
  19. #include "ucmd_lib.h"
  20. #include "ngui.h"
  21. #include "uhttp.h"
  22. #include "ujson.h"
  23. #include "chat_login.h"
  24. #include <stdlib.h>
  25. #include <string.h>
  26. #define DEFAULT_CFG_DATA "/data/CHAT.CFG"
  27. #define DEFAULT_CFG_SHARE "/share/chat.cfg"
  28. #define RESP_CAP (512u * 1024u)
  29. #define JSON_NODES 16384u
  30. #define JSON_SCAP (RESP_CAP + 2u * JSON_NODES)
  31. #define MAX_CONV 128
  32. #define MAX_MSG 240
  33. #define MAX_PICK 256
  34. #define BODY_MAX 4096
  35. #define PAGE_SIZE 50
  36. #define LIVE_PAGE 50
  37. #define POLL_CONV_MS 2000
  38. #define POLL_CONV_IDLE_MS 5000
  39. #define POLL_DIR_MS 12000
  40. #define POLL_DIR_IDLE_MS 20000
  41. #define TYPING_HOLD_MS 1000
  42. #define KEEPALIVE_IDLE_MS 30000
  43. /* widget IDs */
  44. enum {
  45. ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS,
  46. ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND,
  47. ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG,
  48. ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000
  49. };
  50. enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN };
  51. enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM };
  52. /* pending actions, collected while drawing and run after the frame */
  53. enum {
  54. ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
  55. ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
  56. ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
  57. ACT_COOKIE_SCREEN, ACT_BACK
  58. };
  59. struct conv {
  60. char id[48];
  61. char name[64];
  62. char preview[96];
  63. char kind; /* 'c' public, 'p' private, 'd' DM */
  64. char presence; /* DM: 'o' online, 'a' away, 'f' offline */
  65. int unread;
  66. };
  67. struct msg {
  68. char id[48];
  69. char user_id[48];
  70. char author[48];
  71. char created[32]; /* ISO 8601 UTC, sorts as text */
  72. char reply[96]; /* "Name: snippet" */
  73. char extra[112]; /* attachments / thread / reactions line */
  74. char *body; /* Latin-1, malloc'd */
  75. unsigned char action; /* type "me" */
  76. int height;
  77. int layout_w;
  78. int compact;
  79. int day_header;
  80. };
  81. struct pick {
  82. char id[48];
  83. char name[64];
  84. char sub[64];
  85. };
  86. static struct ngui ui;
  87. static struct uhttp http;
  88. static struct uhttp_jar jar;
  89. static struct chat_login login;
  90. static struct ujson json;
  91. static struct ujson_node *jnodes;
  92. static char *jsbuf;
  93. static char *resp;
  94. static unsigned int resp_len;
  95. static enum screen screen = SCR_SERVER;
  96. static enum modal modal = MODAL_NONE;
  97. static int action, action_arg;
  98. static char cfg_path[CHAT_PATH_MAX];
  99. static int cfg_is_default;
  100. static char server[CHAT_SERVER_MAX];
  101. static char server_host[UHTTP_HOST_MAX];
  102. static int server_secure;
  103. static char saved_cookie[CHAT_COOKIE_MAX];
  104. static unsigned int saved_jar_changes;
  105. static char me_id[48];
  106. static char me_name[64];
  107. static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in;
  108. static struct ngui_input cookie_in, compose_in, filter_in;
  109. static struct conv convs[MAX_CONV];
  110. static int nconv;
  111. static int cur = -1; /* index into convs */
  112. static char cur_id[48];
  113. static struct msg msgs[MAX_MSG];
  114. static int nmsg;
  115. static int has_older;
  116. static unsigned int msgs_gen; /* bumped whenever msgs[] changes */
  117. static int history_full;
  118. static struct ngui_scroll tl_scroll, side_scroll, modal_scroll;
  119. static int at_bottom = 1;
  120. static int new_below;
  121. static struct pick picks[MAX_PICK];
  122. static int npick;
  123. static int modal_sel; /* keyboard selection among visible rows */
  124. static unsigned int last_older_ms;
  125. static char status[160];
  126. static int status_err;
  127. static char busy[96];
  128. static int offline;
  129. static unsigned int backoff_ms;
  130. static unsigned int next_conv_poll, next_dir_poll, retry_at;
  131. static unsigned int last_input_ms;
  132. static unsigned int last_net_ms;
  133. static unsigned int client_seq;
  134. /* ---- small string helpers ---- */
  135. static void s_copy(char *d, const char *s, unsigned int cap)
  136. {
  137. unsigned int i = 0;
  138. if (!cap)
  139. return;
  140. while (s && s[i] && i + 1 < cap) {
  141. d[i] = s[i];
  142. i++;
  143. }
  144. d[i] = '\0';
  145. }
  146. static void s_cat(char *d, const char *s, unsigned int cap)
  147. {
  148. unsigned int n = (unsigned int)strlen(d);
  149. if (n < cap)
  150. s_copy(d + n, s, cap - n);
  151. }
  152. static void s_cat_uint(char *d, unsigned int v, unsigned int cap)
  153. {
  154. char tmp[12];
  155. int i = 11;
  156. tmp[i] = '\0';
  157. do {
  158. tmp[--i] = (char)('0' + v % 10);
  159. v /= 10;
  160. } while (v && i > 0);
  161. s_cat(d, tmp + i, cap);
  162. }
  163. static void set_status(const char *a, const char *b, int err)
  164. {
  165. status[0] = '\0';
  166. s_cat(status, a, sizeof(status));
  167. if (b)
  168. s_cat(status, b, sizeof(status));
  169. status_err = err;
  170. ngui_invalidate(&ui);
  171. }
  172. /* ---- UTF-8 -> Latin-1 display text ---- */
  173. static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap,
  174. const char *s)
  175. {
  176. while (*s && n + 1 < cap)
  177. d[n++] = *s++;
  178. return n;
  179. }
  180. /* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip
  181. * it entirely (joiners, variation selectors, skin tones). */
  182. static const char *cp_fallback(unsigned int cp)
  183. {
  184. switch (cp) {
  185. case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'";
  186. case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\"";
  187. case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-";
  188. case 0x2014: case 0x2015: return "--";
  189. case 0x2026: return "...";
  190. case 0x2022: case 0x2023: case 0x25CF: return "\xb7";
  191. case 0x20AC: return "EUR";
  192. case 0x2122: return "TM";
  193. case 0x2192: return "->";
  194. case 0x2190: return "<-";
  195. case 0x2264: return "<=";
  196. case 0x2265: return ">=";
  197. case 0x2260: return "!=";
  198. case 0x2764: case 0x2665: return "<3";
  199. case 0x2705: case 0x2714: case 0x2713: return "[v]";
  200. case 0x274C: case 0x2716: return "[x]";
  201. case 0x26A0: return "/!\\";
  202. case 0x1F44D: return "(y)";
  203. case 0x1F44E: return "(n)";
  204. case 0x1F44B: return "o/";
  205. case 0x1F64F: return "_/\\_";
  206. case 0x1F389: case 0x1F38A: return "*\\o/*";
  207. case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A:
  208. case 0x1F642: case 0x263A: return ":)";
  209. case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D";
  210. case 0x1F609: return ";)";
  211. case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P";
  212. case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":(";
  213. case 0x1F62E: case 0x1F632: return ":O";
  214. case 0x1F914: return ":-/";
  215. case 0x1F525: return "(fire)";
  216. case 0x1F680: return "(rocket)";
  217. case 0x1F440: return "(eyes)";
  218. case 0x200B: case 0x200C: case 0x200D: case 0xFEFF:
  219. return 0;
  220. }
  221. if (cp >= 0xFE00 && cp <= 0xFE0F)
  222. return 0; /* variation selectors */
  223. if (cp >= 0x1F3FB && cp <= 0x1F3FF)
  224. return 0; /* skin tones */
  225. if (cp >= 0x2000 && cp <= 0x200A)
  226. return " ";
  227. return "?";
  228. }
  229. /* Convert UTF-8 to Latin-1 display text. Tabs become spaces, other control
  230. * characters (except newline) are dropped. */
  231. static unsigned int to_latin1(char *d, unsigned int cap, const char *s)
  232. {
  233. const unsigned char *p = (const unsigned char *)s;
  234. unsigned int n = 0;
  235. if (!cap)
  236. return 0;
  237. while (*p && n + 1 < cap) {
  238. unsigned int cp, extra, i;
  239. if (*p < 0x80) {
  240. cp = *p++;
  241. } else {
  242. if ((*p & 0xE0) == 0xC0) {
  243. cp = *p & 0x1F;
  244. extra = 1;
  245. } else if ((*p & 0xF0) == 0xE0) {
  246. cp = *p & 0x0F;
  247. extra = 2;
  248. } else if ((*p & 0xF8) == 0xF0) {
  249. cp = *p & 0x07;
  250. extra = 3;
  251. } else {
  252. p++;
  253. d[n++] = '?';
  254. continue;
  255. }
  256. p++;
  257. for (i = 0; i < extra; i++) {
  258. if ((*p & 0xC0) != 0x80)
  259. break;
  260. cp = (cp << 6) | (*p++ & 0x3F);
  261. }
  262. if (i < extra) {
  263. d[n++] = '?';
  264. continue;
  265. }
  266. }
  267. if (cp == '\t' || cp == 0xA0) {
  268. d[n++] = ' ';
  269. } else if (cp == '\n') {
  270. d[n++] = '\n';
  271. } else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) {
  272. continue;
  273. } else if (cp < 0x100) {
  274. d[n++] = (char)cp;
  275. } else {
  276. const char *f = cp_fallback(cp);
  277. if (f)
  278. n = put_ascii(d, n, cap, f);
  279. }
  280. }
  281. d[n] = '\0';
  282. return n;
  283. }
  284. /* One-line version (newlines become spaces), for previews/snippets. */
  285. static void to_latin1_line(char *d, unsigned int cap, const char *s)
  286. {
  287. unsigned int i;
  288. to_latin1(d, cap, s);
  289. for (i = 0; d[i]; i++)
  290. if (d[i] == '\n')
  291. d[i] = ' ';
  292. }
  293. /* ---- config file ---- */
  294. static int read_file(const char *path, char *buf, unsigned int cap)
  295. {
  296. int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1));
  297. if (n < 0)
  298. return n;
  299. buf[n] = '\0';
  300. return n;
  301. }
  302. static int write_file(const char *path, const char *buf, unsigned int len)
  303. {
  304. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
  305. }
  306. /* The persistent data volume wins when it is mounted and writable; the
  307. * volatile /share is the fallback (live USB, or a board without /data). */
  308. static const char *default_cfg_path(void)
  309. {
  310. struct sys_mount m;
  311. unsigned int i;
  312. for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++)
  313. if (strcmp(m.name, "data") == 0 && !m.ro)
  314. return DEFAULT_CFG_DATA;
  315. return DEFAULT_CFG_SHARE;
  316. }
  317. static int set_server(const char *s)
  318. {
  319. char norm[CHAT_SERVER_MAX];
  320. if (chat_server_normalize(s, norm, sizeof(norm)) != 0)
  321. return -1;
  322. if (chat_server_host(norm, server_host, sizeof(server_host),
  323. &server_secure) != 0)
  324. return -1;
  325. s_copy(server, norm, sizeof(server));
  326. return 0;
  327. }
  328. /* Export the Chat host's cookies and write the config file. */
  329. static void save_config(void)
  330. {
  331. static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128];
  332. int n;
  333. uhttp_jar_header(&jar, server_host, "/api/me", server_secure,
  334. saved_cookie, sizeof(saved_cookie));
  335. saved_jar_changes = jar.changes;
  336. n = chat_config_format(out, sizeof(out), server, saved_cookie);
  337. if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0)
  338. set_status("Could not save the session to ", cfg_path, 1);
  339. memset(out, 0, sizeof(out));
  340. }
  341. /* A server may roll its session cookie: save when the jar changed. */
  342. static void maybe_save_cookie(void)
  343. {
  344. char now[CHAT_COOKIE_MAX];
  345. if (jar.changes == saved_jar_changes || screen != SCR_MAIN)
  346. return;
  347. uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now,
  348. sizeof(now));
  349. saved_jar_changes = jar.changes;
  350. if (strcmp(now, saved_cookie) != 0)
  351. save_config();
  352. }
  353. /* ---- HTTP / JSON plumbing ---- */
  354. static void paint_now(void);
  355. static void net_drop(void)
  356. {
  357. http.keepalive = 0;
  358. uhttp_close(&http);
  359. }
  360. /* Request server + path; JSON body or NULL. Returns the HTTP status or a
  361. * UHTTP_ERR_*; the body is in resp/resp_len. */
  362. static int api(const char *method, const char *path, const char *body)
  363. {
  364. char url[CHAT_SERVER_MAX + 256];
  365. unsigned int len = 0;
  366. int st;
  367. s_copy(url, server, sizeof(url));
  368. s_cat(url, path, sizeof(url));
  369. http.jar = &jar;
  370. http.accept = "application/json";
  371. st = chat_http(&http, method, url, body, resp, RESP_CAP, &len);
  372. resp_len = st > 0 ? len : 0;
  373. last_net_ms = u_ticks_ms();
  374. maybe_save_cookie();
  375. return st;
  376. }
  377. static int parse_resp(void)
  378. {
  379. int root = ujson_parse(&json, resp, resp_len);
  380. return root;
  381. }
  382. static void go_login(const char *why);
  383. /* Common error handling for API calls in the main screen. Returns 1 when
  384. * the status is a success. */
  385. static int api_ok(int st, const char *what)
  386. {
  387. if (st >= 200 && st < 300) {
  388. if (offline) {
  389. offline = 0;
  390. set_status("Connected", 0, 0);
  391. }
  392. backoff_ms = 0;
  393. return 1;
  394. }
  395. if (st == 401) {
  396. go_login("Session expired - please sign in again");
  397. return 0;
  398. }
  399. if (st > 0) {
  400. char code[64];
  401. s_copy(code, what, sizeof(code));
  402. s_cat(code, ": HTTP ", sizeof(code));
  403. s_cat_uint(code, (unsigned int)st, sizeof(code));
  404. set_status(code, 0, 1);
  405. return 0;
  406. }
  407. offline = 1;
  408. backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 :
  409. backoff_ms < 10000 ? 10000 : 30000;
  410. retry_at = u_ticks_ms() + backoff_ms;
  411. set_status("Offline: ", uhttp_error_string(st), 1);
  412. net_drop();
  413. return 0;
  414. }
  415. /* ---- conversations ---- */
  416. static int conv_find(const char *id)
  417. {
  418. int i;
  419. for (i = 0; i < nconv; i++)
  420. if (strcmp(convs[i].id, id) == 0)
  421. return i;
  422. return -1;
  423. }
  424. static void conv_from_json(struct conv *c, int o, int dm)
  425. {
  426. int last;
  427. s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id));
  428. c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0);
  429. c->preview[0] = '\0';
  430. last = ujson_get(&json, o, "lastMessage");
  431. if (ujson_type(&json, last) == UJSON_OBJECT) {
  432. char tmp[96];
  433. to_latin1_line(tmp, sizeof(tmp),
  434. ujson_get_str(&json, last, "authorName"));
  435. s_copy(c->preview, tmp, sizeof(c->preview));
  436. s_cat(c->preview, ": ", sizeof(c->preview));
  437. to_latin1_line(tmp, sizeof(tmp),
  438. ujson_get_str(&json, last, "body"));
  439. s_cat(c->preview, tmp, sizeof(c->preview));
  440. }
  441. if (dm) {
  442. int other = ujson_get(&json, o, "otherUser");
  443. const char *pres = ujson_get_str(&json, o, "presence");
  444. const char *nm = ujson_get_str(&json, other, "name");
  445. if (!nm[0])
  446. nm = ujson_get_str(&json, other, "username");
  447. to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)");
  448. c->kind = 'd';
  449. c->presence = strcmp(pres, "online") == 0 ? 'o' :
  450. strcmp(pres, "away") == 0 ? 'a' : 'f';
  451. } else {
  452. to_latin1_line(c->name, sizeof(c->name),
  453. ujson_get_str(&json, o, "name"));
  454. c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ?
  455. 'p' : 'c';
  456. c->presence = 0;
  457. }
  458. }
  459. static int load_directory(void)
  460. {
  461. static struct conv next[MAX_CONV];
  462. int n = 0, st, root, it, pass;
  463. for (pass = 0; pass < 2; pass++) {
  464. st = api(0, pass ? "/api/dms" : "/api/channels", 0);
  465. if (!api_ok(st, pass ? "Direct messages" : "Channels"))
  466. return -1;
  467. root = parse_resp();
  468. if (root < 0) {
  469. set_status("Bad directory reply: ", json.error, 1);
  470. return -1;
  471. }
  472. for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV;
  473. it = ujson_next(&json, it)) {
  474. if (ujson_truthy(&json, ujson_get(&json, it, "archived")))
  475. continue;
  476. if (pass && ujson_truthy(&json, ujson_get(&json, it,
  477. "isSelf")))
  478. continue;
  479. conv_from_json(&next[n], it, pass);
  480. if (next[n].id[0])
  481. n++;
  482. }
  483. }
  484. memcpy(convs, next, sizeof(struct conv) * (unsigned int)n);
  485. nconv = n;
  486. cur = cur_id[0] ? conv_find(cur_id) : -1;
  487. if (cur >= 0 && at_bottom)
  488. convs[cur].unread = 0; /* we are reading it */
  489. ngui_invalidate(&ui);
  490. return 0;
  491. }
  492. /* ---- messages ---- */
  493. static void msg_free(struct msg *m)
  494. {
  495. free(m->body);
  496. m->body = 0;
  497. }
  498. static void clear_messages(void)
  499. {
  500. int i;
  501. for (i = 0; i < nmsg; i++)
  502. msg_free(&msgs[i]);
  503. nmsg = 0;
  504. msgs_gen++;
  505. has_older = 0;
  506. history_full = 0;
  507. new_below = 0;
  508. }
  509. static int msg_find(const char *id)
  510. {
  511. int i;
  512. for (i = nmsg - 1; i >= 0; i--)
  513. if (strcmp(msgs[i].id, id) == 0)
  514. return i;
  515. return -1;
  516. }
  517. static void build_extra(struct msg *m, int o)
  518. {
  519. int it, n;
  520. m->extra[0] = '\0';
  521. for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
  522. it >= 0; it = ujson_next(&json, it)) {
  523. char name[64];
  524. to_latin1_line(name, sizeof(name),
  525. ujson_get_str(&json, it, "filename"));
  526. if (m->extra[0])
  527. s_cat(m->extra, ", ", sizeof(m->extra));
  528. else
  529. s_cat(m->extra, "[file] ", sizeof(m->extra));
  530. s_cat(m->extra, name, sizeof(m->extra));
  531. }
  532. if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT) {
  533. if (m->extra[0])
  534. s_cat(m->extra, " ", sizeof(m->extra));
  535. s_cat(m->extra, "[GIF]", sizeof(m->extra));
  536. }
  537. if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) {
  538. if (m->extra[0])
  539. s_cat(m->extra, " ", sizeof(m->extra));
  540. s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra));
  541. }
  542. if (ujson_get_str(&json, o, "callUrl")[0]) {
  543. if (m->extra[0])
  544. s_cat(m->extra, " ", sizeof(m->extra));
  545. s_cat(m->extra, "[call]", sizeof(m->extra));
  546. }
  547. n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0);
  548. if (n > 0) {
  549. if (m->extra[0])
  550. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  551. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  552. s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra));
  553. }
  554. n = 0;
  555. for (it = ujson_first(&json, ujson_get(&json, o, "reactions"));
  556. it >= 0; it = ujson_next(&json, it)) {
  557. int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1);
  558. n += c > 0 ? c : 1;
  559. }
  560. if (n > 0) {
  561. if (m->extra[0])
  562. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  563. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  564. s_cat(m->extra, n == 1 ? " reaction" : " reactions",
  565. sizeof(m->extra));
  566. }
  567. if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) {
  568. if (m->extra[0])
  569. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  570. s_cat(m->extra, "pinned", sizeof(m->extra));
  571. }
  572. }
  573. /* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */
  574. static int msg_from_json(struct msg *m, int o)
  575. {
  576. static char body[BODY_MAX + 8];
  577. const char *nm;
  578. int rt;
  579. unsigned int len;
  580. if (ujson_truthy(&json, ujson_get(&json, o, "deleted")))
  581. return -1;
  582. /* Thread replies live in the thread panel, not the timeline. */
  583. if (ujson_get_str(&json, o, "parentId")[0])
  584. return -1;
  585. memset(m, 0, sizeof(*m));
  586. s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id));
  587. if (!m->id[0])
  588. return -1;
  589. s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id));
  590. nm = ujson_get_str(&json, o, "authorName");
  591. if (!nm[0])
  592. nm = ujson_get_str(&json, o, "authorUsername");
  593. to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
  594. s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
  595. sizeof(m->created));
  596. m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
  597. len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body"));
  598. if (len + 1 >= BODY_MAX) {
  599. /* truncated: mark it */
  600. body[BODY_MAX - 4] = '.';
  601. body[BODY_MAX - 3] = '.';
  602. body[BODY_MAX - 2] = '.';
  603. body[BODY_MAX - 1] = '\0';
  604. }
  605. /* Trim trailing newlines/spaces. */
  606. len = (unsigned int)strlen(body);
  607. while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
  608. body[--len] = '\0';
  609. m->body = strdup(body);
  610. if (!m->body)
  611. return -1;
  612. rt = ujson_get(&json, o, "replyTo");
  613. if (ujson_type(&json, rt) == UJSON_OBJECT) {
  614. char tmp[96];
  615. to_latin1_line(m->reply, sizeof(m->reply),
  616. ujson_get_str(&json, rt, "authorName"));
  617. s_cat(m->reply, ": ", sizeof(m->reply));
  618. if (ujson_truthy(&json, ujson_get(&json, rt, "deleted")))
  619. s_copy(tmp, "(deleted)", sizeof(tmp));
  620. else
  621. to_latin1_line(tmp, sizeof(tmp),
  622. ujson_get_str(&json, rt, "body"));
  623. if (!tmp[0])
  624. s_copy(tmp, "(attachment)", sizeof(tmp));
  625. s_cat(m->reply, tmp, sizeof(m->reply));
  626. }
  627. build_extra(m, o);
  628. return 0;
  629. }
  630. static int msg_before(const struct msg *a, const struct msg *b)
  631. {
  632. int c = strcmp(a->created, b->created);
  633. return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0);
  634. }
  635. /* Insert or update a message, keeping msgs sorted. older: we are paging
  636. * back in history (never evict old messages for it). Returns 1 when a new
  637. * message was added, 0 when updated/skipped. */
  638. static int msg_merge(struct msg *m, int older)
  639. {
  640. int i = msg_find(m->id), pos;
  641. msgs_gen++;
  642. if (i >= 0) {
  643. /* Edited body or new reactions: replace in place. */
  644. msg_free(&msgs[i]);
  645. msgs[i] = *m;
  646. return 0;
  647. }
  648. if (nmsg >= MAX_MSG) {
  649. if (older) {
  650. history_full = 1;
  651. msg_free(m);
  652. return 0;
  653. }
  654. msg_free(&msgs[0]);
  655. memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1));
  656. nmsg--;
  657. has_older = 1;
  658. history_full = 1;
  659. }
  660. pos = nmsg;
  661. while (pos > 0 && msg_before(m, &msgs[pos - 1]))
  662. pos--;
  663. memmove(&msgs[pos + 1], &msgs[pos],
  664. sizeof(struct msg) * (unsigned int)(nmsg - pos));
  665. msgs[pos] = *m;
  666. nmsg++;
  667. return 1;
  668. }
  669. /* Merge every message of the parsed reply. Returns the number added. */
  670. static int merge_reply(int root, int older, int *count)
  671. {
  672. int it, added = 0, n = 0;
  673. for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) {
  674. struct msg m;
  675. const char *id = ujson_get_str(&json, it, "id");
  676. n++;
  677. if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) {
  678. /* A deletion we already show: drop it. */
  679. int k = msg_find(id);
  680. if (k >= 0) {
  681. msg_free(&msgs[k]);
  682. memmove(&msgs[k], &msgs[k + 1],
  683. sizeof(struct msg) *
  684. (unsigned int)(nmsg - k - 1));
  685. nmsg--;
  686. msgs_gen++;
  687. }
  688. continue;
  689. }
  690. if (msg_from_json(&m, it) == 0)
  691. added += msg_merge(&m, older);
  692. }
  693. if (count)
  694. *count = n;
  695. return added;
  696. }
  697. static void mark_read(void)
  698. {
  699. char path[96];
  700. int st;
  701. if (cur < 0)
  702. return;
  703. s_copy(path, "/api/channels/", sizeof(path));
  704. s_cat(path, convs[cur].id, sizeof(path));
  705. s_cat(path, "/read", sizeof(path));
  706. st = api("POST", path, 0);
  707. if (api_ok(st, "Mark read"))
  708. convs[cur].unread = 0;
  709. }
  710. static void msgs_path(char *path, unsigned int cap, const char *query)
  711. {
  712. s_copy(path, "/api/channels/", cap);
  713. s_cat(path, cur_id, cap);
  714. s_cat(path, "/messages?", cap);
  715. s_cat(path, query, cap);
  716. }
  717. static void scroll_to_end(void)
  718. {
  719. tl_scroll.offset = 1 << 28; /* clamped when laid out */
  720. at_bottom = 1;
  721. new_below = 0;
  722. }
  723. static void open_conv(int idx)
  724. {
  725. char path[160];
  726. int st, root, n = 0;
  727. if (idx < 0 || idx >= nconv)
  728. return;
  729. cur = idx;
  730. s_copy(cur_id, convs[idx].id, sizeof(cur_id));
  731. clear_messages();
  732. scroll_to_end();
  733. s_copy(busy, "Loading messages...", sizeof(busy));
  734. paint_now();
  735. msgs_path(path, sizeof(path), "limit=50");
  736. st = api(0, path, 0);
  737. busy[0] = '\0';
  738. if (!api_ok(st, "Messages"))
  739. return;
  740. root = parse_resp();
  741. if (root < 0) {
  742. set_status("Bad message reply: ", json.error, 1);
  743. return;
  744. }
  745. merge_reply(root, 1, &n);
  746. has_older = n >= PAGE_SIZE;
  747. scroll_to_end();
  748. mark_read();
  749. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  750. ngui_invalidate(&ui);
  751. }
  752. static int content_height(void);
  753. static void load_older(void)
  754. {
  755. char path[200], q[96];
  756. int st, root, n = 0, before_h, added;
  757. if (cur < 0 || !nmsg || history_full)
  758. return;
  759. last_older_ms = u_ticks_ms();
  760. s_copy(q, "limit=50&before=", sizeof(q));
  761. s_cat(q, msgs[0].id, sizeof(q));
  762. msgs_path(path, sizeof(path), q);
  763. s_copy(busy, "Loading older messages...", sizeof(busy));
  764. paint_now();
  765. st = api(0, path, 0);
  766. busy[0] = '\0';
  767. if (!api_ok(st, "Older messages"))
  768. return;
  769. root = parse_resp();
  770. if (root < 0)
  771. return;
  772. before_h = content_height();
  773. added = merge_reply(root, 1, &n);
  774. has_older = n >= PAGE_SIZE && !history_full;
  775. /* Keep the view on the same message. */
  776. if (added)
  777. tl_scroll.offset += content_height() - before_h;
  778. ngui_invalidate(&ui);
  779. }
  780. static void poll_conv(void)
  781. {
  782. char path[200], q[96];
  783. int st, root, added, n = 0;
  784. if (cur < 0)
  785. return;
  786. if (!nmsg) {
  787. msgs_path(path, sizeof(path), "limit=50");
  788. } else {
  789. s_copy(q, "limit=50&after=", sizeof(q));
  790. s_cat(q, msgs[nmsg - 1].id, sizeof(q));
  791. msgs_path(path, sizeof(path), q);
  792. }
  793. st = api(0, path, 0);
  794. if (st == 404 && nmsg) {
  795. /* The anchor message was deleted: reload the page. */
  796. open_conv(cur);
  797. return;
  798. }
  799. if (!api_ok(st, "Messages"))
  800. return;
  801. root = parse_resp();
  802. if (root < 0) {
  803. set_status("Bad message reply: ", json.error, 1);
  804. return;
  805. }
  806. added = merge_reply(root, 0, &n);
  807. if (n >= LIVE_PAGE) {
  808. /* More than a page arrived: jump to the newest page. */
  809. open_conv(cur);
  810. return;
  811. }
  812. if (added) {
  813. if (at_bottom) {
  814. scroll_to_end();
  815. mark_read();
  816. } else {
  817. new_below += added;
  818. }
  819. ngui_invalidate(&ui);
  820. }
  821. }
  822. static void make_client_id(char *out, unsigned int cap)
  823. {
  824. static const char hex[] = "0123456789abcdef";
  825. unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20);
  826. unsigned int c = ++client_seq, i;
  827. s_copy(out, "nebos-", cap);
  828. for (i = 0; i < 8; i++) {
  829. char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 };
  830. s_cat(out, ch, cap);
  831. }
  832. s_cat(out, "-", cap);
  833. s_cat_uint(out, c, cap);
  834. }
  835. static void send_message(void)
  836. {
  837. static char body[NGUI_INPUT_MAX * 6 + 160];
  838. char path[96], cid[40];
  839. int st, root, r;
  840. unsigned int n = 0;
  841. const char *t = compose_in.text;
  842. while (*t == ' ')
  843. t++;
  844. if (cur < 0 || !*t)
  845. return;
  846. make_client_id(cid, sizeof(cid));
  847. s_copy(body, "{\"body\":", sizeof(body));
  848. n = (unsigned int)strlen(body);
  849. {
  850. /* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */
  851. static char utf8[NGUI_INPUT_MAX * 2 + 4];
  852. unsigned int k = 0;
  853. const unsigned char *p = (const unsigned char *)t;
  854. while (*p && k + 3 < sizeof(utf8)) {
  855. if (*p < 0x80) {
  856. utf8[k++] = (char)*p;
  857. } else {
  858. utf8[k++] = (char)(0xC0 | (*p >> 6));
  859. utf8[k++] = (char)(0x80 | (*p & 0x3F));
  860. }
  861. p++;
  862. }
  863. utf8[k] = '\0';
  864. r = ujson_escape(body + n, sizeof(body) - n, utf8);
  865. }
  866. if (r < 0)
  867. return;
  868. n += (unsigned int)r;
  869. s_cat(body, ",\"clientId\":\"", sizeof(body));
  870. s_cat(body, cid, sizeof(body));
  871. s_cat(body, "\"}", sizeof(body));
  872. s_copy(path, "/api/channels/", sizeof(path));
  873. s_cat(path, cur_id, sizeof(path));
  874. s_cat(path, "/messages", sizeof(path));
  875. s_copy(busy, "Sending...", sizeof(busy));
  876. paint_now();
  877. st = api("POST", path, body);
  878. busy[0] = '\0';
  879. if (!api_ok(st, "Send")) {
  880. if (st > 0) {
  881. char msg[96];
  882. root = parse_resp();
  883. s_copy(msg, root >= 0 ?
  884. ujson_get_str(&json, root, "error") : "", sizeof(msg));
  885. if (msg[0])
  886. set_status("Send failed: ", msg, 1);
  887. }
  888. return; /* the text stays in the composer */
  889. }
  890. ngui_input_set(&compose_in, "");
  891. root = parse_resp();
  892. if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) {
  893. struct msg m;
  894. if (msg_from_json(&m, root) == 0)
  895. msg_merge(&m, 0);
  896. }
  897. scroll_to_end();
  898. mark_read();
  899. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  900. ngui_set_focus(&ui, ID_COMPOSE);
  901. }
  902. /* ---- browse / new DM ---- */
  903. static void load_picks(int dms)
  904. {
  905. int st, root, it;
  906. npick = 0;
  907. ngui_input_set(&filter_in, "");
  908. s_copy(busy, dms ? "Loading people..." : "Loading channels...",
  909. sizeof(busy));
  910. paint_now();
  911. st = api(0, dms ? "/api/users" : "/api/channels/public", 0);
  912. busy[0] = '\0';
  913. if (!api_ok(st, dms ? "Users" : "Public channels"))
  914. return;
  915. root = parse_resp();
  916. if (root < 0)
  917. return;
  918. for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK;
  919. it = ujson_next(&json, it)) {
  920. struct pick *p = &picks[npick];
  921. const char *nm;
  922. s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
  923. if (!p->id[0])
  924. continue;
  925. if (dms) {
  926. if (strcmp(p->id, me_id) == 0)
  927. continue;
  928. nm = ujson_get_str(&json, it, "name");
  929. if (!nm[0])
  930. nm = ujson_get_str(&json, it, "username");
  931. to_latin1_line(p->name, sizeof(p->name), nm);
  932. to_latin1_line(p->sub, sizeof(p->sub),
  933. ujson_get_str(&json, it, "username"));
  934. } else {
  935. to_latin1_line(p->name, sizeof(p->name),
  936. ujson_get_str(&json, it, "name"));
  937. to_latin1_line(p->sub, sizeof(p->sub),
  938. ujson_get_str(&json, it, "description"));
  939. }
  940. npick++;
  941. }
  942. modal = dms ? MODAL_NEWDM : MODAL_BROWSE;
  943. modal_scroll.offset = 0;
  944. modal_sel = 0;
  945. ngui_set_focus(&ui, ID_FILTER);
  946. }
  947. static void pick_action(int idx)
  948. {
  949. char path[128], body[96], id[48];
  950. int st, root;
  951. if (idx < 0 || idx >= npick)
  952. return;
  953. if (modal == MODAL_BROWSE) {
  954. s_copy(path, "/api/channels/", sizeof(path));
  955. s_cat(path, picks[idx].id, sizeof(path));
  956. s_cat(path, "/join", sizeof(path));
  957. s_copy(busy, "Joining...", sizeof(busy));
  958. paint_now();
  959. st = api("POST", path, 0);
  960. busy[0] = '\0';
  961. if (!api_ok(st, "Join"))
  962. return;
  963. s_copy(id, picks[idx].id, sizeof(id));
  964. } else {
  965. s_copy(body, "{\"userId\":", sizeof(body));
  966. if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body),
  967. picks[idx].id) < 0)
  968. return;
  969. s_cat(body, "}", sizeof(body));
  970. s_copy(busy, "Opening conversation...", sizeof(busy));
  971. paint_now();
  972. st = api("POST", "/api/dms", body);
  973. busy[0] = '\0';
  974. if (!api_ok(st, "New DM"))
  975. return;
  976. root = parse_resp();
  977. s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "",
  978. sizeof(id));
  979. }
  980. modal = MODAL_NONE;
  981. if (load_directory() == 0 && id[0]) {
  982. int k = conv_find(id);
  983. if (k >= 0)
  984. open_conv(k);
  985. }
  986. }
  987. /* ---- session ---- */
  988. static void enter_main(void)
  989. {
  990. int root;
  991. screen = SCR_MAIN;
  992. offline = 0;
  993. backoff_ms = 0;
  994. root = parse_resp(); /* the /api/me reply */
  995. if (root >= 0) {
  996. const char *nm = ujson_get_str(&json, root, "name");
  997. s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id));
  998. to_latin1_line(me_name, sizeof(me_name),
  999. nm[0] ? nm : ujson_get_str(&json, root, "username"));
  1000. }
  1001. set_status("Connected", 0, 0);
  1002. if (load_directory() == 0 && nconv > 0 && cur < 0) {
  1003. int i, pick = 0;
  1004. for (i = 0; i < nconv; i++) {
  1005. if (convs[i].kind != 'd' &&
  1006. strcmp(convs[i].name, "general") == 0) {
  1007. pick = i;
  1008. break;
  1009. }
  1010. }
  1011. open_conv(pick);
  1012. }
  1013. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  1014. ngui_set_focus(&ui, ID_COMPOSE);
  1015. }
  1016. static void go_login(const char *why)
  1017. {
  1018. net_drop();
  1019. uhttp_jar_clear(&jar);
  1020. saved_jar_changes = jar.changes;
  1021. saved_cookie[0] = '\0';
  1022. screen = SCR_SERVER;
  1023. modal = MODAL_NONE;
  1024. clear_messages();
  1025. nconv = 0;
  1026. cur = -1;
  1027. cur_id[0] = '\0';
  1028. set_status(why, 0, why != 0);
  1029. ngui_set_focus(&ui, ID_SERVER);
  1030. }
  1031. /* After the jar holds a session: validate it with /api/me. */
  1032. static int check_session(int keep_offline)
  1033. {
  1034. unsigned int len = 0;
  1035. int r;
  1036. s_copy(busy, "Checking session...", sizeof(busy));
  1037. paint_now();
  1038. r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len);
  1039. busy[0] = '\0';
  1040. resp_len = len;
  1041. if (r == 0) {
  1042. save_config();
  1043. enter_main();
  1044. return 0;
  1045. }
  1046. if (r == 1) {
  1047. go_login("The saved session is no longer valid - sign in again");
  1048. return -1;
  1049. }
  1050. if (keep_offline) {
  1051. /* Network trouble: keep the cached session and retry. */
  1052. screen = SCR_MAIN;
  1053. offline = 1;
  1054. backoff_ms = 5000;
  1055. retry_at = u_ticks_ms() + backoff_ms;
  1056. set_status("Offline: ", r < 0 && r > -100 ?
  1057. uhttp_error_string(r) : "server error", 1);
  1058. return -1;
  1059. }
  1060. set_status("Session check failed: ", r < 0 && r > -100 ?
  1061. uhttp_error_string(r) : "server error", 1);
  1062. return -1;
  1063. }
  1064. static void start_login(void)
  1065. {
  1066. int r;
  1067. if (set_server(server_in.text) != 0) {
  1068. set_status("Enter a server such as chat.example.com", 0, 1);
  1069. return;
  1070. }
  1071. if (cfg_in.text[0])
  1072. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  1073. uhttp_jar_clear(&jar);
  1074. s_copy(busy, "Contacting the server...", sizeof(busy));
  1075. paint_now();
  1076. r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP);
  1077. busy[0] = '\0';
  1078. net_drop();
  1079. if (r == CHAT_LOGIN_OK) {
  1080. resp_len = (unsigned int)strlen(resp);
  1081. save_config();
  1082. enter_main();
  1083. return;
  1084. }
  1085. if (r == CHAT_LOGIN_FORM) {
  1086. screen = SCR_CRED;
  1087. set_status("", 0, 0);
  1088. ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER);
  1089. return;
  1090. }
  1091. if (r == CHAT_LOGIN_NOFORM) {
  1092. screen = SCR_COOKIE;
  1093. set_status(login.error, 0, 1);
  1094. ngui_set_focus(&ui, ID_COOKIE);
  1095. return;
  1096. }
  1097. set_status(login.error, 0, 1);
  1098. }
  1099. static void wipe_secrets(void)
  1100. {
  1101. memset(pass_in.text, 0, sizeof(pass_in.text));
  1102. pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0;
  1103. memset(totp_in.text, 0, sizeof(totp_in.text));
  1104. totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0;
  1105. }
  1106. static void submit_login(int with_totp)
  1107. {
  1108. int r;
  1109. if (!user_in.text[0] || !pass_in.text[0]) {
  1110. set_status("Enter the username and password", 0, 1);
  1111. return;
  1112. }
  1113. s_copy(busy, "Signing in...", sizeof(busy));
  1114. paint_now();
  1115. r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text,
  1116. with_totp ? totp_in.text : "", resp, RESP_CAP);
  1117. busy[0] = '\0';
  1118. net_drop();
  1119. if (r == CHAT_LOGIN_TOTP) {
  1120. if (with_totp) {
  1121. set_status("The code was not accepted", 0, 1);
  1122. } else {
  1123. screen = SCR_TOTP;
  1124. set_status("", 0, 0);
  1125. }
  1126. ngui_set_focus(&ui, ID_TOTP);
  1127. return;
  1128. }
  1129. if (r == CHAT_LOGIN_OK) {
  1130. wipe_secrets();
  1131. resp_len = (unsigned int)strlen(resp);
  1132. save_config();
  1133. enter_main();
  1134. return;
  1135. }
  1136. if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) {
  1137. /* A wrong TOTP code is also a 401. */
  1138. set_status(login.error, 0, 1);
  1139. ngui_input_set(&totp_in, "");
  1140. return;
  1141. }
  1142. if (r == CHAT_LOGIN_DENIED) {
  1143. memset(pass_in.text, 0, sizeof(pass_in.text));
  1144. ngui_input_set(&pass_in, "");
  1145. ngui_set_focus(&ui, ID_PASS);
  1146. }
  1147. if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR)
  1148. wipe_secrets();
  1149. if (r == CHAT_LOGIN_PASSKEY)
  1150. screen = SCR_COOKIE;
  1151. set_status(login.error, 0, 1);
  1152. }
  1153. static void use_cookie(void)
  1154. {
  1155. if (set_server(server_in.text) != 0) {
  1156. set_status("Enter a server such as chat.example.com", 0, 1);
  1157. return;
  1158. }
  1159. if (cfg_in.text[0])
  1160. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  1161. uhttp_jar_clear(&jar);
  1162. {
  1163. const char *c = cookie_in.text;
  1164. /* Accept a pasted "Cookie: ..." header too. */
  1165. if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0)
  1166. c += 7;
  1167. if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) {
  1168. set_status("Paste the cookie as name=value", 0, 1);
  1169. return;
  1170. }
  1171. }
  1172. check_session(0);
  1173. if (screen == SCR_MAIN)
  1174. ngui_input_set(&cookie_in, "");
  1175. }
  1176. static void sign_out(void)
  1177. {
  1178. /* Best effort: end the server session too. */
  1179. if (server[0]) {
  1180. s_copy(busy, "Signing out...", sizeof(busy));
  1181. paint_now();
  1182. api(0, "/auth/logout", 0);
  1183. busy[0] = '\0';
  1184. }
  1185. go_login("Signed out");
  1186. {
  1187. static char out[CHAT_SERVER_MAX + 80];
  1188. int n = chat_config_format(out, sizeof(out), server, "");
  1189. if (n > 0)
  1190. write_file(cfg_path, out, (unsigned int)n);
  1191. }
  1192. }
  1193. static void load_config(void)
  1194. {
  1195. static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
  1196. char srv[CHAT_SERVER_MAX];
  1197. int n, migrated = 0;
  1198. n = read_file(cfg_path, buf, sizeof(buf));
  1199. /* First start on a persistent volume: carry a session that an older
  1200. * build saved in /share into /data once. */
  1201. if (n <= 0 && cfg_is_default &&
  1202. strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) {
  1203. n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf));
  1204. migrated = n > 0;
  1205. }
  1206. ngui_input_set(&cfg_in, cfg_path);
  1207. if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
  1208. saved_cookie,
  1209. sizeof(saved_cookie)) != 0) {
  1210. ngui_input_set(&server_in, "chat.cloudron.io");
  1211. saved_cookie[0] = '\0';
  1212. memset(buf, 0, sizeof(buf));
  1213. return;
  1214. }
  1215. memset(buf, 0, sizeof(buf));
  1216. ngui_input_set(&server_in, srv);
  1217. if (set_server(srv) != 0 || !saved_cookie[0])
  1218. return;
  1219. uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
  1220. saved_jar_changes = jar.changes;
  1221. if (migrated)
  1222. save_config();
  1223. check_session(1);
  1224. }
  1225. /* ---- text layout ---- */
  1226. static int line_h(void)
  1227. {
  1228. int h = ngui_text_line_height(&ui, ui.font_px, 0);
  1229. return h > 0 ? h : 16;
  1230. }
  1231. static int text_w(const char *s, unsigned int n, int bold)
  1232. {
  1233. return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0);
  1234. }
  1235. /* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets
  1236. * the bytes to skip to the next line. */
  1237. static unsigned int wrap_line(const char *s, unsigned int n, int maxw,
  1238. unsigned int *adv)
  1239. {
  1240. unsigned int i = 0, end = 0, j;
  1241. if (n && s[0] == '\n') {
  1242. *adv = 1;
  1243. return 0;
  1244. }
  1245. for (;;) {
  1246. j = i;
  1247. while (j < n && s[j] == ' ')
  1248. j++;
  1249. while (j < n && s[j] != ' ' && s[j] != '\n')
  1250. j++;
  1251. if (j == i)
  1252. break;
  1253. if (text_w(s, j, 0) > maxw) {
  1254. if (end == 0) {
  1255. /* One word wider than the line: split it. */
  1256. unsigned int k = 1;
  1257. while (k < j && text_w(s, k + 1, 0) <= maxw)
  1258. k++;
  1259. *adv = k;
  1260. return k;
  1261. }
  1262. break;
  1263. }
  1264. end = j;
  1265. i = j;
  1266. if (j >= n || s[j] == '\n')
  1267. break;
  1268. }
  1269. *adv = end;
  1270. while (*adv < n && s[*adv] == ' ')
  1271. (*adv)++;
  1272. if (*adv < n && s[*adv] == '\n')
  1273. (*adv)++;
  1274. return end;
  1275. }
  1276. static int count_lines(const char *s, int maxw)
  1277. {
  1278. unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
  1279. int lines = 0;
  1280. if (!n)
  1281. return 0;
  1282. while (pos < n) {
  1283. wrap_line(s + pos, n - pos, maxw, &adv);
  1284. if (!adv)
  1285. adv = 1;
  1286. pos += adv;
  1287. lines++;
  1288. }
  1289. return lines;
  1290. }
  1291. #define AVATAR 32
  1292. #define TEXT_X 52
  1293. #define PAD_TOP 8
  1294. #define PAD_GROUP 2
  1295. static int same_day(const struct msg *a, const struct msg *b)
  1296. {
  1297. return strncmp(a->created, b->created, 10) == 0;
  1298. }
  1299. static int same_group(const struct msg *a, const struct msg *b)
  1300. {
  1301. unsigned int ta, tb;
  1302. if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) ||
  1303. b->reply[0] || b->action)
  1304. return 0;
  1305. /* HH:MM at offsets 11..15: within five minutes */
  1306. ta = (unsigned int)atoi(a->created + 11) * 60 +
  1307. (unsigned int)atoi(a->created + 14);
  1308. tb = (unsigned int)atoi(b->created + 11) * 60 +
  1309. (unsigned int)atoi(b->created + 14);
  1310. return tb >= ta && tb - ta <= 5;
  1311. }
  1312. static void layout_msg(int i, int width)
  1313. {
  1314. struct msg *m = &msgs[i];
  1315. int lh = line_h(), h, tw = width - TEXT_X - 12;
  1316. if (tw < 40)
  1317. tw = 40;
  1318. m->day_header = i == 0 || !same_day(&msgs[i - 1], m);
  1319. m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m);
  1320. h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2;
  1321. if (m->day_header)
  1322. h += lh + 12;
  1323. if (m->reply[0])
  1324. h += lh + 2;
  1325. h += count_lines(m->body, tw) * lh;
  1326. if (m->extra[0])
  1327. h += lh + 2;
  1328. h += 2;
  1329. if (!m->compact && h < PAD_TOP + AVATAR + 4)
  1330. h = PAD_TOP + AVATAR + 4;
  1331. m->height = h;
  1332. m->layout_w = width;
  1333. }
  1334. static int tl_width;
  1335. static unsigned int laid_gen;
  1336. static int laid_font = -1;
  1337. /* Heights depend on the width, the font and the neighbours (grouping and
  1338. * day headers), so any change re-lays out every message. */
  1339. static int content_height(void)
  1340. {
  1341. int i, h = has_older || history_full ? 36 : 8;
  1342. int all = laid_gen != msgs_gen || laid_font != line_h();
  1343. for (i = 0; i < nmsg; i++) {
  1344. if (all || msgs[i].layout_w != tl_width)
  1345. layout_msg(i, tl_width);
  1346. h += msgs[i].height;
  1347. }
  1348. laid_gen = msgs_gen;
  1349. laid_font = line_h();
  1350. return h + 8;
  1351. }
  1352. /* ---- drawing helpers ---- */
  1353. static unsigned short avatar_color(const char *id)
  1354. {
  1355. static const unsigned short pal[] = {
  1356. NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0),
  1357. NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a),
  1358. NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8),
  1359. NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40),
  1360. };
  1361. unsigned int h = 0;
  1362. while (*id)
  1363. h = h * 31 + (unsigned char)*id++;
  1364. return pal[h % (sizeof(pal) / sizeof(pal[0]))];
  1365. }
  1366. static void draw_avatar(int x, int y, int size, const char *name,
  1367. const char *id)
  1368. {
  1369. struct ngui_rect r = { x, y, size, size };
  1370. char ini[2];
  1371. int tw;
  1372. ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
  1373. avatar_color(id));
  1374. ini[0] = name[0] ? name[0] : '?';
  1375. if (ini[0] >= 'a' && ini[0] <= 'z')
  1376. ini[0] = (char)(ini[0] - 'a' + 'A');
  1377. ini[1] = '\0';
  1378. tw = text_w(ini, 1, 1);
  1379. ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1,
  1380. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  1381. }
  1382. static void draw_dot(int x, int y, int d, unsigned short color, int filled)
  1383. {
  1384. struct ngui_rect r = { x, y, d, d };
  1385. if (filled)
  1386. ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color);
  1387. else
  1388. ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color);
  1389. }
  1390. static void draw_badge(int right, int y, int count)
  1391. {
  1392. char num[12] = "";
  1393. int tw, w;
  1394. struct ngui_rect r;
  1395. if (count > 99)
  1396. s_copy(num, "99+", sizeof(num));
  1397. else
  1398. s_cat_uint(num, (unsigned int)count, sizeof(num));
  1399. tw = text_w(num, (unsigned int)strlen(num), 1);
  1400. w = tw + 12;
  1401. r.x = right - w;
  1402. r.y = y;
  1403. r.w = w;
  1404. r.h = line_h() + 2;
  1405. ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2,
  1406. ui.theme.accent);
  1407. ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num),
  1408. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  1409. }
  1410. static void draw_lock(int x, int y, unsigned short c)
  1411. {
  1412. struct ngui_rect body = { x, y + 5, 9, 7 };
  1413. struct ngui_rect shackle = { x + 2, y + 1, 5, 6 };
  1414. ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c);
  1415. ngui_fill_rect(&ui, body, c);
  1416. }
  1417. static void label(struct ngui_rect *body, const char *text)
  1418. {
  1419. struct ngui_rect r = ngui_cut_top(body, 20);
  1420. ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim);
  1421. }
  1422. /* ---- login screens ---- */
  1423. static struct ngui_rect card_rect(int h)
  1424. {
  1425. struct ngui_rect r;
  1426. int w = ui.w - 40 < 460 ? ui.w - 40 : 460;
  1427. if (w < 200)
  1428. w = ui.w;
  1429. r.w = w;
  1430. r.h = h;
  1431. r.x = (ui.w - w) / 2;
  1432. r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10;
  1433. return r;
  1434. }
  1435. static void field(struct ngui_rect *body, const char *text, unsigned int id,
  1436. struct ngui_input *in, unsigned int next_id, int submit_act)
  1437. {
  1438. int r;
  1439. label(body, text);
  1440. r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in);
  1441. ngui_cut_top(body, 8);
  1442. if (r & NGUI_INPUT_NEXT)
  1443. ngui_set_focus(&ui, next_id);
  1444. if ((r & NGUI_INPUT_SUBMIT) && submit_act)
  1445. action = submit_act;
  1446. }
  1447. static void draw_status_line(struct ngui_rect *body)
  1448. {
  1449. struct ngui_rect r = ngui_cut_top(body, 22);
  1450. if (busy[0])
  1451. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent);
  1452. else if (status[0])
  1453. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status,
  1454. status_err ? ui.theme.error : ui.theme.text_dim);
  1455. }
  1456. static void notice(struct ngui_rect *body, const char *text)
  1457. {
  1458. struct ngui_rect r = ngui_cut_top(body, 18);
  1459. ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim);
  1460. }
  1461. static void draw_login(void)
  1462. {
  1463. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  1464. struct ngui_rect card, body, r, b;
  1465. int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 :
  1466. screen == SCR_TOTP ? 250 : 300;
  1467. ngui_fill_rect(&ui, all, ui.theme.bg);
  1468. card = card_rect(h);
  1469. ngui_fill_rect(&ui, card, ui.theme.panel);
  1470. ngui_frame(&ui, card, ui.theme.border);
  1471. body = card;
  1472. ngui_inset(&body, 18);
  1473. r = ngui_cut_top(&body, 30);
  1474. ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0);
  1475. if (screen == SCR_SERVER) {
  1476. field(&body, "Server", ID_SERVER, &server_in, ID_CFG,
  1477. ACT_START_LOGIN);
  1478. field(&body, "Config file (session cookie, RAM-only on /share)",
  1479. ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN);
  1480. r = ngui_cut_top(&body, 32);
  1481. b = ngui_cut_left(&r, 110);
  1482. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  1483. action = ACT_START_LOGIN;
  1484. ngui_cut_left(&r, 10);
  1485. b = ngui_cut_left(&r, 170);
  1486. if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie..."))
  1487. action = ACT_COOKIE_SCREEN;
  1488. ngui_cut_top(&body, 8);
  1489. draw_status_line(&body);
  1490. notice(&body, "TLS certificates are not verified: only sign in");
  1491. notice(&body, "on a trusted network. Passkeys and external SSO");
  1492. notice(&body, "are not supported (use the cookie option).");
  1493. } else if (screen == SCR_CRED || screen == SCR_TOTP) {
  1494. r = ngui_cut_top(&body, 22);
  1495. {
  1496. char t[160];
  1497. s_copy(t, "Sign in to ", sizeof(t));
  1498. s_cat(t, login.app_name[0] ? login.app_name : "Chat",
  1499. sizeof(t));
  1500. s_cat(t, " at ", sizeof(t));
  1501. s_cat(t, server_host, sizeof(t));
  1502. ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim);
  1503. }
  1504. if (screen == SCR_CRED) {
  1505. field(&body, "Username or email", ID_USER, &user_in,
  1506. ID_PASS, ACT_SUBMIT);
  1507. field(&body, "Password", ID_PASS, &pass_in, ID_USER,
  1508. ACT_SUBMIT);
  1509. } else {
  1510. field(&body, "Two-factor code (authenticator app)",
  1511. ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP);
  1512. }
  1513. r = ngui_cut_top(&body, 32);
  1514. b = ngui_cut_left(&r, 110);
  1515. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  1516. action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT;
  1517. ngui_cut_left(&r, 10);
  1518. b = ngui_cut_left(&r, 90);
  1519. if (ngui_button(&ui, ID_BACK, b, "Back"))
  1520. action = ACT_BACK;
  1521. ngui_cut_top(&body, 8);
  1522. draw_status_line(&body);
  1523. notice(&body, "The password is sent over unverified TLS and");
  1524. notice(&body, "is never stored.");
  1525. } else {
  1526. field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE,
  1527. ACT_USE_COOKIE);
  1528. field(&body, "Session cookie (e.g. connect.sid=s%3A...)",
  1529. ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE);
  1530. field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER,
  1531. ACT_USE_COOKIE);
  1532. r = ngui_cut_top(&body, 32);
  1533. b = ngui_cut_left(&r, 130);
  1534. if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie"))
  1535. action = ACT_USE_COOKIE;
  1536. ngui_cut_left(&r, 10);
  1537. b = ngui_cut_left(&r, 90);
  1538. if (ngui_button(&ui, ID_BACK, b, "Back"))
  1539. action = ACT_BACK;
  1540. ngui_cut_top(&body, 8);
  1541. draw_status_line(&body);
  1542. notice(&body, "Copy the connect.sid cookie from a signed-in web");
  1543. notice(&body, "browser. It is a bearer credential: it is saved");
  1544. notice(&body, "in the config file until you sign out.");
  1545. }
  1546. }
  1547. /* ---- main screen ---- */
  1548. #define SIDE_ROW 38
  1549. #define SIDE_HEAD 26
  1550. static void draw_sidebar(struct ngui_rect r)
  1551. {
  1552. struct ngui_rect list, btns, b;
  1553. int y, i, section, row_w, scrolls;
  1554. int lh = line_h();
  1555. ngui_fill_rect(&ui, r, ui.theme.panel);
  1556. btns = ngui_cut_bottom(&r, 40);
  1557. ngui_inset(&btns, 6);
  1558. b = ngui_cut_left(&btns, (btns.w - 6) / 2);
  1559. if (ngui_button(&ui, ID_BROWSE, b, "Browse"))
  1560. action = ACT_BROWSE;
  1561. ngui_cut_left(&btns, 6);
  1562. if (ngui_button(&ui, ID_NEWDM, btns, "New DM"))
  1563. action = ACT_NEWDM;
  1564. list = r;
  1565. side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
  1566. ngui_scroll_begin(&ui, list, &side_scroll);
  1567. ngui_scroll_wheel(&ui, list, &side_scroll);
  1568. scrolls = side_scroll.content_h > side_scroll.view_h;
  1569. row_w = list.w - (scrolls ? 16 : 0);
  1570. y = list.y - side_scroll.offset;
  1571. for (section = 0; section < 2; section++) {
  1572. ngui_text_px(&ui, list.x + 10, y + 6,
  1573. section ? "DIRECT MESSAGES" : "CHANNELS",
  1574. section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0);
  1575. y += SIDE_HEAD;
  1576. for (i = 0; i < nconv; i++) {
  1577. struct conv *c = &convs[i];
  1578. struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 };
  1579. int hot, nx, right;
  1580. if ((c->kind == 'd') != section)
  1581. continue;
  1582. hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x,
  1583. ui.mouse_y) &&
  1584. ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y);
  1585. if (i == cur)
  1586. ngui_fill_rect(&ui, row, ui.theme.selection);
  1587. else if (hot)
  1588. ngui_fill_rect(&ui, row, ui.theme.panel_alt);
  1589. if (ui.pressed && modal == MODAL_NONE &&
  1590. ngui_rect_contains(&row, ui.press_x, ui.press_y) &&
  1591. ngui_rect_contains(&list, ui.press_x, ui.press_y)) {
  1592. action = ACT_OPEN_CONV;
  1593. action_arg = i;
  1594. }
  1595. nx = list.x + 26;
  1596. if (c->kind == 'd') {
  1597. unsigned short pc = c->presence == 'o' ?
  1598. NGUI_RGB(0x40, 0xc0, 0x60) :
  1599. c->presence == 'a' ?
  1600. NGUI_RGB(0xe0, 0xb0, 0x30) :
  1601. ui.theme.text_dim;
  1602. draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc,
  1603. c->presence != 'f');
  1604. } else if (c->kind == 'p') {
  1605. draw_lock(list.x + 9, y + 4, ui.theme.text_dim);
  1606. } else {
  1607. ngui_text(&ui, list.x + 10, y + 4, "#",
  1608. ui.theme.text_dim);
  1609. }
  1610. right = list.x + row_w - 8;
  1611. if (c->unread > 0) {
  1612. draw_badge(right, y + 3, c->unread);
  1613. right -= 40;
  1614. }
  1615. {
  1616. struct ngui_rect nr = { nx, y, right - nx, lh + 6 };
  1617. ngui_push_clip(&ui, nr);
  1618. ngui_text_px(&ui, nx, y + 4, c->name,
  1619. (unsigned int)strlen(c->name),
  1620. ui.theme.text, ui.font_px,
  1621. c->unread > 0, 0, 0);
  1622. ngui_pop_clip(&ui);
  1623. }
  1624. if (c->preview[0]) {
  1625. struct ngui_rect pr = { nx, y + 4 + lh,
  1626. list.x + row_w - 8 - nx,
  1627. lh };
  1628. ngui_push_clip(&ui, pr);
  1629. ngui_text_px(&ui, nx, y + 4 + lh, c->preview,
  1630. (unsigned int)strlen(c->preview),
  1631. ui.theme.text_dim, 12, 0, 0, 0);
  1632. ngui_pop_clip(&ui);
  1633. }
  1634. y += SIDE_ROW;
  1635. }
  1636. }
  1637. if (!nconv)
  1638. ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6,
  1639. "(none yet)", ui.theme.text_dim);
  1640. ngui_scroll_end(&ui, list, &side_scroll);
  1641. }
  1642. static void draw_message(struct msg *m, int x, int y, int width)
  1643. {
  1644. int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12;
  1645. unsigned int n, pos = 0, adv;
  1646. if (tw < 40)
  1647. tw = 40;
  1648. if (m->day_header) {
  1649. char d[16];
  1650. int dw;
  1651. struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 };
  1652. s_copy(d, m->created, 11);
  1653. dw = text_w(d, (unsigned int)strlen(d), 0);
  1654. ngui_fill_rect(&ui, line, ui.theme.border);
  1655. ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8,
  1656. y + 4, dw + 16, lh + 4 }, ui.theme.bg);
  1657. ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim);
  1658. y += lh + 12;
  1659. }
  1660. if (!m->compact) {
  1661. char tm[8];
  1662. int aw;
  1663. y += PAD_TOP;
  1664. draw_avatar(x + 10, y, AVATAR, m->author, m->user_id);
  1665. ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
  1666. ui.theme.text, ui.font_px, 1, 0, 0);
  1667. aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
  1668. s_copy(tm, m->created + 11, 6);
  1669. ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm),
  1670. ui.theme.text_dim, 12, 0, 0, 0);
  1671. y += lh + 2;
  1672. } else {
  1673. y += PAD_GROUP;
  1674. }
  1675. if (m->reply[0]) {
  1676. struct ngui_rect rr = { tx, y, tw, lh };
  1677. ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 },
  1678. ui.theme.accent);
  1679. ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply,
  1680. ui.theme.text_dim);
  1681. y += lh + 2;
  1682. }
  1683. n = (unsigned int)strlen(m->body);
  1684. while (pos < n) {
  1685. unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv);
  1686. if (!adv)
  1687. adv = 1;
  1688. ngui_text_px(&ui, tx, y, m->body + pos, len,
  1689. m->action ? ui.theme.accent : ui.theme.text,
  1690. ui.font_px, 0, m->action, 0);
  1691. pos += adv;
  1692. y += lh;
  1693. }
  1694. if (m->extra[0]) {
  1695. struct ngui_rect er = { tx, y + 2, tw, lh };
  1696. ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra,
  1697. ui.theme.text_dim);
  1698. }
  1699. }
  1700. static void draw_timeline(struct ngui_rect r)
  1701. {
  1702. int i, y, total, scrolls, width;
  1703. int was_bottom;
  1704. ngui_fill_rect(&ui, r, ui.theme.bg);
  1705. if (cur < 0) {
  1706. ngui_text(&ui, r.x + 20, r.y + 20,
  1707. nconv ? "Select a conversation" :
  1708. "No conversations yet: browse the public channels",
  1709. ui.theme.text_dim);
  1710. return;
  1711. }
  1712. tl_width = r.w - 16;
  1713. total = content_height();
  1714. tl_scroll.content_h = total;
  1715. ngui_scroll_begin(&ui, r, &tl_scroll);
  1716. if (ngui_scroll_wheel(&ui, r, &tl_scroll))
  1717. last_input_ms = u_ticks_ms();
  1718. scrolls = total > r.h;
  1719. width = r.w - (scrolls ? 16 : 0);
  1720. if (width != tl_width) {
  1721. tl_width = width;
  1722. total = content_height();
  1723. tl_scroll.content_h = total;
  1724. }
  1725. /* Scrolling to the very top pages in older history by itself (the
  1726. * button stays for the pointer). Rate-limited so a failing request
  1727. * cannot spin. */
  1728. if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 &&
  1729. !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500)
  1730. action = ACT_OLDER;
  1731. was_bottom = tl_scroll.offset >= total - r.h - 4;
  1732. at_bottom = was_bottom || !scrolls;
  1733. if (at_bottom)
  1734. new_below = 0;
  1735. y = r.y - tl_scroll.offset;
  1736. if (has_older || history_full) {
  1737. struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 };
  1738. if (history_full) {
  1739. ngui_text(&ui, b.x + 4, b.y + 6,
  1740. "History limit reached", ui.theme.text_dim);
  1741. } else if (b.y + b.h > r.y &&
  1742. (!ui.pressed ||
  1743. ngui_rect_contains(&r, ui.press_x, ui.press_y))) {
  1744. if (ngui_button(&ui, ID_OLDER, b, "Load older messages"))
  1745. action = ACT_OLDER;
  1746. }
  1747. y += 36;
  1748. } else {
  1749. y += 8;
  1750. }
  1751. for (i = 0; i < nmsg; i++) {
  1752. struct msg *m = &msgs[i];
  1753. if (y + m->height > r.y && y < r.y + r.h)
  1754. draw_message(m, r.x, y, width);
  1755. y += m->height;
  1756. }
  1757. if (!nmsg)
  1758. ngui_text(&ui, r.x + 20, r.y + 50,
  1759. "No messages yet - say hello!", ui.theme.text_dim);
  1760. ngui_scroll_end(&ui, r, &tl_scroll);
  1761. if (new_below > 0 && !at_bottom) {
  1762. char t[40] = "";
  1763. struct ngui_rect b;
  1764. s_cat_uint(t, (unsigned int)new_below, sizeof(t));
  1765. s_cat(t, new_below == 1 ? " new message" : " new messages",
  1766. sizeof(t));
  1767. b.w = text_w(t, (unsigned int)strlen(t), 0) + 30;
  1768. b.h = 26;
  1769. b.x = r.x + (width - b.w) / 2;
  1770. b.y = r.y + r.h - b.h - 8;
  1771. if (ngui_button(&ui, ID_NEWMSG, b, t))
  1772. scroll_to_end();
  1773. }
  1774. }
  1775. static int total_unread(void)
  1776. {
  1777. int i, n = 0;
  1778. for (i = 0; i < nconv; i++)
  1779. n += convs[i].unread > 0 ? convs[i].unread : 0;
  1780. return n;
  1781. }
  1782. static void draw_modal(void)
  1783. {
  1784. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  1785. struct ngui_rect card, body, r, list;
  1786. int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis;
  1787. int lh = line_h();
  1788. (void)all;
  1789. if (w < 320)
  1790. w = ui.w - 20;
  1791. if (h < 240)
  1792. h = ui.h - 20;
  1793. card.w = w;
  1794. card.h = h;
  1795. card.x = (ui.w - w) / 2;
  1796. card.y = (ui.h - h) / 2;
  1797. ngui_fill_rect(&ui, card, ui.theme.panel);
  1798. ngui_frame(&ui, card, ui.theme.accent);
  1799. body = card;
  1800. ngui_inset(&body, 14);
  1801. r = ngui_cut_top(&body, 28);
  1802. ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ?
  1803. "Browse public channels" : "New direct message",
  1804. modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0);
  1805. if (ngui_button(&ui, ID_MODAL_CLOSE,
  1806. (struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 },
  1807. "Close"))
  1808. modal = MODAL_NONE;
  1809. ngui_cut_top(&body, 6);
  1810. filter_in.placeholder = "Filter... (Up/Down, Enter)";
  1811. for (i = 0; i < npick; i++)
  1812. if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) ||
  1813. strstr(picks[i].sub, filter_in.text))
  1814. shown++;
  1815. {
  1816. int k = ngui_key_peek(&ui), fr;
  1817. if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  1818. ngui_key(&ui);
  1819. modal_sel += k == NGUI_KEY_UP ? -1 : 1;
  1820. }
  1821. fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30),
  1822. &filter_in);
  1823. if (fr & NGUI_INPUT_CHANGED) {
  1824. modal_scroll.offset = 0;
  1825. modal_sel = 0;
  1826. }
  1827. if (modal_sel >= shown)
  1828. modal_sel = shown - 1;
  1829. if (modal_sel < 0)
  1830. modal_sel = 0;
  1831. if ((fr & NGUI_INPUT_SUBMIT) && shown) {
  1832. int vis = 0;
  1833. for (i = 0; i < npick; i++) {
  1834. if (filter_in.text[0] &&
  1835. !strstr(picks[i].name, filter_in.text) &&
  1836. !strstr(picks[i].sub, filter_in.text))
  1837. continue;
  1838. if (vis++ == modal_sel) {
  1839. action = modal == MODAL_BROWSE ?
  1840. ACT_JOIN : ACT_OPEN_DM;
  1841. action_arg = i;
  1842. break;
  1843. }
  1844. }
  1845. ngui_set_focus(&ui, ID_FILTER);
  1846. }
  1847. if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT))
  1848. modal = MODAL_NONE;
  1849. }
  1850. ngui_cut_top(&body, 8);
  1851. list = body;
  1852. ngui_fill_rect(&ui, list, ui.theme.bg);
  1853. modal_scroll.content_h = shown * 44;
  1854. ngui_scroll_begin(&ui, list, &modal_scroll);
  1855. ngui_scroll_wheel(&ui, list, &modal_scroll);
  1856. y = list.y - modal_scroll.offset;
  1857. vis = 0;
  1858. for (i = 0; i < npick; i++) {
  1859. struct pick *p = &picks[i];
  1860. struct ngui_rect row, b;
  1861. if (filter_in.text[0] && !strstr(p->name, filter_in.text) &&
  1862. !strstr(p->sub, filter_in.text))
  1863. continue;
  1864. if (vis++ == modal_sel) {
  1865. if (y < list.y)
  1866. modal_scroll.offset -= list.y - y;
  1867. else if (y + 44 > list.y + list.h)
  1868. modal_scroll.offset += y + 44 - list.y - list.h;
  1869. y = list.y + (vis - 1) * 44 - modal_scroll.offset;
  1870. ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y,
  1871. list.w - 16, 43 },
  1872. ui.theme.selection);
  1873. }
  1874. row.x = list.x;
  1875. row.y = y;
  1876. row.w = list.w - 16;
  1877. row.h = 42;
  1878. if (y + 44 > list.y && y < list.y + list.h) {
  1879. ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
  1880. row.w, 1 }, ui.theme.border);
  1881. if (modal == MODAL_NEWDM)
  1882. draw_avatar(row.x + 8, y + 6, 30, p->name, p->id);
  1883. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
  1884. row.w - 160, lh + 4 },
  1885. row.x + 48, y + 4,
  1886. p->name,
  1887. ui.theme.text);
  1888. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48,
  1889. y + 4 + lh, row.w - 160, lh },
  1890. row.x + 48, y + 4 + lh, p->sub,
  1891. ui.theme.text_dim);
  1892. if (modal == MODAL_BROWSE)
  1893. ngui_text(&ui, row.x + 14, y + 12, "#",
  1894. ui.theme.text_dim);
  1895. b.x = row.x + row.w - 100;
  1896. b.y = y + 8;
  1897. b.w = 92;
  1898. b.h = 26;
  1899. if ((!ui.pressed ||
  1900. ngui_rect_contains(&list, ui.press_x, ui.press_y)) &&
  1901. ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b,
  1902. modal == MODAL_BROWSE ? "Join" : "Message")) {
  1903. action = modal == MODAL_BROWSE ? ACT_JOIN :
  1904. ACT_OPEN_DM;
  1905. action_arg = i;
  1906. }
  1907. }
  1908. y += 44;
  1909. }
  1910. if (!shown)
  1911. ngui_text(&ui, list.x + 12, list.y + 12,
  1912. npick ? "Nothing matches the filter" :
  1913. modal == MODAL_BROWSE ?
  1914. "You are in every public channel" : "Nobody else here",
  1915. ui.theme.text_dim);
  1916. ngui_scroll_end(&ui, list, &modal_scroll);
  1917. }
  1918. /* Keyboard shortcuts, handled before the composer swallows the keys:
  1919. * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R
  1920. * refresh. With the composer unfocused (Esc): Up/Down switch conversations,
  1921. * Home/End jump in the timeline, and typing refocuses the composer. */
  1922. static void main_keys(void)
  1923. {
  1924. for (;;) {
  1925. int k = ngui_key_peek(&ui);
  1926. if (!k)
  1927. return;
  1928. if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) {
  1929. ngui_scroll_keys(&ui, &tl_scroll);
  1930. continue;
  1931. }
  1932. if (k == 0x02 || k == 0x0E || k == 0x12) {
  1933. ngui_key(&ui);
  1934. action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM :
  1935. ACT_REFRESH;
  1936. return;
  1937. }
  1938. if (ui.focus)
  1939. return;
  1940. if (k == NGUI_KEY_HOME) {
  1941. ngui_key(&ui);
  1942. tl_scroll.offset = 0;
  1943. } else if (k == NGUI_KEY_END) {
  1944. ngui_key(&ui);
  1945. scroll_to_end();
  1946. } else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  1947. int order[MAX_CONV], n = 0, i, pos = -1, sec;
  1948. ngui_key(&ui);
  1949. /* Sidebar order: channels first, then DMs. */
  1950. for (sec = 0; sec < 2; sec++)
  1951. for (i = 0; i < nconv; i++)
  1952. if ((convs[i].kind == 'd') == sec) {
  1953. if (i == cur)
  1954. pos = n;
  1955. order[n++] = i;
  1956. }
  1957. if (!n)
  1958. continue;
  1959. pos = pos < 0 ? 0 : k == NGUI_KEY_UP ?
  1960. (pos > 0 ? pos - 1 : 0) :
  1961. (pos + 1 < n ? pos + 1 : n - 1);
  1962. if (order[pos] != cur) {
  1963. action = ACT_OPEN_CONV;
  1964. action_arg = order[pos];
  1965. return;
  1966. }
  1967. } else if (k >= 0x20 && k <= 0x7E && cur >= 0) {
  1968. ngui_set_focus(&ui, ID_COMPOSE);
  1969. return;
  1970. } else {
  1971. return;
  1972. }
  1973. }
  1974. }
  1975. static void draw_main(void)
  1976. {
  1977. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  1978. struct ngui_rect top, side, bottom, comp, stat, b, tl;
  1979. int side_w = ui.w / 4;
  1980. char t[200];
  1981. unsigned int saved_pressed = ui.pressed;
  1982. /* Nothing under an open modal reacts to the pointer. */
  1983. if (modal != MODAL_NONE)
  1984. ui.pressed = 0;
  1985. if (side_w < 150)
  1986. side_w = 150;
  1987. if (side_w > 260)
  1988. side_w = 260;
  1989. ngui_fill_rect(&ui, all, ui.theme.bg);
  1990. /* top bar */
  1991. top = ngui_cut_top(&all, 38);
  1992. ngui_fill_rect(&ui, top, ui.theme.panel_alt);
  1993. ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w,
  1994. 1 }, ui.theme.border);
  1995. {
  1996. struct ngui_rect tb = top;
  1997. ngui_inset(&tb, 6);
  1998. b = ngui_cut_right(&tb, 86);
  1999. if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out"))
  2000. action = ACT_SIGNOUT;
  2001. ngui_cut_right(&tb, 6);
  2002. b = ngui_cut_right(&tb, 80);
  2003. if (ngui_button(&ui, ID_REFRESH, b, "Refresh"))
  2004. action = ACT_REFRESH;
  2005. t[0] = '\0';
  2006. if (cur >= 0) {
  2007. s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t));
  2008. s_cat(t, convs[cur].name, sizeof(t));
  2009. } else {
  2010. s_cat(t, "Chat", sizeof(t));
  2011. }
  2012. ngui_cut_right(&tb, 10);
  2013. ngui_push_clip(&ui, tb);
  2014. ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t,
  2015. (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0);
  2016. ngui_pop_clip(&ui);
  2017. }
  2018. if (modal == MODAL_NONE) {
  2019. /* A closed modal leaves its filter focused: hand the keyboard
  2020. * back to the composer. */
  2021. if (ui.focus == ID_FILTER)
  2022. ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0);
  2023. main_keys();
  2024. }
  2025. /* bottom: composer + status bar */
  2026. bottom = ngui_cut_bottom(&all, 70);
  2027. ngui_fill_rect(&ui, bottom, ui.theme.panel);
  2028. ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 },
  2029. ui.theme.border);
  2030. stat = ngui_cut_bottom(&bottom, 24);
  2031. comp = bottom;
  2032. ngui_inset(&comp, 7);
  2033. b = ngui_cut_right(&comp, 80);
  2034. compose_in.disabled = cur < 0;
  2035. compose_in.placeholder = cur < 0 ? "" : "Type a message...";
  2036. if (ngui_text_input(&ui, ID_COMPOSE,
  2037. (struct ngui_rect){ comp.x, comp.y, comp.w - 8,
  2038. comp.h }, &compose_in) &
  2039. NGUI_INPUT_SUBMIT)
  2040. action = ACT_SEND;
  2041. if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0)
  2042. action = ACT_SEND;
  2043. ngui_fill_rect(&ui, stat, ui.theme.panel_alt);
  2044. {
  2045. struct ngui_rect sr = stat;
  2046. int un = total_unread();
  2047. ngui_inset(&sr, 3);
  2048. if (offline) {
  2049. b = ngui_cut_right(&sr, 70);
  2050. if (ngui_button(&ui, ID_RETRY, b, "Retry"))
  2051. action = ACT_RETRY;
  2052. }
  2053. t[0] = '\0';
  2054. if (busy[0]) {
  2055. s_cat(t, busy, sizeof(t));
  2056. } else {
  2057. s_cat(t, status[0] ? status : "Connected", sizeof(t));
  2058. if (offline && retry_at) {
  2059. int left = (int)(retry_at - u_ticks_ms());
  2060. if (left > 0) {
  2061. s_cat(t, " (retry in ", sizeof(t));
  2062. s_cat_uint(t, (unsigned int)(left + 999) / 1000,
  2063. sizeof(t));
  2064. s_cat(t, " s)", sizeof(t));
  2065. }
  2066. }
  2067. }
  2068. s_cat(t, " \xb7 ", sizeof(t));
  2069. s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t));
  2070. if (me_name[0]) {
  2071. s_cat(t, " \xb7 ", sizeof(t));
  2072. s_cat(t, me_name, sizeof(t));
  2073. }
  2074. if (un) {
  2075. s_cat(t, " \xb7 ", sizeof(t));
  2076. s_cat_uint(t, (unsigned int)un, sizeof(t));
  2077. s_cat(t, " unread", sizeof(t));
  2078. }
  2079. ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t,
  2080. busy[0] ? ui.theme.accent :
  2081. (offline || status_err) ? ui.theme.error :
  2082. ui.theme.text_dim);
  2083. }
  2084. side = ngui_cut_left(&all, side_w);
  2085. ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1,
  2086. side.h }, ui.theme.border);
  2087. side.w -= 1;
  2088. tl = all;
  2089. if (modal == MODAL_NONE) {
  2090. draw_sidebar(side);
  2091. draw_timeline(tl);
  2092. } else {
  2093. draw_sidebar(side);
  2094. draw_timeline(tl);
  2095. action = ACT_NONE;
  2096. ui.pressed = saved_pressed;
  2097. draw_modal();
  2098. }
  2099. }
  2100. /* ---- frame / main loop ---- */
  2101. static void draw(void)
  2102. {
  2103. if (screen == SCR_MAIN)
  2104. draw_main();
  2105. else
  2106. draw_login();
  2107. }
  2108. /* Present a frame now (status text before a blocking network call). */
  2109. static void paint_now(void)
  2110. {
  2111. int saved_action = action, saved_arg = action_arg;
  2112. ngui_invalidate(&ui);
  2113. if (ngui_begin(&ui)) {
  2114. draw();
  2115. ngui_end(&ui);
  2116. }
  2117. action = saved_action;
  2118. action_arg = saved_arg;
  2119. }
  2120. static void run_action(void)
  2121. {
  2122. int a = action, arg = action_arg;
  2123. action = ACT_NONE;
  2124. switch (a) {
  2125. case ACT_START_LOGIN:
  2126. start_login();
  2127. break;
  2128. case ACT_SUBMIT:
  2129. submit_login(0);
  2130. break;
  2131. case ACT_SUBMIT_TOTP:
  2132. submit_login(1);
  2133. break;
  2134. case ACT_USE_COOKIE:
  2135. use_cookie();
  2136. break;
  2137. case ACT_COOKIE_SCREEN:
  2138. screen = SCR_COOKIE;
  2139. set_status("", 0, 0);
  2140. ngui_set_focus(&ui, ID_COOKIE);
  2141. break;
  2142. case ACT_BACK:
  2143. wipe_secrets();
  2144. screen = SCR_SERVER;
  2145. set_status("", 0, 0);
  2146. ngui_set_focus(&ui, ID_SERVER);
  2147. break;
  2148. case ACT_SEND:
  2149. send_message();
  2150. break;
  2151. case ACT_REFRESH:
  2152. case ACT_RETRY:
  2153. backoff_ms = 0;
  2154. retry_at = 0;
  2155. s_copy(busy, "Refreshing...", sizeof(busy));
  2156. paint_now();
  2157. busy[0] = '\0';
  2158. if (offline && !me_id[0]) {
  2159. check_session(1);
  2160. break;
  2161. }
  2162. if (load_directory() == 0) {
  2163. if (cur >= 0)
  2164. open_conv(cur);
  2165. else if (nconv)
  2166. open_conv(0);
  2167. }
  2168. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  2169. break;
  2170. case ACT_SIGNOUT:
  2171. sign_out();
  2172. break;
  2173. case ACT_OPEN_CONV:
  2174. if (arg != cur)
  2175. open_conv(arg);
  2176. break;
  2177. case ACT_OLDER:
  2178. load_older();
  2179. break;
  2180. case ACT_BROWSE:
  2181. load_picks(0);
  2182. break;
  2183. case ACT_NEWDM:
  2184. load_picks(1);
  2185. break;
  2186. case ACT_JOIN:
  2187. case ACT_OPEN_DM:
  2188. pick_action(arg);
  2189. break;
  2190. }
  2191. ngui_invalidate(&ui);
  2192. }
  2193. static void poll_tick(void)
  2194. {
  2195. unsigned int now = u_ticks_ms();
  2196. int focused = ui.focused;
  2197. if (screen != SCR_MAIN || modal != MODAL_NONE)
  2198. return;
  2199. if (offline) {
  2200. if (retry_at && (int)(now - retry_at) >= 0) {
  2201. retry_at = 0;
  2202. action = ACT_RETRY;
  2203. run_action();
  2204. }
  2205. return;
  2206. }
  2207. /* Do not interrupt typing or scrolling. */
  2208. if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS)
  2209. return;
  2210. if ((int)(now - next_dir_poll) >= 0) {
  2211. load_directory();
  2212. next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS);
  2213. next_conv_poll = now; /* follow with the conversation */
  2214. }
  2215. if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) {
  2216. poll_conv();
  2217. next_conv_poll = u_ticks_ms() +
  2218. (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS);
  2219. }
  2220. /* An open TCP socket pauses the board's net-dev watcher: only keep
  2221. * the connection while the user is actively chatting. */
  2222. if (http.connected &&
  2223. (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) >
  2224. KEEPALIVE_IDLE_MS) &&
  2225. (unsigned int)(u_ticks_ms() - last_net_ms) > 200)
  2226. net_drop();
  2227. }
  2228. void _start(const char *arg)
  2229. {
  2230. struct win_info wi;
  2231. unsigned int w = 980, h = 660;
  2232. resp = (char *)malloc(RESP_CAP);
  2233. jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) *
  2234. JSON_NODES);
  2235. jsbuf = (char *)malloc(JSON_SCAP);
  2236. if (!resp || !jnodes || !jsbuf) {
  2237. u_puts("chat: out of memory\n");
  2238. u_exit(1);
  2239. }
  2240. ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP);
  2241. uhttp_init(&http);
  2242. http.user_agent = "NebOS-Chat/1.0 (uhttp)";
  2243. uhttp_jar_init(&jar);
  2244. if (u_win_create(w, h, "Chat", &wi) != 0 &&
  2245. u_win_create(w = 780, h = 540, "Chat", &wi) != 0 &&
  2246. u_win_create(w = 600, h = 420, "Chat", &wi) != 0) {
  2247. u_puts("chat: no graphics window\n");
  2248. u_exit(1);
  2249. }
  2250. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  2251. ngui_font_attach(&ui);
  2252. server_in.placeholder = "chat.example.com";
  2253. user_in.placeholder = "username";
  2254. pass_in.secret = 1;
  2255. totp_in.placeholder = "123456";
  2256. cookie_in.placeholder = "connect.sid=...";
  2257. if (arg && arg[0]) {
  2258. s_copy(cfg_path, arg, sizeof(cfg_path));
  2259. } else {
  2260. s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path));
  2261. cfg_is_default = 1;
  2262. }
  2263. ngui_set_focus(&ui, ID_SERVER);
  2264. last_input_ms = 0;
  2265. /* First frame, then the (possibly slow) session check. */
  2266. paint_now();
  2267. load_config();
  2268. for (;;) {
  2269. int redraw;
  2270. redraw = ngui_begin(&ui);
  2271. if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) {
  2272. last_input_ms = u_ticks_ms();
  2273. if (screen == SCR_MAIN && !offline)
  2274. maybe_save_cookie();
  2275. }
  2276. if (redraw) {
  2277. draw();
  2278. ngui_end(&ui);
  2279. } else {
  2280. ngui_end_ex(&ui, 0);
  2281. }
  2282. if (action != ACT_NONE)
  2283. run_action();
  2284. else
  2285. poll_tick();
  2286. /* The offline retry countdown needs a once-a-second repaint. */
  2287. if (offline && screen == SCR_MAIN) {
  2288. static unsigned int last_tick;
  2289. if (u_ticks_ms() - last_tick >= 1000) {
  2290. last_tick = u_ticks_ms();
  2291. ngui_invalidate(&ui);
  2292. }
  2293. }
  2294. u_sleep_ms(10);
  2295. }
  2296. }