browser.c 85 KB

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