ucmd_chat.c 64 KB

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