ucmd_chat.c 88 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478
  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 "img.h"
  25. #include <stdlib.h>
  26. #include <stdio.h>
  27. #include <string.h>
  28. #define DEFAULT_CFG_DATA "/data/CHAT.CFG"
  29. #define DEFAULT_CFG_SHARE "/share/chat.cfg"
  30. #define RESP_CAP (512u * 1024u)
  31. #define JSON_NODES 16384u
  32. #define JSON_SCAP (RESP_CAP + 2u * JSON_NODES)
  33. #define MAX_CONV 128
  34. #define MAX_MSG 240
  35. #define MAX_PICK 256
  36. #define BODY_MAX 4096
  37. #define PAGE_SIZE 50
  38. #define LIVE_PAGE 50
  39. #define MSG_IMG_MAX 3
  40. #define CHAT_IMG_W 480
  41. #define CHAT_IMG_H 320
  42. #define CHAT_IMG_MAX 16
  43. #define CHAT_AVATAR_MAX 64
  44. #define CHAT_AVATAR 32
  45. #define CHAT_IMG_BUDGET (6u * 1024u * 1024u)
  46. #define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u)
  47. #define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u)
  48. #define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16)
  49. #define CHAT_PIC_QUEUED 0
  50. #define CHAT_PIC_READY 1
  51. #define CHAT_PIC_FETCHING 2
  52. #define CHAT_PIC_FAILED (-1)
  53. #define POLL_CONV_MS 2000
  54. #define POLL_CONV_IDLE_MS 5000
  55. #define POLL_DIR_MS 12000
  56. #define POLL_DIR_IDLE_MS 20000
  57. #define TYPING_HOLD_MS 1000
  58. #define KEEPALIVE_IDLE_MS 30000
  59. /* widget IDs */
  60. enum {
  61. ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS,
  62. ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND,
  63. ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG,
  64. ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000
  65. };
  66. enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN };
  67. enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM };
  68. /* pending actions, collected while drawing and run after the frame */
  69. enum {
  70. ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE,
  71. ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER,
  72. ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY,
  73. ACT_COOKIE_SCREEN, ACT_BACK
  74. };
  75. struct conv {
  76. char id[48];
  77. char name[64];
  78. char preview[96];
  79. char kind; /* 'c' public, 'p' private, 'd' DM */
  80. char presence; /* DM: 'o' online, 'a' away, 'f' offline */
  81. int unread;
  82. };
  83. struct msg {
  84. char id[48];
  85. char user_id[48];
  86. char author[48];
  87. char *author_pic; /* profile picture URL, or NULL */
  88. char created[32]; /* ISO 8601 UTC, sorts as text */
  89. char reply[96]; /* "Name: snippet" */
  90. char extra[112]; /* attachments / thread / reactions line */
  91. char *body; /* Latin-1, malloc'd */
  92. char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */
  93. unsigned char nimg;
  94. unsigned char action; /* type "me" */
  95. int height;
  96. int layout_w;
  97. int compact;
  98. int day_header;
  99. };
  100. struct pick {
  101. char id[48];
  102. char name[64];
  103. char sub[64];
  104. char pic[256];
  105. };
  106. static struct ngui ui;
  107. static struct uhttp http;
  108. static struct uhttp_jar jar;
  109. static struct chat_login login;
  110. static struct ujson json;
  111. static struct ujson_node *jnodes;
  112. static char *jsbuf;
  113. static char *resp;
  114. static unsigned int resp_len;
  115. static enum screen screen = SCR_SERVER;
  116. static enum modal modal = MODAL_NONE;
  117. static int action, action_arg;
  118. static char cfg_path[CHAT_PATH_MAX];
  119. static int cfg_is_default;
  120. static char server[CHAT_SERVER_MAX];
  121. static char server_host[UHTTP_HOST_MAX];
  122. static int server_secure;
  123. static char saved_cookie[CHAT_COOKIE_MAX];
  124. static unsigned int saved_jar_changes;
  125. static char me_id[48];
  126. static char me_name[64];
  127. static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in;
  128. static struct ngui_input cookie_in, compose_in, filter_in;
  129. static struct conv convs[MAX_CONV];
  130. static int nconv;
  131. static int cur = -1; /* index into convs */
  132. static char cur_id[48];
  133. static struct msg msgs[MAX_MSG];
  134. static int nmsg;
  135. static int has_older;
  136. static unsigned int msgs_gen; /* bumped whenever msgs[] changes */
  137. static int history_full;
  138. static struct ngui_scroll tl_scroll, side_scroll, modal_scroll;
  139. static int at_bottom = 1;
  140. static int new_below;
  141. static struct pick picks[MAX_PICK];
  142. static int npick;
  143. static int modal_sel; /* keyboard selection among visible rows */
  144. static unsigned int last_older_ms;
  145. static char status[160];
  146. static int status_err;
  147. static char busy[96];
  148. static int offline;
  149. static unsigned int backoff_ms;
  150. static unsigned int next_conv_poll, next_dir_poll, retry_at;
  151. static unsigned int last_input_ms;
  152. static unsigned int last_net_ms;
  153. static unsigned int client_seq;
  154. /* ---- small string helpers ---- */
  155. static void s_copy(char *d, const char *s, unsigned int cap)
  156. {
  157. unsigned int i = 0;
  158. if (!cap)
  159. return;
  160. while (s && s[i] && i + 1 < cap) {
  161. d[i] = s[i];
  162. i++;
  163. }
  164. d[i] = '\0';
  165. }
  166. static void s_cat(char *d, const char *s, unsigned int cap)
  167. {
  168. unsigned int n = (unsigned int)strlen(d);
  169. if (n < cap)
  170. s_copy(d + n, s, cap - n);
  171. }
  172. static void s_cat_uint(char *d, unsigned int v, unsigned int cap)
  173. {
  174. char tmp[12];
  175. int i = 11;
  176. tmp[i] = '\0';
  177. do {
  178. tmp[--i] = (char)('0' + v % 10);
  179. v /= 10;
  180. } while (v && i > 0);
  181. s_cat(d, tmp + i, cap);
  182. }
  183. static void set_status(const char *a, const char *b, int err)
  184. {
  185. status[0] = '\0';
  186. s_cat(status, a, sizeof(status));
  187. if (b)
  188. s_cat(status, b, sizeof(status));
  189. status_err = err;
  190. ngui_invalidate(&ui);
  191. }
  192. /* ---- UTF-8 -> Latin-1 display text ---- */
  193. static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap,
  194. const char *s)
  195. {
  196. while (*s && n + 1 < cap)
  197. d[n++] = *s++;
  198. return n;
  199. }
  200. /* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip
  201. * it entirely (joiners, variation selectors, skin tones). */
  202. static const char *cp_fallback(unsigned int cp)
  203. {
  204. switch (cp) {
  205. case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'";
  206. case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\"";
  207. case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-";
  208. case 0x2014: case 0x2015: return "--";
  209. case 0x2026: return "...";
  210. case 0x2022: case 0x2023: case 0x25CF: return "\xb7";
  211. case 0x20AC: return "EUR";
  212. case 0x2122: return "TM";
  213. case 0x2192: return "->";
  214. case 0x2190: return "<-";
  215. case 0x2264: return "<=";
  216. case 0x2265: return ">=";
  217. case 0x2260: return "!=";
  218. case 0x2764: case 0x2665: return "<3";
  219. case 0x2705: case 0x2714: case 0x2713: return "[v]";
  220. case 0x274C: case 0x2716: return "[x]";
  221. case 0x26A0: return "/!\\";
  222. case 0x1F44D: return "(y)";
  223. case 0x1F44E: return "(n)";
  224. case 0x1F44B: return "o/";
  225. case 0x1F64F: return "_/\\_";
  226. case 0x1F389: case 0x1F38A: return "*\\o/*";
  227. case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A:
  228. case 0x1F642: case 0x263A: return ":)";
  229. case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D";
  230. case 0x1F609: return ";)";
  231. case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P";
  232. case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":(";
  233. case 0x1F62E: case 0x1F632: return ":O";
  234. case 0x1F914: return ":-/";
  235. case 0x1F525: return "(fire)";
  236. case 0x1F680: return "(rocket)";
  237. case 0x1F440: return "(eyes)";
  238. case 0x200B: case 0x200C: case 0x200D: case 0xFEFF:
  239. return 0;
  240. }
  241. if (cp >= 0xFE00 && cp <= 0xFE0F)
  242. return 0; /* variation selectors */
  243. if (cp >= 0x1F3FB && cp <= 0x1F3FF)
  244. return 0; /* skin tones */
  245. if (cp >= 0x2000 && cp <= 0x200A)
  246. return " ";
  247. return "?";
  248. }
  249. /* Convert UTF-8 to Latin-1 display text. Tabs become spaces, other control
  250. * characters (except newline) are dropped. */
  251. static unsigned int to_latin1(char *d, unsigned int cap, const char *s)
  252. {
  253. const unsigned char *p = (const unsigned char *)s;
  254. unsigned int n = 0;
  255. if (!cap)
  256. return 0;
  257. while (*p && n + 1 < cap) {
  258. unsigned int cp, extra, i;
  259. if (*p < 0x80) {
  260. cp = *p++;
  261. } else {
  262. if ((*p & 0xE0) == 0xC0) {
  263. cp = *p & 0x1F;
  264. extra = 1;
  265. } else if ((*p & 0xF0) == 0xE0) {
  266. cp = *p & 0x0F;
  267. extra = 2;
  268. } else if ((*p & 0xF8) == 0xF0) {
  269. cp = *p & 0x07;
  270. extra = 3;
  271. } else {
  272. p++;
  273. d[n++] = '?';
  274. continue;
  275. }
  276. p++;
  277. for (i = 0; i < extra; i++) {
  278. if ((*p & 0xC0) != 0x80)
  279. break;
  280. cp = (cp << 6) | (*p++ & 0x3F);
  281. }
  282. if (i < extra) {
  283. d[n++] = '?';
  284. continue;
  285. }
  286. }
  287. if (cp == '\t' || cp == 0xA0) {
  288. d[n++] = ' ';
  289. } else if (cp == '\n') {
  290. d[n++] = '\n';
  291. } else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) {
  292. continue;
  293. } else if (cp < 0x100) {
  294. d[n++] = (char)cp;
  295. } else {
  296. const char *f = cp_fallback(cp);
  297. if (f)
  298. n = put_ascii(d, n, cap, f);
  299. }
  300. }
  301. d[n] = '\0';
  302. return n;
  303. }
  304. /* One-line version (newlines become spaces), for previews/snippets. */
  305. static void to_latin1_line(char *d, unsigned int cap, const char *s)
  306. {
  307. unsigned int i;
  308. to_latin1(d, cap, s);
  309. for (i = 0; d[i]; i++)
  310. if (d[i] == '\n')
  311. d[i] = ' ';
  312. }
  313. /* ---- config file ---- */
  314. static int read_file(const char *path, char *buf, unsigned int cap)
  315. {
  316. int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1));
  317. if (n < 0)
  318. return n;
  319. buf[n] = '\0';
  320. return n;
  321. }
  322. static int write_file(const char *path, const char *buf, unsigned int len)
  323. {
  324. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len);
  325. }
  326. /* The persistent data volume wins when it is mounted and writable; the
  327. * volatile /share is the fallback (live USB, or a board without /data). */
  328. static const char *default_cfg_path(void)
  329. {
  330. struct sys_mount m;
  331. unsigned int i;
  332. for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++)
  333. if (strcmp(m.name, "data") == 0 && !m.ro)
  334. return DEFAULT_CFG_DATA;
  335. return DEFAULT_CFG_SHARE;
  336. }
  337. static int set_server(const char *s)
  338. {
  339. char norm[CHAT_SERVER_MAX];
  340. if (chat_server_normalize(s, norm, sizeof(norm)) != 0)
  341. return -1;
  342. if (chat_server_host(norm, server_host, sizeof(server_host),
  343. &server_secure) != 0)
  344. return -1;
  345. s_copy(server, norm, sizeof(server));
  346. return 0;
  347. }
  348. /* Export the Chat host's cookies and write the config file. */
  349. static void save_config(void)
  350. {
  351. static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128];
  352. int n;
  353. uhttp_jar_header(&jar, server_host, "/api/me", server_secure,
  354. saved_cookie, sizeof(saved_cookie));
  355. saved_jar_changes = jar.changes;
  356. n = chat_config_format(out, sizeof(out), server, saved_cookie);
  357. if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0)
  358. set_status("Could not save the session to ", cfg_path, 1);
  359. memset(out, 0, sizeof(out));
  360. }
  361. /* A server may roll its session cookie: save when the jar changed. */
  362. static void maybe_save_cookie(void)
  363. {
  364. char now[CHAT_COOKIE_MAX];
  365. if (jar.changes == saved_jar_changes || screen != SCR_MAIN)
  366. return;
  367. uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now,
  368. sizeof(now));
  369. saved_jar_changes = jar.changes;
  370. if (strcmp(now, saved_cookie) != 0)
  371. save_config();
  372. }
  373. /* ---- HTTP / JSON plumbing ---- */
  374. static void paint_now(void);
  375. static int line_h(void);
  376. static void net_drop(void)
  377. {
  378. http.keepalive = 0;
  379. uhttp_close(&http);
  380. }
  381. /* Request server + path; JSON body or NULL. Returns the HTTP status or a
  382. * UHTTP_ERR_*; the body is in resp/resp_len. */
  383. static int api(const char *method, const char *path, const char *body)
  384. {
  385. char url[CHAT_SERVER_MAX + 256];
  386. unsigned int len = 0;
  387. int st;
  388. s_copy(url, server, sizeof(url));
  389. s_cat(url, path, sizeof(url));
  390. http.jar = &jar;
  391. http.accept = "application/json";
  392. st = chat_http(&http, method, url, body, resp, RESP_CAP, &len);
  393. resp_len = st > 0 ? len : 0;
  394. last_net_ms = u_ticks_ms();
  395. maybe_save_cookie();
  396. return st;
  397. }
  398. static int parse_resp(void)
  399. {
  400. int root = ujson_parse(&json, resp, resp_len);
  401. return root;
  402. }
  403. /* ---- message images and avatars ---- */
  404. struct chat_pic {
  405. char *url;
  406. struct img_image img;
  407. unsigned int bytes; /* RGB565 bytes in the message-image budget */
  408. unsigned int last_used;
  409. int state; /* CHAT_PIC_* */
  410. };
  411. static struct chat_pic chat_images[CHAT_IMG_MAX];
  412. static int nchat_images;
  413. static unsigned int chat_image_bytes;
  414. static struct chat_pic chat_avatars[CHAT_AVATAR_MAX];
  415. static int nchat_avatars;
  416. static unsigned int chat_pic_clock;
  417. static unsigned char *chat_fetch_buf;
  418. static unsigned char *chat_arena;
  419. static unsigned int chat_arena_size;
  420. static void chat_pic_free(struct chat_pic *p)
  421. {
  422. free(p->url);
  423. free(p->img.px);
  424. free(p->img.alpha);
  425. memset(p, 0, sizeof(*p));
  426. }
  427. static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n,
  428. const char *url)
  429. {
  430. int i;
  431. for (i = 0; i < n; i++)
  432. if (arr[i].url && strcmp(arr[i].url, url) == 0)
  433. return &arr[i];
  434. return 0;
  435. }
  436. /* Pick a cache slot, evicting the least recently used entry when full.
  437. * avatars: their images never change the timeline layout. */
  438. static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max,
  439. const char *url, int avatars)
  440. {
  441. struct chat_pic *p = chat_pic_find(arr, *count, url);
  442. unsigned int best = ~0u;
  443. int i, victim = -1;
  444. if (p)
  445. return p;
  446. if (*count < max) {
  447. p = &arr[*count];
  448. memset(p, 0, sizeof(*p));
  449. p->url = strdup(url);
  450. if (!p->url)
  451. return 0;
  452. (*count)++;
  453. } else {
  454. for (i = 0; i < *count; i++) {
  455. if (arr[i].state == CHAT_PIC_QUEUED ||
  456. arr[i].state == CHAT_PIC_FETCHING)
  457. continue;
  458. if (arr[i].last_used < best) {
  459. best = arr[i].last_used;
  460. victim = i;
  461. }
  462. }
  463. if (victim < 0)
  464. return 0;
  465. p = &arr[victim];
  466. if (!avatars) {
  467. chat_image_bytes -= p->bytes;
  468. msgs_gen++;
  469. }
  470. chat_pic_free(p);
  471. p->url = strdup(url);
  472. if (!p->url)
  473. return 0;
  474. }
  475. p->state = CHAT_PIC_QUEUED;
  476. p->last_used = ++chat_pic_clock;
  477. return p;
  478. }
  479. static struct chat_pic *chat_image_slot(const char *url)
  480. {
  481. return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0);
  482. }
  483. static struct chat_pic *chat_avatar_slot(const char *url)
  484. {
  485. return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX,
  486. url, 1);
  487. }
  488. static int chat_image_room(unsigned int need)
  489. {
  490. while (chat_image_bytes + need > CHAT_IMG_BUDGET) {
  491. unsigned int best = ~0u;
  492. int i, victim = -1;
  493. for (i = 0; i < nchat_images; i++) {
  494. if (chat_images[i].state != CHAT_PIC_READY)
  495. continue;
  496. if (chat_images[i].last_used < best) {
  497. best = chat_images[i].last_used;
  498. victim = i;
  499. }
  500. }
  501. if (victim < 0)
  502. return -1;
  503. chat_image_bytes -= chat_images[victim].bytes;
  504. chat_pic_free(&chat_images[victim]);
  505. msgs_gen++;
  506. }
  507. return 0;
  508. }
  509. static unsigned char *chat_pic_arena_get(unsigned int need)
  510. {
  511. if (need <= chat_arena_size)
  512. return chat_arena;
  513. free(chat_arena);
  514. chat_arena = (unsigned char *)malloc(need);
  515. chat_arena_size = chat_arena ? need : 0;
  516. return chat_arena;
  517. }
  518. /* Clip the scaled avatar to a circle with a 4x4 supersampled edge. The RGB
  519. * pixels stay untouched; only the alpha plane changes. */
  520. static void chat_avatar_mask(unsigned char *alpha, unsigned int w,
  521. unsigned int h)
  522. {
  523. unsigned int x, y;
  524. for (y = 0; y < h; y++) {
  525. for (x = 0; x < w; x++) {
  526. unsigned int hits = 0;
  527. int sx, sy;
  528. for (sy = 0; sy < 4; sy++) {
  529. int py = (int)y * 8 + sy * 2 + 1;
  530. int dy = py - (int)h * 4;
  531. for (sx = 0; sx < 4; sx++) {
  532. int px = (int)x * 8 + sx * 2 + 1;
  533. int dx = px - (int)w * 4;
  534. if (dx * dx + dy * dy <=
  535. (int)w * 4 * (int)w * 4)
  536. hits++;
  537. }
  538. }
  539. alpha[y * w + x] =
  540. (unsigned char)((unsigned int)alpha[y * w + x] *
  541. hits / 16u);
  542. }
  543. }
  544. }
  545. static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar)
  546. {
  547. struct img_info info;
  548. struct img_options opt = {0};
  549. struct img_mem mem;
  550. struct img_image decoded;
  551. struct img_blit blit;
  552. unsigned char *arena, *alpha = 0;
  553. unsigned short *px;
  554. unsigned int est, scale, dw, dh, sw, sh, i, need;
  555. int r;
  556. if (img_sniff(chat_fetch_buf, len, &info) != 0)
  557. return -1;
  558. est = img_estimate(&info);
  559. if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX)
  560. return -1;
  561. arena = chat_pic_arena_get(est);
  562. if (!arena)
  563. return -1;
  564. img_mem_init(&mem, arena, est);
  565. opt.max_pixels = 4u * 1024u * 1024u;
  566. opt.max_w = avatar ? CHAT_AVATAR : CHAT_IMG_W;
  567. opt.max_h = avatar ? CHAT_AVATAR : CHAT_IMG_H;
  568. r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded);
  569. if (r != 0 || !decoded.w || !decoded.h)
  570. return -1;
  571. if (avatar) {
  572. sw = (CHAT_AVATAR << 16) / decoded.w;
  573. sh = (CHAT_AVATAR << 16) / decoded.h;
  574. scale = sw < sh ? sw : sh;
  575. dw = dh = CHAT_AVATAR;
  576. } else {
  577. scale = 65536;
  578. if (decoded.w > CHAT_IMG_W)
  579. scale = (CHAT_IMG_W << 16) / decoded.w;
  580. if (((decoded.h * scale) >> 16) > CHAT_IMG_H)
  581. scale = (CHAT_IMG_H << 16) / decoded.h;
  582. dw = (decoded.w * scale) >> 16;
  583. dh = (decoded.h * scale) >> 16;
  584. if (!dw)
  585. dw = 1;
  586. if (!dh)
  587. dh = 1;
  588. need = dw * dh * 2u;
  589. if (chat_image_room(need) != 0)
  590. return -1;
  591. }
  592. px = (unsigned short *)malloc(dw * dh * 2u);
  593. if (!px)
  594. return -1;
  595. for (i = 0; i < dw * dh; i++)
  596. px[i] = avatar ? 0xFFFF : ui.theme.bg;
  597. if (avatar) {
  598. /* Keep an alpha plane even for an opaque picture: the circular
  599. * mask below clips it to the avatar circle. */
  600. alpha = (unsigned char *)malloc(dw * dh);
  601. if (alpha)
  602. memset(alpha, 255, dw * dh);
  603. }
  604. memset(&blit, 0, sizeof(blit));
  605. blit.dst = px;
  606. blit.dst_w = (int)dw;
  607. blit.dst_h = (int)dh;
  608. blit.clip_x = 0;
  609. blit.clip_y = 0;
  610. blit.clip_w = (int)dw;
  611. blit.clip_h = (int)dh;
  612. blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0;
  613. blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0;
  614. blit.scale = scale;
  615. blit.bg = avatar ? 0xFFFF : ui.theme.bg;
  616. blit.bg2 = blit.bg;
  617. blit.dst_a = alpha;
  618. blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA :
  619. (decoded.alpha ? IMG_BLIT_OVER_DST : 0);
  620. img_draw(&decoded, &blit);
  621. if (avatar && alpha)
  622. chat_avatar_mask(alpha, dw, dh);
  623. p->img.format = decoded.format;
  624. p->img.w = dw;
  625. p->img.h = dh;
  626. p->img.px = px;
  627. p->img.alpha = alpha;
  628. p->img.flags = 0;
  629. p->bytes = avatar ? 0 : dw * dh * 2u;
  630. if (!avatar)
  631. chat_image_bytes += p->bytes;
  632. return 0;
  633. }
  634. /* Install a message-image bitmap decoded by the fetch helper (the helper
  635. * already applied the 480x320 bounds). Avatars are still decoded here at
  636. * 32x32 so the circular mask sees the same square source as before. */
  637. static int chat_pic_store_px(struct chat_pic *p, unsigned char *buf,
  638. unsigned int len, unsigned int dw,
  639. unsigned int dh, int has_alpha)
  640. {
  641. unsigned int npx = dw * dh, need;
  642. unsigned short *px;
  643. unsigned char *alpha = 0;
  644. if (!buf || !dw || !dh || len < npx * 2u)
  645. return -1;
  646. need = npx * 2u;
  647. if (chat_image_room(need) != 0)
  648. return -1;
  649. px = (unsigned short *)malloc(need);
  650. if (!px)
  651. return -1;
  652. memcpy(px, buf, need);
  653. if (has_alpha && len >= need + npx) {
  654. alpha = (unsigned char *)malloc(npx);
  655. if (alpha)
  656. memcpy(alpha, buf + need, npx);
  657. }
  658. p->img.format = 0;
  659. p->img.w = dw;
  660. p->img.h = dh;
  661. p->img.px = px;
  662. p->img.alpha = alpha;
  663. p->img.flags = 0;
  664. p->bytes = need;
  665. chat_image_bytes += need;
  666. return 0;
  667. }
  668. /* ---- asynchronous media fetch ----
  669. *
  670. * chat_http() blocks the UI for the whole body, so every image and avatar
  671. * used to freeze the window for the download plus the decode. Media now
  672. * goes through the same curl __serve helper as the browser: the chat loop
  673. * submits a request file and polls a small done marker, while a private tty
  674. * absorbs the helper's DNS/TLS log lines. Only the (short) decode runs on
  675. * the chat thread. */
  676. static int chat_media_pid = -1;
  677. static int chat_media_tty = -1;
  678. static unsigned int chat_media_session;
  679. static unsigned int chat_media_seq;
  680. static unsigned int chat_media_deadline;
  681. static int chat_media_busy;
  682. static int chat_media_retried;
  683. static struct chat_pic *chat_media_pic;
  684. static int chat_media_avatar;
  685. static char chat_media_req[40], chat_media_body[40];
  686. static char chat_media_meta[40], chat_media_done[40];
  687. static char chat_media_px[40];
  688. static void chat_media_paths(void)
  689. {
  690. if (chat_media_session)
  691. return;
  692. chat_media_session = ((unsigned int)u_getpid() << 16) ^
  693. (u_ticks_ms() & 0xFFFFu);
  694. if (!chat_media_session)
  695. chat_media_session = 1;
  696. snprintf(chat_media_req, sizeof(chat_media_req), "/share/bf%u_0req",
  697. chat_media_session);
  698. snprintf(chat_media_body, sizeof(chat_media_body), "/share/bf%u_0body",
  699. chat_media_session);
  700. snprintf(chat_media_meta, sizeof(chat_media_meta), "/share/bf%u_0meta",
  701. chat_media_session);
  702. snprintf(chat_media_done, sizeof(chat_media_done), "/share/bf%u_0done",
  703. chat_media_session);
  704. snprintf(chat_media_px, sizeof(chat_media_px), "/share/bf%u_0px",
  705. chat_media_session);
  706. }
  707. static void chat_media_tty_drain(void)
  708. {
  709. char sink[256];
  710. int i;
  711. if (chat_media_tty <= 0)
  712. return;
  713. for (i = 0; i < 8; i++)
  714. if (u_tty_read(chat_media_tty, sink, sizeof(sink)) <= 0)
  715. break;
  716. }
  717. static void chat_media_jar_sync(void)
  718. {
  719. u_syscall3(SYS_WRITE_FILE, (int)"/share/bchat.jar", (int)&jar,
  720. (int)sizeof(jar));
  721. }
  722. static int chat_media_start(void)
  723. {
  724. char arg[64];
  725. int t;
  726. chat_media_paths();
  727. if (chat_media_pid > 0 && u_alive((unsigned int)chat_media_pid))
  728. return 0;
  729. chat_media_pid = -1;
  730. if (chat_media_tty == -1) {
  731. t = u_tty_create();
  732. chat_media_tty = t > 0 ? t : 0;
  733. }
  734. chat_media_jar_sync();
  735. snprintf(arg, sizeof(arg), "__serve %u 0 /share/bchat.jar",
  736. chat_media_session);
  737. chat_media_pid = u_spawn("/ramfs/bin/curl", arg, chat_media_tty, "/");
  738. if (chat_media_pid <= 0) {
  739. chat_media_pid = -1;
  740. return -1;
  741. }
  742. return 0;
  743. }
  744. static void chat_media_stop(void)
  745. {
  746. chat_media_tty_drain();
  747. if (chat_media_pid > 0)
  748. u_kill((unsigned int)chat_media_pid);
  749. chat_media_pid = -1;
  750. }
  751. static void chat_media_fail(void)
  752. {
  753. if (chat_media_pic)
  754. chat_media_pic->state = CHAT_PIC_FAILED;
  755. chat_media_pic = 0;
  756. chat_media_busy = 0;
  757. chat_media_retried = 0;
  758. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  759. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  760. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  761. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  762. ngui_invalidate(&ui);
  763. }
  764. static int chat_media_submit(struct chat_pic *p, int avatar)
  765. {
  766. char req[512];
  767. int n;
  768. if (!chat_fetch_buf) {
  769. chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX);
  770. if (!chat_fetch_buf)
  771. return -1;
  772. }
  773. chat_media_paths();
  774. if (chat_media_start() != 0)
  775. return -1;
  776. chat_media_jar_sync();
  777. chat_media_seq++;
  778. if (!chat_media_seq)
  779. chat_media_seq = 1;
  780. chat_media_retried = 0;
  781. if (!avatar)
  782. n = snprintf(req, sizeof(req), "%u %u D %u %u %s\n",
  783. chat_media_seq, CHAT_IMG_FETCH_MAX,
  784. CHAT_IMG_W, CHAT_IMG_H, p->url);
  785. else
  786. n = snprintf(req, sizeof(req), "%u %u %s\n",
  787. chat_media_seq, CHAT_IMG_FETCH_MAX, p->url);
  788. if (n <= 0 || n >= (int)sizeof(req))
  789. return -1;
  790. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  791. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  792. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  793. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  794. if (u_syscall3(SYS_WRITE_FILE, (int)chat_media_req, (int)req, n) < 0)
  795. return -1;
  796. p->state = CHAT_PIC_FETCHING;
  797. chat_media_pic = p;
  798. chat_media_avatar = avatar;
  799. chat_media_busy = 1;
  800. chat_media_deadline = u_ticks_ms() + 30000;
  801. return 0;
  802. }
  803. /* 1 when the outstanding job finished (success or failure). */
  804. static unsigned int chat_meta_uint(char **pp)
  805. {
  806. char *p = *pp;
  807. unsigned int v = 0;
  808. while (*p >= '0' && *p <= '9') {
  809. v = v * 10 + (unsigned int)(*p - '0');
  810. p++;
  811. }
  812. while (*p && *p != '\n')
  813. p++;
  814. if (*p)
  815. p++;
  816. *pp = p;
  817. return v;
  818. }
  819. static int chat_media_poll(void)
  820. {
  821. char done[24], meta[1200];
  822. int rn, st = 0, err = 0;
  823. unsigned int seq;
  824. unsigned int dw = 0, dh = 0, nw = 0, nh = 0, alpha = 0;
  825. unsigned int px_len = 0, dec_err = 0;
  826. if (!chat_media_busy)
  827. return 0;
  828. chat_media_tty_drain();
  829. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_done, (int)done,
  830. (int)(sizeof(done) - 1));
  831. if (rn > 0) {
  832. char *q;
  833. done[rn] = '\0';
  834. seq = (unsigned int)atoi(done);
  835. if (seq != chat_media_seq)
  836. return 0;
  837. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_meta, (int)meta,
  838. (int)(sizeof(meta) - 1));
  839. if (rn > 0) {
  840. meta[rn] = '\0';
  841. q = meta;
  842. (void)chat_meta_uint(&q); /* seq */
  843. st = (int)chat_meta_uint(&q);
  844. err = (int)chat_meta_uint(&q);
  845. (void)chat_meta_uint(&q); /* trunc */
  846. while (*q && *q != '\n') /* encoding */
  847. q++;
  848. if (*q)
  849. q++;
  850. while (*q && *q != '\n') /* content type */
  851. q++;
  852. if (*q)
  853. q++;
  854. while (*q && *q != '\n') /* final URL */
  855. q++;
  856. if (*q)
  857. q++;
  858. (void)chat_meta_uint(&q); /* body bytes */
  859. (void)chat_meta_uint(&q); /* open */
  860. (void)chat_meta_uint(&q); /* first */
  861. (void)chat_meta_uint(&q); /* total */
  862. dw = chat_meta_uint(&q);
  863. dh = chat_meta_uint(&q);
  864. nw = chat_meta_uint(&q);
  865. nh = chat_meta_uint(&q);
  866. alpha = chat_meta_uint(&q);
  867. px_len = chat_meta_uint(&q);
  868. dec_err = chat_meta_uint(&q);
  869. (void)chat_meta_uint(&q); /* dec ms */
  870. }
  871. if (st == 200 && !err && chat_media_pic) {
  872. int stored = 0;
  873. (void)nw;
  874. (void)nh;
  875. if (!chat_media_avatar && px_len && !dec_err &&
  876. dw && dh && px_len <= CHAT_IMG_FETCH_MAX) {
  877. rn = u_syscall3(SYS_READ_FILE, (int)chat_media_px,
  878. (int)chat_fetch_buf,
  879. (int)CHAT_IMG_FETCH_MAX);
  880. if (rn == (int)px_len &&
  881. chat_pic_store_px(chat_media_pic,
  882. chat_fetch_buf, px_len,
  883. dw, dh, (int)alpha) == 0)
  884. stored = 1;
  885. }
  886. if (!stored) {
  887. rn = u_syscall3(SYS_READ_FILE,
  888. (int)chat_media_body,
  889. (int)chat_fetch_buf,
  890. (int)CHAT_IMG_FETCH_MAX);
  891. if (rn > 0 &&
  892. chat_pic_store(chat_media_pic,
  893. (unsigned int)rn,
  894. chat_media_avatar) == 0)
  895. stored = 1;
  896. }
  897. if (stored) {
  898. chat_media_pic->state = CHAT_PIC_READY;
  899. chat_media_pic->last_used = ++chat_pic_clock;
  900. if (!chat_media_avatar) {
  901. msgs_gen++;
  902. if (at_bottom)
  903. tl_scroll.offset = 1 << 28;
  904. }
  905. } else {
  906. chat_media_pic->state = CHAT_PIC_FAILED;
  907. }
  908. } else if (chat_media_pic) {
  909. chat_media_pic->state = CHAT_PIC_FAILED;
  910. }
  911. chat_media_pic = 0;
  912. chat_media_busy = 0;
  913. u_syscall1(SYS_UNLINK, (int)chat_media_done);
  914. u_syscall1(SYS_UNLINK, (int)chat_media_meta);
  915. u_syscall1(SYS_UNLINK, (int)chat_media_body);
  916. u_syscall1(SYS_UNLINK, (int)chat_media_px);
  917. ngui_invalidate(&ui);
  918. return 1;
  919. }
  920. if (chat_media_pid > 0 && !u_alive((unsigned int)chat_media_pid)) {
  921. chat_media_pid = -1;
  922. if (!chat_media_retried && chat_media_start() == 0) {
  923. chat_media_retried = 1;
  924. return 0;
  925. }
  926. chat_media_fail();
  927. return 1;
  928. }
  929. if ((int)(u_ticks_ms() - chat_media_deadline) >= 0) {
  930. chat_media_stop();
  931. chat_media_fail();
  932. return 1;
  933. }
  934. return 0;
  935. }
  936. static void chat_media_tick(void)
  937. {
  938. int i;
  939. if (screen != SCR_MAIN || offline)
  940. return;
  941. if (chat_media_busy) {
  942. chat_media_poll();
  943. return;
  944. }
  945. /* Holding a helper keeps a TCP socket open, which pauses the board's
  946. * net-dev watcher; release it when the window is not being used. */
  947. if (!ui.focused) {
  948. if (chat_media_pid > 0)
  949. chat_media_stop();
  950. return;
  951. }
  952. for (i = 0; i < nchat_images; i++) {
  953. if (chat_images[i].state == CHAT_PIC_QUEUED) {
  954. if (chat_media_submit(&chat_images[i], 0) != 0)
  955. chat_images[i].state = CHAT_PIC_FAILED;
  956. ngui_invalidate(&ui);
  957. return;
  958. }
  959. }
  960. for (i = 0; i < nchat_avatars; i++) {
  961. if (chat_avatars[i].state == CHAT_PIC_QUEUED) {
  962. if (chat_media_submit(&chat_avatars[i], 1) != 0)
  963. chat_avatars[i].state = CHAT_PIC_FAILED;
  964. ngui_invalidate(&ui);
  965. return;
  966. }
  967. }
  968. }
  969. static void chat_media_clear(void)
  970. {
  971. int i;
  972. chat_media_stop();
  973. chat_media_pic = 0;
  974. chat_media_busy = 0;
  975. chat_media_retried = 0;
  976. for (i = 0; i < nchat_images; i++)
  977. chat_pic_free(&chat_images[i]);
  978. for (i = 0; i < nchat_avatars; i++)
  979. chat_pic_free(&chat_avatars[i]);
  980. nchat_images = 0;
  981. nchat_avatars = 0;
  982. chat_image_bytes = 0;
  983. free(chat_fetch_buf);
  984. chat_fetch_buf = 0;
  985. free(chat_arena);
  986. chat_arena = 0;
  987. chat_arena_size = 0;
  988. }
  989. /* Refresh/Retry gives failed pictures another chance. */
  990. static void chat_media_retry(void)
  991. {
  992. int i;
  993. for (i = 0; i < nchat_images; i++)
  994. if (chat_images[i].state == CHAT_PIC_FAILED)
  995. chat_images[i].state = CHAT_PIC_QUEUED;
  996. for (i = 0; i < nchat_avatars; i++)
  997. if (chat_avatars[i].state == CHAT_PIC_FAILED)
  998. chat_avatars[i].state = CHAT_PIC_QUEUED;
  999. ngui_invalidate(&ui);
  1000. }
  1001. /* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten
  1002. * to the /api/avatars/ route the current server serves. */
  1003. static int chat_pic_url(const char *raw, char *out, unsigned int cap)
  1004. {
  1005. static const char old_prefix[] = "/api/v1/profile/avatar/";
  1006. const char *p;
  1007. char tmp[CHAT_IMG_URL_MAX];
  1008. char *q;
  1009. if (!raw || !raw[0])
  1010. return -1;
  1011. p = strstr(raw, old_prefix);
  1012. if (p) {
  1013. s_copy(tmp, "/api/avatars/", sizeof(tmp));
  1014. s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp));
  1015. q = strchr(tmp, '?');
  1016. if (q)
  1017. *q = '\0';
  1018. raw = tmp;
  1019. }
  1020. return uhttp_resolve(server, raw, out, cap);
  1021. }
  1022. static int chat_image_name(const char *mime, const char *filename)
  1023. {
  1024. static const char *const ext[] = {
  1025. ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga",
  1026. ".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam"
  1027. };
  1028. unsigned int i;
  1029. if (mime && strncmp(mime, "image/", 6) == 0)
  1030. return 1;
  1031. if (!filename)
  1032. return 0;
  1033. for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) {
  1034. unsigned int n = (unsigned int)strlen(ext[i]);
  1035. unsigned int j;
  1036. const char *s = filename + strlen(filename);
  1037. if ((unsigned int)strlen(filename) < n)
  1038. continue;
  1039. s -= n;
  1040. for (j = 0; j < n; j++) {
  1041. char a = s[j], b = ext[i][j];
  1042. if (a >= 'A' && a <= 'Z')
  1043. a = (char)(a - 'A' + 'a');
  1044. if (a != b)
  1045. break;
  1046. }
  1047. if (j == n)
  1048. return 1;
  1049. }
  1050. return 0;
  1051. }
  1052. /* Layout/draw dimensions for one message image. *state is the cache state
  1053. * (a missing entry is treated as queued; draw queues it). */
  1054. static void chat_image_measure(const char *url, int tw, int *dw, int *dh,
  1055. unsigned int *scale, int *state)
  1056. {
  1057. struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
  1058. unsigned int sc = 65536;
  1059. if (p && p->state == CHAT_PIC_READY) {
  1060. if ((int)p->img.w > tw)
  1061. sc = ((unsigned int)tw << 16) / p->img.w;
  1062. if (((p->img.h * sc) >> 16) > CHAT_IMG_H)
  1063. sc = (CHAT_IMG_H << 16) / p->img.h;
  1064. *dw = (int)((p->img.w * sc) >> 16);
  1065. *dh = (int)((p->img.h * sc) >> 16);
  1066. if (*dw < 1)
  1067. *dw = 1;
  1068. if (*dh < 1)
  1069. *dh = 1;
  1070. *scale = sc;
  1071. *state = CHAT_PIC_READY;
  1072. return;
  1073. }
  1074. *dw = tw < 320 ? tw : 320;
  1075. if (*dw < 40)
  1076. *dw = 40;
  1077. *dh = 120;
  1078. *scale = 65536;
  1079. *state = p ? p->state : CHAT_PIC_QUEUED;
  1080. }
  1081. static struct ngui_rect chat_clip_rect(void)
  1082. {
  1083. if (ui.nclip > 0)
  1084. return ui.clip[ui.nclip - 1];
  1085. return (struct ngui_rect){ 0, 0, ui.w, ui.h };
  1086. }
  1087. static void chat_image_draw(const char *url, int x, int y, int tw)
  1088. {
  1089. struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url);
  1090. struct ngui_rect clip = chat_clip_rect();
  1091. int dw, dh, state;
  1092. unsigned int scale;
  1093. if (!p)
  1094. p = chat_image_slot(url);
  1095. chat_image_measure(url, tw, &dw, &dh, &scale, &state);
  1096. if (p && p->state == CHAT_PIC_READY) {
  1097. struct img_blit blit;
  1098. memset(&blit, 0, sizeof(blit));
  1099. blit.dst = ui.px;
  1100. blit.dst_w = ui.w;
  1101. blit.dst_h = ui.h;
  1102. blit.clip_x = clip.x;
  1103. blit.clip_y = clip.y;
  1104. blit.clip_w = clip.w;
  1105. blit.clip_h = clip.h;
  1106. blit.x = x;
  1107. blit.y = y;
  1108. blit.scale = scale;
  1109. blit.bg = ui.theme.bg;
  1110. blit.bg2 = ui.theme.bg;
  1111. blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
  1112. img_draw(&p->img, &blit);
  1113. ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh },
  1114. ui.theme.border);
  1115. } else {
  1116. struct ngui_rect box = { x, y, dw, dh };
  1117. ngui_fill_rect(&ui, box, ui.theme.panel_alt);
  1118. ngui_frame(&ui, box, ui.theme.border);
  1119. ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2,
  1120. state == CHAT_PIC_FAILED ?
  1121. "Image could not be loaded" :
  1122. "Loading image...", ui.theme.text_dim);
  1123. }
  1124. }
  1125. static int chat_avatar_draw(const char *url, int x, int y, int size,
  1126. unsigned short fallback)
  1127. {
  1128. struct chat_pic *p;
  1129. if (!url || !url[0])
  1130. return 0;
  1131. p = chat_pic_find(chat_avatars, nchat_avatars, url);
  1132. if (!p)
  1133. p = chat_avatar_slot(url);
  1134. if (p && p->state == CHAT_PIC_READY) {
  1135. struct ngui_rect clip = chat_clip_rect();
  1136. struct img_blit blit;
  1137. memset(&blit, 0, sizeof(blit));
  1138. blit.dst = ui.px;
  1139. blit.dst_w = ui.w;
  1140. blit.dst_h = ui.h;
  1141. blit.clip_x = clip.x;
  1142. blit.clip_y = clip.y;
  1143. blit.clip_w = clip.w;
  1144. blit.clip_h = clip.h;
  1145. blit.x = x;
  1146. blit.y = y;
  1147. blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR;
  1148. blit.bg = fallback;
  1149. blit.bg2 = fallback;
  1150. blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0;
  1151. img_draw(&p->img, &blit);
  1152. return 1;
  1153. }
  1154. return 0;
  1155. }
  1156. static void go_login(const char *why);
  1157. /* Common error handling for API calls in the main screen. Returns 1 when
  1158. * the status is a success. */
  1159. static int api_ok(int st, const char *what)
  1160. {
  1161. if (st >= 200 && st < 300) {
  1162. if (offline) {
  1163. offline = 0;
  1164. set_status("Connected", 0, 0);
  1165. }
  1166. backoff_ms = 0;
  1167. return 1;
  1168. }
  1169. if (st == 401) {
  1170. go_login("Session expired - please sign in again");
  1171. return 0;
  1172. }
  1173. if (st > 0) {
  1174. char code[64];
  1175. s_copy(code, what, sizeof(code));
  1176. s_cat(code, ": HTTP ", sizeof(code));
  1177. s_cat_uint(code, (unsigned int)st, sizeof(code));
  1178. set_status(code, 0, 1);
  1179. return 0;
  1180. }
  1181. offline = 1;
  1182. backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 :
  1183. backoff_ms < 10000 ? 10000 : 30000;
  1184. retry_at = u_ticks_ms() + backoff_ms;
  1185. set_status("Offline: ", uhttp_error_string(st), 1);
  1186. net_drop();
  1187. return 0;
  1188. }
  1189. /* ---- conversations ---- */
  1190. static int conv_find(const char *id)
  1191. {
  1192. int i;
  1193. for (i = 0; i < nconv; i++)
  1194. if (strcmp(convs[i].id, id) == 0)
  1195. return i;
  1196. return -1;
  1197. }
  1198. static void conv_from_json(struct conv *c, int o, int dm)
  1199. {
  1200. int last;
  1201. s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id));
  1202. c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0);
  1203. c->preview[0] = '\0';
  1204. last = ujson_get(&json, o, "lastMessage");
  1205. if (ujson_type(&json, last) == UJSON_OBJECT) {
  1206. char tmp[96];
  1207. to_latin1_line(tmp, sizeof(tmp),
  1208. ujson_get_str(&json, last, "authorName"));
  1209. s_copy(c->preview, tmp, sizeof(c->preview));
  1210. s_cat(c->preview, ": ", sizeof(c->preview));
  1211. to_latin1_line(tmp, sizeof(tmp),
  1212. ujson_get_str(&json, last, "body"));
  1213. s_cat(c->preview, tmp, sizeof(c->preview));
  1214. }
  1215. if (dm) {
  1216. int other = ujson_get(&json, o, "otherUser");
  1217. const char *pres = ujson_get_str(&json, o, "presence");
  1218. const char *nm = ujson_get_str(&json, other, "name");
  1219. if (!nm[0])
  1220. nm = ujson_get_str(&json, other, "username");
  1221. to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)");
  1222. c->kind = 'd';
  1223. c->presence = strcmp(pres, "online") == 0 ? 'o' :
  1224. strcmp(pres, "away") == 0 ? 'a' : 'f';
  1225. } else {
  1226. to_latin1_line(c->name, sizeof(c->name),
  1227. ujson_get_str(&json, o, "name"));
  1228. c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ?
  1229. 'p' : 'c';
  1230. c->presence = 0;
  1231. }
  1232. }
  1233. static int load_directory(void)
  1234. {
  1235. static struct conv next[MAX_CONV];
  1236. int n = 0, st, root, it, pass;
  1237. for (pass = 0; pass < 2; pass++) {
  1238. st = api(0, pass ? "/api/dms" : "/api/channels", 0);
  1239. if (!api_ok(st, pass ? "Direct messages" : "Channels"))
  1240. return -1;
  1241. root = parse_resp();
  1242. if (root < 0) {
  1243. set_status("Bad directory reply: ", json.error, 1);
  1244. return -1;
  1245. }
  1246. for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV;
  1247. it = ujson_next(&json, it)) {
  1248. if (ujson_truthy(&json, ujson_get(&json, it, "archived")))
  1249. continue;
  1250. if (pass && ujson_truthy(&json, ujson_get(&json, it,
  1251. "isSelf")))
  1252. continue;
  1253. conv_from_json(&next[n], it, pass);
  1254. if (next[n].id[0])
  1255. n++;
  1256. }
  1257. }
  1258. memcpy(convs, next, sizeof(struct conv) * (unsigned int)n);
  1259. nconv = n;
  1260. cur = cur_id[0] ? conv_find(cur_id) : -1;
  1261. if (cur >= 0 && at_bottom)
  1262. convs[cur].unread = 0; /* we are reading it */
  1263. ngui_invalidate(&ui);
  1264. return 0;
  1265. }
  1266. /* ---- messages ---- */
  1267. static void msg_free(struct msg *m)
  1268. {
  1269. int i;
  1270. free(m->body);
  1271. m->body = 0;
  1272. free(m->author_pic);
  1273. m->author_pic = 0;
  1274. for (i = 0; i < m->nimg; i++) {
  1275. free(m->img_url[i]);
  1276. m->img_url[i] = 0;
  1277. }
  1278. m->nimg = 0;
  1279. }
  1280. /* Resolve and remember one image URL; duplicates and overflowing messages
  1281. * are ignored. */
  1282. static int msg_add_image(struct msg *m, const char *raw)
  1283. {
  1284. char url[CHAT_IMG_URL_MAX];
  1285. int i;
  1286. if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX)
  1287. return 0;
  1288. if (uhttp_resolve(server, raw, url, sizeof(url)) != 0)
  1289. return 0;
  1290. for (i = 0; i < m->nimg; i++)
  1291. if (strcmp(m->img_url[i], url) == 0)
  1292. return 0;
  1293. m->img_url[m->nimg] = strdup(url);
  1294. if (!m->img_url[m->nimg])
  1295. return -1;
  1296. m->nimg++;
  1297. return 0;
  1298. }
  1299. static void msg_set_author_pic(struct msg *m, const char *raw)
  1300. {
  1301. char url[CHAT_IMG_URL_MAX];
  1302. if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0)
  1303. return;
  1304. m->author_pic = strdup(url);
  1305. }
  1306. static void clear_messages(void)
  1307. {
  1308. int i;
  1309. for (i = 0; i < nmsg; i++)
  1310. msg_free(&msgs[i]);
  1311. nmsg = 0;
  1312. msgs_gen++;
  1313. has_older = 0;
  1314. history_full = 0;
  1315. new_below = 0;
  1316. }
  1317. static int msg_find(const char *id)
  1318. {
  1319. int i;
  1320. for (i = nmsg - 1; i >= 0; i--)
  1321. if (strcmp(msgs[i].id, id) == 0)
  1322. return i;
  1323. return -1;
  1324. }
  1325. static void build_extra(struct msg *m, int o)
  1326. {
  1327. int it, n;
  1328. m->extra[0] = '\0';
  1329. for (it = ujson_first(&json, ujson_get(&json, o, "attachments"));
  1330. it >= 0; it = ujson_next(&json, it)) {
  1331. char name[64];
  1332. const char *mime = ujson_get_str(&json, it, "mime");
  1333. const char *fn = ujson_get_str(&json, it, "filename");
  1334. const char *url = ujson_get_str(&json, it, "url");
  1335. if (chat_image_name(mime, fn) && url[0])
  1336. continue; /* drawn inline by the timeline */
  1337. to_latin1_line(name, sizeof(name), fn);
  1338. if (m->extra[0])
  1339. s_cat(m->extra, ", ", sizeof(m->extra));
  1340. else
  1341. s_cat(m->extra, "[file] ", sizeof(m->extra));
  1342. s_cat(m->extra, name, sizeof(m->extra));
  1343. }
  1344. if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
  1345. !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) {
  1346. if (m->extra[0])
  1347. s_cat(m->extra, " ", sizeof(m->extra));
  1348. s_cat(m->extra, "[GIF]", sizeof(m->extra));
  1349. }
  1350. if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) {
  1351. if (m->extra[0])
  1352. s_cat(m->extra, " ", sizeof(m->extra));
  1353. s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra));
  1354. }
  1355. if (ujson_get_str(&json, o, "callUrl")[0]) {
  1356. if (m->extra[0])
  1357. s_cat(m->extra, " ", sizeof(m->extra));
  1358. s_cat(m->extra, "[call]", sizeof(m->extra));
  1359. }
  1360. n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0);
  1361. if (n > 0) {
  1362. if (m->extra[0])
  1363. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1364. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  1365. s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra));
  1366. }
  1367. n = 0;
  1368. for (it = ujson_first(&json, ujson_get(&json, o, "reactions"));
  1369. it >= 0; it = ujson_next(&json, it)) {
  1370. int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1);
  1371. n += c > 0 ? c : 1;
  1372. }
  1373. if (n > 0) {
  1374. if (m->extra[0])
  1375. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1376. s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra));
  1377. s_cat(m->extra, n == 1 ? " reaction" : " reactions",
  1378. sizeof(m->extra));
  1379. }
  1380. if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) {
  1381. if (m->extra[0])
  1382. s_cat(m->extra, " \xb7 ", sizeof(m->extra));
  1383. s_cat(m->extra, "pinned", sizeof(m->extra));
  1384. }
  1385. }
  1386. /* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */
  1387. static int msg_from_json(struct msg *m, int o)
  1388. {
  1389. static char body[BODY_MAX + 8];
  1390. const char *nm;
  1391. int rt;
  1392. unsigned int len;
  1393. if (ujson_truthy(&json, ujson_get(&json, o, "deleted")))
  1394. return -1;
  1395. /* Thread replies live in the thread panel, not the timeline. */
  1396. if (ujson_get_str(&json, o, "parentId")[0])
  1397. return -1;
  1398. memset(m, 0, sizeof(*m));
  1399. s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id));
  1400. if (!m->id[0])
  1401. return -1;
  1402. s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id));
  1403. nm = ujson_get_str(&json, o, "authorName");
  1404. if (!nm[0])
  1405. nm = ujson_get_str(&json, o, "authorUsername");
  1406. to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?");
  1407. msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture"));
  1408. s_copy(m->created, ujson_get_str(&json, o, "createdAt"),
  1409. sizeof(m->created));
  1410. m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0;
  1411. len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body"));
  1412. if (len + 1 >= BODY_MAX) {
  1413. /* truncated: mark it */
  1414. body[BODY_MAX - 4] = '.';
  1415. body[BODY_MAX - 3] = '.';
  1416. body[BODY_MAX - 2] = '.';
  1417. body[BODY_MAX - 1] = '\0';
  1418. }
  1419. /* Trim trailing newlines/spaces. */
  1420. len = (unsigned int)strlen(body);
  1421. while (len && (body[len - 1] == '\n' || body[len - 1] == ' '))
  1422. body[--len] = '\0';
  1423. m->body = strdup(body);
  1424. if (!m->body) {
  1425. msg_free(m);
  1426. return -1;
  1427. }
  1428. {
  1429. int it;
  1430. const char *mime, *fn;
  1431. for (it = ujson_first(&json,
  1432. ujson_get(&json, o, "attachments"));
  1433. it >= 0; it = ujson_next(&json, it)) {
  1434. mime = ujson_get_str(&json, it, "mime");
  1435. fn = ujson_get_str(&json, it, "filename");
  1436. if (chat_image_name(mime, fn) &&
  1437. msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) {
  1438. msg_free(m);
  1439. return -1;
  1440. }
  1441. }
  1442. }
  1443. if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT &&
  1444. msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"),
  1445. "url")) != 0) {
  1446. msg_free(m);
  1447. return -1;
  1448. }
  1449. if (ujson_type(&json, ujson_get(&json, o, "preview")) == UJSON_OBJECT &&
  1450. msg_add_image(m, ujson_get_str(&json,
  1451. ujson_get(&json, o, "preview"),
  1452. "image")) != 0) {
  1453. msg_free(m);
  1454. return -1;
  1455. }
  1456. rt = ujson_get(&json, o, "replyTo");
  1457. if (ujson_type(&json, rt) == UJSON_OBJECT) {
  1458. char tmp[96];
  1459. to_latin1_line(m->reply, sizeof(m->reply),
  1460. ujson_get_str(&json, rt, "authorName"));
  1461. s_cat(m->reply, ": ", sizeof(m->reply));
  1462. if (ujson_truthy(&json, ujson_get(&json, rt, "deleted")))
  1463. s_copy(tmp, "(deleted)", sizeof(tmp));
  1464. else
  1465. to_latin1_line(tmp, sizeof(tmp),
  1466. ujson_get_str(&json, rt, "body"));
  1467. if (!tmp[0])
  1468. s_copy(tmp, "(attachment)", sizeof(tmp));
  1469. s_cat(m->reply, tmp, sizeof(m->reply));
  1470. }
  1471. build_extra(m, o);
  1472. return 0;
  1473. }
  1474. static int msg_before(const struct msg *a, const struct msg *b)
  1475. {
  1476. int c = strcmp(a->created, b->created);
  1477. return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0);
  1478. }
  1479. /* Insert or update a message, keeping msgs sorted. older: we are paging
  1480. * back in history (never evict old messages for it). Returns 1 when a new
  1481. * message was added, 0 when updated/skipped. */
  1482. static int msg_merge(struct msg *m, int older)
  1483. {
  1484. int i = msg_find(m->id), pos;
  1485. msgs_gen++;
  1486. if (i >= 0) {
  1487. /* Edited body or new reactions: replace in place. */
  1488. msg_free(&msgs[i]);
  1489. msgs[i] = *m;
  1490. return 0;
  1491. }
  1492. if (nmsg >= MAX_MSG) {
  1493. if (older) {
  1494. history_full = 1;
  1495. msg_free(m);
  1496. return 0;
  1497. }
  1498. msg_free(&msgs[0]);
  1499. memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1));
  1500. nmsg--;
  1501. has_older = 1;
  1502. history_full = 1;
  1503. }
  1504. pos = nmsg;
  1505. while (pos > 0 && msg_before(m, &msgs[pos - 1]))
  1506. pos--;
  1507. memmove(&msgs[pos + 1], &msgs[pos],
  1508. sizeof(struct msg) * (unsigned int)(nmsg - pos));
  1509. msgs[pos] = *m;
  1510. nmsg++;
  1511. return 1;
  1512. }
  1513. /* Merge every message of the parsed reply. Returns the number added. */
  1514. static int merge_reply(int root, int older, int *count)
  1515. {
  1516. int it, added = 0, n = 0;
  1517. for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) {
  1518. struct msg m;
  1519. const char *id = ujson_get_str(&json, it, "id");
  1520. n++;
  1521. if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) {
  1522. /* A deletion we already show: drop it. */
  1523. int k = msg_find(id);
  1524. if (k >= 0) {
  1525. msg_free(&msgs[k]);
  1526. memmove(&msgs[k], &msgs[k + 1],
  1527. sizeof(struct msg) *
  1528. (unsigned int)(nmsg - k - 1));
  1529. nmsg--;
  1530. msgs_gen++;
  1531. }
  1532. continue;
  1533. }
  1534. if (msg_from_json(&m, it) == 0)
  1535. added += msg_merge(&m, older);
  1536. }
  1537. if (count)
  1538. *count = n;
  1539. return added;
  1540. }
  1541. static void mark_read(void)
  1542. {
  1543. char path[96];
  1544. int st;
  1545. if (cur < 0)
  1546. return;
  1547. s_copy(path, "/api/channels/", sizeof(path));
  1548. s_cat(path, convs[cur].id, sizeof(path));
  1549. s_cat(path, "/read", sizeof(path));
  1550. st = api("POST", path, 0);
  1551. if (api_ok(st, "Mark read"))
  1552. convs[cur].unread = 0;
  1553. }
  1554. static void msgs_path(char *path, unsigned int cap, const char *query)
  1555. {
  1556. s_copy(path, "/api/channels/", cap);
  1557. s_cat(path, cur_id, cap);
  1558. s_cat(path, "/messages?", cap);
  1559. s_cat(path, query, cap);
  1560. }
  1561. static void scroll_to_end(void)
  1562. {
  1563. tl_scroll.offset = 1 << 28; /* clamped when laid out */
  1564. at_bottom = 1;
  1565. new_below = 0;
  1566. }
  1567. static void open_conv(int idx)
  1568. {
  1569. char path[160];
  1570. int st, root, n = 0;
  1571. if (idx < 0 || idx >= nconv)
  1572. return;
  1573. cur = idx;
  1574. s_copy(cur_id, convs[idx].id, sizeof(cur_id));
  1575. clear_messages();
  1576. scroll_to_end();
  1577. s_copy(busy, "Loading messages...", sizeof(busy));
  1578. paint_now();
  1579. msgs_path(path, sizeof(path), "limit=50");
  1580. st = api(0, path, 0);
  1581. busy[0] = '\0';
  1582. if (!api_ok(st, "Messages"))
  1583. return;
  1584. root = parse_resp();
  1585. if (root < 0) {
  1586. set_status("Bad message reply: ", json.error, 1);
  1587. return;
  1588. }
  1589. merge_reply(root, 1, &n);
  1590. has_older = n >= PAGE_SIZE;
  1591. scroll_to_end();
  1592. mark_read();
  1593. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  1594. ngui_invalidate(&ui);
  1595. }
  1596. static int content_height(void);
  1597. static void load_older(void)
  1598. {
  1599. char path[200], q[96];
  1600. int st, root, n = 0, before_h, added;
  1601. if (cur < 0 || !nmsg || history_full)
  1602. return;
  1603. last_older_ms = u_ticks_ms();
  1604. s_copy(q, "limit=50&before=", sizeof(q));
  1605. s_cat(q, msgs[0].id, sizeof(q));
  1606. msgs_path(path, sizeof(path), q);
  1607. s_copy(busy, "Loading older messages...", sizeof(busy));
  1608. paint_now();
  1609. st = api(0, path, 0);
  1610. busy[0] = '\0';
  1611. if (!api_ok(st, "Older messages"))
  1612. return;
  1613. root = parse_resp();
  1614. if (root < 0)
  1615. return;
  1616. before_h = content_height();
  1617. added = merge_reply(root, 1, &n);
  1618. has_older = n >= PAGE_SIZE && !history_full;
  1619. /* Keep the view on the same message. */
  1620. if (added)
  1621. tl_scroll.offset += content_height() - before_h;
  1622. ngui_invalidate(&ui);
  1623. }
  1624. static void poll_conv(void)
  1625. {
  1626. char path[200], q[96];
  1627. int st, root, added, n = 0;
  1628. if (cur < 0)
  1629. return;
  1630. if (!nmsg) {
  1631. msgs_path(path, sizeof(path), "limit=50");
  1632. } else {
  1633. s_copy(q, "limit=50&after=", sizeof(q));
  1634. s_cat(q, msgs[nmsg - 1].id, sizeof(q));
  1635. msgs_path(path, sizeof(path), q);
  1636. }
  1637. st = api(0, path, 0);
  1638. if (st == 404 && nmsg) {
  1639. /* The anchor message was deleted: reload the page. */
  1640. open_conv(cur);
  1641. return;
  1642. }
  1643. if (!api_ok(st, "Messages"))
  1644. return;
  1645. root = parse_resp();
  1646. if (root < 0) {
  1647. set_status("Bad message reply: ", json.error, 1);
  1648. return;
  1649. }
  1650. added = merge_reply(root, 0, &n);
  1651. if (n >= LIVE_PAGE) {
  1652. /* More than a page arrived: jump to the newest page. */
  1653. open_conv(cur);
  1654. return;
  1655. }
  1656. if (added) {
  1657. if (at_bottom) {
  1658. scroll_to_end();
  1659. mark_read();
  1660. } else {
  1661. new_below += added;
  1662. }
  1663. ngui_invalidate(&ui);
  1664. }
  1665. }
  1666. static void make_client_id(char *out, unsigned int cap)
  1667. {
  1668. static const char hex[] = "0123456789abcdef";
  1669. unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20);
  1670. unsigned int c = ++client_seq, i;
  1671. s_copy(out, "nebos-", cap);
  1672. for (i = 0; i < 8; i++) {
  1673. char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 };
  1674. s_cat(out, ch, cap);
  1675. }
  1676. s_cat(out, "-", cap);
  1677. s_cat_uint(out, c, cap);
  1678. }
  1679. static void send_message(void)
  1680. {
  1681. static char body[NGUI_INPUT_MAX * 6 + 160];
  1682. char path[96], cid[40];
  1683. int st, root, r;
  1684. unsigned int n = 0;
  1685. const char *t = compose_in.text;
  1686. while (*t == ' ')
  1687. t++;
  1688. if (cur < 0 || !*t)
  1689. return;
  1690. make_client_id(cid, sizeof(cid));
  1691. s_copy(body, "{\"body\":", sizeof(body));
  1692. n = (unsigned int)strlen(body);
  1693. {
  1694. /* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */
  1695. static char utf8[NGUI_INPUT_MAX * 2 + 4];
  1696. unsigned int k = 0;
  1697. const unsigned char *p = (const unsigned char *)t;
  1698. while (*p && k + 3 < sizeof(utf8)) {
  1699. if (*p < 0x80) {
  1700. utf8[k++] = (char)*p;
  1701. } else {
  1702. utf8[k++] = (char)(0xC0 | (*p >> 6));
  1703. utf8[k++] = (char)(0x80 | (*p & 0x3F));
  1704. }
  1705. p++;
  1706. }
  1707. utf8[k] = '\0';
  1708. r = ujson_escape(body + n, sizeof(body) - n, utf8);
  1709. }
  1710. if (r < 0)
  1711. return;
  1712. n += (unsigned int)r;
  1713. s_cat(body, ",\"clientId\":\"", sizeof(body));
  1714. s_cat(body, cid, sizeof(body));
  1715. s_cat(body, "\"}", sizeof(body));
  1716. s_copy(path, "/api/channels/", sizeof(path));
  1717. s_cat(path, cur_id, sizeof(path));
  1718. s_cat(path, "/messages", sizeof(path));
  1719. s_copy(busy, "Sending...", sizeof(busy));
  1720. paint_now();
  1721. st = api("POST", path, body);
  1722. busy[0] = '\0';
  1723. if (!api_ok(st, "Send")) {
  1724. if (st > 0) {
  1725. char msg[96];
  1726. root = parse_resp();
  1727. s_copy(msg, root >= 0 ?
  1728. ujson_get_str(&json, root, "error") : "", sizeof(msg));
  1729. if (msg[0])
  1730. set_status("Send failed: ", msg, 1);
  1731. }
  1732. return; /* the text stays in the composer */
  1733. }
  1734. ngui_input_set(&compose_in, "");
  1735. root = parse_resp();
  1736. if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) {
  1737. struct msg m;
  1738. if (msg_from_json(&m, root) == 0)
  1739. msg_merge(&m, 0);
  1740. }
  1741. scroll_to_end();
  1742. mark_read();
  1743. next_conv_poll = u_ticks_ms() + POLL_CONV_MS;
  1744. ngui_set_focus(&ui, ID_COMPOSE);
  1745. }
  1746. /* ---- browse / new DM ---- */
  1747. static void load_picks(int dms)
  1748. {
  1749. int st, root, it;
  1750. npick = 0;
  1751. ngui_input_set(&filter_in, "");
  1752. s_copy(busy, dms ? "Loading people..." : "Loading channels...",
  1753. sizeof(busy));
  1754. paint_now();
  1755. st = api(0, dms ? "/api/users" : "/api/channels/public", 0);
  1756. busy[0] = '\0';
  1757. if (!api_ok(st, dms ? "Users" : "Public channels"))
  1758. return;
  1759. root = parse_resp();
  1760. if (root < 0)
  1761. return;
  1762. for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK;
  1763. it = ujson_next(&json, it)) {
  1764. struct pick *p = &picks[npick];
  1765. const char *nm;
  1766. s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id));
  1767. if (!p->id[0])
  1768. continue;
  1769. p->pic[0] = '\0';
  1770. {
  1771. char url[CHAT_IMG_URL_MAX];
  1772. if (chat_pic_url(ujson_get_str(&json, it, "picture"),
  1773. url, sizeof(url)) == 0)
  1774. s_copy(p->pic, url, sizeof(p->pic));
  1775. }
  1776. if (dms) {
  1777. if (strcmp(p->id, me_id) == 0)
  1778. continue;
  1779. nm = ujson_get_str(&json, it, "name");
  1780. if (!nm[0])
  1781. nm = ujson_get_str(&json, it, "username");
  1782. to_latin1_line(p->name, sizeof(p->name), nm);
  1783. to_latin1_line(p->sub, sizeof(p->sub),
  1784. ujson_get_str(&json, it, "username"));
  1785. } else {
  1786. to_latin1_line(p->name, sizeof(p->name),
  1787. ujson_get_str(&json, it, "name"));
  1788. to_latin1_line(p->sub, sizeof(p->sub),
  1789. ujson_get_str(&json, it, "description"));
  1790. }
  1791. npick++;
  1792. }
  1793. modal = dms ? MODAL_NEWDM : MODAL_BROWSE;
  1794. modal_scroll.offset = 0;
  1795. modal_sel = 0;
  1796. ngui_set_focus(&ui, ID_FILTER);
  1797. }
  1798. static void pick_action(int idx)
  1799. {
  1800. char path[128], body[96], id[48];
  1801. int st, root;
  1802. if (idx < 0 || idx >= npick)
  1803. return;
  1804. if (modal == MODAL_BROWSE) {
  1805. s_copy(path, "/api/channels/", sizeof(path));
  1806. s_cat(path, picks[idx].id, sizeof(path));
  1807. s_cat(path, "/join", sizeof(path));
  1808. s_copy(busy, "Joining...", sizeof(busy));
  1809. paint_now();
  1810. st = api("POST", path, 0);
  1811. busy[0] = '\0';
  1812. if (!api_ok(st, "Join"))
  1813. return;
  1814. s_copy(id, picks[idx].id, sizeof(id));
  1815. } else {
  1816. s_copy(body, "{\"userId\":", sizeof(body));
  1817. if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body),
  1818. picks[idx].id) < 0)
  1819. return;
  1820. s_cat(body, "}", sizeof(body));
  1821. s_copy(busy, "Opening conversation...", sizeof(busy));
  1822. paint_now();
  1823. st = api("POST", "/api/dms", body);
  1824. busy[0] = '\0';
  1825. if (!api_ok(st, "New DM"))
  1826. return;
  1827. root = parse_resp();
  1828. s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "",
  1829. sizeof(id));
  1830. }
  1831. modal = MODAL_NONE;
  1832. if (load_directory() == 0 && id[0]) {
  1833. int k = conv_find(id);
  1834. if (k >= 0)
  1835. open_conv(k);
  1836. }
  1837. }
  1838. /* ---- session ---- */
  1839. static void enter_main(void)
  1840. {
  1841. int root;
  1842. screen = SCR_MAIN;
  1843. offline = 0;
  1844. backoff_ms = 0;
  1845. root = parse_resp(); /* the /api/me reply */
  1846. if (root >= 0) {
  1847. const char *nm = ujson_get_str(&json, root, "name");
  1848. s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id));
  1849. to_latin1_line(me_name, sizeof(me_name),
  1850. nm[0] ? nm : ujson_get_str(&json, root, "username"));
  1851. }
  1852. set_status("Connected", 0, 0);
  1853. if (load_directory() == 0 && nconv > 0 && cur < 0) {
  1854. int i, pick = 0;
  1855. for (i = 0; i < nconv; i++) {
  1856. if (convs[i].kind != 'd' &&
  1857. strcmp(convs[i].name, "general") == 0) {
  1858. pick = i;
  1859. break;
  1860. }
  1861. }
  1862. open_conv(pick);
  1863. }
  1864. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  1865. ngui_set_focus(&ui, ID_COMPOSE);
  1866. }
  1867. static void go_login(const char *why)
  1868. {
  1869. net_drop();
  1870. uhttp_jar_clear(&jar);
  1871. saved_jar_changes = jar.changes;
  1872. saved_cookie[0] = '\0';
  1873. chat_media_clear();
  1874. screen = SCR_SERVER;
  1875. modal = MODAL_NONE;
  1876. clear_messages();
  1877. nconv = 0;
  1878. cur = -1;
  1879. cur_id[0] = '\0';
  1880. set_status(why, 0, why != 0);
  1881. ngui_set_focus(&ui, ID_SERVER);
  1882. }
  1883. /* After the jar holds a session: validate it with /api/me. */
  1884. static int check_session(int keep_offline)
  1885. {
  1886. unsigned int len = 0;
  1887. int r;
  1888. s_copy(busy, "Checking session...", sizeof(busy));
  1889. paint_now();
  1890. r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len);
  1891. busy[0] = '\0';
  1892. resp_len = len;
  1893. if (r == 0) {
  1894. save_config();
  1895. enter_main();
  1896. return 0;
  1897. }
  1898. if (r == 1) {
  1899. go_login("The saved session is no longer valid - sign in again");
  1900. return -1;
  1901. }
  1902. if (keep_offline) {
  1903. /* Network trouble: keep the cached session and retry. */
  1904. screen = SCR_MAIN;
  1905. offline = 1;
  1906. backoff_ms = 5000;
  1907. retry_at = u_ticks_ms() + backoff_ms;
  1908. set_status("Offline: ", r < 0 && r > -100 ?
  1909. uhttp_error_string(r) : "server error", 1);
  1910. return -1;
  1911. }
  1912. set_status("Session check failed: ", r < 0 && r > -100 ?
  1913. uhttp_error_string(r) : "server error", 1);
  1914. return -1;
  1915. }
  1916. static void start_login(void)
  1917. {
  1918. int r;
  1919. if (set_server(server_in.text) != 0) {
  1920. set_status("Enter a server such as chat.example.com", 0, 1);
  1921. return;
  1922. }
  1923. if (cfg_in.text[0])
  1924. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  1925. uhttp_jar_clear(&jar);
  1926. s_copy(busy, "Contacting the server...", sizeof(busy));
  1927. paint_now();
  1928. r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP);
  1929. busy[0] = '\0';
  1930. net_drop();
  1931. if (r == CHAT_LOGIN_OK) {
  1932. resp_len = (unsigned int)strlen(resp);
  1933. save_config();
  1934. enter_main();
  1935. return;
  1936. }
  1937. if (r == CHAT_LOGIN_FORM) {
  1938. screen = SCR_CRED;
  1939. set_status("", 0, 0);
  1940. ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER);
  1941. return;
  1942. }
  1943. if (r == CHAT_LOGIN_NOFORM) {
  1944. screen = SCR_COOKIE;
  1945. set_status(login.error, 0, 1);
  1946. ngui_set_focus(&ui, ID_COOKIE);
  1947. return;
  1948. }
  1949. set_status(login.error, 0, 1);
  1950. }
  1951. static void wipe_secrets(void)
  1952. {
  1953. memset(pass_in.text, 0, sizeof(pass_in.text));
  1954. pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0;
  1955. memset(totp_in.text, 0, sizeof(totp_in.text));
  1956. totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0;
  1957. }
  1958. static void submit_login(int with_totp)
  1959. {
  1960. int r;
  1961. if (!user_in.text[0] || !pass_in.text[0]) {
  1962. set_status("Enter the username and password", 0, 1);
  1963. return;
  1964. }
  1965. s_copy(busy, "Signing in...", sizeof(busy));
  1966. paint_now();
  1967. r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text,
  1968. with_totp ? totp_in.text : "", resp, RESP_CAP);
  1969. busy[0] = '\0';
  1970. net_drop();
  1971. if (r == CHAT_LOGIN_TOTP) {
  1972. if (with_totp) {
  1973. set_status("The code was not accepted", 0, 1);
  1974. } else {
  1975. screen = SCR_TOTP;
  1976. set_status("", 0, 0);
  1977. }
  1978. ngui_set_focus(&ui, ID_TOTP);
  1979. return;
  1980. }
  1981. if (r == CHAT_LOGIN_OK) {
  1982. wipe_secrets();
  1983. resp_len = (unsigned int)strlen(resp);
  1984. save_config();
  1985. enter_main();
  1986. return;
  1987. }
  1988. if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) {
  1989. /* A wrong TOTP code is also a 401. */
  1990. set_status(login.error, 0, 1);
  1991. ngui_input_set(&totp_in, "");
  1992. return;
  1993. }
  1994. if (r == CHAT_LOGIN_DENIED) {
  1995. memset(pass_in.text, 0, sizeof(pass_in.text));
  1996. ngui_input_set(&pass_in, "");
  1997. ngui_set_focus(&ui, ID_PASS);
  1998. }
  1999. if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR)
  2000. wipe_secrets();
  2001. if (r == CHAT_LOGIN_PASSKEY)
  2002. screen = SCR_COOKIE;
  2003. set_status(login.error, 0, 1);
  2004. }
  2005. static void use_cookie(void)
  2006. {
  2007. if (set_server(server_in.text) != 0) {
  2008. set_status("Enter a server such as chat.example.com", 0, 1);
  2009. return;
  2010. }
  2011. if (cfg_in.text[0])
  2012. s_copy(cfg_path, cfg_in.text, sizeof(cfg_path));
  2013. uhttp_jar_clear(&jar);
  2014. {
  2015. const char *c = cookie_in.text;
  2016. /* Accept a pasted "Cookie: ..." header too. */
  2017. if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0)
  2018. c += 7;
  2019. if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) {
  2020. set_status("Paste the cookie as name=value", 0, 1);
  2021. return;
  2022. }
  2023. }
  2024. check_session(0);
  2025. if (screen == SCR_MAIN)
  2026. ngui_input_set(&cookie_in, "");
  2027. }
  2028. static void sign_out(void)
  2029. {
  2030. /* Best effort: end the server session too. */
  2031. if (server[0]) {
  2032. s_copy(busy, "Signing out...", sizeof(busy));
  2033. paint_now();
  2034. api(0, "/auth/logout", 0);
  2035. busy[0] = '\0';
  2036. }
  2037. go_login("Signed out");
  2038. {
  2039. static char out[CHAT_SERVER_MAX + 80];
  2040. int n = chat_config_format(out, sizeof(out), server, "");
  2041. if (n > 0)
  2042. write_file(cfg_path, out, (unsigned int)n);
  2043. }
  2044. }
  2045. static void load_config(void)
  2046. {
  2047. static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256];
  2048. char srv[CHAT_SERVER_MAX];
  2049. int n, migrated = 0;
  2050. n = read_file(cfg_path, buf, sizeof(buf));
  2051. /* First start on a persistent volume: carry a session that an older
  2052. * build saved in /share into /data once. */
  2053. if (n <= 0 && cfg_is_default &&
  2054. strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) {
  2055. n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf));
  2056. migrated = n > 0;
  2057. }
  2058. ngui_input_set(&cfg_in, cfg_path);
  2059. if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv),
  2060. saved_cookie,
  2061. sizeof(saved_cookie)) != 0) {
  2062. ngui_input_set(&server_in, "chat.cloudron.io");
  2063. saved_cookie[0] = '\0';
  2064. memset(buf, 0, sizeof(buf));
  2065. return;
  2066. }
  2067. memset(buf, 0, sizeof(buf));
  2068. ngui_input_set(&server_in, srv);
  2069. if (set_server(srv) != 0 || !saved_cookie[0])
  2070. return;
  2071. uhttp_jar_import(&jar, server_host, server_secure, saved_cookie);
  2072. saved_jar_changes = jar.changes;
  2073. if (migrated)
  2074. save_config();
  2075. check_session(1);
  2076. }
  2077. /* ---- text layout ---- */
  2078. static int line_h(void)
  2079. {
  2080. int h = ngui_text_line_height(&ui, ui.font_px, 0);
  2081. return h > 0 ? h : 16;
  2082. }
  2083. static int text_w(const char *s, unsigned int n, int bold)
  2084. {
  2085. return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0);
  2086. }
  2087. /* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets
  2088. * the bytes to skip to the next line. */
  2089. static unsigned int wrap_line(const char *s, unsigned int n, int maxw,
  2090. unsigned int *adv)
  2091. {
  2092. unsigned int i = 0, end = 0, j;
  2093. if (n && s[0] == '\n') {
  2094. *adv = 1;
  2095. return 0;
  2096. }
  2097. for (;;) {
  2098. j = i;
  2099. while (j < n && s[j] == ' ')
  2100. j++;
  2101. while (j < n && s[j] != ' ' && s[j] != '\n')
  2102. j++;
  2103. if (j == i)
  2104. break;
  2105. if (text_w(s, j, 0) > maxw) {
  2106. if (end == 0) {
  2107. /* One word wider than the line: split it. */
  2108. unsigned int k = 1;
  2109. while (k < j && text_w(s, k + 1, 0) <= maxw)
  2110. k++;
  2111. *adv = k;
  2112. return k;
  2113. }
  2114. break;
  2115. }
  2116. end = j;
  2117. i = j;
  2118. if (j >= n || s[j] == '\n')
  2119. break;
  2120. }
  2121. *adv = end;
  2122. while (*adv < n && s[*adv] == ' ')
  2123. (*adv)++;
  2124. if (*adv < n && s[*adv] == '\n')
  2125. (*adv)++;
  2126. return end;
  2127. }
  2128. static int count_lines(const char *s, int maxw)
  2129. {
  2130. unsigned int n = (unsigned int)strlen(s), pos = 0, adv;
  2131. int lines = 0;
  2132. if (!n)
  2133. return 0;
  2134. while (pos < n) {
  2135. wrap_line(s + pos, n - pos, maxw, &adv);
  2136. if (!adv)
  2137. adv = 1;
  2138. pos += adv;
  2139. lines++;
  2140. }
  2141. return lines;
  2142. }
  2143. #define AVATAR 32
  2144. #define TEXT_X 52
  2145. #define PAD_TOP 8
  2146. #define PAD_GROUP 2
  2147. static int same_day(const struct msg *a, const struct msg *b)
  2148. {
  2149. return strncmp(a->created, b->created, 10) == 0;
  2150. }
  2151. static int same_group(const struct msg *a, const struct msg *b)
  2152. {
  2153. unsigned int ta, tb;
  2154. if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) ||
  2155. b->reply[0] || b->action)
  2156. return 0;
  2157. /* HH:MM at offsets 11..15: within five minutes */
  2158. ta = (unsigned int)atoi(a->created + 11) * 60 +
  2159. (unsigned int)atoi(a->created + 14);
  2160. tb = (unsigned int)atoi(b->created + 11) * 60 +
  2161. (unsigned int)atoi(b->created + 14);
  2162. return tb >= ta && tb - ta <= 5;
  2163. }
  2164. static void layout_msg(int i, int width)
  2165. {
  2166. struct msg *m = &msgs[i];
  2167. int lh = line_h(), h, tw = width - TEXT_X - 12;
  2168. int k;
  2169. if (tw < 40)
  2170. tw = 40;
  2171. m->day_header = i == 0 || !same_day(&msgs[i - 1], m);
  2172. m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m);
  2173. h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2;
  2174. if (m->day_header)
  2175. h += lh + 12;
  2176. if (m->reply[0])
  2177. h += lh + 2;
  2178. h += count_lines(m->body, tw) * lh;
  2179. for (k = 0; k < m->nimg; k++) {
  2180. int dw, dh, state;
  2181. unsigned int scale;
  2182. chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale,
  2183. &state);
  2184. h += dh + 6;
  2185. }
  2186. if (m->extra[0])
  2187. h += lh + 2;
  2188. h += 2;
  2189. if (!m->compact && h < PAD_TOP + AVATAR + 4)
  2190. h = PAD_TOP + AVATAR + 4;
  2191. m->height = h;
  2192. m->layout_w = width;
  2193. }
  2194. static int tl_width;
  2195. static unsigned int laid_gen;
  2196. static int laid_font = -1;
  2197. /* Heights depend on the width, the font and the neighbours (grouping and
  2198. * day headers), so any change re-lays out every message. */
  2199. static int content_height(void)
  2200. {
  2201. int i, h = has_older || history_full ? 36 : 8;
  2202. int all = laid_gen != msgs_gen || laid_font != line_h();
  2203. for (i = 0; i < nmsg; i++) {
  2204. if (all || msgs[i].layout_w != tl_width)
  2205. layout_msg(i, tl_width);
  2206. h += msgs[i].height;
  2207. }
  2208. laid_gen = msgs_gen;
  2209. laid_font = line_h();
  2210. return h + 8;
  2211. }
  2212. /* ---- drawing helpers ---- */
  2213. static unsigned short avatar_color(const char *id)
  2214. {
  2215. static const unsigned short pal[] = {
  2216. NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0),
  2217. NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a),
  2218. NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8),
  2219. NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40),
  2220. };
  2221. unsigned int h = 0;
  2222. while (*id)
  2223. h = h * 31 + (unsigned char)*id++;
  2224. return pal[h % (sizeof(pal) / sizeof(pal[0]))];
  2225. }
  2226. static void draw_avatar(int x, int y, int size, const char *name,
  2227. const char *id, const char *pic)
  2228. {
  2229. struct ngui_rect r = { x, y, size, size };
  2230. char ini[2];
  2231. int tw;
  2232. ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2,
  2233. avatar_color(id));
  2234. if (chat_avatar_draw(pic, x, y, size, avatar_color(id)))
  2235. return;
  2236. ini[0] = name[0] ? name[0] : '?';
  2237. if (ini[0] >= 'a' && ini[0] <= 'z')
  2238. ini[0] = (char)(ini[0] - 'a' + 'A');
  2239. ini[1] = '\0';
  2240. tw = text_w(ini, 1, 1);
  2241. ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1,
  2242. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  2243. }
  2244. static void draw_dot(int x, int y, int d, unsigned short color, int filled)
  2245. {
  2246. struct ngui_rect r = { x, y, d, d };
  2247. if (filled)
  2248. ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color);
  2249. else
  2250. ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color);
  2251. }
  2252. static void draw_badge(int right, int y, int count)
  2253. {
  2254. char num[12] = "";
  2255. int tw, w;
  2256. struct ngui_rect r;
  2257. if (count > 99)
  2258. s_copy(num, "99+", sizeof(num));
  2259. else
  2260. s_cat_uint(num, (unsigned int)count, sizeof(num));
  2261. tw = text_w(num, (unsigned int)strlen(num), 1);
  2262. w = tw + 12;
  2263. r.x = right - w;
  2264. r.y = y;
  2265. r.w = w;
  2266. r.h = line_h() + 2;
  2267. ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2,
  2268. ui.theme.accent);
  2269. ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num),
  2270. NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0);
  2271. }
  2272. static void draw_lock(int x, int y, unsigned short c)
  2273. {
  2274. struct ngui_rect body = { x, y + 5, 9, 7 };
  2275. struct ngui_rect shackle = { x + 2, y + 1, 5, 6 };
  2276. ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c);
  2277. ngui_fill_rect(&ui, body, c);
  2278. }
  2279. static void label(struct ngui_rect *body, const char *text)
  2280. {
  2281. struct ngui_rect r = ngui_cut_top(body, 20);
  2282. ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim);
  2283. }
  2284. /* ---- login screens ---- */
  2285. static struct ngui_rect card_rect(int h)
  2286. {
  2287. struct ngui_rect r;
  2288. int w = ui.w - 40 < 460 ? ui.w - 40 : 460;
  2289. if (w < 200)
  2290. w = ui.w;
  2291. r.w = w;
  2292. r.h = h;
  2293. r.x = (ui.w - w) / 2;
  2294. r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10;
  2295. return r;
  2296. }
  2297. static void field(struct ngui_rect *body, const char *text, unsigned int id,
  2298. struct ngui_input *in, unsigned int next_id, int submit_act)
  2299. {
  2300. int r;
  2301. label(body, text);
  2302. r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in);
  2303. ngui_cut_top(body, 8);
  2304. if (r & NGUI_INPUT_NEXT)
  2305. ngui_set_focus(&ui, next_id);
  2306. if ((r & NGUI_INPUT_SUBMIT) && submit_act)
  2307. action = submit_act;
  2308. }
  2309. static void draw_status_line(struct ngui_rect *body)
  2310. {
  2311. struct ngui_rect r = ngui_cut_top(body, 22);
  2312. if (busy[0])
  2313. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent);
  2314. else if (status[0])
  2315. ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status,
  2316. status_err ? ui.theme.error : ui.theme.text_dim);
  2317. }
  2318. static void notice(struct ngui_rect *body, const char *text)
  2319. {
  2320. struct ngui_rect r = ngui_cut_top(body, 18);
  2321. ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim);
  2322. }
  2323. static void draw_login(void)
  2324. {
  2325. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  2326. struct ngui_rect card, body, r, b;
  2327. int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 :
  2328. screen == SCR_TOTP ? 250 : 300;
  2329. ngui_fill_rect(&ui, all, ui.theme.bg);
  2330. card = card_rect(h);
  2331. ngui_fill_rect(&ui, card, ui.theme.panel);
  2332. ngui_frame(&ui, card, ui.theme.border);
  2333. body = card;
  2334. ngui_inset(&body, 18);
  2335. r = ngui_cut_top(&body, 30);
  2336. ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0);
  2337. if (screen == SCR_SERVER) {
  2338. field(&body, "Server", ID_SERVER, &server_in, ID_CFG,
  2339. ACT_START_LOGIN);
  2340. field(&body, "Config file (session cookie, RAM-only on /share)",
  2341. ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN);
  2342. r = ngui_cut_top(&body, 32);
  2343. b = ngui_cut_left(&r, 110);
  2344. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  2345. action = ACT_START_LOGIN;
  2346. ngui_cut_left(&r, 10);
  2347. b = ngui_cut_left(&r, 170);
  2348. if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie..."))
  2349. action = ACT_COOKIE_SCREEN;
  2350. ngui_cut_top(&body, 8);
  2351. draw_status_line(&body);
  2352. notice(&body, "TLS certificates are not verified: only sign in");
  2353. notice(&body, "on a trusted network. Passkeys and external SSO");
  2354. notice(&body, "are not supported (use the cookie option).");
  2355. } else if (screen == SCR_CRED || screen == SCR_TOTP) {
  2356. r = ngui_cut_top(&body, 22);
  2357. {
  2358. char t[160];
  2359. s_copy(t, "Sign in to ", sizeof(t));
  2360. s_cat(t, login.app_name[0] ? login.app_name : "Chat",
  2361. sizeof(t));
  2362. s_cat(t, " at ", sizeof(t));
  2363. s_cat(t, server_host, sizeof(t));
  2364. ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim);
  2365. }
  2366. if (screen == SCR_CRED) {
  2367. field(&body, "Username or email", ID_USER, &user_in,
  2368. ID_PASS, ACT_SUBMIT);
  2369. field(&body, "Password", ID_PASS, &pass_in, ID_USER,
  2370. ACT_SUBMIT);
  2371. } else {
  2372. field(&body, "Two-factor code (authenticator app)",
  2373. ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP);
  2374. }
  2375. r = ngui_cut_top(&body, 32);
  2376. b = ngui_cut_left(&r, 110);
  2377. if (ngui_button(&ui, ID_SIGNIN, b, "Sign in"))
  2378. action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT;
  2379. ngui_cut_left(&r, 10);
  2380. b = ngui_cut_left(&r, 90);
  2381. if (ngui_button(&ui, ID_BACK, b, "Back"))
  2382. action = ACT_BACK;
  2383. ngui_cut_top(&body, 8);
  2384. draw_status_line(&body);
  2385. notice(&body, "The password is sent over unverified TLS and");
  2386. notice(&body, "is never stored.");
  2387. } else {
  2388. field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE,
  2389. ACT_USE_COOKIE);
  2390. field(&body, "Session cookie (e.g. connect.sid=s%3A...)",
  2391. ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE);
  2392. field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER,
  2393. ACT_USE_COOKIE);
  2394. r = ngui_cut_top(&body, 32);
  2395. b = ngui_cut_left(&r, 130);
  2396. if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie"))
  2397. action = ACT_USE_COOKIE;
  2398. ngui_cut_left(&r, 10);
  2399. b = ngui_cut_left(&r, 90);
  2400. if (ngui_button(&ui, ID_BACK, b, "Back"))
  2401. action = ACT_BACK;
  2402. ngui_cut_top(&body, 8);
  2403. draw_status_line(&body);
  2404. notice(&body, "Copy the connect.sid cookie from a signed-in web");
  2405. notice(&body, "browser. It is a bearer credential: it is saved");
  2406. notice(&body, "in the config file until you sign out.");
  2407. }
  2408. }
  2409. /* ---- main screen ---- */
  2410. #define SIDE_ROW 38
  2411. #define SIDE_HEAD 26
  2412. static void draw_sidebar(struct ngui_rect r)
  2413. {
  2414. struct ngui_rect list, btns, b;
  2415. int y, i, section, row_w;
  2416. int lh = line_h();
  2417. ngui_fill_rect(&ui, r, ui.theme.panel);
  2418. btns = ngui_cut_bottom(&r, 40);
  2419. ngui_inset(&btns, 6);
  2420. b = ngui_cut_left(&btns, (btns.w - 6) / 2);
  2421. if (ngui_button(&ui, ID_BROWSE, b, "Browse"))
  2422. action = ACT_BROWSE;
  2423. ngui_cut_left(&btns, 6);
  2424. if (ngui_button(&ui, ID_NEWDM, btns, "New DM"))
  2425. action = ACT_NEWDM;
  2426. list = r;
  2427. side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8;
  2428. ngui_scroll_begin(&ui, list, &side_scroll);
  2429. ngui_scroll_wheel(&ui, list, &side_scroll);
  2430. row_w = list.w;
  2431. y = list.y - side_scroll.offset;
  2432. for (section = 0; section < 2; section++) {
  2433. ngui_text_px(&ui, list.x + 10, y + 6,
  2434. section ? "DIRECT MESSAGES" : "CHANNELS",
  2435. section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0);
  2436. y += SIDE_HEAD;
  2437. for (i = 0; i < nconv; i++) {
  2438. struct conv *c = &convs[i];
  2439. struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 };
  2440. int hot, nx, right;
  2441. if ((c->kind == 'd') != section)
  2442. continue;
  2443. hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x,
  2444. ui.mouse_y) &&
  2445. ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y);
  2446. if (i == cur)
  2447. ngui_fill_rect(&ui, row, ui.theme.selection);
  2448. else if (hot)
  2449. ngui_fill_rect(&ui, row, ui.theme.panel_alt);
  2450. if (ui.pressed && modal == MODAL_NONE &&
  2451. ngui_rect_contains(&row, ui.press_x, ui.press_y) &&
  2452. ngui_rect_contains(&list, ui.press_x, ui.press_y)) {
  2453. action = ACT_OPEN_CONV;
  2454. action_arg = i;
  2455. }
  2456. nx = list.x + 26;
  2457. if (c->kind == 'd') {
  2458. unsigned short pc = c->presence == 'o' ?
  2459. NGUI_RGB(0x40, 0xc0, 0x60) :
  2460. c->presence == 'a' ?
  2461. NGUI_RGB(0xe0, 0xb0, 0x30) :
  2462. ui.theme.text_dim;
  2463. draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc,
  2464. c->presence != 'f');
  2465. } else if (c->kind == 'p') {
  2466. draw_lock(list.x + 9, y + 4, ui.theme.text_dim);
  2467. } else {
  2468. ngui_text(&ui, list.x + 10, y + 4, "#",
  2469. ui.theme.text_dim);
  2470. }
  2471. right = list.x + row_w - 8;
  2472. if (c->unread > 0) {
  2473. draw_badge(right, y + 3, c->unread);
  2474. right -= 40;
  2475. }
  2476. {
  2477. struct ngui_rect nr = { nx, y, right - nx, lh + 6 };
  2478. ngui_push_clip(&ui, nr);
  2479. ngui_text_px(&ui, nx, y + 4, c->name,
  2480. (unsigned int)strlen(c->name),
  2481. ui.theme.text, ui.font_px,
  2482. c->unread > 0, 0, 0);
  2483. ngui_pop_clip(&ui);
  2484. }
  2485. if (c->preview[0]) {
  2486. struct ngui_rect pr = { nx, y + 4 + lh,
  2487. list.x + row_w - 8 - nx,
  2488. lh };
  2489. ngui_push_clip(&ui, pr);
  2490. ngui_text_px(&ui, nx, y + 4 + lh, c->preview,
  2491. (unsigned int)strlen(c->preview),
  2492. ui.theme.text_dim, 12, 0, 0, 0);
  2493. ngui_pop_clip(&ui);
  2494. }
  2495. y += SIDE_ROW;
  2496. }
  2497. }
  2498. if (!nconv)
  2499. ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6,
  2500. "(none yet)", ui.theme.text_dim);
  2501. ngui_scroll_end(&ui, list, &side_scroll);
  2502. }
  2503. static void draw_message(struct msg *m, int x, int y, int width)
  2504. {
  2505. int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12;
  2506. unsigned int n, pos = 0, adv;
  2507. if (tw < 40)
  2508. tw = 40;
  2509. if (m->day_header) {
  2510. char d[16];
  2511. int dw;
  2512. struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 };
  2513. s_copy(d, m->created, 11);
  2514. dw = text_w(d, (unsigned int)strlen(d), 0);
  2515. ngui_fill_rect(&ui, line, ui.theme.border);
  2516. ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8,
  2517. y + 4, dw + 16, lh + 4 }, ui.theme.bg);
  2518. ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim);
  2519. y += lh + 12;
  2520. }
  2521. if (!m->compact) {
  2522. char tm[8];
  2523. int aw;
  2524. y += PAD_TOP;
  2525. draw_avatar(x + 10, y, AVATAR, m->author, m->user_id,
  2526. m->author_pic);
  2527. ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author),
  2528. ui.theme.text, ui.font_px, 1, 0, 0);
  2529. aw = text_w(m->author, (unsigned int)strlen(m->author), 1);
  2530. s_copy(tm, m->created + 11, 6);
  2531. ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm),
  2532. ui.theme.text_dim, 12, 0, 0, 0);
  2533. y += lh + 2;
  2534. } else {
  2535. y += PAD_GROUP;
  2536. }
  2537. if (m->reply[0]) {
  2538. struct ngui_rect rr = { tx, y, tw, lh };
  2539. ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 },
  2540. ui.theme.accent);
  2541. ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply,
  2542. ui.theme.text_dim);
  2543. y += lh + 2;
  2544. }
  2545. n = (unsigned int)strlen(m->body);
  2546. while (pos < n) {
  2547. unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv);
  2548. if (!adv)
  2549. adv = 1;
  2550. ngui_text_px(&ui, tx, y, m->body + pos, len,
  2551. m->action ? ui.theme.accent : ui.theme.text,
  2552. ui.font_px, 0, m->action, 0);
  2553. pos += adv;
  2554. y += lh;
  2555. }
  2556. {
  2557. int k;
  2558. for (k = 0; k < m->nimg; k++) {
  2559. int dw, dh, state;
  2560. unsigned int scale;
  2561. chat_image_measure(m->img_url[k], tw, &dw, &dh,
  2562. &scale, &state);
  2563. chat_image_draw(m->img_url[k], tx, y, tw);
  2564. y += dh + 6;
  2565. }
  2566. }
  2567. if (m->extra[0]) {
  2568. struct ngui_rect er = { tx, y + 2, tw, lh };
  2569. ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra,
  2570. ui.theme.text_dim);
  2571. }
  2572. }
  2573. static void draw_timeline(struct ngui_rect r)
  2574. {
  2575. int i, y, total, scrolls, width;
  2576. int was_bottom;
  2577. ngui_fill_rect(&ui, r, ui.theme.bg);
  2578. if (cur < 0) {
  2579. ngui_text(&ui, r.x + 20, r.y + 20,
  2580. nconv ? "Select a conversation" :
  2581. "No conversations yet: browse the public channels",
  2582. ui.theme.text_dim);
  2583. return;
  2584. }
  2585. tl_width = r.w;
  2586. total = content_height();
  2587. tl_scroll.content_h = total;
  2588. ngui_scroll_begin(&ui, r, &tl_scroll);
  2589. if (ngui_scroll_wheel(&ui, r, &tl_scroll))
  2590. last_input_ms = u_ticks_ms();
  2591. scrolls = total > r.h;
  2592. width = r.w;
  2593. /* Scrolling to the very top pages in older history by itself (the
  2594. * button stays for the pointer). Rate-limited so a failing request
  2595. * cannot spin. */
  2596. if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 &&
  2597. !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500)
  2598. action = ACT_OLDER;
  2599. was_bottom = tl_scroll.offset >= total - r.h - 4;
  2600. at_bottom = was_bottom || !scrolls;
  2601. if (at_bottom)
  2602. new_below = 0;
  2603. y = r.y - tl_scroll.offset;
  2604. if (has_older || history_full) {
  2605. struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 };
  2606. if (history_full) {
  2607. ngui_text(&ui, b.x + 4, b.y + 6,
  2608. "History limit reached", ui.theme.text_dim);
  2609. } else if (b.y + b.h > r.y &&
  2610. (!ui.pressed ||
  2611. ngui_rect_contains(&r, ui.press_x, ui.press_y))) {
  2612. if (ngui_button(&ui, ID_OLDER, b, "Load older messages"))
  2613. action = ACT_OLDER;
  2614. }
  2615. y += 36;
  2616. } else {
  2617. y += 8;
  2618. }
  2619. for (i = 0; i < nmsg; i++) {
  2620. struct msg *m = &msgs[i];
  2621. if (y + m->height > r.y && y < r.y + r.h)
  2622. draw_message(m, r.x, y, width);
  2623. y += m->height;
  2624. }
  2625. if (!nmsg)
  2626. ngui_text(&ui, r.x + 20, r.y + 50,
  2627. "No messages yet - say hello!", ui.theme.text_dim);
  2628. ngui_scroll_end(&ui, r, &tl_scroll);
  2629. if (new_below > 0 && !at_bottom) {
  2630. char t[40] = "";
  2631. struct ngui_rect b;
  2632. s_cat_uint(t, (unsigned int)new_below, sizeof(t));
  2633. s_cat(t, new_below == 1 ? " new message" : " new messages",
  2634. sizeof(t));
  2635. b.w = text_w(t, (unsigned int)strlen(t), 0) + 30;
  2636. b.h = 26;
  2637. b.x = r.x + (width - b.w) / 2;
  2638. b.y = r.y + r.h - b.h - 8;
  2639. if (ngui_button(&ui, ID_NEWMSG, b, t))
  2640. scroll_to_end();
  2641. }
  2642. }
  2643. static int total_unread(void)
  2644. {
  2645. int i, n = 0;
  2646. for (i = 0; i < nconv; i++)
  2647. n += convs[i].unread > 0 ? convs[i].unread : 0;
  2648. return n;
  2649. }
  2650. static void draw_modal(void)
  2651. {
  2652. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  2653. struct ngui_rect card, body, r, list;
  2654. int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis;
  2655. int lh = line_h();
  2656. (void)all;
  2657. if (w < 320)
  2658. w = ui.w - 20;
  2659. if (h < 240)
  2660. h = ui.h - 20;
  2661. card.w = w;
  2662. card.h = h;
  2663. card.x = (ui.w - w) / 2;
  2664. card.y = (ui.h - h) / 2;
  2665. ngui_fill_rect(&ui, card, ui.theme.panel);
  2666. ngui_frame(&ui, card, ui.theme.accent);
  2667. body = card;
  2668. ngui_inset(&body, 14);
  2669. r = ngui_cut_top(&body, 28);
  2670. ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ?
  2671. "Browse public channels" : "New direct message",
  2672. modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0);
  2673. if (ngui_button(&ui, ID_MODAL_CLOSE,
  2674. (struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 },
  2675. "Close"))
  2676. modal = MODAL_NONE;
  2677. ngui_cut_top(&body, 6);
  2678. filter_in.placeholder = "Filter... (Up/Down, Enter)";
  2679. for (i = 0; i < npick; i++)
  2680. if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) ||
  2681. strstr(picks[i].sub, filter_in.text))
  2682. shown++;
  2683. {
  2684. int k = ngui_key_peek(&ui), fr;
  2685. if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  2686. ngui_key(&ui);
  2687. modal_sel += k == NGUI_KEY_UP ? -1 : 1;
  2688. }
  2689. fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30),
  2690. &filter_in);
  2691. if (fr & NGUI_INPUT_CHANGED) {
  2692. modal_scroll.offset = 0;
  2693. modal_sel = 0;
  2694. }
  2695. if (modal_sel >= shown)
  2696. modal_sel = shown - 1;
  2697. if (modal_sel < 0)
  2698. modal_sel = 0;
  2699. if ((fr & NGUI_INPUT_SUBMIT) && shown) {
  2700. int vis = 0;
  2701. for (i = 0; i < npick; i++) {
  2702. if (filter_in.text[0] &&
  2703. !strstr(picks[i].name, filter_in.text) &&
  2704. !strstr(picks[i].sub, filter_in.text))
  2705. continue;
  2706. if (vis++ == modal_sel) {
  2707. action = modal == MODAL_BROWSE ?
  2708. ACT_JOIN : ACT_OPEN_DM;
  2709. action_arg = i;
  2710. break;
  2711. }
  2712. }
  2713. ngui_set_focus(&ui, ID_FILTER);
  2714. }
  2715. if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT))
  2716. modal = MODAL_NONE;
  2717. }
  2718. ngui_cut_top(&body, 8);
  2719. list = body;
  2720. ngui_fill_rect(&ui, list, ui.theme.bg);
  2721. modal_scroll.content_h = shown * 44;
  2722. ngui_scroll_begin(&ui, list, &modal_scroll);
  2723. ngui_scroll_wheel(&ui, list, &modal_scroll);
  2724. y = list.y - modal_scroll.offset;
  2725. vis = 0;
  2726. for (i = 0; i < npick; i++) {
  2727. struct pick *p = &picks[i];
  2728. struct ngui_rect row, b;
  2729. if (filter_in.text[0] && !strstr(p->name, filter_in.text) &&
  2730. !strstr(p->sub, filter_in.text))
  2731. continue;
  2732. if (vis++ == modal_sel) {
  2733. if (y < list.y)
  2734. modal_scroll.offset -= list.y - y;
  2735. else if (y + 44 > list.y + list.h)
  2736. modal_scroll.offset += y + 44 - list.y - list.h;
  2737. y = list.y + (vis - 1) * 44 - modal_scroll.offset;
  2738. ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y,
  2739. list.w - 16, 43 },
  2740. ui.theme.selection);
  2741. }
  2742. row.x = list.x;
  2743. row.y = y;
  2744. row.w = list.w - 16;
  2745. row.h = 42;
  2746. if (y + 44 > list.y && y < list.y + list.h) {
  2747. ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43,
  2748. row.w, 1 }, ui.theme.border);
  2749. if (modal == MODAL_NEWDM)
  2750. draw_avatar(row.x + 8, y + 6, 30, p->name, p->id,
  2751. p->pic);
  2752. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y,
  2753. row.w - 160, lh + 4 },
  2754. row.x + 48, y + 4,
  2755. p->name,
  2756. ui.theme.text);
  2757. ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48,
  2758. y + 4 + lh, row.w - 160, lh },
  2759. row.x + 48, y + 4 + lh, p->sub,
  2760. ui.theme.text_dim);
  2761. if (modal == MODAL_BROWSE)
  2762. ngui_text(&ui, row.x + 14, y + 12, "#",
  2763. ui.theme.text_dim);
  2764. b.x = row.x + row.w - 100;
  2765. b.y = y + 8;
  2766. b.w = 92;
  2767. b.h = 26;
  2768. if ((!ui.pressed ||
  2769. ngui_rect_contains(&list, ui.press_x, ui.press_y)) &&
  2770. ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b,
  2771. modal == MODAL_BROWSE ? "Join" : "Message")) {
  2772. action = modal == MODAL_BROWSE ? ACT_JOIN :
  2773. ACT_OPEN_DM;
  2774. action_arg = i;
  2775. }
  2776. }
  2777. y += 44;
  2778. }
  2779. if (!shown)
  2780. ngui_text(&ui, list.x + 12, list.y + 12,
  2781. npick ? "Nothing matches the filter" :
  2782. modal == MODAL_BROWSE ?
  2783. "You are in every public channel" : "Nobody else here",
  2784. ui.theme.text_dim);
  2785. ngui_scroll_end(&ui, list, &modal_scroll);
  2786. }
  2787. /* Keyboard shortcuts, handled before the composer swallows the keys:
  2788. * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R
  2789. * refresh. With the composer unfocused (Esc): Up/Down switch conversations,
  2790. * Home/End jump in the timeline, and typing refocuses the composer. */
  2791. static void main_keys(void)
  2792. {
  2793. for (;;) {
  2794. int k = ngui_key_peek(&ui);
  2795. if (!k)
  2796. return;
  2797. if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) {
  2798. ngui_scroll_keys(&ui, &tl_scroll);
  2799. continue;
  2800. }
  2801. if (k == 0x02 || k == 0x0E || k == 0x12) {
  2802. ngui_key(&ui);
  2803. action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM :
  2804. ACT_REFRESH;
  2805. return;
  2806. }
  2807. if (ui.focus)
  2808. return;
  2809. if (k == NGUI_KEY_HOME) {
  2810. ngui_key(&ui);
  2811. tl_scroll.offset = 0;
  2812. } else if (k == NGUI_KEY_END) {
  2813. ngui_key(&ui);
  2814. scroll_to_end();
  2815. } else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) {
  2816. int order[MAX_CONV], n = 0, i, pos = -1, sec;
  2817. ngui_key(&ui);
  2818. /* Sidebar order: channels first, then DMs. */
  2819. for (sec = 0; sec < 2; sec++)
  2820. for (i = 0; i < nconv; i++)
  2821. if ((convs[i].kind == 'd') == sec) {
  2822. if (i == cur)
  2823. pos = n;
  2824. order[n++] = i;
  2825. }
  2826. if (!n)
  2827. continue;
  2828. pos = pos < 0 ? 0 : k == NGUI_KEY_UP ?
  2829. (pos > 0 ? pos - 1 : 0) :
  2830. (pos + 1 < n ? pos + 1 : n - 1);
  2831. if (order[pos] != cur) {
  2832. action = ACT_OPEN_CONV;
  2833. action_arg = order[pos];
  2834. return;
  2835. }
  2836. } else if (k >= 0x20 && k <= 0x7E && cur >= 0) {
  2837. ngui_set_focus(&ui, ID_COMPOSE);
  2838. return;
  2839. } else {
  2840. return;
  2841. }
  2842. }
  2843. }
  2844. static void draw_main(void)
  2845. {
  2846. struct ngui_rect all = { 0, 0, ui.w, ui.h };
  2847. struct ngui_rect top, side, bottom, comp, stat, b, tl;
  2848. int side_w = ui.w / 4;
  2849. char t[200];
  2850. unsigned int saved_pressed = ui.pressed;
  2851. /* Nothing under an open modal reacts to the pointer. */
  2852. if (modal != MODAL_NONE)
  2853. ui.pressed = 0;
  2854. if (side_w < 150)
  2855. side_w = 150;
  2856. if (side_w > 260)
  2857. side_w = 260;
  2858. ngui_fill_rect(&ui, all, ui.theme.bg);
  2859. /* top bar */
  2860. top = ngui_cut_top(&all, 38);
  2861. ngui_fill_rect(&ui, top, ui.theme.panel_alt);
  2862. ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w,
  2863. 1 }, ui.theme.border);
  2864. {
  2865. struct ngui_rect tb = top;
  2866. ngui_inset(&tb, 6);
  2867. b = ngui_cut_right(&tb, 86);
  2868. if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out"))
  2869. action = ACT_SIGNOUT;
  2870. ngui_cut_right(&tb, 6);
  2871. b = ngui_cut_right(&tb, 80);
  2872. if (ngui_button(&ui, ID_REFRESH, b, "Refresh"))
  2873. action = ACT_REFRESH;
  2874. t[0] = '\0';
  2875. if (cur >= 0) {
  2876. s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t));
  2877. s_cat(t, convs[cur].name, sizeof(t));
  2878. } else {
  2879. s_cat(t, "Chat", sizeof(t));
  2880. }
  2881. ngui_cut_right(&tb, 10);
  2882. ngui_push_clip(&ui, tb);
  2883. ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t,
  2884. (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0);
  2885. ngui_pop_clip(&ui);
  2886. }
  2887. if (modal == MODAL_NONE) {
  2888. /* A closed modal leaves its filter focused: hand the keyboard
  2889. * back to the composer. */
  2890. if (ui.focus == ID_FILTER)
  2891. ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0);
  2892. main_keys();
  2893. }
  2894. /* bottom: composer + status bar */
  2895. bottom = ngui_cut_bottom(&all, 70);
  2896. ngui_fill_rect(&ui, bottom, ui.theme.panel);
  2897. ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 },
  2898. ui.theme.border);
  2899. stat = ngui_cut_bottom(&bottom, 24);
  2900. comp = bottom;
  2901. ngui_inset(&comp, 7);
  2902. b = ngui_cut_right(&comp, 80);
  2903. compose_in.disabled = cur < 0;
  2904. compose_in.placeholder = cur < 0 ? "" : "Type a message...";
  2905. if (ngui_text_input(&ui, ID_COMPOSE,
  2906. (struct ngui_rect){ comp.x, comp.y, comp.w - 8,
  2907. comp.h }, &compose_in) &
  2908. NGUI_INPUT_SUBMIT)
  2909. action = ACT_SEND;
  2910. if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0)
  2911. action = ACT_SEND;
  2912. ngui_fill_rect(&ui, stat, ui.theme.panel_alt);
  2913. {
  2914. struct ngui_rect sr = stat;
  2915. int un = total_unread();
  2916. ngui_inset(&sr, 3);
  2917. if (offline) {
  2918. b = ngui_cut_right(&sr, 70);
  2919. if (ngui_button(&ui, ID_RETRY, b, "Retry"))
  2920. action = ACT_RETRY;
  2921. }
  2922. t[0] = '\0';
  2923. if (busy[0]) {
  2924. s_cat(t, busy, sizeof(t));
  2925. } else {
  2926. s_cat(t, status[0] ? status : "Connected", sizeof(t));
  2927. if (offline && retry_at) {
  2928. int left = (int)(retry_at - u_ticks_ms());
  2929. if (left > 0) {
  2930. s_cat(t, " (retry in ", sizeof(t));
  2931. s_cat_uint(t, (unsigned int)(left + 999) / 1000,
  2932. sizeof(t));
  2933. s_cat(t, " s)", sizeof(t));
  2934. }
  2935. }
  2936. }
  2937. s_cat(t, " \xb7 ", sizeof(t));
  2938. s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t));
  2939. if (me_name[0]) {
  2940. s_cat(t, " \xb7 ", sizeof(t));
  2941. s_cat(t, me_name, sizeof(t));
  2942. }
  2943. if (un) {
  2944. s_cat(t, " \xb7 ", sizeof(t));
  2945. s_cat_uint(t, (unsigned int)un, sizeof(t));
  2946. s_cat(t, " unread", sizeof(t));
  2947. }
  2948. ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t,
  2949. busy[0] ? ui.theme.accent :
  2950. (offline || status_err) ? ui.theme.error :
  2951. ui.theme.text_dim);
  2952. }
  2953. side = ngui_cut_left(&all, side_w);
  2954. ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1,
  2955. side.h }, ui.theme.border);
  2956. side.w -= 1;
  2957. tl = all;
  2958. if (modal == MODAL_NONE) {
  2959. draw_sidebar(side);
  2960. draw_timeline(tl);
  2961. } else {
  2962. draw_sidebar(side);
  2963. draw_timeline(tl);
  2964. action = ACT_NONE;
  2965. ui.pressed = saved_pressed;
  2966. draw_modal();
  2967. }
  2968. }
  2969. /* ---- frame / main loop ---- */
  2970. static void draw(void)
  2971. {
  2972. if (screen == SCR_MAIN)
  2973. draw_main();
  2974. else
  2975. draw_login();
  2976. }
  2977. /* Present a frame now (status text before a blocking network call). */
  2978. static void paint_now(void)
  2979. {
  2980. int saved_action = action, saved_arg = action_arg;
  2981. ngui_invalidate(&ui);
  2982. if (ngui_begin(&ui)) {
  2983. draw();
  2984. ngui_end(&ui);
  2985. }
  2986. action = saved_action;
  2987. action_arg = saved_arg;
  2988. }
  2989. static void run_action(void)
  2990. {
  2991. int a = action, arg = action_arg;
  2992. action = ACT_NONE;
  2993. switch (a) {
  2994. case ACT_START_LOGIN:
  2995. start_login();
  2996. break;
  2997. case ACT_SUBMIT:
  2998. submit_login(0);
  2999. break;
  3000. case ACT_SUBMIT_TOTP:
  3001. submit_login(1);
  3002. break;
  3003. case ACT_USE_COOKIE:
  3004. use_cookie();
  3005. break;
  3006. case ACT_COOKIE_SCREEN:
  3007. screen = SCR_COOKIE;
  3008. set_status("", 0, 0);
  3009. ngui_set_focus(&ui, ID_COOKIE);
  3010. break;
  3011. case ACT_BACK:
  3012. wipe_secrets();
  3013. screen = SCR_SERVER;
  3014. set_status("", 0, 0);
  3015. ngui_set_focus(&ui, ID_SERVER);
  3016. break;
  3017. case ACT_SEND:
  3018. send_message();
  3019. break;
  3020. case ACT_REFRESH:
  3021. case ACT_RETRY:
  3022. backoff_ms = 0;
  3023. retry_at = 0;
  3024. chat_media_retry();
  3025. s_copy(busy, "Refreshing...", sizeof(busy));
  3026. paint_now();
  3027. busy[0] = '\0';
  3028. if (offline && !me_id[0]) {
  3029. check_session(1);
  3030. break;
  3031. }
  3032. if (load_directory() == 0) {
  3033. if (cur >= 0)
  3034. open_conv(cur);
  3035. else if (nconv)
  3036. open_conv(0);
  3037. }
  3038. next_dir_poll = u_ticks_ms() + POLL_DIR_MS;
  3039. break;
  3040. case ACT_SIGNOUT:
  3041. sign_out();
  3042. break;
  3043. case ACT_OPEN_CONV:
  3044. if (arg != cur)
  3045. open_conv(arg);
  3046. break;
  3047. case ACT_OLDER:
  3048. load_older();
  3049. break;
  3050. case ACT_BROWSE:
  3051. load_picks(0);
  3052. break;
  3053. case ACT_NEWDM:
  3054. load_picks(1);
  3055. break;
  3056. case ACT_JOIN:
  3057. case ACT_OPEN_DM:
  3058. pick_action(arg);
  3059. break;
  3060. }
  3061. ngui_invalidate(&ui);
  3062. }
  3063. static void poll_tick(void)
  3064. {
  3065. unsigned int now = u_ticks_ms();
  3066. int focused = ui.focused;
  3067. if (screen != SCR_MAIN || modal != MODAL_NONE)
  3068. return;
  3069. if (offline) {
  3070. if (retry_at && (int)(now - retry_at) >= 0) {
  3071. retry_at = 0;
  3072. action = ACT_RETRY;
  3073. run_action();
  3074. }
  3075. return;
  3076. }
  3077. /* Do not interrupt typing or scrolling. */
  3078. if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS)
  3079. return;
  3080. if ((int)(now - next_dir_poll) >= 0) {
  3081. load_directory();
  3082. next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS);
  3083. next_conv_poll = now; /* follow with the conversation */
  3084. }
  3085. if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) {
  3086. poll_conv();
  3087. next_conv_poll = u_ticks_ms() +
  3088. (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS);
  3089. }
  3090. /* An open TCP socket pauses the board's net-dev watcher: only keep
  3091. * the connection while the user is actively chatting. */
  3092. if (http.connected &&
  3093. (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) >
  3094. KEEPALIVE_IDLE_MS) &&
  3095. (unsigned int)(u_ticks_ms() - last_net_ms) > 200)
  3096. net_drop();
  3097. }
  3098. void _start(const char *arg)
  3099. {
  3100. struct win_info wi;
  3101. unsigned int w = 980, h = 660;
  3102. resp = (char *)malloc(RESP_CAP);
  3103. jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) *
  3104. JSON_NODES);
  3105. jsbuf = (char *)malloc(JSON_SCAP);
  3106. if (!resp || !jnodes || !jsbuf) {
  3107. u_puts("chat: out of memory\n");
  3108. u_exit(1);
  3109. }
  3110. ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP);
  3111. uhttp_init(&http);
  3112. http.user_agent = "NebOS-Chat/1.0 (uhttp)";
  3113. uhttp_jar_init(&jar);
  3114. if (u_win_create(w, h, "Chat", &wi) != 0 &&
  3115. u_win_create(w = 780, h = 540, "Chat", &wi) != 0 &&
  3116. u_win_create(w = 600, h = 420, "Chat", &wi) != 0) {
  3117. u_puts("chat: no graphics window\n");
  3118. u_exit(1);
  3119. }
  3120. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  3121. ngui_font_attach(&ui);
  3122. server_in.placeholder = "chat.example.com";
  3123. user_in.placeholder = "username";
  3124. pass_in.secret = 1;
  3125. totp_in.placeholder = "123456";
  3126. cookie_in.placeholder = "connect.sid=...";
  3127. if (arg && arg[0]) {
  3128. s_copy(cfg_path, arg, sizeof(cfg_path));
  3129. } else {
  3130. s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path));
  3131. cfg_is_default = 1;
  3132. }
  3133. ngui_set_focus(&ui, ID_SERVER);
  3134. last_input_ms = 0;
  3135. /* First frame, then the (possibly slow) session check. */
  3136. paint_now();
  3137. load_config();
  3138. for (;;) {
  3139. int redraw;
  3140. redraw = ngui_begin(&ui);
  3141. if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) {
  3142. last_input_ms = u_ticks_ms();
  3143. if (screen == SCR_MAIN && !offline)
  3144. maybe_save_cookie();
  3145. }
  3146. if (redraw) {
  3147. draw();
  3148. ngui_end(&ui);
  3149. } else {
  3150. ngui_end_ex(&ui, 0);
  3151. }
  3152. if (action != ACT_NONE)
  3153. run_action();
  3154. else
  3155. poll_tick();
  3156. chat_media_tick();
  3157. /* The offline retry countdown needs a once-a-second repaint. */
  3158. if (offline && screen == SCR_MAIN) {
  3159. static unsigned int last_tick;
  3160. if (u_ticks_ms() - last_tick >= 1000) {
  3161. last_tick = u_ticks_ms();
  3162. ngui_invalidate(&ui);
  3163. }
  3164. }
  3165. u_sleep_ms(10);
  3166. }
  3167. }