browser.c 100 KB

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