/* chat: native client for Cloudron Chat on the ngui canvas toolkit. * * Login is the native Cloudron OIDC driver in chat_login.c (username, * password, optional TOTP) or a pasted session cookie. The session cookie is * kept in a uhttp cookie jar and saved with the server address in a small * config file: /data/CHAT.CFG on an installed disk, /share/chat.cfg when * there is no persistent /data mount, or the path given as argument. * The password is never stored. * * Everything else is the Chat REST API over uhttp: the channel and DM * directory, message pages (newest first, older paging with ?before=, live * updates with ?after=), sending, read markers, joining public channels and * opening DMs. There is no WebSocket: the open conversation is polled every * ~2 s and the directory every ~12 s, and polling waits while the user types. * * Network calls block the UI; the frame showing the "Loading" status is * presented first. TLS certificates are NOT verified (tls.c phase A), which * the login screen says. */ #include "ucmd_lib.h" #include "ngui.h" #include "uhttp.h" #include "ujson.h" #include "chat_login.h" #include "img.h" #include #include #include #define DEFAULT_CFG_DATA "/data/CHAT.CFG" #define DEFAULT_CFG_SHARE "/share/chat.cfg" #define RESP_CAP (512u * 1024u) #define JSON_NODES 16384u #define JSON_SCAP (RESP_CAP + 2u * JSON_NODES) #define MAX_CONV 128 #define MAX_MSG 240 #define MAX_PICK 256 #define BODY_MAX 4096 #define PAGE_SIZE 50 #define LIVE_PAGE 50 #define MSG_IMG_MAX 3 #define CHAT_IMG_W 480 #define CHAT_IMG_H 320 #define CHAT_IMG_MAX 16 #define CHAT_AVATAR_MAX 64 #define CHAT_AVATAR 32 #define CHAT_IMG_BUDGET (6u * 1024u * 1024u) #define CHAT_IMG_ARENA_MAX (12u * 1024u * 1024u) #define CHAT_IMG_FETCH_MAX (4u * 1024u * 1024u) #define CHAT_IMG_URL_MAX (UHTTP_HOST_MAX + UHTTP_PATH_MAX + 16) #define CHAT_PIC_QUEUED 0 #define CHAT_PIC_READY 1 #define CHAT_PIC_FETCHING 2 #define CHAT_PIC_FAILED (-1) #define POLL_CONV_MS 2000 #define POLL_CONV_IDLE_MS 5000 #define POLL_DIR_MS 12000 #define POLL_DIR_IDLE_MS 20000 #define TYPING_HOLD_MS 1000 #define KEEPALIVE_IDLE_MS 30000 /* widget IDs */ enum { ID_SERVER = 1, ID_CFG, ID_SIGNIN, ID_COOKIE_MODE, ID_USER, ID_PASS, ID_TOTP, ID_BACK, ID_COOKIE, ID_USE_COOKIE, ID_COMPOSE, ID_SEND, ID_REFRESH, ID_SIGNOUT, ID_BROWSE, ID_NEWDM, ID_OLDER, ID_NEWMSG, ID_RETRY, ID_MODAL_CLOSE, ID_FILTER, ID_MODAL_ROW = 1000 }; enum screen { SCR_SERVER, SCR_CRED, SCR_TOTP, SCR_COOKIE, SCR_MAIN }; enum modal { MODAL_NONE, MODAL_BROWSE, MODAL_NEWDM }; /* pending actions, collected while drawing and run after the frame */ enum { ACT_NONE, ACT_START_LOGIN, ACT_SUBMIT, ACT_SUBMIT_TOTP, ACT_USE_COOKIE, ACT_SEND, ACT_REFRESH, ACT_SIGNOUT, ACT_OPEN_CONV, ACT_OLDER, ACT_BROWSE, ACT_NEWDM, ACT_JOIN, ACT_OPEN_DM, ACT_RETRY, ACT_COOKIE_SCREEN, ACT_BACK }; struct conv { char id[48]; char name[64]; char preview[96]; char kind; /* 'c' public, 'p' private, 'd' DM */ char presence; /* DM: 'o' online, 'a' away, 'f' offline */ int unread; }; struct msg { char id[48]; char user_id[48]; char author[48]; char *author_pic; /* profile picture URL, or NULL */ char created[32]; /* ISO 8601 UTC, sorts as text */ char reply[96]; /* "Name: snippet" */ char extra[112]; /* attachments / thread / reactions line */ char *body; /* Latin-1, malloc'd */ char *img_url[MSG_IMG_MAX]; /* image attachments, malloc'd URLs */ unsigned char nimg; unsigned char action; /* type "me" */ int height; int layout_w; int compact; int day_header; }; struct pick { char id[48]; char name[64]; char sub[64]; char pic[256]; }; static struct ngui ui; static struct uhttp http; static struct uhttp_jar jar; static struct chat_login login; static struct ujson json; static struct ujson_node *jnodes; static char *jsbuf; static char *resp; static unsigned int resp_len; static enum screen screen = SCR_SERVER; static enum modal modal = MODAL_NONE; static int action, action_arg; static char cfg_path[CHAT_PATH_MAX]; static int cfg_is_default; static char server[CHAT_SERVER_MAX]; static char server_host[UHTTP_HOST_MAX]; static int server_secure; static char saved_cookie[CHAT_COOKIE_MAX]; static unsigned int saved_jar_changes; static char me_id[48]; static char me_name[64]; static struct ngui_input server_in, cfg_in, user_in, pass_in, totp_in; static struct ngui_input cookie_in, compose_in, filter_in; static struct conv convs[MAX_CONV]; static int nconv; static int cur = -1; /* index into convs */ static char cur_id[48]; static struct msg msgs[MAX_MSG]; static int nmsg; static int has_older; static unsigned int msgs_gen; /* bumped whenever msgs[] changes */ static int history_full; static struct ngui_scroll tl_scroll, side_scroll, modal_scroll; static int at_bottom = 1; static int new_below; static struct pick picks[MAX_PICK]; static int npick; static int modal_sel; /* keyboard selection among visible rows */ static unsigned int last_older_ms; static char status[160]; static int status_err; static char busy[96]; static int offline; static unsigned int backoff_ms; static unsigned int next_conv_poll, next_dir_poll, retry_at; static unsigned int last_input_ms; static unsigned int last_net_ms; static unsigned int client_seq; /* ---- small string helpers ---- */ static void s_copy(char *d, const char *s, unsigned int cap) { unsigned int i = 0; if (!cap) return; while (s && s[i] && i + 1 < cap) { d[i] = s[i]; i++; } d[i] = '\0'; } static void s_cat(char *d, const char *s, unsigned int cap) { unsigned int n = (unsigned int)strlen(d); if (n < cap) s_copy(d + n, s, cap - n); } static void s_cat_uint(char *d, unsigned int v, unsigned int cap) { char tmp[12]; int i = 11; tmp[i] = '\0'; do { tmp[--i] = (char)('0' + v % 10); v /= 10; } while (v && i > 0); s_cat(d, tmp + i, cap); } static void set_status(const char *a, const char *b, int err) { status[0] = '\0'; s_cat(status, a, sizeof(status)); if (b) s_cat(status, b, sizeof(status)); status_err = err; ngui_invalidate(&ui); } /* ---- UTF-8 -> Latin-1 display text ---- */ static unsigned int put_ascii(char *d, unsigned int n, unsigned int cap, const char *s) { while (*s && n + 1 < cap) d[n++] = *s++; return n; } /* Map a code point outside Latin-1 to a short ASCII stand-in; NULL to skip * it entirely (joiners, variation selectors, skin tones). */ static const char *cp_fallback(unsigned int cp) { switch (cp) { case 0x2018: case 0x2019: case 0x201A: case 0x2032: return "'"; case 0x201C: case 0x201D: case 0x201E: case 0x2033: return "\""; case 0x2010: case 0x2011: case 0x2012: case 0x2013: return "-"; case 0x2014: case 0x2015: return "--"; case 0x2026: return "..."; case 0x2022: case 0x2023: case 0x25CF: return "\xb7"; case 0x20AC: return "EUR"; case 0x2122: return "TM"; case 0x2192: return "->"; case 0x2190: return "<-"; case 0x2264: return "<="; case 0x2265: return ">="; case 0x2260: return "!="; case 0x2764: case 0x2665: return "<3"; case 0x2705: case 0x2714: case 0x2713: return "[v]"; case 0x274C: case 0x2716: return "[x]"; case 0x26A0: return "/!\\"; case 0x1F44D: return "(y)"; case 0x1F44E: return "(n)"; case 0x1F44B: return "o/"; case 0x1F64F: return "_/\\_"; case 0x1F389: case 0x1F38A: return "*\\o/*"; case 0x1F600: case 0x1F603: case 0x1F604: case 0x1F60A: case 0x1F642: case 0x263A: return ":)"; case 0x1F601: case 0x1F606: case 0x1F602: case 0x1F923: return ":D"; case 0x1F609: return ";)"; case 0x1F61B: case 0x1F61C: case 0x1F61D: return ":P"; case 0x1F622: case 0x1F62D: case 0x1F641: case 0x2639: return ":("; case 0x1F62E: case 0x1F632: return ":O"; case 0x1F914: return ":-/"; case 0x1F525: return "(fire)"; case 0x1F680: return "(rocket)"; case 0x1F440: return "(eyes)"; case 0x200B: case 0x200C: case 0x200D: case 0xFEFF: return 0; } if (cp >= 0xFE00 && cp <= 0xFE0F) return 0; /* variation selectors */ if (cp >= 0x1F3FB && cp <= 0x1F3FF) return 0; /* skin tones */ if (cp >= 0x2000 && cp <= 0x200A) return " "; return "?"; } /* Convert UTF-8 to Latin-1 display text. Tabs become spaces, other control * characters (except newline) are dropped. */ static unsigned int to_latin1(char *d, unsigned int cap, const char *s) { const unsigned char *p = (const unsigned char *)s; unsigned int n = 0; if (!cap) return 0; while (*p && n + 1 < cap) { unsigned int cp, extra, i; if (*p < 0x80) { cp = *p++; } else { if ((*p & 0xE0) == 0xC0) { cp = *p & 0x1F; extra = 1; } else if ((*p & 0xF0) == 0xE0) { cp = *p & 0x0F; extra = 2; } else if ((*p & 0xF8) == 0xF0) { cp = *p & 0x07; extra = 3; } else { p++; d[n++] = '?'; continue; } p++; for (i = 0; i < extra; i++) { if ((*p & 0xC0) != 0x80) break; cp = (cp << 6) | (*p++ & 0x3F); } if (i < extra) { d[n++] = '?'; continue; } } if (cp == '\t' || cp == 0xA0) { d[n++] = ' '; } else if (cp == '\n') { d[n++] = '\n'; } else if (cp < 0x20 || cp == 0x7F || (cp >= 0x80 && cp < 0xA0)) { continue; } else if (cp < 0x100) { d[n++] = (char)cp; } else { const char *f = cp_fallback(cp); if (f) n = put_ascii(d, n, cap, f); } } d[n] = '\0'; return n; } /* One-line version (newlines become spaces), for previews/snippets. */ static void to_latin1_line(char *d, unsigned int cap, const char *s) { unsigned int i; to_latin1(d, cap, s); for (i = 0; d[i]; i++) if (d[i] == '\n') d[i] = ' '; } /* ---- config file ---- */ static int read_file(const char *path, char *buf, unsigned int cap) { int n = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)(cap - 1)); if (n < 0) return n; buf[n] = '\0'; return n; } static int write_file(const char *path, const char *buf, unsigned int len) { return u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, (int)len); } /* The persistent data volume wins when it is mounted and writable; the * volatile /share is the fallback (live USB, or a board without /data). */ static const char *default_cfg_path(void) { struct sys_mount m; unsigned int i; for (i = 0; u_syscall2(SYS_LIST_MOUNTS, (int)i, (int)&m) == 1; i++) if (strcmp(m.name, "data") == 0 && !m.ro) return DEFAULT_CFG_DATA; return DEFAULT_CFG_SHARE; } static int set_server(const char *s) { char norm[CHAT_SERVER_MAX]; if (chat_server_normalize(s, norm, sizeof(norm)) != 0) return -1; if (chat_server_host(norm, server_host, sizeof(server_host), &server_secure) != 0) return -1; s_copy(server, norm, sizeof(server)); return 0; } /* Export the Chat host's cookies and write the config file. */ static void save_config(void) { static char out[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 128]; int n; uhttp_jar_header(&jar, server_host, "/api/me", server_secure, saved_cookie, sizeof(saved_cookie)); saved_jar_changes = jar.changes; n = chat_config_format(out, sizeof(out), server, saved_cookie); if (n < 0 || write_file(cfg_path, out, (unsigned int)n) < 0) set_status("Could not save the session to ", cfg_path, 1); memset(out, 0, sizeof(out)); } /* A server may roll its session cookie: save when the jar changed. */ static void maybe_save_cookie(void) { char now[CHAT_COOKIE_MAX]; if (jar.changes == saved_jar_changes || screen != SCR_MAIN) return; uhttp_jar_header(&jar, server_host, "/api/me", server_secure, now, sizeof(now)); saved_jar_changes = jar.changes; if (strcmp(now, saved_cookie) != 0) save_config(); } /* ---- HTTP / JSON plumbing ---- */ static void paint_now(void); static int line_h(void); static void net_drop(void) { http.keepalive = 0; uhttp_close(&http); } /* Request server + path; JSON body or NULL. Returns the HTTP status or a * UHTTP_ERR_*; the body is in resp/resp_len. */ static int api(const char *method, const char *path, const char *body) { char url[CHAT_SERVER_MAX + 256]; unsigned int len = 0; int st; s_copy(url, server, sizeof(url)); s_cat(url, path, sizeof(url)); http.jar = &jar; http.accept = "application/json"; st = chat_http(&http, method, url, body, resp, RESP_CAP, &len); resp_len = st > 0 ? len : 0; last_net_ms = u_ticks_ms(); maybe_save_cookie(); return st; } static int parse_resp(void) { int root = ujson_parse(&json, resp, resp_len); return root; } /* ---- message images and avatars ---- */ struct chat_pic { char *url; struct img_image img; unsigned int bytes; /* RGB565 bytes in the message-image budget */ unsigned int last_used; int state; /* CHAT_PIC_* */ }; static struct chat_pic chat_images[CHAT_IMG_MAX]; static int nchat_images; static unsigned int chat_image_bytes; static struct chat_pic chat_avatars[CHAT_AVATAR_MAX]; static int nchat_avatars; static unsigned int chat_pic_clock; static unsigned char *chat_fetch_buf; static unsigned char *chat_arena; static unsigned int chat_arena_size; static void chat_pic_free(struct chat_pic *p) { free(p->url); free(p->img.px); free(p->img.alpha); memset(p, 0, sizeof(*p)); } static struct chat_pic *chat_pic_find(struct chat_pic *arr, int n, const char *url) { int i; for (i = 0; i < n; i++) if (arr[i].url && strcmp(arr[i].url, url) == 0) return &arr[i]; return 0; } /* Pick a cache slot, evicting the least recently used entry when full. * avatars: their images never change the timeline layout. */ static struct chat_pic *chat_pic_slot(struct chat_pic *arr, int *count, int max, const char *url, int avatars) { struct chat_pic *p = chat_pic_find(arr, *count, url); unsigned int best = ~0u; int i, victim = -1; if (p) return p; if (*count < max) { p = &arr[*count]; memset(p, 0, sizeof(*p)); p->url = strdup(url); if (!p->url) return 0; (*count)++; } else { for (i = 0; i < *count; i++) { if (arr[i].state == CHAT_PIC_QUEUED || arr[i].state == CHAT_PIC_FETCHING) continue; if (arr[i].last_used < best) { best = arr[i].last_used; victim = i; } } if (victim < 0) return 0; p = &arr[victim]; if (!avatars) { chat_image_bytes -= p->bytes; msgs_gen++; } chat_pic_free(p); p->url = strdup(url); if (!p->url) return 0; } p->state = CHAT_PIC_QUEUED; p->last_used = ++chat_pic_clock; return p; } static struct chat_pic *chat_image_slot(const char *url) { return chat_pic_slot(chat_images, &nchat_images, CHAT_IMG_MAX, url, 0); } static struct chat_pic *chat_avatar_slot(const char *url) { return chat_pic_slot(chat_avatars, &nchat_avatars, CHAT_AVATAR_MAX, url, 1); } static int chat_image_room(unsigned int need) { while (chat_image_bytes + need > CHAT_IMG_BUDGET) { unsigned int best = ~0u; int i, victim = -1; for (i = 0; i < nchat_images; i++) { if (chat_images[i].state != CHAT_PIC_READY) continue; if (chat_images[i].last_used < best) { best = chat_images[i].last_used; victim = i; } } if (victim < 0) return -1; chat_image_bytes -= chat_images[victim].bytes; chat_pic_free(&chat_images[victim]); msgs_gen++; } return 0; } static unsigned char *chat_pic_arena_get(unsigned int need) { if (need <= chat_arena_size) return chat_arena; free(chat_arena); chat_arena = (unsigned char *)malloc(need); chat_arena_size = chat_arena ? need : 0; return chat_arena; } /* Clip the scaled avatar to a circle with a 4x4 supersampled edge. The RGB * pixels stay untouched; only the alpha plane changes. */ static void chat_avatar_mask(unsigned char *alpha, unsigned int w, unsigned int h) { unsigned int x, y; for (y = 0; y < h; y++) { for (x = 0; x < w; x++) { unsigned int hits = 0; int sx, sy; for (sy = 0; sy < 4; sy++) { int py = (int)y * 8 + sy * 2 + 1; int dy = py - (int)h * 4; for (sx = 0; sx < 4; sx++) { int px = (int)x * 8 + sx * 2 + 1; int dx = px - (int)w * 4; if (dx * dx + dy * dy <= (int)w * 4 * (int)w * 4) hits++; } } alpha[y * w + x] = (unsigned char)((unsigned int)alpha[y * w + x] * hits / 16u); } } } static int chat_pic_store(struct chat_pic *p, unsigned int len, int avatar) { struct img_info info; struct img_options opt = {0}; struct img_mem mem; struct img_image decoded; struct img_blit blit; unsigned char *arena, *alpha = 0; unsigned short *px; unsigned int est, scale, dw, dh, sw, sh, i, need; int r; if (img_sniff(chat_fetch_buf, len, &info) != 0) return -1; est = img_estimate(&info); if (est == 0xFFFFFFFFu || est > CHAT_IMG_ARENA_MAX) return -1; arena = chat_pic_arena_get(est); if (!arena) return -1; img_mem_init(&mem, arena, est); opt.max_pixels = 4u * 1024u * 1024u; opt.max_w = avatar ? CHAT_AVATAR : CHAT_IMG_W; opt.max_h = avatar ? CHAT_AVATAR : CHAT_IMG_H; r = img_decode(chat_fetch_buf, len, &opt, &mem, &decoded); if (r != 0 || !decoded.w || !decoded.h) return -1; if (avatar) { sw = (CHAT_AVATAR << 16) / decoded.w; sh = (CHAT_AVATAR << 16) / decoded.h; scale = sw < sh ? sw : sh; dw = dh = CHAT_AVATAR; } else { scale = 65536; if (decoded.w > CHAT_IMG_W) scale = (CHAT_IMG_W << 16) / decoded.w; if (((decoded.h * scale) >> 16) > CHAT_IMG_H) scale = (CHAT_IMG_H << 16) / decoded.h; dw = (decoded.w * scale) >> 16; dh = (decoded.h * scale) >> 16; if (!dw) dw = 1; if (!dh) dh = 1; need = dw * dh * 2u; if (chat_image_room(need) != 0) return -1; } px = (unsigned short *)malloc(dw * dh * 2u); if (!px) return -1; for (i = 0; i < dw * dh; i++) px[i] = avatar ? 0xFFFF : ui.theme.bg; if (avatar) { /* Keep an alpha plane even for an opaque picture: the circular * mask below clips it to the avatar circle. */ alpha = (unsigned char *)malloc(dw * dh); if (alpha) memset(alpha, 255, dw * dh); } memset(&blit, 0, sizeof(blit)); blit.dst = px; blit.dst_w = (int)dw; blit.dst_h = (int)dh; blit.clip_x = 0; blit.clip_y = 0; blit.clip_w = (int)dw; blit.clip_h = (int)dh; blit.x = avatar ? (int)(dw - ((decoded.w * scale) >> 16)) / 2 : 0; blit.y = avatar ? (int)(dh - ((decoded.h * scale) >> 16)) / 2 : 0; blit.scale = scale; blit.bg = avatar ? 0xFFFF : ui.theme.bg; blit.bg2 = blit.bg; blit.dst_a = alpha; blit.flags = alpha ? IMG_BLIT_SAVE_ALPHA : (decoded.alpha ? IMG_BLIT_OVER_DST : 0); img_draw(&decoded, &blit); if (avatar && alpha) chat_avatar_mask(alpha, dw, dh); p->img.format = decoded.format; p->img.w = dw; p->img.h = dh; p->img.px = px; p->img.alpha = alpha; p->img.flags = 0; p->bytes = avatar ? 0 : dw * dh * 2u; if (!avatar) chat_image_bytes += p->bytes; return 0; } /* Install a message-image bitmap decoded by the fetch helper (the helper * already applied the 480x320 bounds). Avatars are still decoded here at * 32x32 so the circular mask sees the same square source as before. */ static int chat_pic_store_px(struct chat_pic *p, unsigned char *buf, unsigned int len, unsigned int dw, unsigned int dh, int has_alpha) { unsigned int npx = dw * dh, need; unsigned short *px; unsigned char *alpha = 0; if (!buf || !dw || !dh || len < npx * 2u) return -1; need = npx * 2u; if (chat_image_room(need) != 0) return -1; px = (unsigned short *)malloc(need); if (!px) return -1; memcpy(px, buf, need); if (has_alpha && len >= need + npx) { alpha = (unsigned char *)malloc(npx); if (alpha) memcpy(alpha, buf + need, npx); } p->img.format = 0; p->img.w = dw; p->img.h = dh; p->img.px = px; p->img.alpha = alpha; p->img.flags = 0; p->bytes = need; chat_image_bytes += need; return 0; } /* ---- asynchronous media fetch ---- * * chat_http() blocks the UI for the whole body, so every image and avatar * used to freeze the window for the download plus the decode. Media now * goes through the same curl __serve helper as the browser: the chat loop * submits a request file and polls a small done marker, while a private tty * absorbs the helper's DNS/TLS log lines. Only the (short) decode runs on * the chat thread. */ static int chat_media_pid = -1; static int chat_media_tty = -1; static unsigned int chat_media_session; static unsigned int chat_media_seq; static unsigned int chat_media_deadline; static int chat_media_busy; static int chat_media_retried; static struct chat_pic *chat_media_pic; static int chat_media_avatar; static char chat_media_req[40], chat_media_body[40]; static char chat_media_meta[40], chat_media_done[40]; static char chat_media_px[40]; static void chat_media_paths(void) { if (chat_media_session) return; chat_media_session = ((unsigned int)u_getpid() << 16) ^ (u_ticks_ms() & 0xFFFFu); if (!chat_media_session) chat_media_session = 1; snprintf(chat_media_req, sizeof(chat_media_req), "/share/bf%u_0req", chat_media_session); snprintf(chat_media_body, sizeof(chat_media_body), "/share/bf%u_0body", chat_media_session); snprintf(chat_media_meta, sizeof(chat_media_meta), "/share/bf%u_0meta", chat_media_session); snprintf(chat_media_done, sizeof(chat_media_done), "/share/bf%u_0done", chat_media_session); snprintf(chat_media_px, sizeof(chat_media_px), "/share/bf%u_0px", chat_media_session); } static void chat_media_tty_drain(void) { char sink[256]; int i; if (chat_media_tty <= 0) return; for (i = 0; i < 8; i++) if (u_tty_read(chat_media_tty, sink, sizeof(sink)) <= 0) break; } static void chat_media_jar_sync(void) { u_syscall3(SYS_WRITE_FILE, (int)"/share/bchat.jar", (int)&jar, (int)sizeof(jar)); } static int chat_media_start(void) { char arg[64]; int t; chat_media_paths(); if (chat_media_pid > 0 && u_alive((unsigned int)chat_media_pid)) return 0; chat_media_pid = -1; if (chat_media_tty == -1) { t = u_tty_create(); chat_media_tty = t > 0 ? t : 0; } chat_media_jar_sync(); snprintf(arg, sizeof(arg), "__serve %u 0 /share/bchat.jar", chat_media_session); chat_media_pid = u_spawn("/ramfs/bin/curl", arg, chat_media_tty, "/"); if (chat_media_pid <= 0) { chat_media_pid = -1; return -1; } return 0; } static void chat_media_stop(void) { chat_media_tty_drain(); if (chat_media_pid > 0) u_kill((unsigned int)chat_media_pid); chat_media_pid = -1; } static void chat_media_fail(void) { if (chat_media_pic) chat_media_pic->state = CHAT_PIC_FAILED; chat_media_pic = 0; chat_media_busy = 0; chat_media_retried = 0; u_syscall1(SYS_UNLINK, (int)chat_media_done); u_syscall1(SYS_UNLINK, (int)chat_media_meta); u_syscall1(SYS_UNLINK, (int)chat_media_body); u_syscall1(SYS_UNLINK, (int)chat_media_px); ngui_invalidate(&ui); } static int chat_media_submit(struct chat_pic *p, int avatar) { char req[512]; int n; if (!chat_fetch_buf) { chat_fetch_buf = (unsigned char *)malloc(CHAT_IMG_FETCH_MAX); if (!chat_fetch_buf) return -1; } chat_media_paths(); if (chat_media_start() != 0) return -1; chat_media_jar_sync(); chat_media_seq++; if (!chat_media_seq) chat_media_seq = 1; chat_media_retried = 0; if (!avatar) n = snprintf(req, sizeof(req), "%u %u D %u %u %s\n", chat_media_seq, CHAT_IMG_FETCH_MAX, CHAT_IMG_W, CHAT_IMG_H, p->url); else n = snprintf(req, sizeof(req), "%u %u %s\n", chat_media_seq, CHAT_IMG_FETCH_MAX, p->url); if (n <= 0 || n >= (int)sizeof(req)) return -1; u_syscall1(SYS_UNLINK, (int)chat_media_done); u_syscall1(SYS_UNLINK, (int)chat_media_meta); u_syscall1(SYS_UNLINK, (int)chat_media_body); u_syscall1(SYS_UNLINK, (int)chat_media_px); if (u_syscall3(SYS_WRITE_FILE, (int)chat_media_req, (int)req, n) < 0) return -1; p->state = CHAT_PIC_FETCHING; chat_media_pic = p; chat_media_avatar = avatar; chat_media_busy = 1; chat_media_deadline = u_ticks_ms() + 30000; return 0; } /* 1 when the outstanding job finished (success or failure). */ static unsigned int chat_meta_uint(char **pp) { char *p = *pp; unsigned int v = 0; while (*p >= '0' && *p <= '9') { v = v * 10 + (unsigned int)(*p - '0'); p++; } while (*p && *p != '\n') p++; if (*p) p++; *pp = p; return v; } static int chat_media_poll(void) { char done[24], meta[1200]; int rn, st = 0, err = 0; unsigned int seq; unsigned int dw = 0, dh = 0, nw = 0, nh = 0, alpha = 0; unsigned int px_len = 0, dec_err = 0; if (!chat_media_busy) return 0; chat_media_tty_drain(); rn = u_syscall3(SYS_READ_FILE, (int)chat_media_done, (int)done, (int)(sizeof(done) - 1)); if (rn > 0) { char *q; done[rn] = '\0'; seq = (unsigned int)atoi(done); if (seq != chat_media_seq) return 0; rn = u_syscall3(SYS_READ_FILE, (int)chat_media_meta, (int)meta, (int)(sizeof(meta) - 1)); if (rn > 0) { meta[rn] = '\0'; q = meta; (void)chat_meta_uint(&q); /* seq */ st = (int)chat_meta_uint(&q); err = (int)chat_meta_uint(&q); (void)chat_meta_uint(&q); /* trunc */ while (*q && *q != '\n') /* encoding */ q++; if (*q) q++; while (*q && *q != '\n') /* content type */ q++; if (*q) q++; while (*q && *q != '\n') /* final URL */ q++; if (*q) q++; (void)chat_meta_uint(&q); /* body bytes */ (void)chat_meta_uint(&q); /* open */ (void)chat_meta_uint(&q); /* first */ (void)chat_meta_uint(&q); /* total */ dw = chat_meta_uint(&q); dh = chat_meta_uint(&q); nw = chat_meta_uint(&q); nh = chat_meta_uint(&q); alpha = chat_meta_uint(&q); px_len = chat_meta_uint(&q); dec_err = chat_meta_uint(&q); (void)chat_meta_uint(&q); /* dec ms */ } if (st == 200 && !err && chat_media_pic) { int stored = 0; (void)nw; (void)nh; if (!chat_media_avatar && px_len && !dec_err && dw && dh && px_len <= CHAT_IMG_FETCH_MAX) { rn = u_syscall3(SYS_READ_FILE, (int)chat_media_px, (int)chat_fetch_buf, (int)CHAT_IMG_FETCH_MAX); if (rn == (int)px_len && chat_pic_store_px(chat_media_pic, chat_fetch_buf, px_len, dw, dh, (int)alpha) == 0) stored = 1; } if (!stored) { rn = u_syscall3(SYS_READ_FILE, (int)chat_media_body, (int)chat_fetch_buf, (int)CHAT_IMG_FETCH_MAX); if (rn > 0 && chat_pic_store(chat_media_pic, (unsigned int)rn, chat_media_avatar) == 0) stored = 1; } if (stored) { chat_media_pic->state = CHAT_PIC_READY; chat_media_pic->last_used = ++chat_pic_clock; if (!chat_media_avatar) { msgs_gen++; if (at_bottom) tl_scroll.offset = 1 << 28; } } else { chat_media_pic->state = CHAT_PIC_FAILED; } } else if (chat_media_pic) { chat_media_pic->state = CHAT_PIC_FAILED; } chat_media_pic = 0; chat_media_busy = 0; u_syscall1(SYS_UNLINK, (int)chat_media_done); u_syscall1(SYS_UNLINK, (int)chat_media_meta); u_syscall1(SYS_UNLINK, (int)chat_media_body); u_syscall1(SYS_UNLINK, (int)chat_media_px); ngui_invalidate(&ui); return 1; } if (chat_media_pid > 0 && !u_alive((unsigned int)chat_media_pid)) { chat_media_pid = -1; if (!chat_media_retried && chat_media_start() == 0) { chat_media_retried = 1; return 0; } chat_media_fail(); return 1; } if ((int)(u_ticks_ms() - chat_media_deadline) >= 0) { chat_media_stop(); chat_media_fail(); return 1; } return 0; } static void chat_media_tick(void) { int i; if (screen != SCR_MAIN || offline) return; if (chat_media_busy) { chat_media_poll(); return; } /* Holding a helper keeps a TCP socket open, which pauses the board's * net-dev watcher; release it when the window is not being used. */ if (!ui.focused) { if (chat_media_pid > 0) chat_media_stop(); return; } for (i = 0; i < nchat_images; i++) { if (chat_images[i].state == CHAT_PIC_QUEUED) { if (chat_media_submit(&chat_images[i], 0) != 0) chat_images[i].state = CHAT_PIC_FAILED; ngui_invalidate(&ui); return; } } for (i = 0; i < nchat_avatars; i++) { if (chat_avatars[i].state == CHAT_PIC_QUEUED) { if (chat_media_submit(&chat_avatars[i], 1) != 0) chat_avatars[i].state = CHAT_PIC_FAILED; ngui_invalidate(&ui); return; } } } static void chat_media_clear(void) { int i; chat_media_stop(); chat_media_pic = 0; chat_media_busy = 0; chat_media_retried = 0; for (i = 0; i < nchat_images; i++) chat_pic_free(&chat_images[i]); for (i = 0; i < nchat_avatars; i++) chat_pic_free(&chat_avatars[i]); nchat_images = 0; nchat_avatars = 0; chat_image_bytes = 0; free(chat_fetch_buf); chat_fetch_buf = 0; free(chat_arena); chat_arena = 0; chat_arena_size = 0; } /* Refresh/Retry gives failed pictures another chance. */ static void chat_media_retry(void) { int i; for (i = 0; i < nchat_images; i++) if (chat_images[i].state == CHAT_PIC_FAILED) chat_images[i].state = CHAT_PIC_QUEUED; for (i = 0; i < nchat_avatars; i++) if (chat_avatars[i].state == CHAT_PIC_FAILED) chat_avatars[i].state = CHAT_PIC_QUEUED; ngui_invalidate(&ui); } /* Resolve a picture URL; Cloudron's older profile-avatar path is rewritten * to the /api/avatars/ route the current server serves. */ static int chat_pic_url(const char *raw, char *out, unsigned int cap) { static const char old_prefix[] = "/api/v1/profile/avatar/"; const char *p; char tmp[CHAT_IMG_URL_MAX]; char *q; if (!raw || !raw[0]) return -1; p = strstr(raw, old_prefix); if (p) { s_copy(tmp, "/api/avatars/", sizeof(tmp)); s_cat(tmp, p + sizeof(old_prefix) - 1, sizeof(tmp)); q = strchr(tmp, '?'); if (q) *q = '\0'; raw = tmp; } return uhttp_resolve(server, raw, out, cap); } static int chat_image_name(const char *mime, const char *filename) { static const char *const ext[] = { ".png", ".jpg", ".jpeg", ".gif", ".bmp", ".tga", ".ppm", ".pgm", ".pbm", ".ico", ".cur", ".pam" }; unsigned int i; if (mime && strncmp(mime, "image/", 6) == 0) return 1; if (!filename) return 0; for (i = 0; i < sizeof(ext) / sizeof(ext[0]); i++) { unsigned int n = (unsigned int)strlen(ext[i]); unsigned int j; const char *s = filename + strlen(filename); if ((unsigned int)strlen(filename) < n) continue; s -= n; for (j = 0; j < n; j++) { char a = s[j], b = ext[i][j]; if (a >= 'A' && a <= 'Z') a = (char)(a - 'A' + 'a'); if (a != b) break; } if (j == n) return 1; } return 0; } /* Layout/draw dimensions for one message image. *state is the cache state * (a missing entry is treated as queued; draw queues it). */ static void chat_image_measure(const char *url, int tw, int *dw, int *dh, unsigned int *scale, int *state) { struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url); unsigned int sc = 65536; if (p && p->state == CHAT_PIC_READY) { if ((int)p->img.w > tw) sc = ((unsigned int)tw << 16) / p->img.w; if (((p->img.h * sc) >> 16) > CHAT_IMG_H) sc = (CHAT_IMG_H << 16) / p->img.h; *dw = (int)((p->img.w * sc) >> 16); *dh = (int)((p->img.h * sc) >> 16); if (*dw < 1) *dw = 1; if (*dh < 1) *dh = 1; *scale = sc; *state = CHAT_PIC_READY; return; } *dw = tw < 320 ? tw : 320; if (*dw < 40) *dw = 40; *dh = 120; *scale = 65536; *state = p ? p->state : CHAT_PIC_QUEUED; } static struct ngui_rect chat_clip_rect(void) { if (ui.nclip > 0) return ui.clip[ui.nclip - 1]; return (struct ngui_rect){ 0, 0, ui.w, ui.h }; } static void chat_image_draw(const char *url, int x, int y, int tw) { struct chat_pic *p = chat_pic_find(chat_images, nchat_images, url); struct ngui_rect clip = chat_clip_rect(); int dw, dh, state; unsigned int scale; if (!p) p = chat_image_slot(url); chat_image_measure(url, tw, &dw, &dh, &scale, &state); if (p && p->state == CHAT_PIC_READY) { struct img_blit blit; memset(&blit, 0, sizeof(blit)); blit.dst = ui.px; blit.dst_w = ui.w; blit.dst_h = ui.h; blit.clip_x = clip.x; blit.clip_y = clip.y; blit.clip_w = clip.w; blit.clip_h = clip.h; blit.x = x; blit.y = y; blit.scale = scale; blit.bg = ui.theme.bg; blit.bg2 = ui.theme.bg; blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0; img_draw(&p->img, &blit); ngui_frame(&ui, (struct ngui_rect){ x, y, dw, dh }, ui.theme.border); } else { struct ngui_rect box = { x, y, dw, dh }; ngui_fill_rect(&ui, box, ui.theme.panel_alt); ngui_frame(&ui, box, ui.theme.border); ngui_text_ellipsis(&ui, box, x + 8, y + (dh - line_h()) / 2, state == CHAT_PIC_FAILED ? "Image could not be loaded" : "Loading image...", ui.theme.text_dim); } } static int chat_avatar_draw(const char *url, int x, int y, int size, unsigned short fallback) { struct chat_pic *p; if (!url || !url[0]) return 0; p = chat_pic_find(chat_avatars, nchat_avatars, url); if (!p) p = chat_avatar_slot(url); if (p && p->state == CHAT_PIC_READY) { struct ngui_rect clip = chat_clip_rect(); struct img_blit blit; memset(&blit, 0, sizeof(blit)); blit.dst = ui.px; blit.dst_w = ui.w; blit.dst_h = ui.h; blit.clip_x = clip.x; blit.clip_y = clip.y; blit.clip_w = clip.w; blit.clip_h = clip.h; blit.x = x; blit.y = y; blit.scale = ((unsigned int)size << 16) / CHAT_AVATAR; blit.bg = fallback; blit.bg2 = fallback; blit.flags = p->img.alpha ? IMG_BLIT_OVER_DST : 0; img_draw(&p->img, &blit); return 1; } return 0; } static void go_login(const char *why); /* Common error handling for API calls in the main screen. Returns 1 when * the status is a success. */ static int api_ok(int st, const char *what) { if (st >= 200 && st < 300) { if (offline) { offline = 0; set_status("Connected", 0, 0); } backoff_ms = 0; return 1; } if (st == 401) { go_login("Session expired - please sign in again"); return 0; } if (st > 0) { char code[64]; s_copy(code, what, sizeof(code)); s_cat(code, ": HTTP ", sizeof(code)); s_cat_uint(code, (unsigned int)st, sizeof(code)); set_status(code, 0, 1); return 0; } offline = 1; backoff_ms = backoff_ms == 0 ? 2000 : backoff_ms < 5000 ? 5000 : backoff_ms < 10000 ? 10000 : 30000; retry_at = u_ticks_ms() + backoff_ms; set_status("Offline: ", uhttp_error_string(st), 1); net_drop(); return 0; } /* ---- conversations ---- */ static int conv_find(const char *id) { int i; for (i = 0; i < nconv; i++) if (strcmp(convs[i].id, id) == 0) return i; return -1; } static void conv_from_json(struct conv *c, int o, int dm) { int last; s_copy(c->id, ujson_get_str(&json, o, "id"), sizeof(c->id)); c->unread = (int)ujson_int(&json, ujson_get(&json, o, "unreadCount"), 0); c->preview[0] = '\0'; last = ujson_get(&json, o, "lastMessage"); if (ujson_type(&json, last) == UJSON_OBJECT) { char tmp[96]; to_latin1_line(tmp, sizeof(tmp), ujson_get_str(&json, last, "authorName")); s_copy(c->preview, tmp, sizeof(c->preview)); s_cat(c->preview, ": ", sizeof(c->preview)); to_latin1_line(tmp, sizeof(tmp), ujson_get_str(&json, last, "body")); s_cat(c->preview, tmp, sizeof(c->preview)); } if (dm) { int other = ujson_get(&json, o, "otherUser"); const char *pres = ujson_get_str(&json, o, "presence"); const char *nm = ujson_get_str(&json, other, "name"); if (!nm[0]) nm = ujson_get_str(&json, other, "username"); to_latin1_line(c->name, sizeof(c->name), nm[0] ? nm : "(unknown)"); c->kind = 'd'; c->presence = strcmp(pres, "online") == 0 ? 'o' : strcmp(pres, "away") == 0 ? 'a' : 'f'; } else { to_latin1_line(c->name, sizeof(c->name), ujson_get_str(&json, o, "name")); c->kind = strcmp(ujson_get_str(&json, o, "type"), "private") == 0 ? 'p' : 'c'; c->presence = 0; } } static int load_directory(void) { static struct conv next[MAX_CONV]; int n = 0, st, root, it, pass; for (pass = 0; pass < 2; pass++) { st = api(0, pass ? "/api/dms" : "/api/channels", 0); if (!api_ok(st, pass ? "Direct messages" : "Channels")) return -1; root = parse_resp(); if (root < 0) { set_status("Bad directory reply: ", json.error, 1); return -1; } for (it = ujson_first(&json, root); it >= 0 && n < MAX_CONV; it = ujson_next(&json, it)) { if (ujson_truthy(&json, ujson_get(&json, it, "archived"))) continue; if (pass && ujson_truthy(&json, ujson_get(&json, it, "isSelf"))) continue; conv_from_json(&next[n], it, pass); if (next[n].id[0]) n++; } } memcpy(convs, next, sizeof(struct conv) * (unsigned int)n); nconv = n; cur = cur_id[0] ? conv_find(cur_id) : -1; if (cur >= 0 && at_bottom) convs[cur].unread = 0; /* we are reading it */ ngui_invalidate(&ui); return 0; } /* ---- messages ---- */ static void msg_free(struct msg *m) { int i; free(m->body); m->body = 0; free(m->author_pic); m->author_pic = 0; for (i = 0; i < m->nimg; i++) { free(m->img_url[i]); m->img_url[i] = 0; } m->nimg = 0; } /* Resolve and remember one image URL; duplicates and overflowing messages * are ignored. */ static int msg_add_image(struct msg *m, const char *raw) { char url[CHAT_IMG_URL_MAX]; int i; if (!raw || !raw[0] || m->nimg >= MSG_IMG_MAX) return 0; if (uhttp_resolve(server, raw, url, sizeof(url)) != 0) return 0; for (i = 0; i < m->nimg; i++) if (strcmp(m->img_url[i], url) == 0) return 0; m->img_url[m->nimg] = strdup(url); if (!m->img_url[m->nimg]) return -1; m->nimg++; return 0; } static void msg_set_author_pic(struct msg *m, const char *raw) { char url[CHAT_IMG_URL_MAX]; if (!raw[0] || chat_pic_url(raw, url, sizeof(url)) != 0) return; m->author_pic = strdup(url); } static void clear_messages(void) { int i; for (i = 0; i < nmsg; i++) msg_free(&msgs[i]); nmsg = 0; msgs_gen++; has_older = 0; history_full = 0; new_below = 0; } static int msg_find(const char *id) { int i; for (i = nmsg - 1; i >= 0; i--) if (strcmp(msgs[i].id, id) == 0) return i; return -1; } static void build_extra(struct msg *m, int o) { int it, n; m->extra[0] = '\0'; for (it = ujson_first(&json, ujson_get(&json, o, "attachments")); it >= 0; it = ujson_next(&json, it)) { char name[64]; const char *mime = ujson_get_str(&json, it, "mime"); const char *fn = ujson_get_str(&json, it, "filename"); const char *url = ujson_get_str(&json, it, "url"); if (chat_image_name(mime, fn) && url[0]) continue; /* drawn inline by the timeline */ to_latin1_line(name, sizeof(name), fn); if (m->extra[0]) s_cat(m->extra, ", ", sizeof(m->extra)); else s_cat(m->extra, "[file] ", sizeof(m->extra)); s_cat(m->extra, name, sizeof(m->extra)); } if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT && !ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")[0]) { if (m->extra[0]) s_cat(m->extra, " ", sizeof(m->extra)); s_cat(m->extra, "[GIF]", sizeof(m->extra)); } if (strcmp(ujson_get_str(&json, o, "type"), "poll") == 0) { if (m->extra[0]) s_cat(m->extra, " ", sizeof(m->extra)); s_cat(m->extra, "[poll - open in the web app]", sizeof(m->extra)); } if (ujson_get_str(&json, o, "callUrl")[0]) { if (m->extra[0]) s_cat(m->extra, " ", sizeof(m->extra)); s_cat(m->extra, "[call]", sizeof(m->extra)); } n = (int)ujson_int(&json, ujson_get(&json, o, "threadCount"), 0); if (n > 0) { if (m->extra[0]) s_cat(m->extra, " \xb7 ", sizeof(m->extra)); s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra)); s_cat(m->extra, n == 1 ? " reply" : " replies", sizeof(m->extra)); } n = 0; for (it = ujson_first(&json, ujson_get(&json, o, "reactions")); it >= 0; it = ujson_next(&json, it)) { int c = (int)ujson_int(&json, ujson_get(&json, it, "count"), 1); n += c > 0 ? c : 1; } if (n > 0) { if (m->extra[0]) s_cat(m->extra, " \xb7 ", sizeof(m->extra)); s_cat_uint(m->extra, (unsigned int)n, sizeof(m->extra)); s_cat(m->extra, n == 1 ? " reaction" : " reactions", sizeof(m->extra)); } if (ujson_truthy(&json, ujson_get(&json, o, "pinned"))) { if (m->extra[0]) s_cat(m->extra, " \xb7 ", sizeof(m->extra)); s_cat(m->extra, "pinned", sizeof(m->extra)); } } /* Fill m from a message object; 0 ok, -1 skip (deleted/thread reply). */ static int msg_from_json(struct msg *m, int o) { static char body[BODY_MAX + 8]; const char *nm; int rt; unsigned int len; if (ujson_truthy(&json, ujson_get(&json, o, "deleted"))) return -1; /* Thread replies live in the thread panel, not the timeline. */ if (ujson_get_str(&json, o, "parentId")[0]) return -1; memset(m, 0, sizeof(*m)); s_copy(m->id, ujson_get_str(&json, o, "id"), sizeof(m->id)); if (!m->id[0]) return -1; s_copy(m->user_id, ujson_get_str(&json, o, "userId"), sizeof(m->user_id)); nm = ujson_get_str(&json, o, "authorName"); if (!nm[0]) nm = ujson_get_str(&json, o, "authorUsername"); to_latin1_line(m->author, sizeof(m->author), nm[0] ? nm : "?"); msg_set_author_pic(m, ujson_get_str(&json, o, "authorPicture")); s_copy(m->created, ujson_get_str(&json, o, "createdAt"), sizeof(m->created)); m->action = strcmp(ujson_get_str(&json, o, "type"), "me") == 0; len = to_latin1(body, BODY_MAX, ujson_get_str(&json, o, "body")); if (len + 1 >= BODY_MAX) { /* truncated: mark it */ body[BODY_MAX - 4] = '.'; body[BODY_MAX - 3] = '.'; body[BODY_MAX - 2] = '.'; body[BODY_MAX - 1] = '\0'; } /* Trim trailing newlines/spaces. */ len = (unsigned int)strlen(body); while (len && (body[len - 1] == '\n' || body[len - 1] == ' ')) body[--len] = '\0'; m->body = strdup(body); if (!m->body) { msg_free(m); return -1; } { int it; const char *mime, *fn; for (it = ujson_first(&json, ujson_get(&json, o, "attachments")); it >= 0; it = ujson_next(&json, it)) { mime = ujson_get_str(&json, it, "mime"); fn = ujson_get_str(&json, it, "filename"); if (chat_image_name(mime, fn) && msg_add_image(m, ujson_get_str(&json, it, "url")) != 0) { msg_free(m); return -1; } } } if (ujson_type(&json, ujson_get(&json, o, "gif")) == UJSON_OBJECT && msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "gif"), "url")) != 0) { msg_free(m); return -1; } if (ujson_type(&json, ujson_get(&json, o, "preview")) == UJSON_OBJECT && msg_add_image(m, ujson_get_str(&json, ujson_get(&json, o, "preview"), "image")) != 0) { msg_free(m); return -1; } rt = ujson_get(&json, o, "replyTo"); if (ujson_type(&json, rt) == UJSON_OBJECT) { char tmp[96]; to_latin1_line(m->reply, sizeof(m->reply), ujson_get_str(&json, rt, "authorName")); s_cat(m->reply, ": ", sizeof(m->reply)); if (ujson_truthy(&json, ujson_get(&json, rt, "deleted"))) s_copy(tmp, "(deleted)", sizeof(tmp)); else to_latin1_line(tmp, sizeof(tmp), ujson_get_str(&json, rt, "body")); if (!tmp[0]) s_copy(tmp, "(attachment)", sizeof(tmp)); s_cat(m->reply, tmp, sizeof(m->reply)); } build_extra(m, o); return 0; } static int msg_before(const struct msg *a, const struct msg *b) { int c = strcmp(a->created, b->created); return c < 0 || (c == 0 && strcmp(a->id, b->id) < 0); } /* Insert or update a message, keeping msgs sorted. older: we are paging * back in history (never evict old messages for it). Returns 1 when a new * message was added, 0 when updated/skipped. */ static int msg_merge(struct msg *m, int older) { int i = msg_find(m->id), pos; msgs_gen++; if (i >= 0) { /* Edited body or new reactions: replace in place. */ msg_free(&msgs[i]); msgs[i] = *m; return 0; } if (nmsg >= MAX_MSG) { if (older) { history_full = 1; msg_free(m); return 0; } msg_free(&msgs[0]); memmove(&msgs[0], &msgs[1], sizeof(struct msg) * (MAX_MSG - 1)); nmsg--; has_older = 1; history_full = 1; } pos = nmsg; while (pos > 0 && msg_before(m, &msgs[pos - 1])) pos--; memmove(&msgs[pos + 1], &msgs[pos], sizeof(struct msg) * (unsigned int)(nmsg - pos)); msgs[pos] = *m; nmsg++; return 1; } /* Merge every message of the parsed reply. Returns the number added. */ static int merge_reply(int root, int older, int *count) { int it, added = 0, n = 0; for (it = ujson_first(&json, root); it >= 0; it = ujson_next(&json, it)) { struct msg m; const char *id = ujson_get_str(&json, it, "id"); n++; if (ujson_truthy(&json, ujson_get(&json, it, "deleted"))) { /* A deletion we already show: drop it. */ int k = msg_find(id); if (k >= 0) { msg_free(&msgs[k]); memmove(&msgs[k], &msgs[k + 1], sizeof(struct msg) * (unsigned int)(nmsg - k - 1)); nmsg--; msgs_gen++; } continue; } if (msg_from_json(&m, it) == 0) added += msg_merge(&m, older); } if (count) *count = n; return added; } static void mark_read(void) { char path[96]; int st; if (cur < 0) return; s_copy(path, "/api/channels/", sizeof(path)); s_cat(path, convs[cur].id, sizeof(path)); s_cat(path, "/read", sizeof(path)); st = api("POST", path, 0); if (api_ok(st, "Mark read")) convs[cur].unread = 0; } static void msgs_path(char *path, unsigned int cap, const char *query) { s_copy(path, "/api/channels/", cap); s_cat(path, cur_id, cap); s_cat(path, "/messages?", cap); s_cat(path, query, cap); } static void scroll_to_end(void) { tl_scroll.offset = 1 << 28; /* clamped when laid out */ at_bottom = 1; new_below = 0; } static void open_conv(int idx) { char path[160]; int st, root, n = 0; if (idx < 0 || idx >= nconv) return; cur = idx; s_copy(cur_id, convs[idx].id, sizeof(cur_id)); clear_messages(); scroll_to_end(); s_copy(busy, "Loading messages...", sizeof(busy)); paint_now(); msgs_path(path, sizeof(path), "limit=50"); st = api(0, path, 0); busy[0] = '\0'; if (!api_ok(st, "Messages")) return; root = parse_resp(); if (root < 0) { set_status("Bad message reply: ", json.error, 1); return; } merge_reply(root, 1, &n); has_older = n >= PAGE_SIZE; scroll_to_end(); mark_read(); next_conv_poll = u_ticks_ms() + POLL_CONV_MS; ngui_invalidate(&ui); } static int content_height(void); static void load_older(void) { char path[200], q[96]; int st, root, n = 0, before_h, added; if (cur < 0 || !nmsg || history_full) return; last_older_ms = u_ticks_ms(); s_copy(q, "limit=50&before=", sizeof(q)); s_cat(q, msgs[0].id, sizeof(q)); msgs_path(path, sizeof(path), q); s_copy(busy, "Loading older messages...", sizeof(busy)); paint_now(); st = api(0, path, 0); busy[0] = '\0'; if (!api_ok(st, "Older messages")) return; root = parse_resp(); if (root < 0) return; before_h = content_height(); added = merge_reply(root, 1, &n); has_older = n >= PAGE_SIZE && !history_full; /* Keep the view on the same message. */ if (added) tl_scroll.offset += content_height() - before_h; ngui_invalidate(&ui); } static void poll_conv(void) { char path[200], q[96]; int st, root, added, n = 0; if (cur < 0) return; if (!nmsg) { msgs_path(path, sizeof(path), "limit=50"); } else { s_copy(q, "limit=50&after=", sizeof(q)); s_cat(q, msgs[nmsg - 1].id, sizeof(q)); msgs_path(path, sizeof(path), q); } st = api(0, path, 0); if (st == 404 && nmsg) { /* The anchor message was deleted: reload the page. */ open_conv(cur); return; } if (!api_ok(st, "Messages")) return; root = parse_resp(); if (root < 0) { set_status("Bad message reply: ", json.error, 1); return; } added = merge_reply(root, 0, &n); if (n >= LIVE_PAGE) { /* More than a page arrived: jump to the newest page. */ open_conv(cur); return; } if (added) { if (at_bottom) { scroll_to_end(); mark_read(); } else { new_below += added; } ngui_invalidate(&ui); } } static void make_client_id(char *out, unsigned int cap) { static const char hex[] = "0123456789abcdef"; unsigned int v = u_ticks_ms() ^ ((unsigned int)u_getpid() << 20); unsigned int c = ++client_seq, i; s_copy(out, "nebos-", cap); for (i = 0; i < 8; i++) { char ch[2] = { hex[(v >> (28 - 4 * i)) & 15], 0 }; s_cat(out, ch, cap); } s_cat(out, "-", cap); s_cat_uint(out, c, cap); } static void send_message(void) { static char body[NGUI_INPUT_MAX * 6 + 160]; char path[96], cid[40]; int st, root, r; unsigned int n = 0; const char *t = compose_in.text; while (*t == ' ') t++; if (cur < 0 || !*t) return; make_client_id(cid, sizeof(cid)); s_copy(body, "{\"body\":", sizeof(body)); n = (unsigned int)strlen(body); { /* The field holds Latin-1/ASCII: encode as UTF-8 for JSON. */ static char utf8[NGUI_INPUT_MAX * 2 + 4]; unsigned int k = 0; const unsigned char *p = (const unsigned char *)t; while (*p && k + 3 < sizeof(utf8)) { if (*p < 0x80) { utf8[k++] = (char)*p; } else { utf8[k++] = (char)(0xC0 | (*p >> 6)); utf8[k++] = (char)(0x80 | (*p & 0x3F)); } p++; } utf8[k] = '\0'; r = ujson_escape(body + n, sizeof(body) - n, utf8); } if (r < 0) return; n += (unsigned int)r; s_cat(body, ",\"clientId\":\"", sizeof(body)); s_cat(body, cid, sizeof(body)); s_cat(body, "\"}", sizeof(body)); s_copy(path, "/api/channels/", sizeof(path)); s_cat(path, cur_id, sizeof(path)); s_cat(path, "/messages", sizeof(path)); s_copy(busy, "Sending...", sizeof(busy)); paint_now(); st = api("POST", path, body); busy[0] = '\0'; if (!api_ok(st, "Send")) { if (st > 0) { char msg[96]; root = parse_resp(); s_copy(msg, root >= 0 ? ujson_get_str(&json, root, "error") : "", sizeof(msg)); if (msg[0]) set_status("Send failed: ", msg, 1); } return; /* the text stays in the composer */ } ngui_input_set(&compose_in, ""); root = parse_resp(); if (root >= 0 && ujson_type(&json, root) == UJSON_OBJECT) { struct msg m; if (msg_from_json(&m, root) == 0) msg_merge(&m, 0); } scroll_to_end(); mark_read(); next_conv_poll = u_ticks_ms() + POLL_CONV_MS; ngui_set_focus(&ui, ID_COMPOSE); } /* ---- browse / new DM ---- */ static void load_picks(int dms) { int st, root, it; npick = 0; ngui_input_set(&filter_in, ""); s_copy(busy, dms ? "Loading people..." : "Loading channels...", sizeof(busy)); paint_now(); st = api(0, dms ? "/api/users" : "/api/channels/public", 0); busy[0] = '\0'; if (!api_ok(st, dms ? "Users" : "Public channels")) return; root = parse_resp(); if (root < 0) return; for (it = ujson_first(&json, root); it >= 0 && npick < MAX_PICK; it = ujson_next(&json, it)) { struct pick *p = &picks[npick]; const char *nm; s_copy(p->id, ujson_get_str(&json, it, "id"), sizeof(p->id)); if (!p->id[0]) continue; p->pic[0] = '\0'; { char url[CHAT_IMG_URL_MAX]; if (chat_pic_url(ujson_get_str(&json, it, "picture"), url, sizeof(url)) == 0) s_copy(p->pic, url, sizeof(p->pic)); } if (dms) { if (strcmp(p->id, me_id) == 0) continue; nm = ujson_get_str(&json, it, "name"); if (!nm[0]) nm = ujson_get_str(&json, it, "username"); to_latin1_line(p->name, sizeof(p->name), nm); to_latin1_line(p->sub, sizeof(p->sub), ujson_get_str(&json, it, "username")); } else { to_latin1_line(p->name, sizeof(p->name), ujson_get_str(&json, it, "name")); to_latin1_line(p->sub, sizeof(p->sub), ujson_get_str(&json, it, "description")); } npick++; } modal = dms ? MODAL_NEWDM : MODAL_BROWSE; modal_scroll.offset = 0; modal_sel = 0; ngui_set_focus(&ui, ID_FILTER); } static void pick_action(int idx) { char path[128], body[96], id[48]; int st, root; if (idx < 0 || idx >= npick) return; if (modal == MODAL_BROWSE) { s_copy(path, "/api/channels/", sizeof(path)); s_cat(path, picks[idx].id, sizeof(path)); s_cat(path, "/join", sizeof(path)); s_copy(busy, "Joining...", sizeof(busy)); paint_now(); st = api("POST", path, 0); busy[0] = '\0'; if (!api_ok(st, "Join")) return; s_copy(id, picks[idx].id, sizeof(id)); } else { s_copy(body, "{\"userId\":", sizeof(body)); if (ujson_escape(body + strlen(body), sizeof(body) - strlen(body), picks[idx].id) < 0) return; s_cat(body, "}", sizeof(body)); s_copy(busy, "Opening conversation...", sizeof(busy)); paint_now(); st = api("POST", "/api/dms", body); busy[0] = '\0'; if (!api_ok(st, "New DM")) return; root = parse_resp(); s_copy(id, root >= 0 ? ujson_get_str(&json, root, "id") : "", sizeof(id)); } modal = MODAL_NONE; if (load_directory() == 0 && id[0]) { int k = conv_find(id); if (k >= 0) open_conv(k); } } /* ---- session ---- */ static void enter_main(void) { int root; screen = SCR_MAIN; offline = 0; backoff_ms = 0; root = parse_resp(); /* the /api/me reply */ if (root >= 0) { const char *nm = ujson_get_str(&json, root, "name"); s_copy(me_id, ujson_get_str(&json, root, "id"), sizeof(me_id)); to_latin1_line(me_name, sizeof(me_name), nm[0] ? nm : ujson_get_str(&json, root, "username")); } set_status("Connected", 0, 0); if (load_directory() == 0 && nconv > 0 && cur < 0) { int i, pick = 0; for (i = 0; i < nconv; i++) { if (convs[i].kind != 'd' && strcmp(convs[i].name, "general") == 0) { pick = i; break; } } open_conv(pick); } next_dir_poll = u_ticks_ms() + POLL_DIR_MS; ngui_set_focus(&ui, ID_COMPOSE); } static void go_login(const char *why) { net_drop(); uhttp_jar_clear(&jar); saved_jar_changes = jar.changes; saved_cookie[0] = '\0'; chat_media_clear(); screen = SCR_SERVER; modal = MODAL_NONE; clear_messages(); nconv = 0; cur = -1; cur_id[0] = '\0'; set_status(why, 0, why != 0); ngui_set_focus(&ui, ID_SERVER); } /* After the jar holds a session: validate it with /api/me. */ static int check_session(int keep_offline) { unsigned int len = 0; int r; s_copy(busy, "Checking session...", sizeof(busy)); paint_now(); r = chat_session_check(&http, &jar, server, resp, RESP_CAP, &len); busy[0] = '\0'; resp_len = len; if (r == 0) { save_config(); enter_main(); return 0; } if (r == 1) { go_login("The saved session is no longer valid - sign in again"); return -1; } if (keep_offline) { /* Network trouble: keep the cached session and retry. */ screen = SCR_MAIN; offline = 1; backoff_ms = 5000; retry_at = u_ticks_ms() + backoff_ms; set_status("Offline: ", r < 0 && r > -100 ? uhttp_error_string(r) : "server error", 1); return -1; } set_status("Session check failed: ", r < 0 && r > -100 ? uhttp_error_string(r) : "server error", 1); return -1; } static void start_login(void) { int r; if (set_server(server_in.text) != 0) { set_status("Enter a server such as chat.example.com", 0, 1); return; } if (cfg_in.text[0]) s_copy(cfg_path, cfg_in.text, sizeof(cfg_path)); uhttp_jar_clear(&jar); s_copy(busy, "Contacting the server...", sizeof(busy)); paint_now(); r = chat_login_start(&login, &http, &jar, server, resp, RESP_CAP); busy[0] = '\0'; net_drop(); if (r == CHAT_LOGIN_OK) { resp_len = (unsigned int)strlen(resp); save_config(); enter_main(); return; } if (r == CHAT_LOGIN_FORM) { screen = SCR_CRED; set_status("", 0, 0); ngui_set_focus(&ui, user_in.len ? ID_PASS : ID_USER); return; } if (r == CHAT_LOGIN_NOFORM) { screen = SCR_COOKIE; set_status(login.error, 0, 1); ngui_set_focus(&ui, ID_COOKIE); return; } set_status(login.error, 0, 1); } static void wipe_secrets(void) { memset(pass_in.text, 0, sizeof(pass_in.text)); pass_in.len = pass_in.cursor = pass_in.anchor = pass_in.scroll = 0; memset(totp_in.text, 0, sizeof(totp_in.text)); totp_in.len = totp_in.cursor = totp_in.anchor = totp_in.scroll = 0; } static void submit_login(int with_totp) { int r; if (!user_in.text[0] || !pass_in.text[0]) { set_status("Enter the username and password", 0, 1); return; } s_copy(busy, "Signing in...", sizeof(busy)); paint_now(); r = chat_login_submit(&login, &http, &jar, user_in.text, pass_in.text, with_totp ? totp_in.text : "", resp, RESP_CAP); busy[0] = '\0'; net_drop(); if (r == CHAT_LOGIN_TOTP) { if (with_totp) { set_status("The code was not accepted", 0, 1); } else { screen = SCR_TOTP; set_status("", 0, 0); } ngui_set_focus(&ui, ID_TOTP); return; } if (r == CHAT_LOGIN_OK) { wipe_secrets(); resp_len = (unsigned int)strlen(resp); save_config(); enter_main(); return; } if (r == CHAT_LOGIN_DENIED && screen == SCR_TOTP) { /* A wrong TOTP code is also a 401. */ set_status(login.error, 0, 1); ngui_input_set(&totp_in, ""); return; } if (r == CHAT_LOGIN_DENIED) { memset(pass_in.text, 0, sizeof(pass_in.text)); ngui_input_set(&pass_in, ""); ngui_set_focus(&ui, ID_PASS); } if (r == CHAT_LOGIN_PASSKEY || r == CHAT_LOGIN_ERROR) wipe_secrets(); if (r == CHAT_LOGIN_PASSKEY) screen = SCR_COOKIE; set_status(login.error, 0, 1); } static void use_cookie(void) { if (set_server(server_in.text) != 0) { set_status("Enter a server such as chat.example.com", 0, 1); return; } if (cfg_in.text[0]) s_copy(cfg_path, cfg_in.text, sizeof(cfg_path)); uhttp_jar_clear(&jar); { const char *c = cookie_in.text; /* Accept a pasted "Cookie: ..." header too. */ if (strncmp(c, "Cookie:", 7) == 0 || strncmp(c, "cookie:", 7) == 0) c += 7; if (uhttp_jar_import(&jar, server_host, server_secure, c) <= 0) { set_status("Paste the cookie as name=value", 0, 1); return; } } check_session(0); if (screen == SCR_MAIN) ngui_input_set(&cookie_in, ""); } static void sign_out(void) { /* Best effort: end the server session too. */ if (server[0]) { s_copy(busy, "Signing out...", sizeof(busy)); paint_now(); api(0, "/auth/logout", 0); busy[0] = '\0'; } go_login("Signed out"); { static char out[CHAT_SERVER_MAX + 80]; int n = chat_config_format(out, sizeof(out), server, ""); if (n > 0) write_file(cfg_path, out, (unsigned int)n); } } static void load_config(void) { static char buf[CHAT_COOKIE_MAX + CHAT_SERVER_MAX + 256]; char srv[CHAT_SERVER_MAX]; int n, migrated = 0; n = read_file(cfg_path, buf, sizeof(buf)); /* First start on a persistent volume: carry a session that an older * build saved in /share into /data once. */ if (n <= 0 && cfg_is_default && strcmp(cfg_path, DEFAULT_CFG_DATA) == 0) { n = read_file(DEFAULT_CFG_SHARE, buf, sizeof(buf)); migrated = n > 0; } ngui_input_set(&cfg_in, cfg_path); if (n <= 0 || chat_config_parse(buf, (unsigned int)n, srv, sizeof(srv), saved_cookie, sizeof(saved_cookie)) != 0) { ngui_input_set(&server_in, "chat.cloudron.io"); saved_cookie[0] = '\0'; memset(buf, 0, sizeof(buf)); return; } memset(buf, 0, sizeof(buf)); ngui_input_set(&server_in, srv); if (set_server(srv) != 0 || !saved_cookie[0]) return; uhttp_jar_import(&jar, server_host, server_secure, saved_cookie); saved_jar_changes = jar.changes; if (migrated) save_config(); check_session(1); } /* ---- text layout ---- */ static int line_h(void) { int h = ngui_text_line_height(&ui, ui.font_px, 0); return h > 0 ? h : 16; } static int text_w(const char *s, unsigned int n, int bold) { return (int)ngui_text_width_px(&ui, s, n, ui.font_px, bold, 0, 0); } /* Length of the next wrapped line of s (n bytes) for width maxw; *adv gets * the bytes to skip to the next line. */ static unsigned int wrap_line(const char *s, unsigned int n, int maxw, unsigned int *adv) { unsigned int i = 0, end = 0, j; if (n && s[0] == '\n') { *adv = 1; return 0; } for (;;) { j = i; while (j < n && s[j] == ' ') j++; while (j < n && s[j] != ' ' && s[j] != '\n') j++; if (j == i) break; if (text_w(s, j, 0) > maxw) { if (end == 0) { /* One word wider than the line: split it. */ unsigned int k = 1; while (k < j && text_w(s, k + 1, 0) <= maxw) k++; *adv = k; return k; } break; } end = j; i = j; if (j >= n || s[j] == '\n') break; } *adv = end; while (*adv < n && s[*adv] == ' ') (*adv)++; if (*adv < n && s[*adv] == '\n') (*adv)++; return end; } static int count_lines(const char *s, int maxw) { unsigned int n = (unsigned int)strlen(s), pos = 0, adv; int lines = 0; if (!n) return 0; while (pos < n) { wrap_line(s + pos, n - pos, maxw, &adv); if (!adv) adv = 1; pos += adv; lines++; } return lines; } #define AVATAR 32 #define TEXT_X 52 #define PAD_TOP 8 #define PAD_GROUP 2 static int same_day(const struct msg *a, const struct msg *b) { return strncmp(a->created, b->created, 10) == 0; } static int same_group(const struct msg *a, const struct msg *b) { unsigned int ta, tb; if (strcmp(a->user_id, b->user_id) != 0 || !same_day(a, b) || b->reply[0] || b->action) return 0; /* HH:MM at offsets 11..15: within five minutes */ ta = (unsigned int)atoi(a->created + 11) * 60 + (unsigned int)atoi(a->created + 14); tb = (unsigned int)atoi(b->created + 11) * 60 + (unsigned int)atoi(b->created + 14); return tb >= ta && tb - ta <= 5; } static void layout_msg(int i, int width) { struct msg *m = &msgs[i]; int lh = line_h(), h, tw = width - TEXT_X - 12; int k; if (tw < 40) tw = 40; m->day_header = i == 0 || !same_day(&msgs[i - 1], m); m->compact = i > 0 && !m->day_header && same_group(&msgs[i - 1], m); h = m->compact ? PAD_GROUP : PAD_TOP + lh + 2; if (m->day_header) h += lh + 12; if (m->reply[0]) h += lh + 2; h += count_lines(m->body, tw) * lh; for (k = 0; k < m->nimg; k++) { int dw, dh, state; unsigned int scale; chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale, &state); h += dh + 6; } if (m->extra[0]) h += lh + 2; h += 2; if (!m->compact && h < PAD_TOP + AVATAR + 4) h = PAD_TOP + AVATAR + 4; m->height = h; m->layout_w = width; } static int tl_width; static unsigned int laid_gen; static int laid_font = -1; /* Heights depend on the width, the font and the neighbours (grouping and * day headers), so any change re-lays out every message. */ static int content_height(void) { int i, h = has_older || history_full ? 36 : 8; int all = laid_gen != msgs_gen || laid_font != line_h(); for (i = 0; i < nmsg; i++) { if (all || msgs[i].layout_w != tl_width) layout_msg(i, tl_width); h += msgs[i].height; } laid_gen = msgs_gen; laid_font = line_h(); return h + 8; } /* ---- drawing helpers ---- */ static unsigned short avatar_color(const char *id) { static const unsigned short pal[] = { NGUI_RGB(0xd0, 0x5a, 0x5a), NGUI_RGB(0x5a, 0x9a, 0xd0), NGUI_RGB(0x5a, 0xb0, 0x70), NGUI_RGB(0xc0, 0x8a, 0x3a), NGUI_RGB(0x9a, 0x6a, 0xc8), NGUI_RGB(0x3a, 0xa8, 0xa8), NGUI_RGB(0xc8, 0x6a, 0xa0), NGUI_RGB(0x80, 0x90, 0x40), }; unsigned int h = 0; while (*id) h = h * 31 + (unsigned char)*id++; return pal[h % (sizeof(pal) / sizeof(pal[0]))]; } static void draw_avatar(int x, int y, int size, const char *name, const char *id, const char *pic) { struct ngui_rect r = { x, y, size, size }; char ini[2]; int tw; ngui_fill_round_rect(&ui, r, size / 2, size / 2, size / 2, size / 2, avatar_color(id)); if (chat_avatar_draw(pic, x, y, size, avatar_color(id))) return; ini[0] = name[0] ? name[0] : '?'; if (ini[0] >= 'a' && ini[0] <= 'z') ini[0] = (char)(ini[0] - 'a' + 'A'); ini[1] = '\0'; tw = text_w(ini, 1, 1); ngui_text_px(&ui, x + (size - tw) / 2, y + (size - line_h()) / 2, ini, 1, NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0); } static void draw_dot(int x, int y, int d, unsigned short color, int filled) { struct ngui_rect r = { x, y, d, d }; if (filled) ngui_fill_round_rect(&ui, r, d / 2, d / 2, d / 2, d / 2, color); else ngui_frame_round(&ui, r, d / 2, d / 2, d / 2, d / 2, 1, color); } static void draw_badge(int right, int y, int count) { char num[12] = ""; int tw, w; struct ngui_rect r; if (count > 99) s_copy(num, "99+", sizeof(num)); else s_cat_uint(num, (unsigned int)count, sizeof(num)); tw = text_w(num, (unsigned int)strlen(num), 1); w = tw + 12; r.x = right - w; r.y = y; r.w = w; r.h = line_h() + 2; ngui_fill_round_rect(&ui, r, r.h / 2, r.h / 2, r.h / 2, r.h / 2, ui.theme.accent); ngui_text_px(&ui, r.x + 6, y + 1, num, (unsigned int)strlen(num), NGUI_RGB(0xff, 0xff, 0xff), ui.font_px, 1, 0, 0); } static void draw_lock(int x, int y, unsigned short c) { struct ngui_rect body = { x, y + 5, 9, 7 }; struct ngui_rect shackle = { x + 2, y + 1, 5, 6 }; ngui_frame_round(&ui, shackle, 2, 2, 0, 0, 1, c); ngui_fill_rect(&ui, body, c); } static void label(struct ngui_rect *body, const char *text) { struct ngui_rect r = ngui_cut_top(body, 20); ngui_text(&ui, r.x, r.y + 2, text, ui.theme.text_dim); } /* ---- login screens ---- */ static struct ngui_rect card_rect(int h) { struct ngui_rect r; int w = ui.w - 40 < 460 ? ui.w - 40 : 460; if (w < 200) w = ui.w; r.w = w; r.h = h; r.x = (ui.w - w) / 2; r.y = (ui.h - h) / 2 > 10 ? (ui.h - h) / 2 : 10; return r; } static void field(struct ngui_rect *body, const char *text, unsigned int id, struct ngui_input *in, unsigned int next_id, int submit_act) { int r; label(body, text); r = ngui_text_input(&ui, id, ngui_cut_top(body, 30), in); ngui_cut_top(body, 8); if (r & NGUI_INPUT_NEXT) ngui_set_focus(&ui, next_id); if ((r & NGUI_INPUT_SUBMIT) && submit_act) action = submit_act; } static void draw_status_line(struct ngui_rect *body) { struct ngui_rect r = ngui_cut_top(body, 22); if (busy[0]) ngui_text_ellipsis(&ui, r, r.x, r.y + 2, busy, ui.theme.accent); else if (status[0]) ngui_text_ellipsis(&ui, r, r.x, r.y + 2, status, status_err ? ui.theme.error : ui.theme.text_dim); } static void notice(struct ngui_rect *body, const char *text) { struct ngui_rect r = ngui_cut_top(body, 18); ngui_text_ellipsis(&ui, r, r.x, r.y, text, ui.theme.text_dim); } static void draw_login(void) { struct ngui_rect all = { 0, 0, ui.w, ui.h }; struct ngui_rect card, body, r, b; int h = screen == SCR_SERVER ? 380 : screen == SCR_COOKIE ? 400 : screen == SCR_TOTP ? 250 : 300; ngui_fill_rect(&ui, all, ui.theme.bg); card = card_rect(h); ngui_fill_rect(&ui, card, ui.theme.panel); ngui_frame(&ui, card, ui.theme.border); body = card; ngui_inset(&body, 18); r = ngui_cut_top(&body, 30); ngui_text_px(&ui, r.x, r.y, "NebOS Chat", 10, ui.theme.text, 22, 1, 0, 0); if (screen == SCR_SERVER) { field(&body, "Server", ID_SERVER, &server_in, ID_CFG, ACT_START_LOGIN); field(&body, "Config file (session cookie, RAM-only on /share)", ID_CFG, &cfg_in, ID_SERVER, ACT_START_LOGIN); r = ngui_cut_top(&body, 32); b = ngui_cut_left(&r, 110); if (ngui_button(&ui, ID_SIGNIN, b, "Sign in")) action = ACT_START_LOGIN; ngui_cut_left(&r, 10); b = ngui_cut_left(&r, 170); if (ngui_button(&ui, ID_COOKIE_MODE, b, "Paste a cookie...")) action = ACT_COOKIE_SCREEN; ngui_cut_top(&body, 8); draw_status_line(&body); notice(&body, "TLS certificates are not verified: only sign in"); notice(&body, "on a trusted network. Passkeys and external SSO"); notice(&body, "are not supported (use the cookie option)."); } else if (screen == SCR_CRED || screen == SCR_TOTP) { r = ngui_cut_top(&body, 22); { char t[160]; s_copy(t, "Sign in to ", sizeof(t)); s_cat(t, login.app_name[0] ? login.app_name : "Chat", sizeof(t)); s_cat(t, " at ", sizeof(t)); s_cat(t, server_host, sizeof(t)); ngui_text_ellipsis(&ui, r, r.x, r.y, t, ui.theme.text_dim); } if (screen == SCR_CRED) { field(&body, "Username or email", ID_USER, &user_in, ID_PASS, ACT_SUBMIT); field(&body, "Password", ID_PASS, &pass_in, ID_USER, ACT_SUBMIT); } else { field(&body, "Two-factor code (authenticator app)", ID_TOTP, &totp_in, ID_TOTP, ACT_SUBMIT_TOTP); } r = ngui_cut_top(&body, 32); b = ngui_cut_left(&r, 110); if (ngui_button(&ui, ID_SIGNIN, b, "Sign in")) action = screen == SCR_TOTP ? ACT_SUBMIT_TOTP : ACT_SUBMIT; ngui_cut_left(&r, 10); b = ngui_cut_left(&r, 90); if (ngui_button(&ui, ID_BACK, b, "Back")) action = ACT_BACK; ngui_cut_top(&body, 8); draw_status_line(&body); notice(&body, "The password is sent over unverified TLS and"); notice(&body, "is never stored."); } else { field(&body, "Server", ID_SERVER, &server_in, ID_COOKIE, ACT_USE_COOKIE); field(&body, "Session cookie (e.g. connect.sid=s%3A...)", ID_COOKIE, &cookie_in, ID_CFG, ACT_USE_COOKIE); field(&body, "Config file", ID_CFG, &cfg_in, ID_SERVER, ACT_USE_COOKIE); r = ngui_cut_top(&body, 32); b = ngui_cut_left(&r, 130); if (ngui_button(&ui, ID_USE_COOKIE, b, "Use cookie")) action = ACT_USE_COOKIE; ngui_cut_left(&r, 10); b = ngui_cut_left(&r, 90); if (ngui_button(&ui, ID_BACK, b, "Back")) action = ACT_BACK; ngui_cut_top(&body, 8); draw_status_line(&body); notice(&body, "Copy the connect.sid cookie from a signed-in web"); notice(&body, "browser. It is a bearer credential: it is saved"); notice(&body, "in the config file until you sign out."); } } /* ---- main screen ---- */ #define SIDE_ROW 38 #define SIDE_HEAD 26 static void draw_sidebar(struct ngui_rect r) { struct ngui_rect list, btns, b; int y, i, section, row_w, scrolls; int lh = line_h(); ngui_fill_rect(&ui, r, ui.theme.panel); btns = ngui_cut_bottom(&r, 40); ngui_inset(&btns, 6); b = ngui_cut_left(&btns, (btns.w - 6) / 2); if (ngui_button(&ui, ID_BROWSE, b, "Browse")) action = ACT_BROWSE; ngui_cut_left(&btns, 6); if (ngui_button(&ui, ID_NEWDM, btns, "New DM")) action = ACT_NEWDM; list = r; side_scroll.content_h = 2 * SIDE_HEAD + nconv * SIDE_ROW + 8; ngui_scroll_begin(&ui, list, &side_scroll); ngui_scroll_wheel(&ui, list, &side_scroll); scrolls = side_scroll.content_h > side_scroll.view_h; row_w = list.w - (scrolls ? 16 : 0); y = list.y - side_scroll.offset; for (section = 0; section < 2; section++) { ngui_text_px(&ui, list.x + 10, y + 6, section ? "DIRECT MESSAGES" : "CHANNELS", section ? 15 : 8, ui.theme.text_dim, 12, 1, 0, 0); y += SIDE_HEAD; for (i = 0; i < nconv; i++) { struct conv *c = &convs[i]; struct ngui_rect row = { list.x, y, row_w, SIDE_ROW - 2 }; int hot, nx, right; if ((c->kind == 'd') != section) continue; hot = ui.inside && ngui_rect_contains(&row, ui.mouse_x, ui.mouse_y) && ngui_rect_contains(&list, ui.mouse_x, ui.mouse_y); if (i == cur) ngui_fill_rect(&ui, row, ui.theme.selection); else if (hot) ngui_fill_rect(&ui, row, ui.theme.panel_alt); if (ui.pressed && modal == MODAL_NONE && ngui_rect_contains(&row, ui.press_x, ui.press_y) && ngui_rect_contains(&list, ui.press_x, ui.press_y)) { action = ACT_OPEN_CONV; action_arg = i; } nx = list.x + 26; if (c->kind == 'd') { unsigned short pc = c->presence == 'o' ? NGUI_RGB(0x40, 0xc0, 0x60) : c->presence == 'a' ? NGUI_RGB(0xe0, 0xb0, 0x30) : ui.theme.text_dim; draw_dot(list.x + 10, y + 6 + (lh - 9) / 2, 9, pc, c->presence != 'f'); } else if (c->kind == 'p') { draw_lock(list.x + 9, y + 4, ui.theme.text_dim); } else { ngui_text(&ui, list.x + 10, y + 4, "#", ui.theme.text_dim); } right = list.x + row_w - 8; if (c->unread > 0) { draw_badge(right, y + 3, c->unread); right -= 40; } { struct ngui_rect nr = { nx, y, right - nx, lh + 6 }; ngui_push_clip(&ui, nr); ngui_text_px(&ui, nx, y + 4, c->name, (unsigned int)strlen(c->name), ui.theme.text, ui.font_px, c->unread > 0, 0, 0); ngui_pop_clip(&ui); } if (c->preview[0]) { struct ngui_rect pr = { nx, y + 4 + lh, list.x + row_w - 8 - nx, lh }; ngui_push_clip(&ui, pr); ngui_text_px(&ui, nx, y + 4 + lh, c->preview, (unsigned int)strlen(c->preview), ui.theme.text_dim, 12, 0, 0, 0); ngui_pop_clip(&ui); } y += SIDE_ROW; } } if (!nconv) ngui_text(&ui, list.x + 10, list.y + SIDE_HEAD + 6, "(none yet)", ui.theme.text_dim); ngui_scroll_end(&ui, list, &side_scroll); } static void draw_message(struct msg *m, int x, int y, int width) { int lh = line_h(), tx = x + TEXT_X, tw = width - TEXT_X - 12; unsigned int n, pos = 0, adv; if (tw < 40) tw = 40; if (m->day_header) { char d[16]; int dw; struct ngui_rect line = { x + 12, y + 6 + lh / 2, width - 24, 1 }; s_copy(d, m->created, 11); dw = text_w(d, (unsigned int)strlen(d), 0); ngui_fill_rect(&ui, line, ui.theme.border); ngui_fill_rect(&ui, (struct ngui_rect){ x + (width - dw) / 2 - 8, y + 4, dw + 16, lh + 4 }, ui.theme.bg); ngui_text(&ui, x + (width - dw) / 2, y + 6, d, ui.theme.text_dim); y += lh + 12; } if (!m->compact) { char tm[8]; int aw; y += PAD_TOP; draw_avatar(x + 10, y, AVATAR, m->author, m->user_id, m->author_pic); ngui_text_px(&ui, tx, y, m->author, (unsigned int)strlen(m->author), ui.theme.text, ui.font_px, 1, 0, 0); aw = text_w(m->author, (unsigned int)strlen(m->author), 1); s_copy(tm, m->created + 11, 6); ngui_text_px(&ui, tx + aw + 10, y, tm, (unsigned int)strlen(tm), ui.theme.text_dim, 12, 0, 0, 0); y += lh + 2; } else { y += PAD_GROUP; } if (m->reply[0]) { struct ngui_rect rr = { tx, y, tw, lh }; ngui_fill_rect(&ui, (struct ngui_rect){ tx, y + 1, 3, lh - 2 }, ui.theme.accent); ngui_text_ellipsis(&ui, rr, tx + 8, y, m->reply, ui.theme.text_dim); y += lh + 2; } n = (unsigned int)strlen(m->body); while (pos < n) { unsigned int len = wrap_line(m->body + pos, n - pos, tw, &adv); if (!adv) adv = 1; ngui_text_px(&ui, tx, y, m->body + pos, len, m->action ? ui.theme.accent : ui.theme.text, ui.font_px, 0, m->action, 0); pos += adv; y += lh; } { int k; for (k = 0; k < m->nimg; k++) { int dw, dh, state; unsigned int scale; chat_image_measure(m->img_url[k], tw, &dw, &dh, &scale, &state); chat_image_draw(m->img_url[k], tx, y, tw); y += dh + 6; } } if (m->extra[0]) { struct ngui_rect er = { tx, y + 2, tw, lh }; ngui_text_ellipsis(&ui, er, tx, y + 2, m->extra, ui.theme.text_dim); } } static void draw_timeline(struct ngui_rect r) { int i, y, total, scrolls, width; int was_bottom; ngui_fill_rect(&ui, r, ui.theme.bg); if (cur < 0) { ngui_text(&ui, r.x + 20, r.y + 20, nconv ? "Select a conversation" : "No conversations yet: browse the public channels", ui.theme.text_dim); return; } tl_width = r.w - 16; total = content_height(); tl_scroll.content_h = total; ngui_scroll_begin(&ui, r, &tl_scroll); if (ngui_scroll_wheel(&ui, r, &tl_scroll)) last_input_ms = u_ticks_ms(); scrolls = total > r.h; width = r.w - (scrolls ? 16 : 0); if (width != tl_width) { tl_width = width; total = content_height(); tl_scroll.content_h = total; } /* Scrolling to the very top pages in older history by itself (the * button stays for the pointer). Rate-limited so a failing request * cannot spin. */ if (has_older && !history_full && scrolls && tl_scroll.offset <= 0 && !offline && (unsigned int)(u_ticks_ms() - last_older_ms) > 1500) action = ACT_OLDER; was_bottom = tl_scroll.offset >= total - r.h - 4; at_bottom = was_bottom || !scrolls; if (at_bottom) new_below = 0; y = r.y - tl_scroll.offset; if (has_older || history_full) { struct ngui_rect b = { r.x + (width - 200) / 2, y + 4, 200, 28 }; if (history_full) { ngui_text(&ui, b.x + 4, b.y + 6, "History limit reached", ui.theme.text_dim); } else if (b.y + b.h > r.y && (!ui.pressed || ngui_rect_contains(&r, ui.press_x, ui.press_y))) { if (ngui_button(&ui, ID_OLDER, b, "Load older messages")) action = ACT_OLDER; } y += 36; } else { y += 8; } for (i = 0; i < nmsg; i++) { struct msg *m = &msgs[i]; if (y + m->height > r.y && y < r.y + r.h) draw_message(m, r.x, y, width); y += m->height; } if (!nmsg) ngui_text(&ui, r.x + 20, r.y + 50, "No messages yet - say hello!", ui.theme.text_dim); ngui_scroll_end(&ui, r, &tl_scroll); if (new_below > 0 && !at_bottom) { char t[40] = ""; struct ngui_rect b; s_cat_uint(t, (unsigned int)new_below, sizeof(t)); s_cat(t, new_below == 1 ? " new message" : " new messages", sizeof(t)); b.w = text_w(t, (unsigned int)strlen(t), 0) + 30; b.h = 26; b.x = r.x + (width - b.w) / 2; b.y = r.y + r.h - b.h - 8; if (ngui_button(&ui, ID_NEWMSG, b, t)) scroll_to_end(); } } static int total_unread(void) { int i, n = 0; for (i = 0; i < nconv; i++) n += convs[i].unread > 0 ? convs[i].unread : 0; return n; } static void draw_modal(void) { struct ngui_rect all = { 0, 0, ui.w, ui.h }; struct ngui_rect card, body, r, list; int w = ui.w * 7 / 10, h = ui.h * 8 / 10, i, y, shown = 0, vis; int lh = line_h(); (void)all; if (w < 320) w = ui.w - 20; if (h < 240) h = ui.h - 20; card.w = w; card.h = h; card.x = (ui.w - w) / 2; card.y = (ui.h - h) / 2; ngui_fill_rect(&ui, card, ui.theme.panel); ngui_frame(&ui, card, ui.theme.accent); body = card; ngui_inset(&body, 14); r = ngui_cut_top(&body, 28); ngui_text_px(&ui, r.x, r.y, modal == MODAL_BROWSE ? "Browse public channels" : "New direct message", modal == MODAL_BROWSE ? 22 : 18, ui.theme.text, 18, 1, 0, 0); if (ngui_button(&ui, ID_MODAL_CLOSE, (struct ngui_rect){ r.x + r.w - 80, r.y, 80, 26 }, "Close")) modal = MODAL_NONE; ngui_cut_top(&body, 6); filter_in.placeholder = "Filter... (Up/Down, Enter)"; for (i = 0; i < npick; i++) if (!filter_in.text[0] || strstr(picks[i].name, filter_in.text) || strstr(picks[i].sub, filter_in.text)) shown++; { int k = ngui_key_peek(&ui), fr; if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) { ngui_key(&ui); modal_sel += k == NGUI_KEY_UP ? -1 : 1; } fr = ngui_text_input(&ui, ID_FILTER, ngui_cut_top(&body, 30), &filter_in); if (fr & NGUI_INPUT_CHANGED) { modal_scroll.offset = 0; modal_sel = 0; } if (modal_sel >= shown) modal_sel = shown - 1; if (modal_sel < 0) modal_sel = 0; if ((fr & NGUI_INPUT_SUBMIT) && shown) { int vis = 0; for (i = 0; i < npick; i++) { if (filter_in.text[0] && !strstr(picks[i].name, filter_in.text) && !strstr(picks[i].sub, filter_in.text)) continue; if (vis++ == modal_sel) { action = modal == MODAL_BROWSE ? ACT_JOIN : ACT_OPEN_DM; action_arg = i; break; } } ngui_set_focus(&ui, ID_FILTER); } if ((fr & NGUI_INPUT_CANCEL) && !(fr & NGUI_INPUT_NEXT)) modal = MODAL_NONE; } ngui_cut_top(&body, 8); list = body; ngui_fill_rect(&ui, list, ui.theme.bg); modal_scroll.content_h = shown * 44; ngui_scroll_begin(&ui, list, &modal_scroll); ngui_scroll_wheel(&ui, list, &modal_scroll); y = list.y - modal_scroll.offset; vis = 0; for (i = 0; i < npick; i++) { struct pick *p = &picks[i]; struct ngui_rect row, b; if (filter_in.text[0] && !strstr(p->name, filter_in.text) && !strstr(p->sub, filter_in.text)) continue; if (vis++ == modal_sel) { if (y < list.y) modal_scroll.offset -= list.y - y; else if (y + 44 > list.y + list.h) modal_scroll.offset += y + 44 - list.y - list.h; y = list.y + (vis - 1) * 44 - modal_scroll.offset; ngui_fill_rect(&ui, (struct ngui_rect){ list.x, y, list.w - 16, 43 }, ui.theme.selection); } row.x = list.x; row.y = y; row.w = list.w - 16; row.h = 42; if (y + 44 > list.y && y < list.y + list.h) { ngui_fill_rect(&ui, (struct ngui_rect){ row.x, y + 43, row.w, 1 }, ui.theme.border); if (modal == MODAL_NEWDM) draw_avatar(row.x + 8, y + 6, 30, p->name, p->id, p->pic); ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y, row.w - 160, lh + 4 }, row.x + 48, y + 4, p->name, ui.theme.text); ngui_text_ellipsis(&ui, (struct ngui_rect){ row.x + 48, y + 4 + lh, row.w - 160, lh }, row.x + 48, y + 4 + lh, p->sub, ui.theme.text_dim); if (modal == MODAL_BROWSE) ngui_text(&ui, row.x + 14, y + 12, "#", ui.theme.text_dim); b.x = row.x + row.w - 100; b.y = y + 8; b.w = 92; b.h = 26; if ((!ui.pressed || ngui_rect_contains(&list, ui.press_x, ui.press_y)) && ngui_button(&ui, ID_MODAL_ROW + (unsigned int)i, b, modal == MODAL_BROWSE ? "Join" : "Message")) { action = modal == MODAL_BROWSE ? ACT_JOIN : ACT_OPEN_DM; action_arg = i; } } y += 44; } if (!shown) ngui_text(&ui, list.x + 12, list.y + 12, npick ? "Nothing matches the filter" : modal == MODAL_BROWSE ? "You are in every public channel" : "Nobody else here", ui.theme.text_dim); ngui_scroll_end(&ui, list, &modal_scroll); } /* Keyboard shortcuts, handled before the composer swallows the keys: * PgUp/PgDn scroll the timeline; Ctrl+B browse, Ctrl+N new DM, Ctrl+R * refresh. With the composer unfocused (Esc): Up/Down switch conversations, * Home/End jump in the timeline, and typing refocuses the composer. */ static void main_keys(void) { for (;;) { int k = ngui_key_peek(&ui); if (!k) return; if (k == NGUI_KEY_PAGE_UP || k == NGUI_KEY_PAGE_DOWN) { ngui_scroll_keys(&ui, &tl_scroll); continue; } if (k == 0x02 || k == 0x0E || k == 0x12) { ngui_key(&ui); action = k == 0x02 ? ACT_BROWSE : k == 0x0E ? ACT_NEWDM : ACT_REFRESH; return; } if (ui.focus) return; if (k == NGUI_KEY_HOME) { ngui_key(&ui); tl_scroll.offset = 0; } else if (k == NGUI_KEY_END) { ngui_key(&ui); scroll_to_end(); } else if (k == NGUI_KEY_UP || k == NGUI_KEY_DOWN) { int order[MAX_CONV], n = 0, i, pos = -1, sec; ngui_key(&ui); /* Sidebar order: channels first, then DMs. */ for (sec = 0; sec < 2; sec++) for (i = 0; i < nconv; i++) if ((convs[i].kind == 'd') == sec) { if (i == cur) pos = n; order[n++] = i; } if (!n) continue; pos = pos < 0 ? 0 : k == NGUI_KEY_UP ? (pos > 0 ? pos - 1 : 0) : (pos + 1 < n ? pos + 1 : n - 1); if (order[pos] != cur) { action = ACT_OPEN_CONV; action_arg = order[pos]; return; } } else if (k >= 0x20 && k <= 0x7E && cur >= 0) { ngui_set_focus(&ui, ID_COMPOSE); return; } else { return; } } } static void draw_main(void) { struct ngui_rect all = { 0, 0, ui.w, ui.h }; struct ngui_rect top, side, bottom, comp, stat, b, tl; int side_w = ui.w / 4; char t[200]; unsigned int saved_pressed = ui.pressed; /* Nothing under an open modal reacts to the pointer. */ if (modal != MODAL_NONE) ui.pressed = 0; if (side_w < 150) side_w = 150; if (side_w > 260) side_w = 260; ngui_fill_rect(&ui, all, ui.theme.bg); /* top bar */ top = ngui_cut_top(&all, 38); ngui_fill_rect(&ui, top, ui.theme.panel_alt); ngui_fill_rect(&ui, (struct ngui_rect){ top.x, top.y + top.h - 1, top.w, 1 }, ui.theme.border); { struct ngui_rect tb = top; ngui_inset(&tb, 6); b = ngui_cut_right(&tb, 86); if (ngui_button(&ui, ID_SIGNOUT, b, "Sign out")) action = ACT_SIGNOUT; ngui_cut_right(&tb, 6); b = ngui_cut_right(&tb, 80); if (ngui_button(&ui, ID_REFRESH, b, "Refresh")) action = ACT_REFRESH; t[0] = '\0'; if (cur >= 0) { s_cat(t, convs[cur].kind == 'd' ? "@ " : "# ", sizeof(t)); s_cat(t, convs[cur].name, sizeof(t)); } else { s_cat(t, "Chat", sizeof(t)); } ngui_cut_right(&tb, 10); ngui_push_clip(&ui, tb); ngui_text_px(&ui, tb.x + 4, tb.y + (tb.h - 20) / 2, t, (unsigned int)strlen(t), ui.theme.text, 18, 1, 0, 0); ngui_pop_clip(&ui); } if (modal == MODAL_NONE) { /* A closed modal leaves its filter focused: hand the keyboard * back to the composer. */ if (ui.focus == ID_FILTER) ngui_set_focus(&ui, cur >= 0 ? ID_COMPOSE : 0); main_keys(); } /* bottom: composer + status bar */ bottom = ngui_cut_bottom(&all, 70); ngui_fill_rect(&ui, bottom, ui.theme.panel); ngui_fill_rect(&ui, (struct ngui_rect){ bottom.x, bottom.y, bottom.w, 1 }, ui.theme.border); stat = ngui_cut_bottom(&bottom, 24); comp = bottom; ngui_inset(&comp, 7); b = ngui_cut_right(&comp, 80); compose_in.disabled = cur < 0; compose_in.placeholder = cur < 0 ? "" : "Type a message..."; if (ngui_text_input(&ui, ID_COMPOSE, (struct ngui_rect){ comp.x, comp.y, comp.w - 8, comp.h }, &compose_in) & NGUI_INPUT_SUBMIT) action = ACT_SEND; if (ngui_button(&ui, ID_SEND, b, "Send") && cur >= 0) action = ACT_SEND; ngui_fill_rect(&ui, stat, ui.theme.panel_alt); { struct ngui_rect sr = stat; int un = total_unread(); ngui_inset(&sr, 3); if (offline) { b = ngui_cut_right(&sr, 70); if (ngui_button(&ui, ID_RETRY, b, "Retry")) action = ACT_RETRY; } t[0] = '\0'; if (busy[0]) { s_cat(t, busy, sizeof(t)); } else { s_cat(t, status[0] ? status : "Connected", sizeof(t)); if (offline && retry_at) { int left = (int)(retry_at - u_ticks_ms()); if (left > 0) { s_cat(t, " (retry in ", sizeof(t)); s_cat_uint(t, (unsigned int)(left + 999) / 1000, sizeof(t)); s_cat(t, " s)", sizeof(t)); } } } s_cat(t, " \xb7 ", sizeof(t)); s_cat(t, server_secure ? "TLS unverified" : "no TLS", sizeof(t)); if (me_name[0]) { s_cat(t, " \xb7 ", sizeof(t)); s_cat(t, me_name, sizeof(t)); } if (un) { s_cat(t, " \xb7 ", sizeof(t)); s_cat_uint(t, (unsigned int)un, sizeof(t)); s_cat(t, " unread", sizeof(t)); } ngui_text_ellipsis(&ui, sr, sr.x + 4, sr.y + 1, t, busy[0] ? ui.theme.accent : (offline || status_err) ? ui.theme.error : ui.theme.text_dim); } side = ngui_cut_left(&all, side_w); ngui_fill_rect(&ui, (struct ngui_rect){ side.x + side.w - 1, side.y, 1, side.h }, ui.theme.border); side.w -= 1; tl = all; if (modal == MODAL_NONE) { draw_sidebar(side); draw_timeline(tl); } else { draw_sidebar(side); draw_timeline(tl); action = ACT_NONE; ui.pressed = saved_pressed; draw_modal(); } } /* ---- frame / main loop ---- */ static void draw(void) { if (screen == SCR_MAIN) draw_main(); else draw_login(); } /* Present a frame now (status text before a blocking network call). */ static void paint_now(void) { int saved_action = action, saved_arg = action_arg; ngui_invalidate(&ui); if (ngui_begin(&ui)) { draw(); ngui_end(&ui); } action = saved_action; action_arg = saved_arg; } static void run_action(void) { int a = action, arg = action_arg; action = ACT_NONE; switch (a) { case ACT_START_LOGIN: start_login(); break; case ACT_SUBMIT: submit_login(0); break; case ACT_SUBMIT_TOTP: submit_login(1); break; case ACT_USE_COOKIE: use_cookie(); break; case ACT_COOKIE_SCREEN: screen = SCR_COOKIE; set_status("", 0, 0); ngui_set_focus(&ui, ID_COOKIE); break; case ACT_BACK: wipe_secrets(); screen = SCR_SERVER; set_status("", 0, 0); ngui_set_focus(&ui, ID_SERVER); break; case ACT_SEND: send_message(); break; case ACT_REFRESH: case ACT_RETRY: backoff_ms = 0; retry_at = 0; chat_media_retry(); s_copy(busy, "Refreshing...", sizeof(busy)); paint_now(); busy[0] = '\0'; if (offline && !me_id[0]) { check_session(1); break; } if (load_directory() == 0) { if (cur >= 0) open_conv(cur); else if (nconv) open_conv(0); } next_dir_poll = u_ticks_ms() + POLL_DIR_MS; break; case ACT_SIGNOUT: sign_out(); break; case ACT_OPEN_CONV: if (arg != cur) open_conv(arg); break; case ACT_OLDER: load_older(); break; case ACT_BROWSE: load_picks(0); break; case ACT_NEWDM: load_picks(1); break; case ACT_JOIN: case ACT_OPEN_DM: pick_action(arg); break; } ngui_invalidate(&ui); } static void poll_tick(void) { unsigned int now = u_ticks_ms(); int focused = ui.focused; if (screen != SCR_MAIN || modal != MODAL_NONE) return; if (offline) { if (retry_at && (int)(now - retry_at) >= 0) { retry_at = 0; action = ACT_RETRY; run_action(); } return; } /* Do not interrupt typing or scrolling. */ if ((unsigned int)(now - last_input_ms) < TYPING_HOLD_MS) return; if ((int)(now - next_dir_poll) >= 0) { load_directory(); next_dir_poll = now + (focused ? POLL_DIR_MS : POLL_DIR_IDLE_MS); next_conv_poll = now; /* follow with the conversation */ } if (cur >= 0 && !offline && (int)(now - next_conv_poll) >= 0) { poll_conv(); next_conv_poll = u_ticks_ms() + (focused ? POLL_CONV_MS : POLL_CONV_IDLE_MS); } /* An open TCP socket pauses the board's net-dev watcher: only keep * the connection while the user is actively chatting. */ if (http.connected && (!focused || (unsigned int)(u_ticks_ms() - last_input_ms) > KEEPALIVE_IDLE_MS) && (unsigned int)(u_ticks_ms() - last_net_ms) > 200) net_drop(); } void _start(const char *arg) { struct win_info wi; unsigned int w = 980, h = 660; resp = (char *)malloc(RESP_CAP); jnodes = (struct ujson_node *)malloc(sizeof(struct ujson_node) * JSON_NODES); jsbuf = (char *)malloc(JSON_SCAP); if (!resp || !jnodes || !jsbuf) { u_puts("chat: out of memory\n"); u_exit(1); } ujson_init(&json, jnodes, JSON_NODES, jsbuf, JSON_SCAP); uhttp_init(&http); http.user_agent = "NebOS-Chat/1.0 (uhttp)"; uhttp_jar_init(&jar); if (u_win_create(w, h, "Chat", &wi) != 0 && u_win_create(w = 780, h = 540, "Chat", &wi) != 0 && u_win_create(w = 600, h = 420, "Chat", &wi) != 0) { u_puts("chat: no graphics window\n"); u_exit(1); } ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height); ngui_font_attach(&ui); server_in.placeholder = "chat.example.com"; user_in.placeholder = "username"; pass_in.secret = 1; totp_in.placeholder = "123456"; cookie_in.placeholder = "connect.sid=..."; if (arg && arg[0]) { s_copy(cfg_path, arg, sizeof(cfg_path)); } else { s_copy(cfg_path, default_cfg_path(), sizeof(cfg_path)); cfg_is_default = 1; } ngui_set_focus(&ui, ID_SERVER); last_input_ms = 0; /* First frame, then the (possibly slow) session check. */ paint_now(); load_config(); for (;;) { int redraw; redraw = ngui_begin(&ui); if (ui.key_head != ui.key_tail || ui.pressed || ui.scroll_y) { last_input_ms = u_ticks_ms(); if (screen == SCR_MAIN && !offline) maybe_save_cookie(); } if (redraw) { draw(); ngui_end(&ui); } else { ngui_end_ex(&ui, 0); } if (action != ACT_NONE) run_action(); else poll_tick(); chat_media_tick(); /* The offline retry countdown needs a once-a-second repaint. */ if (offline && screen == SCR_MAIN) { static unsigned int last_tick; if (u_ticks_ms() - last_tick >= 1000) { last_tick = u_ticks_ms(); ngui_invalidate(&ui); } } u_sleep_ms(10); } }