browser.c 73 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * No JavaScript and no forms; external CSS is loaded over uhttp, and images
  5. * are decoded with img.c and drawn inline. Large buffers (page body and the
  6. * image decode arena) live in the per-process SYS_MEM_ALLOC heap; the DOM and
  7. * the image/CSS I/O scratch use fixed static arenas.
  8. */
  9. #include "ucmd_lib.h"
  10. #include "ngui.h"
  11. #include "browser_html.h"
  12. #include "uhttp.h"
  13. #include "img.h"
  14. #include "inflate.h"
  15. #define BR_W 960
  16. #define BR_H 640
  17. /* CSS media queries are evaluated as a desktop browser. */
  18. #define BR_VIEWPORT_W 1000
  19. #define BR_TOOLBAR_H 30
  20. #define BR_STATUS_H 18
  21. #define BR_HEAP_INIT (6u * 1024u * 1024u)
  22. #define BR_HEAP_MAX (32u * 1024u * 1024u)
  23. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  24. #define BR_IMG_FILE_MAX (512u * 1024u)
  25. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  26. #define BR_MAX_IMAGES 16
  27. #define BR_IMG_ARENA (24u * 1024u * 1024u)
  28. #define BR_IMG_LAYOUT_W 1000
  29. #define BR_CSS_MAX (832u * 1024u)
  30. #define BR_CSS_COMP_MAX (192u * 1024u)
  31. #define BR_MAX_SHEETS 6
  32. #define BR_HISTORY 16
  33. #define BR_URL_MAX 512
  34. #define BR_STATUS_MAX 200
  35. #define BR_IMG_RGB565(r, g, b) \
  36. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  37. #define BR_GRAY 0x8410
  38. enum {
  39. ID_URL = 1,
  40. ID_GO,
  41. ID_BACK,
  42. ID_FORWARD,
  43. ID_RELOAD,
  44. ID_HOME
  45. };
  46. #define ACT_NAV (1u << 0)
  47. #define ACT_BACK (1u << 1)
  48. #define ACT_FORWARD (1u << 2)
  49. #define ACT_RELOAD (1u << 3)
  50. #define ACT_HOME (1u << 4)
  51. #define ACT_CLOSE (1u << 5)
  52. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  53. ACT_HOME | ACT_CLOSE)
  54. struct br_image {
  55. int state; /* 0 empty, 1 ready */
  56. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  57. int native_w, native_h;
  58. char err[32];
  59. };
  60. static struct ngui ui;
  61. static struct ngui_input url_in;
  62. static struct ngui_scroll page_scroll;
  63. static struct br_doc doc;
  64. static struct br_image images[BR_MAX_IMAGES];
  65. static int image_count;
  66. /* Images are loaded one per main-loop iteration so the parsed page stays
  67. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  68. static int preload_active;
  69. static int preload_pending;
  70. static int preload_wait;
  71. static unsigned int preload_node;
  72. static int preload_loaded;
  73. static int preload_scroll;
  74. static char post_status_text[BR_STATUS_MAX];
  75. static int post_status_error;
  76. static unsigned int post_status_ttl;
  77. /* Content-relative position/height of each <img>, recorded by the measure
  78. * pass so image loading can be deferred until it is near the viewport. */
  79. static unsigned short img_top[BR_MAX_NODES];
  80. static unsigned short img_h[BR_MAX_NODES];
  81. static unsigned char *heap;
  82. static unsigned int heap_size = 0;
  83. static unsigned int heap_used = 0;
  84. /* One reusable I/O buffer and one shared decode arena: decoded pixels are
  85. * scaled down to a display bitmap, then the arena is reused for the next
  86. * image. This keeps 4K screenshots inside the 32 MB heap. The two halves
  87. * double as the gzip input scratch for page/CSS fetches, where the heap has
  88. * no room for another multi-megabyte body. */
  89. static unsigned char *image_io_buf;
  90. #define image_file_buf (image_io_buf)
  91. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  92. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  93. static struct inflate image_inflate_ws;
  94. static unsigned char *image_arena;
  95. static unsigned int image_arena_size;
  96. static void *heap_alloc(unsigned int bytes, unsigned int align);
  97. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  98. #error "CSS scratch must fit in image_io_buf"
  99. #endif
  100. static char page_url[BR_URL_MAX];
  101. static char page_title[BR_TITLE_MAX];
  102. static char cwd[64];
  103. static int page_is_local;
  104. static int page_loading;
  105. static char status_text[BR_STATUS_MAX];
  106. static unsigned int status_until;
  107. static int status_error;
  108. static char history[BR_HISTORY][BR_URL_MAX];
  109. static int hist_len, hist_pos;
  110. static char click_url[BR_URL_MAX];
  111. static char pending_url[BR_URL_MAX];
  112. static unsigned int pending_action;
  113. static int cancel_fetch;
  114. static int quit;
  115. static struct ngui_rect page_rect;
  116. /* layout output */
  117. struct lay_run {
  118. unsigned short off, len;
  119. unsigned short gap;
  120. unsigned short color;
  121. unsigned short href;
  122. char lit[28];
  123. short img;
  124. unsigned short iw, ih;
  125. unsigned char scale, bold, underline;
  126. unsigned char has_lit;
  127. };
  128. struct lay {
  129. int draw;
  130. struct ngui *ui;
  131. int left, right;
  132. int y;
  133. int line_x, line_y, line_h;
  134. int run_x;
  135. int align;
  136. int depth;
  137. int space_pending;
  138. struct lay_run runs[96];
  139. int nruns;
  140. };
  141. struct hit {
  142. int x, y, w, h;
  143. unsigned short node;
  144. };
  145. #define HIT_MAX 96
  146. static struct hit hits[HIT_MAX];
  147. static int nhits;
  148. static unsigned short block_h[BR_MAX_NODES];
  149. static char li_marker[BR_MAX_NODES][6];
  150. /* one connection object; the browser fetches one resource at a time */
  151. /* ---- tiny strings ---- */
  152. static unsigned int s_len(const char *s)
  153. {
  154. unsigned int n = 0;
  155. while (s && s[n])
  156. n++;
  157. return n;
  158. }
  159. static void s_copy(char *d, const char *s, unsigned int cap)
  160. {
  161. unsigned int i = 0;
  162. if (!cap)
  163. return;
  164. while (s && s[i] && i + 1 < cap) {
  165. d[i] = s[i];
  166. i++;
  167. }
  168. d[i] = '\0';
  169. }
  170. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  171. {
  172. while (s && *s && *n + 1 < cap)
  173. d[(*n)++] = *s++;
  174. d[*n] = '\0';
  175. }
  176. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  177. unsigned int cap)
  178. {
  179. char tmp[12];
  180. unsigned int i = 0, j;
  181. do {
  182. tmp[i++] = (char)('0' + v % 10);
  183. v /= 10;
  184. } while (v && i < sizeof(tmp));
  185. for (j = 0; j < i && *n + 1 < cap; j++)
  186. d[(*n)++] = tmp[i - 1 - j];
  187. d[*n] = '\0';
  188. }
  189. static int s_eq(const char *a, const char *b)
  190. {
  191. while (*a && *b) {
  192. if (*a != *b)
  193. return 0;
  194. a++;
  195. b++;
  196. }
  197. return *a == *b;
  198. }
  199. static int starts_with(const char *s, const char *p)
  200. {
  201. unsigned int i = 0;
  202. while (p[i]) {
  203. if (s[i] != p[i])
  204. return 0;
  205. i++;
  206. }
  207. return 1;
  208. }
  209. static int contains_ci(const char *s, const char *p)
  210. {
  211. unsigned int i, j;
  212. for (i = 0; s[i]; i++) {
  213. for (j = 0; p[j]; j++) {
  214. char a = s[i + j];
  215. if (a >= 'A' && a <= 'Z')
  216. a = (char)(a - 'A' + 'a');
  217. if (a != p[j])
  218. break;
  219. }
  220. if (!p[j])
  221. return 1;
  222. }
  223. return 0;
  224. }
  225. static char *trim(char *s)
  226. {
  227. unsigned int n;
  228. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  229. s++;
  230. n = s_len(s);
  231. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  232. s[n - 1] == '\r' || s[n - 1] == '\n'))
  233. s[--n] = '\0';
  234. return s;
  235. }
  236. /* ---- per-process heap ---- */
  237. static int heap_start(void)
  238. {
  239. heap = (unsigned char *)u_mem_alloc(BR_HEAP_INIT);
  240. if (!heap) {
  241. heap_size = heap_used = 0;
  242. return -1;
  243. }
  244. heap_size = BR_HEAP_INIT;
  245. heap_used = 0;
  246. image_io_buf = (unsigned char *)heap_alloc(2u * BR_IMG_FILE_MAX, 16);
  247. if (!image_io_buf) {
  248. heap_size = heap_used = 0;
  249. return -1;
  250. }
  251. return 0;
  252. }
  253. static void heap_clear(void)
  254. {
  255. u_mem_free();
  256. heap = 0;
  257. heap_size = heap_used = 0;
  258. image_io_buf = 0;
  259. image_arena = 0;
  260. image_arena_size = 0;
  261. }
  262. static void *heap_alloc(unsigned int bytes, unsigned int align)
  263. {
  264. unsigned int start, want;
  265. if (!heap || bytes == 0)
  266. return 0;
  267. if (align < 1)
  268. align = 1;
  269. if (align & (align - 1))
  270. return 0;
  271. start = (heap_used + align - 1) & ~(align - 1);
  272. if (start > BR_HEAP_MAX || bytes > BR_HEAP_MAX - start)
  273. return 0;
  274. if (start + bytes > heap_size) {
  275. want = heap_size ? heap_size : BR_HEAP_INIT;
  276. while (want < start + bytes) {
  277. if (want > BR_HEAP_MAX / 2) {
  278. want = BR_HEAP_MAX;
  279. break;
  280. }
  281. want *= 2;
  282. }
  283. if (want < start + bytes || want > BR_HEAP_MAX)
  284. return 0;
  285. if (u_mem_grow(want) != 0)
  286. return 0;
  287. heap_size = want;
  288. }
  289. heap_used = start + bytes;
  290. return heap + start;
  291. }
  292. /* ---- status ---- */
  293. static void set_status(const char *s, int err, unsigned int ttl_ms)
  294. {
  295. s_copy(status_text, s, sizeof(status_text));
  296. status_error = err;
  297. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  298. ngui_invalidate(&ui);
  299. }
  300. /* ---- images ---- */
  301. static void image_reset(void)
  302. {
  303. int i;
  304. for (i = 0; i < BR_MAX_IMAGES; i++) {
  305. images[i].state = 0;
  306. images[i].native_w = images[i].native_h = 0;
  307. images[i].err[0] = '\0';
  308. }
  309. image_count = 0;
  310. preload_active = 0;
  311. preload_pending = 0;
  312. preload_wait = 0;
  313. preload_node = 0;
  314. preload_loaded = 0;
  315. }
  316. /* Decode into the shared arena, then copy/scale the result into a display
  317. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  318. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  319. * pixels. Transparent edges are composited over white. */
  320. static int decode_image_data(const unsigned char *data, unsigned int len,
  321. struct br_image *bi)
  322. {
  323. struct img_info info;
  324. struct img_options opt;
  325. struct img_mem mem;
  326. struct img_image decoded;
  327. unsigned int est, bytes, i;
  328. unsigned short *px;
  329. int dw, dh, r;
  330. if (img_sniff(data, len, &info) != 0) {
  331. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  332. return -1;
  333. }
  334. est = img_estimate(&info);
  335. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA) {
  336. s_copy(bi->err, "image too large", sizeof(bi->err));
  337. return -1;
  338. }
  339. if (!image_arena) {
  340. image_arena = (unsigned char *)heap_alloc(BR_IMG_ARENA, 16);
  341. if (!image_arena) {
  342. s_copy(bi->err, "out of memory", sizeof(bi->err));
  343. return -1;
  344. }
  345. image_arena_size = BR_IMG_ARENA;
  346. }
  347. img_mem_init(&mem, image_arena, image_arena_size);
  348. opt.max_pixels = BR_IMG_PIX_MAX;
  349. r = img_decode(data, len, &opt, &mem, &decoded);
  350. if (r != 0) {
  351. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  352. return -1;
  353. }
  354. if (decoded.w == 0 || decoded.h == 0) {
  355. s_copy(bi->err, "empty image", sizeof(bi->err));
  356. return -1;
  357. }
  358. bi->native_w = (int)decoded.w;
  359. bi->native_h = (int)decoded.h;
  360. dw = (int)decoded.w;
  361. dh = (int)decoded.h;
  362. if (dw > BR_IMG_LAYOUT_W) {
  363. dh = (int)((unsigned int)decoded.h * BR_IMG_LAYOUT_W /
  364. decoded.w);
  365. dw = BR_IMG_LAYOUT_W;
  366. }
  367. if (dh < 1)
  368. dh = 1;
  369. if (dw < 1)
  370. dw = 1;
  371. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  372. px = (unsigned short *)heap_alloc(bytes, 16);
  373. if (!px) {
  374. s_copy(bi->err, "out of memory", sizeof(bi->err));
  375. return -1;
  376. }
  377. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  378. px[i] = ui.theme.bg;
  379. {
  380. struct img_blit b;
  381. b.dst = px;
  382. b.dst_w = dw;
  383. b.dst_h = dh;
  384. b.clip_x = 0;
  385. b.clip_y = 0;
  386. b.clip_w = dw;
  387. b.clip_h = dh;
  388. b.x = 0;
  389. b.y = 0;
  390. b.scale = ((unsigned int)dw << 16) / decoded.w;
  391. b.bg = ui.theme.bg;
  392. b.bg2 = ui.theme.bg;
  393. b.flags = IMG_BLIT_OVER_DST;
  394. img_draw(&decoded, &b);
  395. }
  396. bi->img.format = decoded.format;
  397. bi->img.w = (unsigned int)dw;
  398. bi->img.h = (unsigned int)dh;
  399. bi->img.px = px;
  400. bi->img.alpha = 0;
  401. bi->img.flags = 0;
  402. bi->state = 1;
  403. return 0;
  404. }
  405. /* ---- URL / local path handling ---- */
  406. static int is_http(const char *s)
  407. {
  408. return starts_with(s, "http://") || starts_with(s, "https://");
  409. }
  410. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  411. static int normalize_abs(const char *in, char *out, unsigned int cap)
  412. {
  413. char seg[64];
  414. unsigned int i = 0, o = 1;
  415. int depth = 0;
  416. int trailing;
  417. if (!in || in[0] != '/' || cap < 2)
  418. return -1;
  419. trailing = 0;
  420. {
  421. unsigned int n = s_len(in);
  422. if (n > 1 && in[n - 1] == '/')
  423. trailing = 1;
  424. }
  425. out[0] = '/';
  426. while (in[i]) {
  427. unsigned int n = 0;
  428. while (in[i] == '/')
  429. i++;
  430. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  431. if (n + 1 < sizeof(seg))
  432. seg[n++] = in[i];
  433. i++;
  434. }
  435. seg[n] = '\0';
  436. if (n == 0)
  437. break;
  438. if (s_eq(seg, "."))
  439. continue;
  440. if (s_eq(seg, "..")) {
  441. if (depth > 0) {
  442. while (o > 1 && out[o - 1] != '/')
  443. o--;
  444. if (o > 1)
  445. o--;
  446. depth--;
  447. }
  448. continue;
  449. }
  450. if (o > 1) {
  451. if (o + 1 >= cap)
  452. return -1;
  453. out[o++] = '/';
  454. }
  455. if (o + n + 1 >= cap)
  456. return -1;
  457. {
  458. unsigned int j;
  459. for (j = 0; j < n; j++)
  460. out[o++] = seg[j];
  461. }
  462. depth++;
  463. }
  464. if (trailing && o > 1) {
  465. if (o + 1 >= cap)
  466. return -1;
  467. out[o++] = '/';
  468. }
  469. out[o] = '\0';
  470. return 0;
  471. }
  472. static void make_abs_local(const char *in, char *out, unsigned int cap)
  473. {
  474. char joined[BR_URL_MAX];
  475. if (!in || !in[0]) {
  476. s_copy(out, cwd[0] ? cwd : "/", cap);
  477. return;
  478. }
  479. if (in[0] == '/') {
  480. if (normalize_abs(in, out, cap) != 0)
  481. s_copy(out, in, cap);
  482. return;
  483. }
  484. {
  485. unsigned int n = 0;
  486. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  487. s_append(joined, &n, "/", sizeof(joined));
  488. s_append(joined, &n, in, sizeof(joined));
  489. }
  490. if (normalize_abs(joined, out, cap) != 0)
  491. s_copy(out, joined, cap);
  492. }
  493. static int path_dir(const char *path, char *out, unsigned int cap)
  494. {
  495. unsigned int i, last = 0;
  496. for (i = 0; path[i]; i++)
  497. if (path[i] == '/')
  498. last = i;
  499. if (last == 0) {
  500. if (cap < 2)
  501. return -1;
  502. out[0] = '/';
  503. out[1] = '\0';
  504. return 0;
  505. }
  506. if (last + 1 >= cap)
  507. return -1;
  508. {
  509. unsigned int j;
  510. for (j = 0; j < last; j++)
  511. out[j] = path[j];
  512. out[last] = '\0';
  513. }
  514. return 0;
  515. }
  516. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  517. static int resolve_link(const char *base, const char *href, char *out,
  518. unsigned int cap)
  519. {
  520. char joined[BR_URL_MAX];
  521. if (!href || !href[0] || href[0] == '#')
  522. return -1;
  523. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  524. starts_with(href, "data:") || starts_with(href, "tel:"))
  525. return -1;
  526. if (starts_with(href, "about:")) {
  527. s_copy(out, href, cap);
  528. return 0;
  529. }
  530. if (is_http(href)) {
  531. s_copy(out, href, cap);
  532. return 0;
  533. }
  534. if (starts_with(href, "//")) {
  535. if (is_http(base)) {
  536. unsigned int n = 0;
  537. s_append(out, &n, starts_with(base, "https:") ?
  538. "https:" : "http:", cap);
  539. s_append(out, &n, href, cap);
  540. return 0;
  541. }
  542. return -1;
  543. }
  544. if (is_http(base)) {
  545. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  546. }
  547. /* local page */
  548. if (href[0] == '/') {
  549. if (normalize_abs(href, out, cap) != 0)
  550. return -1;
  551. return 0;
  552. }
  553. {
  554. char dir[BR_URL_MAX];
  555. unsigned int n = 0;
  556. if (s_eq(base, "about:home"))
  557. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  558. else if (path_dir(base, dir, sizeof(dir)) != 0)
  559. s_copy(dir, "/", sizeof(dir));
  560. s_append(joined, &n, dir, sizeof(joined));
  561. if (n == 0 || joined[n - 1] != '/')
  562. s_append(joined, &n, "/", sizeof(joined));
  563. s_append(joined, &n, href, sizeof(joined));
  564. }
  565. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  566. }
  567. /* Best-effort decompression: keep the first `cap` bytes and discard the
  568. * rest instead of failing when a page or stylesheet is larger than the
  569. * buffer. The stream is still walked to the end, so a normal page is
  570. * verified; a truncated compressed input still returns whatever was decoded
  571. * so far. */
  572. struct trunc_buf {
  573. unsigned char *dst;
  574. unsigned int cap, pos;
  575. int full;
  576. };
  577. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  578. {
  579. struct trunc_buf *m = (struct trunc_buf *)ctx;
  580. if (len > m->cap - m->pos) {
  581. unsigned int room = m->cap - m->pos;
  582. if (room) {
  583. unsigned int i;
  584. for (i = 0; i < room; i++)
  585. m->dst[m->pos + i] = data[i];
  586. m->pos += room;
  587. }
  588. m->full = 1;
  589. return 0;
  590. }
  591. {
  592. unsigned int i;
  593. for (i = 0; i < len; i++)
  594. m->dst[m->pos + i] = data[i];
  595. }
  596. m->pos += len;
  597. return 0;
  598. }
  599. static void worker_wait_ui(void);
  600. static void inflate_ui_pump(void *ctx)
  601. {
  602. static unsigned int last;
  603. unsigned int now = u_ticks_ms();
  604. (void)ctx;
  605. if ((int)(now - last) >= 50) {
  606. last = now;
  607. worker_wait_ui();
  608. }
  609. }
  610. static int inflate_trunc(const unsigned char *src, unsigned int len,
  611. unsigned char *dst, unsigned int cap,
  612. unsigned int *outlen, int gzip, int *truncated)
  613. {
  614. struct inflate_src in;
  615. struct inflate_sink sink;
  616. struct trunc_buf m;
  617. unsigned int got = 0;
  618. int r;
  619. in.p = src;
  620. in.len = len;
  621. in.more = 0;
  622. in.ctx = 0;
  623. m.dst = dst;
  624. m.cap = cap;
  625. m.pos = 0;
  626. m.full = 0;
  627. sink.write = trunc_write;
  628. sink.ctx = &m;
  629. inflate_init(&image_inflate_ws, &in, &sink);
  630. image_inflate_ws.progress = inflate_ui_pump;
  631. image_inflate_ws.progress_ctx = 0;
  632. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  633. inflate_zlib(&image_inflate_ws, &got);
  634. *outlen = m.pos;
  635. *truncated = m.full || r != 0;
  636. if (r != 0 && m.pos == 0)
  637. return -1;
  638. return 0;
  639. }
  640. /* ---- headless fetch helper ------------------------------------------- *
  641. *
  642. * Network I/O runs in a separate ring-3 process (`curl __fetch`): it writes
  643. * the raw response and a small metadata file under /share. While it works,
  644. * the browser keeps drawing and scrolling its own window, so a slow DNS/TLS
  645. * handshake or a multi-megabyte body never freezes the UI.
  646. */
  647. #define FETCH_REQ "/share/bfreq"
  648. #define FETCH_BODY "/share/bfbody"
  649. #define FETCH_META "/share/bfmeta"
  650. #define FETCH_ABORT (-2)
  651. struct fetch_meta {
  652. int status;
  653. int error;
  654. int trunc;
  655. unsigned int len;
  656. char encoding[16];
  657. char ctype[64];
  658. char final[BR_URL_MAX];
  659. };
  660. static void draw(unsigned int *action);
  661. static void handle_keys(unsigned int *action);
  662. static void handle_page_click(unsigned int *action);
  663. static int fetch_helper_tty = -2;
  664. static struct fetch_meta fetch_meta;
  665. static unsigned int meta_uint(char **pp)
  666. {
  667. char *p = *pp;
  668. unsigned int v = 0;
  669. while (*p >= '0' && *p <= '9') {
  670. v = v * 10 + (unsigned int)(*p - '0');
  671. p++;
  672. }
  673. while (*p && *p != '\n')
  674. p++;
  675. if (*p == '\n')
  676. p++;
  677. *pp = p;
  678. return v;
  679. }
  680. static void meta_str(char **pp, char *out, unsigned int cap)
  681. {
  682. char *p = *pp;
  683. unsigned int n = 0;
  684. while (*p && *p != '\n' && n + 1 < cap)
  685. out[n++] = *p++;
  686. out[n] = '\0';
  687. while (*p && *p != '\n')
  688. p++;
  689. if (*p == '\n')
  690. p++;
  691. *pp = p;
  692. }
  693. static void worker_wait_ui(void)
  694. {
  695. unsigned int action = 0;
  696. if (!ngui_begin(&ui))
  697. return;
  698. draw(&action);
  699. handle_keys(&action);
  700. handle_page_click(&action);
  701. if (action & ACT_WAIT_NAV) {
  702. pending_action |= action & ACT_WAIT_NAV;
  703. if ((action & ACT_NAV) && click_url[0])
  704. s_copy(pending_url, click_url, sizeof(pending_url));
  705. click_url[0] = '\0';
  706. cancel_fetch = 1;
  707. }
  708. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  709. ngui_invalidate(&ui);
  710. ngui_end(&ui);
  711. }
  712. static int worker_fetch(const char *url, unsigned int cap,
  713. struct fetch_meta *m, char *err, unsigned int errcap)
  714. {
  715. static char req[768], meta[1024];
  716. char *p;
  717. unsigned int n = 0, deadline, i;
  718. int rn, pid;
  719. struct sys_stat st;
  720. if (cancel_fetch || pending_action)
  721. return FETCH_ABORT;
  722. if (u_stat("/share", &st) != 0 || !st.is_dir ||
  723. u_stat("/ramfs/bin/curl", &st) != 0) {
  724. s_copy(err, "network helper unavailable", errcap);
  725. return -1;
  726. }
  727. s_append_dec(req, &n, cap, sizeof(req));
  728. s_append(req, &n, " ", sizeof(req));
  729. s_append(req, &n, url, sizeof(req));
  730. s_append(req, &n, "\n", sizeof(req));
  731. u_syscall1(SYS_UNLINK, (int)FETCH_META);
  732. if (u_syscall3(SYS_WRITE_FILE, (int)FETCH_REQ, (int)req, (int)n) < 0) {
  733. s_copy(err, "cannot queue network request", errcap);
  734. return -1;
  735. }
  736. if (fetch_helper_tty == -2) {
  737. int t = u_tty_create();
  738. fetch_helper_tty = t > 0 ? t : 0;
  739. }
  740. pid = u_spawn("/ramfs/bin/curl", "__fetch", fetch_helper_tty, "/");
  741. if (pid <= 0) {
  742. s_copy(err, "cannot start network helper", errcap);
  743. return -1;
  744. }
  745. deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  746. while (u_alive(pid)) {
  747. worker_wait_ui();
  748. if (cancel_fetch || pending_action) {
  749. u_kill(pid);
  750. for (i = 0; i < 40 && u_alive(pid); i++)
  751. u_sleep_ms(5);
  752. /* The reaper releases a dead helper's NIC ownership;
  753. * give it a scheduling chance before the next request. */
  754. u_sleep_ms(10);
  755. return FETCH_ABORT;
  756. }
  757. if ((int)(u_ticks_ms() - deadline) >= 0) {
  758. u_kill(pid);
  759. s_copy(err, "network request timed out", errcap);
  760. return -1;
  761. }
  762. u_sleep_ms(20);
  763. }
  764. if (cancel_fetch || pending_action)
  765. return FETCH_ABORT;
  766. rn = u_syscall3(SYS_READ_FILE, (int)FETCH_META, (int)meta,
  767. (int)(sizeof(meta) - 1));
  768. if (rn <= 0) {
  769. s_copy(err, "network helper failed", errcap);
  770. return -1;
  771. }
  772. meta[rn] = '\0';
  773. p = meta;
  774. m->status = (int)meta_uint(&p);
  775. m->error = (int)meta_uint(&p);
  776. m->trunc = (int)meta_uint(&p);
  777. meta_str(&p, m->encoding, sizeof(m->encoding));
  778. meta_str(&p, m->ctype, sizeof(m->ctype));
  779. meta_str(&p, m->final, sizeof(m->final));
  780. m->len = meta_uint(&p);
  781. if (m->error) {
  782. s_copy(err, uhttp_error_string(m->error), errcap);
  783. return -1;
  784. }
  785. return 0;
  786. }
  787. static int fetch_remote(const char *url, unsigned int cap,
  788. unsigned char *plain, unsigned int plaincap,
  789. unsigned char *comp, unsigned int compcap,
  790. struct fetch_meta *m, int *truncated,
  791. char *err, unsigned int errcap)
  792. {
  793. int rv, zr, was_trunc;
  794. rv = worker_fetch(url, cap, m, err, errcap);
  795. if (rv == FETCH_ABORT)
  796. return FETCH_ABORT;
  797. if (rv != 0)
  798. return -1;
  799. if (contains_ci(m->encoding, "gzip") ||
  800. contains_ci(m->encoding, "deflate")) {
  801. unsigned int comp_len = 0, plen = 0;
  802. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)comp,
  803. (int)compcap);
  804. if (rv < 0) {
  805. s_copy(err, "empty response", errcap);
  806. return -1;
  807. }
  808. comp_len = (unsigned int)rv;
  809. if (comp_len < m->len) {
  810. s_copy(err, "compressed response is too large", errcap);
  811. return -1;
  812. }
  813. if (contains_ci(m->encoding, "deflate"))
  814. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  815. &plen, 0, &was_trunc);
  816. else
  817. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  818. &plen, 1, &was_trunc);
  819. if (zr != 0) {
  820. s_copy(err, "compressed response is corrupt", errcap);
  821. return -1;
  822. }
  823. *truncated = m->trunc || was_trunc;
  824. return (cancel_fetch || pending_action) ? FETCH_ABORT :
  825. (int)plen;
  826. }
  827. rv = u_syscall3(SYS_READ_FILE, (int)FETCH_BODY, (int)plain,
  828. (int)plaincap);
  829. if (rv < 0) {
  830. s_copy(err, "empty response", errcap);
  831. return -1;
  832. }
  833. *truncated = m->trunc || ((unsigned int)rv < m->len);
  834. return (cancel_fetch || pending_action) ? FETCH_ABORT : rv;
  835. }
  836. /* ---- HTTP / file fetch ---- */
  837. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  838. unsigned int *outlen, int *is_local, char *ctype,
  839. unsigned int ctcap, char *final, unsigned int finalcap,
  840. char *err, unsigned int errcap, int *truncated)
  841. {
  842. unsigned char *buf;
  843. unsigned int len;
  844. int tr = 0;
  845. int rv;
  846. *out = 0;
  847. *outlen = 0;
  848. *truncated = 0;
  849. if (final && finalcap)
  850. final[0] = '\0';
  851. if (ctype && ctcap)
  852. ctype[0] = '\0';
  853. if (url[0] == '/') {
  854. buf = (unsigned char *)heap_alloc(cap, 16);
  855. if (!buf) {
  856. s_copy(err, "out of memory", errcap);
  857. return -1;
  858. }
  859. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf, (int)cap);
  860. if (rv < 0) {
  861. s_copy(err, "file not found", errcap);
  862. return -1;
  863. }
  864. *out = buf;
  865. *outlen = (unsigned int)rv;
  866. *is_local = 1;
  867. if (ctype)
  868. s_copy(ctype, "text/html", ctcap);
  869. if (final)
  870. s_copy(final, url, finalcap);
  871. if ((unsigned int)rv == cap)
  872. *truncated = 1;
  873. return 0;
  874. }
  875. buf = (unsigned char *)heap_alloc(cap, 16);
  876. if (!buf) {
  877. s_copy(err, "out of memory", errcap);
  878. return -1;
  879. }
  880. rv = fetch_remote(url, cap, buf, cap, image_io_buf, BR_PAGE_COMP_MAX,
  881. &fetch_meta, &tr, err, errcap);
  882. if (rv == FETCH_ABORT)
  883. return FETCH_ABORT;
  884. if (rv < 0)
  885. return -1;
  886. len = (unsigned int)rv;
  887. if (len == 0) {
  888. s_copy(err, "empty response", errcap);
  889. return -1;
  890. }
  891. if (ctype)
  892. s_copy(ctype, fetch_meta.ctype, ctcap);
  893. if (final && fetch_meta.final[0])
  894. s_copy(final, fetch_meta.final, finalcap);
  895. *is_local = 0;
  896. *out = buf;
  897. *outlen = len;
  898. *truncated = tr;
  899. return 0;
  900. }
  901. /* Fetch an image into the fixed scratch buffers. The page heap is already
  902. * carrying the 24 MB decode arena and every scaled bitmap, so images must not
  903. * allocate their file body from it as well. */
  904. static int fetch_image(const char *url, unsigned int cap,
  905. unsigned char **out, unsigned int *outlen,
  906. char *err, unsigned int errcap)
  907. {
  908. unsigned int len;
  909. int tr = 0;
  910. int rv;
  911. *out = 0;
  912. *outlen = 0;
  913. if (cap > BR_IMG_FILE_MAX)
  914. cap = BR_IMG_FILE_MAX;
  915. if (url[0] == '/') {
  916. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  917. (int)cap);
  918. if (rv < 0) {
  919. s_copy(err, "file not found", errcap);
  920. return -1;
  921. }
  922. *out = image_file_buf;
  923. *outlen = (unsigned int)rv;
  924. return 0;
  925. }
  926. rv = fetch_remote(url, cap, image_file_buf, cap, image_comp_buf,
  927. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  928. if (rv == FETCH_ABORT)
  929. return FETCH_ABORT;
  930. if (rv < 0)
  931. return -1;
  932. len = (unsigned int)rv;
  933. if (len == 0) {
  934. s_copy(err, "empty image", errcap);
  935. return -1;
  936. }
  937. *out = image_file_buf;
  938. *outlen = len;
  939. return 0;
  940. }
  941. /* Read one stylesheet into the shared static buffer. CSS is parsed
  942. * immediately, so it does not need the page heap; this leaves the heap for
  943. * the 2 MB page body, the decode arena and the scaled image bitmaps. */
  944. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  945. char *err, unsigned int errcap)
  946. {
  947. unsigned int len;
  948. int tr = 0;
  949. int rv;
  950. *out = 0;
  951. *outlen = 0;
  952. if (url[0] == '/') {
  953. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  954. (int)BR_CSS_MAX);
  955. if (rv < 0) {
  956. s_copy(err, "stylesheet not found", errcap);
  957. return -1;
  958. }
  959. *out = image_io_buf;
  960. *outlen = (unsigned int)rv;
  961. return 0;
  962. }
  963. rv = fetch_remote(url, BR_CSS_MAX, image_io_buf, BR_CSS_MAX,
  964. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  965. &fetch_meta, &tr, err, errcap);
  966. if (rv == FETCH_ABORT)
  967. return FETCH_ABORT;
  968. if (rv < 0)
  969. return -1;
  970. len = (unsigned int)rv;
  971. if (len == 0) {
  972. s_copy(err, "empty stylesheet", errcap);
  973. return -1;
  974. }
  975. *out = image_io_buf;
  976. *outlen = len;
  977. return 0;
  978. }
  979. static void redraw_now(void);
  980. static char error_page[1024];
  981. static void show_error(const char *title, const char *detail)
  982. {
  983. char *page = error_page;
  984. unsigned int n = 0;
  985. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  986. s_append(page, &n, title, sizeof(error_page));
  987. s_append(page, &n, "</h2><p>", sizeof(error_page));
  988. {
  989. const char *p = detail;
  990. while (*p && n + 1 < sizeof(error_page)) {
  991. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  992. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  993. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  994. else page[n++] = *p;
  995. p++;
  996. }
  997. }
  998. page[n] = '\0';
  999. s_append(page, &n, "</p><p>", sizeof(error_page));
  1000. s_append(page, &n, page_url, sizeof(error_page));
  1001. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  1002. sizeof(error_page));
  1003. br_parse(&doc, page, n);
  1004. preload_active = 0;
  1005. preload_pending = 0;
  1006. preload_wait = 0;
  1007. s_copy(page_title, title, sizeof(page_title));
  1008. page_loading = 0;
  1009. set_status(title, 1, 0);
  1010. ngui_invalidate(&ui);
  1011. }
  1012. static int decode_direct_image(const unsigned char *data, unsigned int len,
  1013. unsigned int node)
  1014. {
  1015. if (image_count >= BR_MAX_IMAGES)
  1016. return -1;
  1017. if (decode_image_data(data, len, &images[0]) != 0)
  1018. return -1;
  1019. doc.nodes[node].img_index = 0;
  1020. image_count = 1;
  1021. return 0;
  1022. }
  1023. static int ancestor_is(unsigned int node, unsigned int tag)
  1024. {
  1025. unsigned int p = doc.nodes[node].parent;
  1026. while (p) {
  1027. if (doc.nodes[p].tag == tag)
  1028. return 1;
  1029. p = doc.nodes[p].parent;
  1030. }
  1031. return 0;
  1032. }
  1033. static int load_stylesheets(void)
  1034. {
  1035. unsigned int i, sheets = 0;
  1036. for (i = 0; i < doc.nnode && sheets < BR_MAX_SHEETS; i++) {
  1037. struct br_node *nd = &doc.nodes[i];
  1038. const char *rel, *href;
  1039. char url[BR_URL_MAX];
  1040. unsigned char *data;
  1041. unsigned int len;
  1042. char err[64];
  1043. int rv;
  1044. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1045. continue;
  1046. rel = br_rel(&doc, i);
  1047. if (!contains_ci(rel, "stylesheet"))
  1048. continue;
  1049. href = br_href(&doc, i);
  1050. if (!href[0])
  1051. continue;
  1052. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1053. continue;
  1054. rv = fetch_css(url, &data, &len, err, sizeof(err));
  1055. if (rv == FETCH_ABORT)
  1056. return FETCH_ABORT;
  1057. if (rv != 0)
  1058. continue;
  1059. if (len)
  1060. br_parse_css_text(&doc, (const char *)data, len);
  1061. sheets++;
  1062. }
  1063. br_parse_inline_css(&doc);
  1064. br_reset_styles(&doc);
  1065. return 0;
  1066. }
  1067. static void preload_begin(void)
  1068. {
  1069. preload_active = 1;
  1070. preload_pending = 0;
  1071. preload_wait = 1;
  1072. preload_node = 0;
  1073. preload_loaded = 0;
  1074. preload_scroll = 0;
  1075. }
  1076. /* Load at most one image per call. Images below the current viewport are
  1077. * left pending until the page is scrolled; this keeps a long article with
  1078. * many 4K screenshots from stalling on content the user cannot see yet. */
  1079. static void preload_step(void)
  1080. {
  1081. while (preload_active && preload_node < doc.nnode) {
  1082. unsigned int i = preload_node;
  1083. struct br_node *nd = &doc.nodes[i];
  1084. const char *src;
  1085. char url[BR_URL_MAX];
  1086. unsigned char *data;
  1087. unsigned int len;
  1088. char err[64];
  1089. char msg[64];
  1090. unsigned int n = 0;
  1091. int rv;
  1092. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_IMG ||
  1093. nd->img_index >= 0) {
  1094. preload_node++;
  1095. continue;
  1096. }
  1097. if (ancestor_is(i, BR_TAG_NOSCRIPT)) {
  1098. preload_node++;
  1099. continue;
  1100. }
  1101. src = br_src(&doc, i);
  1102. if (!src[0] || contains_ci(src, ".svg") ||
  1103. starts_with(src, "data:")) {
  1104. preload_node++;
  1105. continue;
  1106. }
  1107. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  1108. preload_node++;
  1109. continue;
  1110. }
  1111. if (image_count >= BR_MAX_IMAGES) {
  1112. preload_node = doc.nnode;
  1113. break;
  1114. }
  1115. if (img_top[i] >
  1116. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  1117. preload_active = 0;
  1118. preload_pending = 1;
  1119. preload_scroll = page_scroll.offset;
  1120. set_status(post_status_text, post_status_error,
  1121. post_status_ttl);
  1122. ngui_invalidate(&ui);
  1123. return;
  1124. }
  1125. preload_node = i + 1;
  1126. s_append(msg, &n, "Loading images ", sizeof(msg));
  1127. s_append_dec(msg, &n, (unsigned int)preload_loaded + 1,
  1128. sizeof(msg));
  1129. s_append(msg, &n, "...", sizeof(msg));
  1130. set_status(msg, 0, 0);
  1131. ngui_invalidate(&ui);
  1132. data = 0;
  1133. len = 0;
  1134. rv = fetch_image(url, BR_IMG_FILE_MAX, &data, &len, err,
  1135. sizeof(err));
  1136. if (rv == FETCH_ABORT) {
  1137. preload_active = 0;
  1138. preload_pending = 0;
  1139. return;
  1140. }
  1141. if (rv == 0 &&
  1142. decode_image_data(data, len, &images[image_count]) == 0) {
  1143. nd->img_index = (short)image_count;
  1144. image_count++;
  1145. preload_loaded++;
  1146. }
  1147. ngui_invalidate(&ui);
  1148. return;
  1149. }
  1150. preload_active = 0;
  1151. preload_pending = 0;
  1152. set_status(post_status_text, post_status_error, post_status_ttl);
  1153. ngui_invalidate(&ui);
  1154. }
  1155. static void history_push(const char *url)
  1156. {
  1157. if (!url || !url[0])
  1158. return;
  1159. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  1160. s_eq(history[hist_pos], url))
  1161. return;
  1162. if (hist_len > 0 && hist_pos + 1 < hist_len)
  1163. hist_len = hist_pos + 1;
  1164. if (hist_len < BR_HISTORY) {
  1165. s_copy(history[hist_len], url, BR_URL_MAX);
  1166. hist_pos = hist_len;
  1167. hist_len++;
  1168. } else {
  1169. int i;
  1170. for (i = 1; i < BR_HISTORY; i++)
  1171. s_copy(history[i - 1], history[i], BR_URL_MAX);
  1172. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  1173. hist_pos = BR_HISTORY - 1;
  1174. }
  1175. }
  1176. static void load_page(const char *url, int local, int push)
  1177. {
  1178. unsigned char *body = 0;
  1179. unsigned int len = 0;
  1180. int truncated = 0;
  1181. struct img_info image_info;
  1182. char ctype[64];
  1183. char final[BR_URL_MAX];
  1184. char err[80];
  1185. const char *detail = 0;
  1186. int rv;
  1187. final[0] = '\0';
  1188. cancel_fetch = 0;
  1189. preload_active = 0;
  1190. preload_pending = 0;
  1191. heap_clear();
  1192. image_reset();
  1193. page_scroll.offset = 0;
  1194. page_scroll.dragging = 0;
  1195. br_parse_plain(&doc, "", 0); /* blank while loading */
  1196. page_title[0] = '\0';
  1197. page_loading = 1;
  1198. page_is_local = local;
  1199. s_copy(page_url, url, sizeof(page_url));
  1200. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1201. url_in.len = s_len(url_in.text);
  1202. url_in.cursor = url_in.len;
  1203. url_in.scroll = 0;
  1204. ngui_set_focus(&ui, 0);
  1205. if (final[0])
  1206. final[0] = '\0';
  1207. if (push)
  1208. history_push(url);
  1209. set_status("Loading...", 0, 0);
  1210. ngui_invalidate(&ui);
  1211. redraw_now();
  1212. if (heap_start() != 0) {
  1213. show_error("Out of memory", "Cannot allocate the page buffer");
  1214. return;
  1215. }
  1216. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  1217. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  1218. &truncated);
  1219. if (rv == FETCH_ABORT)
  1220. return;
  1221. if (rv != 0) {
  1222. detail = err;
  1223. show_error("Cannot load this page", detail);
  1224. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1225. url_in.len = s_len(url_in.text);
  1226. url_in.cursor = url_in.len;
  1227. url_in.scroll = 0;
  1228. return;
  1229. }
  1230. page_is_local = local;
  1231. if (final[0]) {
  1232. s_copy(page_url, final, sizeof(page_url));
  1233. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1234. url_in.len = s_len(url_in.text);
  1235. url_in.cursor = url_in.len;
  1236. url_in.scroll = 0;
  1237. }
  1238. if (contains_ci(ctype, "text/plain")) {
  1239. br_parse_plain(&doc, (const char *)body, len);
  1240. } else if (contains_ci(ctype, "image/") ||
  1241. (!contains_ci(ctype, "text/html") &&
  1242. img_sniff(body, len, &image_info) == 0)) {
  1243. unsigned int node = br_parse_image_doc(&doc, page_url);
  1244. if (node)
  1245. decode_direct_image(body, len, node);
  1246. s_copy(page_title, "Image", sizeof(page_title));
  1247. } else {
  1248. br_parse(&doc, (const char *)body, len);
  1249. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  1250. sizeof(page_title));
  1251. if (load_stylesheets() == FETCH_ABORT)
  1252. return;
  1253. if (pending_action)
  1254. return;
  1255. }
  1256. post_status_text[0] = '\0';
  1257. post_status_error = 0;
  1258. post_status_ttl = 0;
  1259. if (truncated) {
  1260. s_copy(post_status_text, "Page truncated at the buffer limit",
  1261. sizeof(post_status_text));
  1262. post_status_ttl = 6000;
  1263. } else if (doc.truncated) {
  1264. s_copy(post_status_text, "Page truncated by the parser",
  1265. sizeof(post_status_text));
  1266. post_status_ttl = 6000;
  1267. } else if (starts_with(page_url, "https://")) {
  1268. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  1269. sizeof(post_status_text));
  1270. post_status_ttl = 6000;
  1271. }
  1272. preload_begin();
  1273. page_loading = 0;
  1274. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1275. url_in.len = s_len(url_in.text);
  1276. url_in.cursor = url_in.len;
  1277. url_in.scroll = 0;
  1278. ngui_set_focus(&ui, 0);
  1279. ngui_invalidate(&ui);
  1280. }
  1281. static void load_home(int push)
  1282. {
  1283. cancel_fetch = 0;
  1284. preload_active = 0;
  1285. preload_pending = 0;
  1286. heap_clear();
  1287. image_reset();
  1288. page_scroll.offset = 0;
  1289. page_scroll.dragging = 0;
  1290. br_parse_plain(&doc, "", 0);
  1291. page_loading = 1;
  1292. page_is_local = 0;
  1293. s_copy(page_url, "about:home", sizeof(page_url));
  1294. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1295. url_in.len = s_len(url_in.text);
  1296. url_in.cursor = url_in.len;
  1297. url_in.scroll = 0;
  1298. ngui_set_focus(&ui, 0);
  1299. if (push)
  1300. history_push(page_url);
  1301. ngui_invalidate(&ui);
  1302. redraw_now();
  1303. if (heap_start() != 0) {
  1304. show_error("Out of memory", "Cannot allocate the browser heap");
  1305. return;
  1306. }
  1307. {
  1308. static const char home[] =
  1309. "<html><head><title>Nebs Browser</title><style>"
  1310. "body { margin: 10px; color: #e4e6f0; }"
  1311. "h1 { color: #7fb0ff; }"
  1312. ".box { background-color: #262b3a; margin: 12px; "
  1313. "padding: 10px; }"
  1314. "a { color: #7fb0ff; }"
  1315. "pre { background-color: #32384a; }"
  1316. "</style></head><body>"
  1317. "<h1>Nebs Browser</h1>"
  1318. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  1319. "shared HTTP client and the image library.</p>"
  1320. "<div class=\"box\"><b>Try:</b>"
  1321. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  1322. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  1323. "<li><a href=\"http://10.0.2.2:8000/\">"
  1324. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  1325. "<li><a href=\"https://example.com/\">"
  1326. "https://example.com/</a> (TLS, not verified)</li>"
  1327. "</ul></div>"
  1328. "<p>Type a URL in the bar above. Esc closes the "
  1329. "window, Ctrl+L focuses the address bar.</p>"
  1330. "<pre>javascript: not supported\nforms: not supported"
  1331. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  1332. "</body></html>";
  1333. br_parse(&doc, home, sizeof(home) - 1);
  1334. br_parse_inline_css(&doc);
  1335. br_reset_styles(&doc);
  1336. s_copy(page_title, doc.title, sizeof(page_title));
  1337. }
  1338. post_status_text[0] = '\0';
  1339. post_status_error = 0;
  1340. post_status_ttl = 0;
  1341. page_loading = 0;
  1342. set_status("", 0, 0);
  1343. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1344. url_in.len = s_len(url_in.text);
  1345. url_in.cursor = url_in.len;
  1346. url_in.scroll = 0;
  1347. ngui_set_focus(&ui, 0);
  1348. ngui_invalidate(&ui);
  1349. }
  1350. static void navigate(const char *input, int push)
  1351. {
  1352. char target[BR_URL_MAX];
  1353. char *t;
  1354. if (!input)
  1355. return;
  1356. s_copy(target, input, sizeof(target));
  1357. t = trim(target);
  1358. if (!t[0])
  1359. return;
  1360. if (s_eq(t, "about:home")) {
  1361. load_home(push);
  1362. return;
  1363. }
  1364. if (starts_with(t, "file://")) {
  1365. make_abs_local(t + 7, target, sizeof(target));
  1366. load_page(target, 1, push);
  1367. return;
  1368. }
  1369. if (is_http(t)) {
  1370. load_page(t, 0, push);
  1371. return;
  1372. }
  1373. {
  1374. struct sys_stat st;
  1375. if (t[0] == '/' || (u_stat(t, &st) == 0 && !st.is_dir)) {
  1376. make_abs_local(t, target, sizeof(target));
  1377. load_page(target, 1, push);
  1378. return;
  1379. }
  1380. }
  1381. {
  1382. char with_scheme[BR_URL_MAX];
  1383. unsigned int n = 0;
  1384. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  1385. s_append(with_scheme, &n, t, sizeof(with_scheme));
  1386. load_page(with_scheme, 0, push);
  1387. }
  1388. }
  1389. /* ---- layout ---- */
  1390. static struct br_style base_style(void)
  1391. {
  1392. struct br_style s = { 0 };
  1393. s.color = ui.theme.text;
  1394. s.bg = ui.theme.bg;
  1395. s.has_bg = 0;
  1396. s.border_color = 0;
  1397. s.scale = 1;
  1398. s.bold = 0;
  1399. s.underline = 0;
  1400. s.align = BR_ALIGN_LEFT;
  1401. s.display = BR_DISPLAY_BLOCK;
  1402. s.no_bullet = 0;
  1403. s.uppercase = 0;
  1404. s.border_w = 0;
  1405. s.width_kind = s.max_width_kind = s.height_kind = 0;
  1406. s.width = s.max_width = s.height = 0;
  1407. s.line_h_pct = 0;
  1408. s.line_h_px = 0;
  1409. s.mt = s.mb = s.ml = s.mr = 0;
  1410. s.pt = s.pb = s.pl = s.pr = 0;
  1411. return s;
  1412. }
  1413. static int run_width(const struct lay_run *r)
  1414. {
  1415. if (r->img >= 0)
  1416. return r->iw;
  1417. if (r->img == -2)
  1418. return r->iw;
  1419. {
  1420. unsigned int n = r->has_lit ? s_len(r->lit) : r->len;
  1421. return (int)(n * (unsigned int)(8 * r->scale) +
  1422. (r->bold ? 1u : 0u));
  1423. }
  1424. }
  1425. static void flush_line(struct lay *l)
  1426. {
  1427. int total, x, i;
  1428. if (!l->nruns && l->line_x == l->left) {
  1429. l->line_h = 0;
  1430. return;
  1431. }
  1432. total = l->line_x - l->left;
  1433. x = l->left;
  1434. if (l->align == BR_ALIGN_CENTER)
  1435. x += (l->right - l->left - total) / 2;
  1436. else if (l->align == BR_ALIGN_RIGHT)
  1437. x = l->right - total;
  1438. if (x < l->left)
  1439. x = l->left;
  1440. for (i = 0; i < l->nruns; i++) {
  1441. struct lay_run *r = &l->runs[i];
  1442. int w = run_width(r);
  1443. x += r->gap;
  1444. if (l->draw) {
  1445. if (r->img == -2) {
  1446. int hh = r->ih ? r->ih : 20;
  1447. ngui_fill_rect(l->ui,
  1448. (struct ngui_rect){x, l->line_y, w, hh},
  1449. l->ui->theme.panel_alt);
  1450. ngui_frame(l->ui,
  1451. (struct ngui_rect){x, l->line_y, w, hh},
  1452. l->ui->theme.border);
  1453. ngui_text_styled(l->ui, x + 6, l->line_y + 2,
  1454. r->lit, s_len(r->lit), r->color,
  1455. r->scale, r->bold);
  1456. } else if (r->img >= 0) {
  1457. struct br_image *bi = &images[r->img];
  1458. if (bi->state == 1) {
  1459. struct img_blit b;
  1460. b.dst = l->ui->px;
  1461. b.dst_w = l->ui->w;
  1462. b.dst_h = l->ui->h;
  1463. b.clip_x = page_rect.x;
  1464. b.clip_y = page_rect.y;
  1465. b.clip_w = page_rect.w - 12;
  1466. b.clip_h = page_rect.h;
  1467. b.x = x;
  1468. b.y = l->line_y;
  1469. b.scale = ((unsigned int)r->iw << 16) /
  1470. bi->img.w;
  1471. b.bg = ui.theme.bg;
  1472. b.bg2 = ui.theme.bg;
  1473. b.flags = IMG_BLIT_OVER_DST;
  1474. img_draw(&bi->img, &b);
  1475. }
  1476. } else {
  1477. const char *s = r->has_lit ? r->lit :
  1478. doc.text + r->off;
  1479. unsigned int n = r->has_lit ? s_len(r->lit) :
  1480. r->len;
  1481. ngui_text_styled(l->ui, x, l->line_y, s, n,
  1482. r->color, r->scale, r->bold);
  1483. if (r->underline)
  1484. ngui_fill_rect(l->ui,
  1485. (struct ngui_rect){x,
  1486. l->line_y + 16 * r->scale - 2,
  1487. w, 1}, r->color);
  1488. }
  1489. if (r->href) {
  1490. if (nhits < HIT_MAX) {
  1491. struct hit *h = &hits[nhits];
  1492. int hh = r->img >= 0 ? r->ih :
  1493. 16 * r->scale;
  1494. int merge = nhits > 0 &&
  1495. hits[nhits - 1].node == r->href &&
  1496. hits[nhits - 1].y == l->line_y &&
  1497. hits[nhits - 1].h == hh &&
  1498. x <= hits[nhits - 1].x +
  1499. hits[nhits - 1].w + 2;
  1500. if (merge) {
  1501. struct hit *p = &hits[nhits - 1];
  1502. int end = x + w;
  1503. if (end > p->x + p->w)
  1504. p->w = end - p->x;
  1505. } else {
  1506. h->x = x;
  1507. h->y = l->line_y;
  1508. h->w = w;
  1509. h->h = hh;
  1510. h->node = r->href;
  1511. nhits++;
  1512. }
  1513. }
  1514. }
  1515. }
  1516. x += w;
  1517. }
  1518. l->y += l->line_h + 2;
  1519. l->nruns = 0;
  1520. l->line_x = l->left;
  1521. l->run_x = l->left;
  1522. l->line_h = 0;
  1523. l->space_pending = 0;
  1524. }
  1525. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  1526. const struct br_style *st, unsigned short href,
  1527. const char *lit)
  1528. {
  1529. unsigned int n = lit ? s_len(lit) : len;
  1530. int w = (int)(n * (unsigned int)(8 * st->scale) +
  1531. (st->bold ? 1u : 0u));
  1532. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1533. flush_line(l);
  1534. if (l->nruns == 0) {
  1535. l->line_y = l->y;
  1536. l->line_h = 0;
  1537. }
  1538. {
  1539. struct lay_run *r = &l->runs[l->nruns++];
  1540. int gap = l->line_x - l->run_x;
  1541. if (gap < 0)
  1542. gap = 0;
  1543. r->gap = (unsigned short)gap;
  1544. r->off = off;
  1545. r->len = len;
  1546. r->color = st->color;
  1547. r->href = href;
  1548. r->has_lit = 0;
  1549. r->lit[0] = '\0';
  1550. if (lit && lit[0]) {
  1551. unsigned int i;
  1552. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  1553. r->lit[i] = lit[i];
  1554. r->lit[i] = '\0';
  1555. r->has_lit = 1;
  1556. }
  1557. r->img = -1;
  1558. r->iw = r->ih = 0;
  1559. r->scale = st->scale;
  1560. r->bold = st->bold;
  1561. r->underline = st->underline;
  1562. }
  1563. l->line_x += w;
  1564. l->run_x = l->line_x;
  1565. {
  1566. int lh = 16 * st->scale;
  1567. if (st->line_h_px)
  1568. lh = st->line_h_px;
  1569. else if (st->line_h_pct)
  1570. lh = (16 * st->scale) * st->line_h_pct / 100;
  1571. if (lh < 16 * st->scale)
  1572. lh = 16 * st->scale;
  1573. if (l->line_h < lh)
  1574. l->line_h = lh;
  1575. }
  1576. }
  1577. static void add_image_run(struct lay *l, unsigned int node,
  1578. const struct br_style *st, unsigned short href)
  1579. {
  1580. struct br_image *bi = 0;
  1581. int idx = doc.nodes[node].img_index;
  1582. int dw, dh, maxw;
  1583. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  1584. bi = &images[idx];
  1585. if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
  1586. if (l->line_x + 8 <= l->right)
  1587. l->line_x += 8;
  1588. }
  1589. l->space_pending = 0;
  1590. if (!bi) {
  1591. const char *alt = br_alt(&doc, node);
  1592. struct br_style gs = *st;
  1593. char tmp[96];
  1594. unsigned int n = 0;
  1595. int w;
  1596. gs.color = BR_GRAY;
  1597. gs.underline = 0;
  1598. s_append(tmp, &n, "[", sizeof(tmp));
  1599. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  1600. s_append(tmp, &n, "]", sizeof(tmp));
  1601. w = (int)(n * (unsigned int)(8 * gs.scale));
  1602. if (l->line_x + w > l->right &&
  1603. (l->nruns > 0 || l->line_x > l->left))
  1604. flush_line(l);
  1605. add_run(l, 0, 0, &gs, href, tmp);
  1606. if (!l->draw) {
  1607. int t = l->line_y < 0 ? 0 : l->line_y;
  1608. int hh = 16 * gs.scale;
  1609. if (t > 65535)
  1610. t = 65535;
  1611. if (hh > 65535)
  1612. hh = 65535;
  1613. img_top[node] = (unsigned short)t;
  1614. img_h[node] = (unsigned short)hh;
  1615. }
  1616. return;
  1617. }
  1618. maxw = l->right - l->left;
  1619. if (maxw < 8)
  1620. maxw = 8;
  1621. {
  1622. int iw = bi->native_w, ih = bi->native_h;
  1623. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  1624. if (iw <= 0 || ih <= 0) {
  1625. iw = (int)bi->img.w;
  1626. ih = (int)bi->img.h;
  1627. }
  1628. dw = iw;
  1629. dh = ih;
  1630. if (doc.nodes[node].width_attr) {
  1631. int want = doc.nodes[node].width_attr;
  1632. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  1633. have_w = 1;
  1634. }
  1635. if (doc.nodes[node].height_attr) {
  1636. int want = doc.nodes[node].height_attr;
  1637. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  1638. have_h = 1;
  1639. }
  1640. if (have_w && !have_h)
  1641. dh = ih ? ih * dw / iw : 0;
  1642. if (have_h && !have_w)
  1643. dw = iw ? iw * dh / ih : 0;
  1644. if (st->width_kind) {
  1645. css_w = 1;
  1646. dw = st->width_kind == 2 ? maxw * (int)st->width / 100 :
  1647. (int)st->width;
  1648. }
  1649. if (st->height_kind) {
  1650. css_h = 1;
  1651. dh = st->height_kind == 2 ? maxw * (int)st->height / 100 :
  1652. (int)st->height;
  1653. }
  1654. if (css_w && !css_h)
  1655. dh = ih ? ih * dw / iw : 0;
  1656. if (css_h && !css_w)
  1657. dw = iw ? iw * dh / ih : 0;
  1658. if (st->max_width_kind) {
  1659. int mw = st->max_width_kind == 2 ?
  1660. maxw * (int)st->max_width / 100 :
  1661. (int)st->max_width;
  1662. if (mw > 0 && dw > mw) {
  1663. dh = iw ? ih * mw / iw : 0;
  1664. dw = mw;
  1665. }
  1666. }
  1667. }
  1668. if (dw < 8)
  1669. dw = 8;
  1670. if (dh < 8)
  1671. dh = 8;
  1672. if (dw > maxw) {
  1673. dh = dw ? dh * maxw / dw : dh;
  1674. dw = maxw;
  1675. }
  1676. if (!l->draw) {
  1677. int t = l->line_y < 0 ? 0 : l->line_y;
  1678. if (t > 65535)
  1679. t = 65535;
  1680. if (dh > 65535)
  1681. dh = 65535;
  1682. img_top[node] = (unsigned short)t;
  1683. img_h[node] = (unsigned short)dh;
  1684. }
  1685. if (l->line_x + dw > l->right && (l->nruns > 0 ||
  1686. l->line_x > l->left))
  1687. flush_line(l);
  1688. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1689. flush_line(l);
  1690. if (l->nruns == 0) {
  1691. l->line_y = l->y;
  1692. l->line_h = 0;
  1693. }
  1694. {
  1695. struct lay_run *r = &l->runs[l->nruns++];
  1696. int gap = l->line_x - l->run_x;
  1697. if (gap < 0)
  1698. gap = 0;
  1699. r->gap = (unsigned short)gap;
  1700. r->off = 0;
  1701. r->len = 0;
  1702. r->color = 0;
  1703. r->href = href;
  1704. r->has_lit = 0;
  1705. r->lit[0] = '\0';
  1706. r->img = (short)idx;
  1707. r->iw = (unsigned short)dw;
  1708. r->ih = (unsigned short)dh;
  1709. r->scale = 1;
  1710. r->bold = 0;
  1711. r->underline = 0;
  1712. }
  1713. l->line_x += dw;
  1714. l->run_x = l->line_x;
  1715. if (l->line_h < dh)
  1716. l->line_h = dh;
  1717. }
  1718. static void emit_text(struct lay *l, const char *s, unsigned int len,
  1719. const struct br_style *st, unsigned short href, int pre)
  1720. {
  1721. unsigned int i = 0;
  1722. unsigned int base;
  1723. int cw = 8 * st->scale;
  1724. int adv = cw + (st->bold ? 1 : 0);
  1725. if (!s || !len)
  1726. return;
  1727. base = (unsigned int)(s - doc.text);
  1728. if (st->uppercase) {
  1729. char *p = (char *)s;
  1730. unsigned int j;
  1731. for (j = 0; j < len; j++)
  1732. if (p[j] >= 'a' && p[j] <= 'z')
  1733. p[j] = (char)(p[j] - 'a' + 'A');
  1734. }
  1735. if (pre) {
  1736. while (i < len) {
  1737. unsigned int start;
  1738. if (s[i] == '\n') {
  1739. flush_line(l);
  1740. i++;
  1741. continue;
  1742. }
  1743. if (s[i] == ' ') {
  1744. if (l->line_x + cw > l->right &&
  1745. (l->nruns > 0 || l->line_x > l->left))
  1746. flush_line(l);
  1747. else
  1748. l->line_x += cw;
  1749. i++;
  1750. continue;
  1751. }
  1752. start = i;
  1753. while (i < len && s[i] != ' ' && s[i] != '\n')
  1754. i++;
  1755. {
  1756. unsigned int n = i - start;
  1757. int w = (int)(n * (unsigned int)adv);
  1758. if (l->line_x + w > l->right &&
  1759. (l->nruns > 0 || l->line_x > l->left))
  1760. flush_line(l);
  1761. if (w > l->right - l->left) {
  1762. int maxc = (l->right - l->left) / adv;
  1763. unsigned int off = start;
  1764. if (maxc < 1)
  1765. maxc = 1;
  1766. while (n > 0) {
  1767. unsigned int take = n >
  1768. (unsigned int)maxc ?
  1769. (unsigned int)maxc : n;
  1770. add_run(l, (unsigned short)(base + off),
  1771. (unsigned short)take,
  1772. st, href, 0);
  1773. off += take;
  1774. n -= take;
  1775. if (n)
  1776. flush_line(l);
  1777. }
  1778. } else {
  1779. add_run(l, (unsigned short)(base + start),
  1780. (unsigned short)n, st, href, 0);
  1781. }
  1782. }
  1783. }
  1784. return;
  1785. }
  1786. while (i < len) {
  1787. unsigned int start, n;
  1788. int w;
  1789. if (s[i] == ' ') {
  1790. l->space_pending = 1;
  1791. i++;
  1792. continue;
  1793. }
  1794. start = i;
  1795. while (i < len && s[i] != ' ')
  1796. i++;
  1797. n = i - start;
  1798. w = (int)(n * (unsigned int)adv);
  1799. if (l->space_pending &&
  1800. (l->nruns > 0 || l->line_x > l->left)) {
  1801. if (l->line_x + cw <= l->right)
  1802. l->line_x += cw;
  1803. }
  1804. l->space_pending = 0;
  1805. if (l->line_x + w > l->right &&
  1806. (l->nruns > 0 || l->line_x > l->left))
  1807. flush_line(l);
  1808. if (w > l->right - l->left) {
  1809. int maxc = (l->right - l->left) / adv;
  1810. unsigned int off = start;
  1811. if (maxc < 1)
  1812. maxc = 1;
  1813. while (n > 0) {
  1814. unsigned int take = n > (unsigned int)maxc ?
  1815. (unsigned int)maxc : n;
  1816. add_run(l, (unsigned short)(base + off),
  1817. (unsigned short)take, st, href, 0);
  1818. off += take;
  1819. n -= take;
  1820. if (n)
  1821. flush_line(l);
  1822. }
  1823. } else if (n) {
  1824. add_run(l, (unsigned short)(base + start),
  1825. (unsigned short)n, st, href, 0);
  1826. }
  1827. }
  1828. }
  1829. static int list_index(unsigned int parent, unsigned int node)
  1830. {
  1831. unsigned int n = 0, i;
  1832. for (i = doc.nodes[parent].first; i && i != node;
  1833. i = doc.nodes[i].next)
  1834. if (doc.nodes[i].tag == BR_TAG_LI)
  1835. n++;
  1836. return (int)n + 1;
  1837. }
  1838. static const char *form_text(unsigned int node)
  1839. {
  1840. const char *v = br_value(&doc, node);
  1841. const char *p = br_placeholder(&doc, node);
  1842. const char *t = br_type(&doc, node);
  1843. if (s_eq(t, "hidden"))
  1844. return 0;
  1845. if (s_eq(t, "submit") || s_eq(t, "button") || s_eq(t, "reset"))
  1846. return v[0] ? v : "Button";
  1847. if (v[0])
  1848. return v;
  1849. if (p[0])
  1850. return p;
  1851. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  1852. return "Text";
  1853. if (doc.nodes[node].tag == BR_TAG_SELECT)
  1854. return "Select";
  1855. return "Search";
  1856. }
  1857. static void add_form_run(struct lay *l, unsigned int node,
  1858. const struct br_style *st, unsigned short href)
  1859. {
  1860. const char *text = form_text(node);
  1861. struct lay_run *r;
  1862. int tw, w, h = 20, i;
  1863. if (!text)
  1864. return;
  1865. tw = (int)s_len(text) * 8 * st->scale;
  1866. if (st->width_kind == 1)
  1867. w = st->width;
  1868. else if (st->width_kind == 2)
  1869. w = (l->right - l->left) * (int)st->width / 100;
  1870. else
  1871. w = tw + 18;
  1872. if (w < 64)
  1873. w = 64;
  1874. if (w > l->right - l->left)
  1875. w = l->right - l->left;
  1876. if (w < 8)
  1877. w = 8;
  1878. if (l->line_x + w > l->right &&
  1879. (l->nruns > 0 || l->line_x > l->left))
  1880. flush_line(l);
  1881. if (l->nruns >= 96)
  1882. return;
  1883. r = &l->runs[l->nruns++];
  1884. r->gap = (unsigned short)(l->line_x - l->run_x);
  1885. r->off = r->len = 0;
  1886. r->color = st->color;
  1887. r->href = href;
  1888. r->has_lit = 1;
  1889. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  1890. r->lit[i] = text[i];
  1891. r->lit[i] = '\0';
  1892. r->img = -2;
  1893. r->iw = (unsigned short)w;
  1894. r->ih = (unsigned short)h;
  1895. r->scale = st->scale;
  1896. r->bold = st->bold;
  1897. r->underline = 0;
  1898. l->line_x += w;
  1899. l->run_x = l->line_x;
  1900. if (l->line_h < h)
  1901. l->line_h = h;
  1902. }
  1903. static void layout_children(struct lay *l, unsigned int parent,
  1904. const struct br_style *pst, int depth,
  1905. unsigned short link);
  1906. static void layout_flex_children(struct lay *l, unsigned int parent,
  1907. const struct br_style *pst, int depth,
  1908. unsigned short link);
  1909. static void layout_grid_children(struct lay *l, unsigned int parent,
  1910. const struct br_style *pst, int depth,
  1911. unsigned short link);
  1912. static void layout_block(struct lay *l, unsigned int node,
  1913. const struct br_style *st, int depth,
  1914. unsigned short link)
  1915. {
  1916. int old_left = l->left, old_right = l->right, old_align = l->align;
  1917. int top, l0, r0;
  1918. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  1919. return;
  1920. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  1921. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  1922. doc.nodes[node].tag == BR_TAG_SELECT) {
  1923. if (!(doc.nodes[node].tag == BR_TAG_INPUT &&
  1924. s_eq(br_type(&doc, node), "hidden")))
  1925. add_form_run(l, node, st, link);
  1926. l->y += 20;
  1927. return;
  1928. }
  1929. flush_line(l);
  1930. l->y += st->mt;
  1931. top = l->y;
  1932. l0 = old_left + st->ml;
  1933. r0 = old_right - st->mr;
  1934. if (r0 < l0 + 16)
  1935. r0 = l0 + 16;
  1936. if (l->draw && st->has_bg && block_h[node])
  1937. ngui_fill_rect(l->ui, (struct ngui_rect){l0, top, r0 - l0,
  1938. block_h[node]},
  1939. st->bg);
  1940. if (l->draw && st->border_w && block_h[node])
  1941. ngui_frame(l->ui, (struct ngui_rect){l0, top, r0 - l0,
  1942. block_h[node]},
  1943. st->border_color);
  1944. l->left = l0 + st->pl;
  1945. l->right = r0 - st->pr;
  1946. if (l->right < l->left + 8)
  1947. l->right = l->left + 8;
  1948. l->align = st->align;
  1949. l->y += st->pt;
  1950. if (doc.nodes[node].tag == BR_TAG_HR) {
  1951. if (l->draw)
  1952. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  1953. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  1954. l->y += 8;
  1955. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  1956. int vw = l->right - l->left;
  1957. int vh;
  1958. if (doc.nodes[node].width_pct)
  1959. vw = vw * doc.nodes[node].width_attr / 100;
  1960. else if (doc.nodes[node].width_attr)
  1961. vw = doc.nodes[node].width_attr;
  1962. if (vw > l->right - l->left)
  1963. vw = l->right - l->left;
  1964. if (vw < 8)
  1965. vw = 8;
  1966. vh = vw * 9 / 16;
  1967. if (vh > 240)
  1968. vh = 240;
  1969. if (vh < 80)
  1970. vh = 80;
  1971. if (l->draw) {
  1972. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  1973. vw, vh}, 0xD69A);
  1974. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  1975. vw, vh}, 0x8410);
  1976. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  1977. 0x4208);
  1978. }
  1979. l->y += vh + 4;
  1980. } else {
  1981. if (doc.nodes[node].tag == BR_TAG_LI && !st->no_bullet) {
  1982. char *m = li_marker[node];
  1983. if (!m[0]) {
  1984. unsigned int parent = doc.nodes[node].parent;
  1985. if (parent &&
  1986. doc.nodes[parent].tag == BR_TAG_OL) {
  1987. int idx = list_index(parent, node);
  1988. unsigned int n = 0;
  1989. s_append_dec(m, &n, (unsigned int)idx, 6);
  1990. s_append(m, &n, ".", 6);
  1991. } else {
  1992. s_copy(m, "-", 6);
  1993. }
  1994. }
  1995. if (l->draw) {
  1996. int mw = (int)s_len(m) * 8;
  1997. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  1998. st->color);
  1999. }
  2000. }
  2001. if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  2002. st->grid_gap > 0)
  2003. layout_grid_children(l, node, st, depth + 1, link);
  2004. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col)
  2005. layout_flex_children(l, node, st, depth + 1, link);
  2006. else
  2007. layout_children(l, node, st, depth + 1, link);
  2008. }
  2009. flush_line(l);
  2010. l->y += st->pb;
  2011. l->left = old_left;
  2012. l->right = old_right;
  2013. l->align = old_align;
  2014. l->y += st->mb;
  2015. if (!l->draw) {
  2016. int h = l->y - top;
  2017. if (h < 0)
  2018. h = 0;
  2019. if (h > 65535)
  2020. h = 65535;
  2021. block_h[node] = (unsigned short)h;
  2022. }
  2023. }
  2024. static int text_node_blank(const struct br_node *nd)
  2025. {
  2026. const char *t = doc.text + nd->text_off;
  2027. unsigned int i;
  2028. for (i = 0; i < nd->text_len; i++)
  2029. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  2030. t[i] != '\r')
  2031. return 0;
  2032. return 1;
  2033. }
  2034. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  2035. * text/image widths in the subtree, plus padding and margins. This keeps
  2036. * Bootstrap's floated nav items on one line instead of giving each the whole
  2037. * row. */
  2038. static int intrinsic_width(unsigned int node, const struct br_style *pst,
  2039. int depth)
  2040. {
  2041. unsigned int c;
  2042. int w = 0;
  2043. if (depth > 12)
  2044. return 0;
  2045. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  2046. struct br_node *nd = &doc.nodes[c];
  2047. struct br_style cs;
  2048. if (nd->type == BR_NODE_TEXT) {
  2049. w += (int)nd->text_len * (8 * pst->scale) +
  2050. (pst->bold ? 1 : 0);
  2051. continue;
  2052. }
  2053. br_style_for(&doc, c, pst, &cs);
  2054. if (cs.display == BR_DISPLAY_NONE)
  2055. continue;
  2056. if (cs.float_left)
  2057. w += 8;
  2058. if (nd->tag == BR_TAG_BR) {
  2059. w += 8;
  2060. continue;
  2061. }
  2062. if (nd->tag == BR_TAG_IMG) {
  2063. int idx = nd->img_index;
  2064. if (idx >= 0 && idx < image_count &&
  2065. images[idx].state == 1)
  2066. w += (int)images[idx].img.w;
  2067. else if (nd->width_attr)
  2068. w += nd->width_attr;
  2069. else
  2070. w += 64;
  2071. continue;
  2072. }
  2073. w += cs.pl + cs.pr + cs.ml + cs.mr;
  2074. w += intrinsic_width(c, &cs, depth + 1);
  2075. if (w > 4096)
  2076. break;
  2077. }
  2078. return w;
  2079. }
  2080. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  2081. * the main user: .row > .col-md-* with float:left and a percentage width.
  2082. * Each column is laid out with its own left/right edge and the row advances
  2083. * to the tallest column. Returns the first child not consumed. */
  2084. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  2085. const struct br_style *pst, int depth,
  2086. unsigned short link)
  2087. {
  2088. unsigned int n = first;
  2089. int row_left = l->left, row_right = l->right;
  2090. int row_top, row_bottom, x, any = 0;
  2091. flush_line(l);
  2092. row_top = l->y;
  2093. row_bottom = l->y;
  2094. x = row_left;
  2095. while (n) {
  2096. struct br_node *nd = &doc.nodes[n];
  2097. struct br_style cs;
  2098. int colw;
  2099. if (nd->type == BR_NODE_TEXT) {
  2100. if (text_node_blank(nd)) {
  2101. n = nd->next;
  2102. continue;
  2103. }
  2104. break;
  2105. }
  2106. br_style_for(&doc, n, pst, &cs);
  2107. if (cs.display == BR_DISPLAY_NONE) {
  2108. n = nd->next;
  2109. continue;
  2110. }
  2111. if (!cs.float_left || cs.display != BR_DISPLAY_BLOCK)
  2112. break;
  2113. if (cs.width_kind == 2)
  2114. colw = (row_right - row_left) * (int)cs.width / 100;
  2115. else if (cs.width_kind == 1)
  2116. colw = (int)cs.width;
  2117. else {
  2118. colw = intrinsic_width(n, &cs, 0) +
  2119. cs.pl + cs.pr + cs.ml + cs.mr + 8;
  2120. if (colw < 8)
  2121. colw = 8;
  2122. }
  2123. if (colw < 8)
  2124. colw = 8;
  2125. if (colw > row_right - row_left)
  2126. colw = row_right - row_left;
  2127. if (any && x + colw > row_right) {
  2128. row_top = row_bottom;
  2129. row_bottom = row_top;
  2130. x = row_left;
  2131. }
  2132. l->left = x;
  2133. l->right = x + colw;
  2134. if (l->right < l->left + 8)
  2135. l->right = l->left + 8;
  2136. l->y = row_top;
  2137. l->line_x = l->left;
  2138. l->run_x = l->left;
  2139. l->line_y = l->y;
  2140. l->line_h = 0;
  2141. l->nruns = 0;
  2142. l->space_pending = 0;
  2143. l->align = cs.align;
  2144. layout_block(l, n, &cs, depth + 1, link);
  2145. if (l->y > row_bottom)
  2146. row_bottom = l->y;
  2147. x += colw;
  2148. any++;
  2149. n = nd->next;
  2150. }
  2151. l->left = row_left;
  2152. l->right = row_right;
  2153. l->y = row_bottom;
  2154. l->line_x = l->left;
  2155. l->run_x = l->left;
  2156. l->line_y = l->y;
  2157. l->line_h = 0;
  2158. l->nruns = 0;
  2159. l->space_pending = 0;
  2160. return n;
  2161. }
  2162. /* A deliberately simple flex row: items are placed left to right, grow
  2163. * items share the leftover width, and a row wraps when the next item does not
  2164. * fit. It is enough for site headers, cards and Wikipedia's main-page boxes;
  2165. * flex-direction: column uses the normal block path. */
  2166. static int flex_item_width(struct lay *l, unsigned int n,
  2167. const struct br_style *cs, int avail)
  2168. {
  2169. struct br_node *nd = &doc.nodes[n];
  2170. (void)l;
  2171. int w;
  2172. if (cs->width_kind == 2)
  2173. w = avail * (int)cs->width / 100;
  2174. else if (cs->width_kind == 1)
  2175. w = (int)cs->width;
  2176. else if (nd->tag == BR_TAG_IMG) {
  2177. int idx = nd->img_index;
  2178. if (idx >= 0 && idx < image_count &&
  2179. images[idx].state == 1)
  2180. w = (int)images[idx].img.w;
  2181. else if (nd->width_attr)
  2182. w = (int)nd->width_attr;
  2183. else
  2184. w = 64;
  2185. } else {
  2186. w = intrinsic_width(n, cs, 0);
  2187. w += cs->pl + cs->pr + cs->ml + cs->mr;
  2188. }
  2189. if (w < 24)
  2190. w = 24;
  2191. if (w > avail)
  2192. w = avail;
  2193. return w;
  2194. }
  2195. static void layout_flex_children(struct lay *l, unsigned int parent,
  2196. const struct br_style *pst, int depth,
  2197. unsigned short link)
  2198. {
  2199. unsigned int n, c;
  2200. int row_left = l->left, row_right = l->right;
  2201. int avail = row_right - row_left;
  2202. int grow_count = 0, fixed = 0, grow_w;
  2203. int x = row_left, row_top = l->y, row_bottom = l->y, any = 0;
  2204. if (avail < 160 || depth > 24) {
  2205. layout_children(l, parent, pst, depth, link);
  2206. return;
  2207. }
  2208. /* If direct text is not just whitespace, normal block flow handles it
  2209. * better than pretending it is a flex item. */
  2210. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2211. struct br_node *nd = &doc.nodes[c];
  2212. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  2213. layout_children(l, parent, pst, depth, link);
  2214. return;
  2215. }
  2216. }
  2217. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2218. struct br_node *nd = &doc.nodes[c];
  2219. struct br_style cs;
  2220. if (nd->type == BR_NODE_TEXT)
  2221. continue;
  2222. br_style_for(&doc, c, pst, &cs);
  2223. if (cs.display == BR_DISPLAY_NONE)
  2224. continue;
  2225. if (cs.flex_grow && !cs.width_kind)
  2226. grow_count++;
  2227. else
  2228. fixed += flex_item_width(l, c, &cs, avail);
  2229. }
  2230. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  2231. if (grow_w < 96)
  2232. grow_w = 96;
  2233. n = doc.nodes[parent].first;
  2234. while (n) {
  2235. struct br_node *nd = &doc.nodes[n];
  2236. struct br_style cs;
  2237. unsigned short lk = link;
  2238. int colw;
  2239. if (nd->type == BR_NODE_TEXT) {
  2240. n = nd->next;
  2241. continue;
  2242. }
  2243. br_style_for(&doc, n, pst, &cs);
  2244. if (cs.display == BR_DISPLAY_NONE) {
  2245. n = nd->next;
  2246. continue;
  2247. }
  2248. if (nd->tag == BR_TAG_A && nd->href_off)
  2249. lk = (unsigned short)n;
  2250. if (cs.flex_grow && !cs.width_kind)
  2251. colw = grow_w;
  2252. else
  2253. colw = flex_item_width(l, n, &cs, avail);
  2254. if (colw > row_right - row_left)
  2255. colw = row_right - row_left;
  2256. if (any && x + colw > row_right) {
  2257. row_top = row_bottom;
  2258. row_bottom = row_top;
  2259. x = row_left;
  2260. }
  2261. l->left = x;
  2262. l->right = x + colw;
  2263. if (l->right < l->left + 8)
  2264. l->right = l->left + 8;
  2265. l->y = row_top;
  2266. l->line_x = l->left;
  2267. l->run_x = l->left;
  2268. l->line_y = l->y;
  2269. l->line_h = 0;
  2270. l->nruns = 0;
  2271. l->space_pending = 0;
  2272. l->align = cs.align;
  2273. layout_block(l, n, &cs, depth + 1, lk);
  2274. if (l->y > row_bottom)
  2275. row_bottom = l->y;
  2276. x += colw;
  2277. any++;
  2278. n = nd->next;
  2279. }
  2280. l->left = row_left;
  2281. l->right = row_right;
  2282. l->y = row_bottom;
  2283. l->line_x = l->left;
  2284. l->run_x = l->left;
  2285. l->line_y = l->y;
  2286. l->line_h = 0;
  2287. l->nruns = 0;
  2288. l->space_pending = 0;
  2289. }
  2290. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  2291. * plus the grid-area hints used by site shells (site notice/footer full
  2292. * width, column-start left, page-content right). Anything more elaborate
  2293. * falls back to normal block flow. */
  2294. static int grid_track_width(unsigned char kind, unsigned short val,
  2295. int avail, int other)
  2296. {
  2297. if (kind == 2)
  2298. return avail * (int)val / 100;
  2299. if (kind == 1)
  2300. return val;
  2301. return other;
  2302. }
  2303. static void layout_grid_children(struct lay *l, unsigned int parent,
  2304. const struct br_style *pst, int depth,
  2305. unsigned short link)
  2306. {
  2307. unsigned int n;
  2308. int row_left = l->left, row_right = l->right;
  2309. int avail = row_right - row_left;
  2310. int gap = pst->grid_gap;
  2311. int track_total = avail - gap;
  2312. int col0, col1, x0, x1;
  2313. int row_y, row_bottom, have_left = 0, have_right = 0;
  2314. unsigned int c;
  2315. if (avail < 32 || depth > 24)
  2316. return;
  2317. if (track_total < 16)
  2318. track_total = 16;
  2319. col0 = grid_track_width((unsigned char)(pst->width_kind),
  2320. pst->width, track_total, 0);
  2321. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  2322. pst->max_width, track_total, 0);
  2323. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  2324. int w0 = pst->width ? pst->width : 1;
  2325. int w1 = pst->max_width ? pst->max_width : 1;
  2326. col0 = track_total * w0 / (w0 + w1);
  2327. col1 = track_total - col0;
  2328. } else if (pst->width_kind == 3) {
  2329. col0 = track_total - col1;
  2330. if (col0 < 24)
  2331. col0 = 24;
  2332. } else if (pst->max_width_kind == 3) {
  2333. col1 = track_total - col0;
  2334. if (col1 < 24)
  2335. col1 = 24;
  2336. }
  2337. if (col0 < 24)
  2338. col0 = 24;
  2339. if (col1 < 24)
  2340. col1 = 24;
  2341. if (col0 + col1 > track_total) {
  2342. col1 = track_total - col0;
  2343. if (col1 < 24)
  2344. col1 = 24;
  2345. }
  2346. x0 = row_left;
  2347. x1 = row_left + col0 + gap;
  2348. /* Direct text makes a grid ambiguous; use block flow instead. */
  2349. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2350. struct br_node *nd = &doc.nodes[c];
  2351. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  2352. layout_children(l, parent, pst, depth, link);
  2353. return;
  2354. }
  2355. }
  2356. row_y = row_bottom = l->y;
  2357. n = doc.nodes[parent].first;
  2358. while (n) {
  2359. struct br_node *nd = &doc.nodes[n];
  2360. struct br_style cs;
  2361. unsigned short lk = link;
  2362. int slot, x, w;
  2363. if (nd->type == BR_NODE_TEXT) {
  2364. n = nd->next;
  2365. continue;
  2366. }
  2367. br_style_for(&doc, n, pst, &cs);
  2368. if (cs.display == BR_DISPLAY_NONE) {
  2369. n = nd->next;
  2370. continue;
  2371. }
  2372. if (nd->tag == BR_TAG_A && nd->href_off)
  2373. lk = (unsigned short)n;
  2374. slot = cs.grid_slot;
  2375. if (!slot) {
  2376. if (!have_left)
  2377. slot = 2;
  2378. else if (!have_right)
  2379. slot = 3;
  2380. else
  2381. slot = 2;
  2382. }
  2383. if (slot == 1) {
  2384. if (have_left || have_right) {
  2385. row_y = row_bottom;
  2386. have_left = have_right = 0;
  2387. }
  2388. x = row_left;
  2389. w = avail;
  2390. } else if (slot == 2) {
  2391. if (have_left) {
  2392. row_y = row_bottom;
  2393. have_left = have_right = 0;
  2394. }
  2395. x = x0;
  2396. w = col0;
  2397. have_left = 1;
  2398. } else {
  2399. if (have_right) {
  2400. row_y = row_bottom;
  2401. have_left = have_right = 0;
  2402. }
  2403. x = x1;
  2404. w = col1;
  2405. have_right = 1;
  2406. }
  2407. l->left = x;
  2408. l->right = x + w;
  2409. if (l->right < l->left + 8)
  2410. l->right = l->left + 8;
  2411. l->y = row_y;
  2412. l->line_x = l->left;
  2413. l->run_x = l->left;
  2414. l->line_y = l->y;
  2415. l->line_h = 0;
  2416. l->nruns = 0;
  2417. l->space_pending = 0;
  2418. l->align = cs.align;
  2419. layout_block(l, n, &cs, depth + 1, lk);
  2420. if (l->y > row_bottom)
  2421. row_bottom = l->y;
  2422. n = nd->next;
  2423. }
  2424. l->left = row_left;
  2425. l->right = row_right;
  2426. l->y = row_bottom;
  2427. l->line_x = l->left;
  2428. l->run_x = l->left;
  2429. l->line_y = l->y;
  2430. l->line_h = 0;
  2431. l->nruns = 0;
  2432. l->space_pending = 0;
  2433. }
  2434. static void layout_children(struct lay *l, unsigned int parent,
  2435. const struct br_style *pst, int depth,
  2436. unsigned short link)
  2437. {
  2438. unsigned int n;
  2439. if (depth > 24)
  2440. return;
  2441. n = doc.nodes[parent].first;
  2442. while (n) {
  2443. struct br_node *nd = &doc.nodes[n];
  2444. struct br_style cs;
  2445. unsigned short lk = link;
  2446. if (nd->type == BR_NODE_TEXT) {
  2447. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  2448. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  2449. n = nd->next;
  2450. continue;
  2451. }
  2452. br_style_for(&doc, n, pst, &cs);
  2453. if (cs.display == BR_DISPLAY_NONE) {
  2454. n = nd->next;
  2455. continue;
  2456. }
  2457. if (nd->tag == BR_TAG_A && nd->href_off)
  2458. lk = (unsigned short)n;
  2459. if (nd->tag == BR_TAG_BR) {
  2460. flush_line(l);
  2461. n = nd->next;
  2462. continue;
  2463. }
  2464. if (nd->tag == BR_TAG_HR) {
  2465. flush_line(l);
  2466. if (l->draw)
  2467. ngui_fill_rect(l->ui,
  2468. (struct ngui_rect){l->left, l->y + 2,
  2469. l->right - l->left, 1}, BR_GRAY);
  2470. l->y += 8;
  2471. n = nd->next;
  2472. continue;
  2473. }
  2474. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  2475. nd->tag == BR_TAG_SELECT) {
  2476. if (!(nd->tag == BR_TAG_INPUT &&
  2477. s_eq(br_type(&doc, n), "hidden")))
  2478. add_form_run(l, n, &cs, lk);
  2479. n = nd->next;
  2480. continue;
  2481. }
  2482. if (nd->tag == BR_TAG_IMG) {
  2483. add_image_run(l, n, &cs, lk);
  2484. n = nd->next;
  2485. continue;
  2486. }
  2487. if (nd->tag == BR_TAG_VIDEO) {
  2488. layout_block(l, n, &cs, depth + 1, lk);
  2489. n = nd->next;
  2490. continue;
  2491. }
  2492. if (cs.float_left && cs.display == BR_DISPLAY_BLOCK) {
  2493. n = layout_float_group(l, n, pst, depth, link);
  2494. continue;
  2495. }
  2496. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  2497. layout_block(l, n, &cs, depth + 1, lk);
  2498. else {
  2499. layout_children(l, n, &cs, depth + 1, lk);
  2500. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  2501. l->space_pending = 1;
  2502. }
  2503. n = nd->next;
  2504. }
  2505. }
  2506. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  2507. * runs and a recursive page can otherwise overflow the stack. */
  2508. static struct lay layout_state;
  2509. static int measure_page(int left, int right)
  2510. {
  2511. struct lay *l = &layout_state;
  2512. struct br_style base = base_style();
  2513. unsigned int i;
  2514. for (i = 0; i < BR_MAX_NODES; i++) {
  2515. block_h[i] = 0;
  2516. img_top[i] = 0;
  2517. img_h[i] = 0;
  2518. }
  2519. l->draw = 0;
  2520. l->ui = 0;
  2521. l->left = left;
  2522. l->right = right;
  2523. l->y = 0;
  2524. l->line_x = left;
  2525. l->run_x = left;
  2526. l->line_y = 0;
  2527. l->line_h = 0;
  2528. l->align = BR_ALIGN_LEFT;
  2529. l->depth = 0;
  2530. l->nruns = 0;
  2531. l->space_pending = 0;
  2532. layout_children(l, doc.root, &base, 0, 0);
  2533. return l->y + 8;
  2534. }
  2535. static void render_page(int left, int right, int y0)
  2536. {
  2537. struct lay *l = &layout_state;
  2538. struct br_style base = base_style();
  2539. l->draw = 1;
  2540. l->ui = &ui;
  2541. l->left = left;
  2542. l->right = right;
  2543. l->y = y0;
  2544. l->line_x = left;
  2545. l->run_x = left;
  2546. l->line_y = y0;
  2547. l->line_h = 0;
  2548. l->align = BR_ALIGN_LEFT;
  2549. l->depth = 0;
  2550. l->nruns = 0;
  2551. l->space_pending = 0;
  2552. nhits = 0;
  2553. layout_children(l, doc.root, &base, 0, 0);
  2554. }
  2555. /* ---- UI ---- */
  2556. static int find_hit(int x, int y)
  2557. {
  2558. int i;
  2559. for (i = nhits - 1; i >= 0; i--) {
  2560. struct hit *h = &hits[i];
  2561. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  2562. y < h->y + h->h)
  2563. return (int)h->node;
  2564. }
  2565. return 0;
  2566. }
  2567. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  2568. {
  2569. int x = r.x + 4, y = r.y + 4, h = 22;
  2570. int compact = r.w < 560;
  2571. int go_w = r.w < 420 ? 32 : 42;
  2572. int in_x, in_w, res;
  2573. ngui_fill_rect(&ui, r, ui.theme.panel);
  2574. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  2575. ui.theme.border);
  2576. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  2577. NGUI_ICON_CHEVRON_LEFT))
  2578. *action |= ACT_BACK;
  2579. x += 32;
  2580. if (!compact) {
  2581. if (ngui_icon_button(&ui, ID_FORWARD,
  2582. (struct ngui_rect){x, y, 28, h},
  2583. NGUI_ICON_CHEVRON_RIGHT))
  2584. *action |= ACT_FORWARD;
  2585. x += 32;
  2586. }
  2587. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  2588. NGUI_ICON_REFRESH))
  2589. *action |= ACT_RELOAD;
  2590. x += 32;
  2591. if (!compact) {
  2592. if (ngui_icon_button(&ui, ID_HOME,
  2593. (struct ngui_rect){x, y, 28, h},
  2594. NGUI_ICON_HOME))
  2595. *action |= ACT_HOME;
  2596. x += 32;
  2597. }
  2598. in_x = x + 2;
  2599. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  2600. if (in_w < 60)
  2601. in_w = 60;
  2602. res = ngui_text_input(&ui, ID_URL,
  2603. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  2604. if (res & NGUI_INPUT_SUBMIT)
  2605. *action |= ACT_NAV;
  2606. if (res & NGUI_INPUT_CANCEL)
  2607. ngui_set_focus(&ui, 0);
  2608. if (ngui_button(&ui, ID_GO,
  2609. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  2610. "Go"))
  2611. *action |= ACT_NAV;
  2612. }
  2613. static int page_hover_node(void)
  2614. {
  2615. if (!ui.inside)
  2616. return 0;
  2617. if (ui.mouse_x < page_rect.x ||
  2618. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  2619. ui.mouse_y < page_rect.y ||
  2620. ui.mouse_y >= page_rect.y + page_rect.h)
  2621. return 0;
  2622. return find_hit(ui.mouse_x, ui.mouse_y);
  2623. }
  2624. static void draw_page(struct ngui_rect page)
  2625. {
  2626. int left, right, ch;
  2627. int old_panel, old_dim;
  2628. page_rect = page;
  2629. ngui_fill_rect(&ui, page, ui.theme.bg);
  2630. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  2631. const char *s = page_loading ? "Loading..." : "No page";
  2632. int w = (int)ngui_text_width(s);
  2633. ngui_text(&ui, page.x + (page.w - w) / 2,
  2634. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  2635. page_scroll.content_h = 0;
  2636. page_scroll.view_h = page.h;
  2637. return;
  2638. }
  2639. if (page.w < 40 || page.h < 40)
  2640. return;
  2641. left = page.x + 8;
  2642. right = page.x + page.w - 16;
  2643. ch = measure_page(left, right);
  2644. page_scroll.content_h = ch;
  2645. page_scroll.view_h = page.h;
  2646. ngui_scroll_begin(&ui, page, &page_scroll);
  2647. render_page(left, right, page.y + 4 - page_scroll.offset);
  2648. old_panel = ui.theme.panel_alt;
  2649. old_dim = ui.theme.text_dim;
  2650. ui.theme.panel_alt = 0xC618;
  2651. ui.theme.text_dim = 0x8410;
  2652. ngui_scroll_end(&ui, page, &page_scroll);
  2653. ui.theme.panel_alt = old_panel;
  2654. ui.theme.text_dim = old_dim;
  2655. }
  2656. static void draw_status(struct ngui_rect r)
  2657. {
  2658. char msg[BR_URL_MAX + 32];
  2659. unsigned int n = 0;
  2660. int hover = page_hover_node();
  2661. unsigned short color;
  2662. const char *kind;
  2663. ngui_fill_rect(&ui, r, ui.theme.panel);
  2664. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  2665. ui.theme.border);
  2666. if (hover) {
  2667. const char *href = br_href(&doc, (unsigned int)hover);
  2668. char url[BR_URL_MAX];
  2669. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  2670. s_append(msg, &n, "Link: ", sizeof(msg));
  2671. s_append(msg, &n, url, sizeof(msg));
  2672. } else {
  2673. s_copy(msg, "Link", sizeof(msg));
  2674. }
  2675. color = ui.theme.accent;
  2676. } else if (status_text[0]) {
  2677. s_copy(msg, status_text, sizeof(msg));
  2678. color = status_error ? ui.theme.error : ui.theme.text;
  2679. } else if (page_title[0]) {
  2680. s_copy(msg, page_title, sizeof(msg));
  2681. color = ui.theme.text;
  2682. } else {
  2683. s_copy(msg, "Ready", sizeof(msg));
  2684. color = ui.theme.text_dim;
  2685. }
  2686. kind = s_eq(page_url, "about:home") ? "HOME" :
  2687. page_is_local ? "FILE" :
  2688. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  2689. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  2690. {
  2691. int kw = (int)ngui_text_width(kind);
  2692. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  2693. ui.theme.text_dim);
  2694. }
  2695. }
  2696. static void draw(unsigned int *action)
  2697. {
  2698. struct ngui_rect r = {0, 0, ui.w, ui.h};
  2699. struct ngui_rect toolbar, status, page;
  2700. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  2701. status = ngui_cut_bottom(&r, BR_STATUS_H);
  2702. page = r;
  2703. draw_toolbar(toolbar, action);
  2704. draw_page(page);
  2705. draw_status(status);
  2706. }
  2707. static void redraw_now(void)
  2708. {
  2709. unsigned int action = 0;
  2710. ngui_begin(&ui);
  2711. draw(&action);
  2712. ngui_end(&ui);
  2713. }
  2714. static void handle_keys(unsigned int *action)
  2715. {
  2716. int k;
  2717. if (ngui_focus(&ui))
  2718. return;
  2719. if (ngui_scroll_keys(&ui, &page_scroll))
  2720. ngui_invalidate(&ui);
  2721. while ((k = ngui_key(&ui)) != 0) {
  2722. switch (k) {
  2723. case NGUI_KEY_ESC:
  2724. *action |= ACT_CLOSE;
  2725. break;
  2726. case NGUI_KEY_TAB:
  2727. case 0x0C: /* Ctrl+L */
  2728. ngui_set_focus(&ui, ID_URL);
  2729. break;
  2730. case 0x12: /* Ctrl+R */
  2731. *action |= ACT_RELOAD;
  2732. break;
  2733. case NGUI_KEY_BACKSPACE:
  2734. *action |= ACT_BACK;
  2735. break;
  2736. case NGUI_KEY_UP:
  2737. ngui_scroll_to(&page_scroll,
  2738. page_scroll.offset - 24);
  2739. ngui_invalidate(&ui);
  2740. break;
  2741. case NGUI_KEY_DOWN:
  2742. ngui_scroll_to(&page_scroll,
  2743. page_scroll.offset + 24);
  2744. ngui_invalidate(&ui);
  2745. break;
  2746. case NGUI_KEY_HOME:
  2747. ngui_scroll_to(&page_scroll, 0);
  2748. ngui_invalidate(&ui);
  2749. break;
  2750. case NGUI_KEY_END:
  2751. ngui_scroll_to(&page_scroll,
  2752. page_scroll.content_h -
  2753. page_scroll.view_h);
  2754. ngui_invalidate(&ui);
  2755. break;
  2756. default:
  2757. break;
  2758. }
  2759. }
  2760. }
  2761. static void handle_page_click(unsigned int *action)
  2762. {
  2763. int node;
  2764. char url[BR_URL_MAX];
  2765. if (!ui.pressed)
  2766. return;
  2767. if (ui.press_x < page_rect.x ||
  2768. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  2769. ui.press_y < page_rect.y ||
  2770. ui.press_y >= page_rect.y + page_rect.h)
  2771. return;
  2772. node = find_hit(ui.press_x, ui.press_y);
  2773. if (!node)
  2774. return;
  2775. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  2776. sizeof(url)) != 0)
  2777. return;
  2778. s_copy(click_url, url, sizeof(click_url));
  2779. *action |= ACT_NAV;
  2780. }
  2781. void _start(const char *arg)
  2782. {
  2783. struct win_info wi;
  2784. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0) {
  2785. u_puts("browser: no graphics window\n");
  2786. u_exit(1);
  2787. }
  2788. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  2789. url_in.placeholder = "http://...";
  2790. br_doc_init(&doc);
  2791. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  2792. ui.theme.accent);
  2793. br_set_viewport(BR_VIEWPORT_W);
  2794. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  2795. s_copy(cwd, "/", sizeof(cwd));
  2796. heap_clear();
  2797. page_scroll.offset = 0;
  2798. page_scroll.content_h = 0;
  2799. if (arg && arg[0])
  2800. navigate(arg, 1);
  2801. else
  2802. load_home(1);
  2803. for (;;) {
  2804. unsigned int action = 0;
  2805. unsigned int now;
  2806. click_url[0] = '\0';
  2807. if (pending_action) {
  2808. action |= pending_action & ACT_WAIT_NAV;
  2809. if (pending_url[0])
  2810. s_copy(click_url, pending_url, sizeof(click_url));
  2811. pending_action = 0;
  2812. pending_url[0] = '\0';
  2813. cancel_fetch = 0;
  2814. } else if (preload_active) {
  2815. if (preload_wait)
  2816. preload_wait = 0;
  2817. else
  2818. preload_step();
  2819. } else if (preload_pending &&
  2820. page_scroll.offset != preload_scroll) {
  2821. preload_scroll = page_scroll.offset;
  2822. preload_pending = 0;
  2823. preload_active = 1;
  2824. }
  2825. now = u_ticks_ms();
  2826. if (status_until && (int)(now - status_until) >= 0) {
  2827. status_text[0] = '\0';
  2828. status_until = 0;
  2829. status_error = 0;
  2830. ngui_invalidate(&ui);
  2831. }
  2832. if (!ngui_begin(&ui)) {
  2833. /* A queued navigation (e.g. Enter in the URL bar during
  2834. * a slow fetch) must be handled even when this frame
  2835. * needs no redraw. */
  2836. if (!action) {
  2837. u_sleep_ms(10);
  2838. continue;
  2839. }
  2840. } else {
  2841. draw(&action);
  2842. handle_keys(&action);
  2843. handle_page_click(&action);
  2844. ngui_end(&ui);
  2845. }
  2846. if (action & ACT_NAV) {
  2847. if (click_url[0]) {
  2848. navigate(click_url, 1);
  2849. click_url[0] = '\0';
  2850. } else {
  2851. navigate(url_in.text, 1);
  2852. }
  2853. }
  2854. if (action & ACT_BACK) {
  2855. if (hist_pos > 0) {
  2856. hist_pos--;
  2857. navigate(history[hist_pos], 0);
  2858. }
  2859. }
  2860. if (action & ACT_FORWARD) {
  2861. if (hist_pos + 1 < hist_len) {
  2862. hist_pos++;
  2863. navigate(history[hist_pos], 0);
  2864. }
  2865. }
  2866. if (action & ACT_RELOAD) {
  2867. if (s_eq(page_url, "about:home"))
  2868. load_home(0);
  2869. else
  2870. navigate(page_url, 0);
  2871. }
  2872. if (action & ACT_HOME)
  2873. load_home(1);
  2874. if (action & ACT_CLOSE)
  2875. quit = 1;
  2876. if (quit)
  2877. break;
  2878. if (pending_action)
  2879. continue;
  2880. u_sleep_ms(10);
  2881. }
  2882. u_win_close();
  2883. u_exit(0);
  2884. }