browser.c 101 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236
  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. /* Start wide enough for the desktop nav; smaller screens fall back to
  19. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  20. #define BR_W 1100
  21. #define BR_H 700
  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. /* heap_clear() detaches the fonts, so attach them again before the
  1317. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  1318. if (heap_start() != 0) {
  1319. show_error("Out of memory", "Cannot allocate the page buffer");
  1320. return;
  1321. }
  1322. ngui_font_attach(&ui);
  1323. redraw_now();
  1324. browser_rules_alloc();
  1325. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  1326. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  1327. &truncated);
  1328. if (rv == FETCH_ABORT)
  1329. return;
  1330. if (rv != 0) {
  1331. detail = err;
  1332. show_error("Cannot load this page", detail);
  1333. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1334. url_in.len = s_len(url_in.text);
  1335. url_in.cursor = url_in.len;
  1336. url_in.scroll = 0;
  1337. return;
  1338. }
  1339. page_is_local = local;
  1340. if (final[0]) {
  1341. s_copy(page_url, final, sizeof(page_url));
  1342. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1343. url_in.len = s_len(url_in.text);
  1344. url_in.cursor = url_in.len;
  1345. url_in.scroll = 0;
  1346. }
  1347. if (contains_ci(ctype, "text/plain")) {
  1348. br_parse_plain(&doc, (const char *)body, len);
  1349. } else if (contains_ci(ctype, "image/") ||
  1350. (!contains_ci(ctype, "text/html") &&
  1351. img_sniff(body, len, &image_info) == 0)) {
  1352. unsigned int node = br_parse_image_doc(&doc, page_url);
  1353. if (node)
  1354. decode_direct_image(body, len, node);
  1355. s_copy(page_title, "Image", sizeof(page_title));
  1356. } else {
  1357. br_set_viewport(ui.w);
  1358. br_parse(&doc, (const char *)body, len);
  1359. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  1360. sizeof(page_title));
  1361. if (load_stylesheets() == FETCH_ABORT)
  1362. return;
  1363. if (pending_action)
  1364. return;
  1365. }
  1366. post_status_text[0] = '\0';
  1367. post_status_error = 0;
  1368. post_status_ttl = 0;
  1369. if (truncated) {
  1370. s_copy(post_status_text, "Page truncated at the buffer limit",
  1371. sizeof(post_status_text));
  1372. post_status_ttl = 6000;
  1373. } else if (doc.truncated) {
  1374. s_copy(post_status_text, "Page truncated by the parser",
  1375. sizeof(post_status_text));
  1376. post_status_ttl = 6000;
  1377. } else if (starts_with(page_url, "https://")) {
  1378. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  1379. sizeof(post_status_text));
  1380. post_status_ttl = 6000;
  1381. }
  1382. preload_begin();
  1383. page_loading = 0;
  1384. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1385. url_in.len = s_len(url_in.text);
  1386. url_in.cursor = url_in.len;
  1387. url_in.scroll = 0;
  1388. ngui_set_focus(&ui, 0);
  1389. ngui_invalidate(&ui);
  1390. }
  1391. static void load_home(int push)
  1392. {
  1393. cancel_fetch = 0;
  1394. preload_active = 0;
  1395. preload_pending = 0;
  1396. heap_clear();
  1397. image_reset();
  1398. layout_valid = 0;
  1399. page_scroll.offset = 0;
  1400. page_scroll.dragging = 0;
  1401. br_parse_plain(&doc, "", 0);
  1402. page_loading = 1;
  1403. page_is_local = 0;
  1404. s_copy(page_url, "about:home", sizeof(page_url));
  1405. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1406. url_in.len = s_len(url_in.text);
  1407. url_in.cursor = url_in.len;
  1408. url_in.scroll = 0;
  1409. ngui_set_focus(&ui, 0);
  1410. if (push)
  1411. history_push(page_url);
  1412. ngui_invalidate(&ui);
  1413. /* See load_page(): reattach the fonts before the first redraw. */
  1414. if (heap_start() != 0) {
  1415. show_error("Out of memory", "Cannot allocate the browser heap");
  1416. return;
  1417. }
  1418. ngui_font_attach(&ui);
  1419. redraw_now();
  1420. browser_rules_alloc();
  1421. {
  1422. static const char home[] =
  1423. "<html><head><title>NebOS Browser</title><style>"
  1424. "body { margin: 10px; color: #e4e6f0; }"
  1425. "h1 { color: #7fb0ff; }"
  1426. ".box { background-color: #262b3a; margin: 12px; "
  1427. "padding: 10px; }"
  1428. "a { color: #7fb0ff; }"
  1429. "pre { background-color: #32384a; }"
  1430. "</style></head><body>"
  1431. "<h1>NebOS Browser</h1>"
  1432. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  1433. "shared HTTP client and the image library.</p>"
  1434. "<div class=\"box\"><b>Try:</b>"
  1435. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  1436. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  1437. "<li><a href=\"http://10.0.2.2:8000/\">"
  1438. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  1439. "<li><a href=\"https://example.com/\">"
  1440. "https://example.com/</a> (TLS, not verified)</li>"
  1441. "</ul></div>"
  1442. "<p>Type a URL in the bar above. Esc closes the "
  1443. "window, Ctrl+L focuses the address bar.</p>"
  1444. "<pre>javascript: not supported\nforms: not supported"
  1445. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  1446. "</body></html>";
  1447. br_set_viewport(ui.w);
  1448. br_parse(&doc, home, sizeof(home) - 1);
  1449. br_parse_inline_css(&doc);
  1450. br_reset_styles(&doc);
  1451. s_copy(page_title, doc.title, sizeof(page_title));
  1452. }
  1453. post_status_text[0] = '\0';
  1454. post_status_error = 0;
  1455. post_status_ttl = 0;
  1456. page_loading = 0;
  1457. set_status("", 0, 0);
  1458. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  1459. url_in.len = s_len(url_in.text);
  1460. url_in.cursor = url_in.len;
  1461. url_in.scroll = 0;
  1462. ngui_set_focus(&ui, 0);
  1463. ngui_invalidate(&ui);
  1464. }
  1465. static void navigate(const char *input, int push)
  1466. {
  1467. char target[BR_URL_MAX];
  1468. char *t;
  1469. if (!input)
  1470. return;
  1471. s_copy(target, input, sizeof(target));
  1472. t = trim(target);
  1473. if (!t[0])
  1474. return;
  1475. if (s_eq(t, "about:home")) {
  1476. load_home(push);
  1477. return;
  1478. }
  1479. if (starts_with(t, "file://")) {
  1480. make_abs_local(t + 7, target, sizeof(target));
  1481. load_page(target, 1, push);
  1482. return;
  1483. }
  1484. if (is_http(t)) {
  1485. load_page(t, 0, push);
  1486. return;
  1487. }
  1488. {
  1489. struct sys_stat st;
  1490. if (t[0] == '/' || (u_stat(t, &st) == 0 && !st.is_dir)) {
  1491. make_abs_local(t, target, sizeof(target));
  1492. load_page(target, 1, push);
  1493. return;
  1494. }
  1495. }
  1496. {
  1497. char with_scheme[BR_URL_MAX];
  1498. unsigned int n = 0;
  1499. s_append(with_scheme, &n, "http://", sizeof(with_scheme));
  1500. s_append(with_scheme, &n, t, sizeof(with_scheme));
  1501. load_page(with_scheme, 0, push);
  1502. }
  1503. }
  1504. /* ---- layout ---- */
  1505. static struct br_style base_style(void)
  1506. {
  1507. struct br_style s = { 0 };
  1508. s.color = ui.theme.text;
  1509. s.bg = ui.theme.bg;
  1510. s.has_bg = 0;
  1511. s.border_color = 0;
  1512. s.font_px = 16;
  1513. s.bold = 0;
  1514. s.italic = 0;
  1515. s.mono = 0;
  1516. s.underline = 0;
  1517. s.align = BR_ALIGN_LEFT;
  1518. s.display = BR_DISPLAY_BLOCK;
  1519. s.no_bullet = 0;
  1520. s.uppercase = 0;
  1521. s.border_w = 0;
  1522. s.width_kind = s.max_width_kind = s.height_kind = 0;
  1523. s.width = s.max_width = s.height = 0;
  1524. s.line_h_pct = 0;
  1525. s.line_h_px = 0;
  1526. s.mt = s.mb = s.ml = s.mr = 0;
  1527. s.pt = s.pb = s.pl = s.pr = 0;
  1528. return s;
  1529. }
  1530. static int run_width(const struct lay_run *r)
  1531. {
  1532. if (r->img >= 0)
  1533. return r->iw;
  1534. if (r->img == -2)
  1535. return r->iw;
  1536. return (int)r->w;
  1537. }
  1538. static void flush_line(struct lay *l)
  1539. {
  1540. int total, x, i, vis;
  1541. if (!l->nruns && l->line_x == l->left) {
  1542. l->line_h = 0;
  1543. return;
  1544. }
  1545. total = l->line_x - l->left;
  1546. x = l->left;
  1547. vis = 1;
  1548. if (l->draw) {
  1549. int lh = l->line_h ? l->line_h : 16;
  1550. vis = l->line_y + lh >= page_rect.y &&
  1551. l->line_y <= page_rect.y + page_rect.h;
  1552. }
  1553. if (l->align == BR_ALIGN_CENTER)
  1554. x += (l->right - l->left - total) / 2;
  1555. else if (l->align == BR_ALIGN_RIGHT)
  1556. x = l->right - total;
  1557. if (x < l->left)
  1558. x = l->left;
  1559. for (i = 0; i < l->nruns; i++) {
  1560. struct lay_run *r = &l->runs[i];
  1561. int w = run_width(r);
  1562. int ry = l->line_y + r->dy;
  1563. x += r->gap;
  1564. if (l->draw && vis) {
  1565. if (r->img == -2) {
  1566. int hh = r->ih ? r->ih : 20;
  1567. ngui_fill_rect(l->ui,
  1568. (struct ngui_rect){x, ry, w, hh},
  1569. l->ui->theme.panel_alt);
  1570. ngui_frame(l->ui,
  1571. (struct ngui_rect){x, ry, w, hh},
  1572. l->ui->theme.border);
  1573. ngui_text_px(l->ui, x + 6, ry + 2,
  1574. r->lit, s_len(r->lit), r->color,
  1575. r->font_px, r->bold, r->italic,
  1576. r->mono);
  1577. } else if (r->img >= 0) {
  1578. struct br_image *bi = &images[r->img];
  1579. if (bi->state == 1) {
  1580. struct img_blit b;
  1581. b.dst = l->ui->px;
  1582. b.dst_w = l->ui->w;
  1583. b.dst_h = l->ui->h;
  1584. b.clip_x = page_rect.x;
  1585. b.clip_y = page_rect.y;
  1586. b.clip_w = page_rect.w - 12;
  1587. b.clip_h = page_rect.h;
  1588. b.x = x;
  1589. b.y = ry;
  1590. b.scale = ((unsigned int)r->iw << 16) /
  1591. bi->img.w;
  1592. b.bg = ui.theme.bg;
  1593. b.bg2 = ui.theme.bg;
  1594. b.flags = IMG_BLIT_OVER_DST;
  1595. img_draw(&bi->img, &b);
  1596. }
  1597. } else {
  1598. const char *s = r->has_lit ? r->lit :
  1599. doc.text + r->off;
  1600. unsigned int n = r->has_lit ? s_len(r->lit) :
  1601. r->len;
  1602. ngui_text_px(l->ui, x, ry, s, n,
  1603. r->color, r->font_px, r->bold,
  1604. r->italic, r->mono);
  1605. if (r->underline)
  1606. ngui_fill_rect(l->ui,
  1607. (struct ngui_rect){x,
  1608. ry +
  1609. ngui_text_ascent(l->ui,
  1610. r->font_px,
  1611. r->mono) + 2,
  1612. w, 1}, r->color);
  1613. }
  1614. if (r->href) {
  1615. if (nhits < HIT_MAX) {
  1616. struct hit *h = &hits[nhits];
  1617. int hh = r->img >= 0 ? r->ih :
  1618. ngui_text_line_height(l->ui,
  1619. r->font_px, r->mono);
  1620. int merge = nhits > 0 &&
  1621. hits[nhits - 1].node == r->href &&
  1622. hits[nhits - 1].y == ry &&
  1623. hits[nhits - 1].h == hh &&
  1624. x <= hits[nhits - 1].x +
  1625. hits[nhits - 1].w + 2;
  1626. if (merge) {
  1627. struct hit *p = &hits[nhits - 1];
  1628. int end = x + w;
  1629. if (end > p->x + p->w)
  1630. p->w = end - p->x;
  1631. } else {
  1632. h->x = x;
  1633. h->y = ry;
  1634. h->w = w;
  1635. h->h = hh;
  1636. h->node = r->href;
  1637. nhits++;
  1638. }
  1639. }
  1640. }
  1641. }
  1642. x += w;
  1643. }
  1644. l->y += l->line_h + 2;
  1645. l->nruns = 0;
  1646. l->line_x = l->left;
  1647. l->run_x = l->left;
  1648. l->line_h = 0;
  1649. l->space_pending = 0;
  1650. }
  1651. static void add_run(struct lay *l, unsigned short off, unsigned short len,
  1652. const struct br_style *st, unsigned short href,
  1653. const char *lit)
  1654. {
  1655. unsigned int n = lit ? s_len(lit) : len;
  1656. const char *tp = lit ? lit : doc.text + off;
  1657. int w = (int)ngui_text_width_px(l->ui, tp, n, st->font_px,
  1658. st->bold, st->italic, st->mono);
  1659. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1660. flush_line(l);
  1661. if (l->nruns == 0) {
  1662. l->line_y = l->y;
  1663. l->line_h = 0;
  1664. }
  1665. {
  1666. struct lay_run *r = &l->runs[l->nruns++];
  1667. int gap = l->line_x - l->run_x;
  1668. if (gap < 0)
  1669. gap = 0;
  1670. r->gap = (unsigned short)gap;
  1671. r->off = off;
  1672. r->len = len;
  1673. r->color = st->color;
  1674. r->href = href;
  1675. r->dy = 0;
  1676. r->has_lit = 0;
  1677. r->lit[0] = '\0';
  1678. if (lit && lit[0]) {
  1679. unsigned int i;
  1680. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  1681. r->lit[i] = lit[i];
  1682. r->lit[i] = '\0';
  1683. r->has_lit = 1;
  1684. }
  1685. r->img = -1;
  1686. r->iw = r->ih = 0;
  1687. r->font_px = st->font_px;
  1688. r->bold = st->bold;
  1689. r->italic = st->italic;
  1690. r->mono = st->mono;
  1691. /* A control with its own background is a button, not body copy;
  1692. * an inherited link underline would strike through the fill. */
  1693. r->underline = st->underline && !st->has_bg;
  1694. r->w = (unsigned short)w;
  1695. if (r->has_lit)
  1696. r->w = (unsigned short)ngui_text_width_px(
  1697. l->ui, r->lit, s_len(r->lit), r->font_px,
  1698. r->bold, r->italic, r->mono);
  1699. w = r->w;
  1700. }
  1701. l->line_x += w;
  1702. l->run_x = l->line_x;
  1703. {
  1704. int lh = ngui_text_line_height(l->ui, st->font_px, st->mono);
  1705. if (st->line_h_px)
  1706. lh = st->line_h_px;
  1707. else if (st->line_h_pct)
  1708. lh = st->font_px * st->line_h_pct / 100;
  1709. if (lh < ngui_text_line_height(l->ui, st->font_px, st->mono))
  1710. lh = ngui_text_line_height(l->ui, st->font_px,
  1711. st->mono);
  1712. if (l->line_h < lh)
  1713. l->line_h = lh;
  1714. }
  1715. }
  1716. static void add_image_run(struct lay *l, unsigned int node,
  1717. const struct br_style *st, unsigned short href)
  1718. {
  1719. struct br_image *bi = 0;
  1720. int idx = doc.nodes[node].img_index;
  1721. int dw, dh, maxw;
  1722. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  1723. bi = &images[idx];
  1724. if (l->space_pending && (l->nruns > 0 || l->line_x > l->left)) {
  1725. int sp = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  1726. st->bold, st->italic,
  1727. st->mono);
  1728. if (l->line_x + sp <= l->right)
  1729. l->line_x += sp;
  1730. }
  1731. l->space_pending = 0;
  1732. if (!bi) {
  1733. const char *alt = br_alt(&doc, node);
  1734. struct br_style gs = *st;
  1735. char tmp[96];
  1736. unsigned int n = 0;
  1737. int w;
  1738. gs.color = BR_GRAY;
  1739. gs.underline = 0;
  1740. s_append(tmp, &n, "[", sizeof(tmp));
  1741. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  1742. s_append(tmp, &n, "]", sizeof(tmp));
  1743. w = (int)ngui_text_width_px(l->ui, tmp, n, gs.font_px,
  1744. gs.bold, gs.italic, gs.mono);
  1745. if (l->line_x + w > l->right &&
  1746. (l->nruns > 0 || l->line_x > l->left))
  1747. flush_line(l);
  1748. add_run(l, 0, 0, &gs, href, tmp);
  1749. if (!l->draw) {
  1750. int t = l->line_y < 0 ? 0 : l->line_y;
  1751. int hh = ngui_text_line_height(l->ui, gs.font_px,
  1752. gs.mono);
  1753. if (t > 65535)
  1754. t = 65535;
  1755. if (hh > 65535)
  1756. hh = 65535;
  1757. img_top[node] = (unsigned short)t;
  1758. img_h[node] = (unsigned short)hh;
  1759. }
  1760. return;
  1761. }
  1762. maxw = l->right - l->left;
  1763. if (maxw < 8)
  1764. maxw = 8;
  1765. {
  1766. int iw = bi->native_w, ih = bi->native_h;
  1767. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  1768. if (iw <= 0 || ih <= 0) {
  1769. iw = (int)bi->img.w;
  1770. ih = (int)bi->img.h;
  1771. }
  1772. dw = iw;
  1773. dh = ih;
  1774. if (doc.nodes[node].width_attr) {
  1775. int want = doc.nodes[node].width_attr;
  1776. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  1777. have_w = 1;
  1778. }
  1779. if (doc.nodes[node].height_attr) {
  1780. int want = doc.nodes[node].height_attr;
  1781. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  1782. have_h = 1;
  1783. }
  1784. if (have_w && !have_h)
  1785. dh = ih ? ih * dw / iw : 0;
  1786. if (have_h && !have_w)
  1787. dw = iw ? iw * dh / ih : 0;
  1788. if (st->width_kind) {
  1789. css_w = 1;
  1790. dw = st->width_kind == 2 ? maxw * (int)st->width / 100 :
  1791. (int)st->width;
  1792. }
  1793. if (st->height_kind) {
  1794. css_h = 1;
  1795. dh = st->height_kind == 2 ? maxw * (int)st->height / 100 :
  1796. (int)st->height;
  1797. }
  1798. if (css_w && !css_h)
  1799. dh = ih ? ih * dw / iw : 0;
  1800. if (css_h && !css_w)
  1801. dw = iw ? iw * dh / ih : 0;
  1802. if (st->max_width_kind) {
  1803. int mw = st->max_width_kind == 2 ?
  1804. maxw * (int)st->max_width / 100 :
  1805. (int)st->max_width;
  1806. if (mw > 0 && dw > mw) {
  1807. dh = iw ? ih * mw / iw : 0;
  1808. dw = mw;
  1809. }
  1810. }
  1811. }
  1812. if (dw < 8)
  1813. dw = 8;
  1814. if (dh < 8)
  1815. dh = 8;
  1816. if (dw > maxw) {
  1817. dh = dw ? dh * maxw / dw : dh;
  1818. dw = maxw;
  1819. }
  1820. if (!l->draw) {
  1821. int t = l->line_y < 0 ? 0 : l->line_y;
  1822. if (t > 65535)
  1823. t = 65535;
  1824. if (dh > 65535)
  1825. dh = 65535;
  1826. img_top[node] = (unsigned short)t;
  1827. img_h[node] = (unsigned short)dh;
  1828. }
  1829. if (l->line_x + dw > l->right && (l->nruns > 0 ||
  1830. l->line_x > l->left))
  1831. flush_line(l);
  1832. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  1833. flush_line(l);
  1834. if (l->nruns == 0) {
  1835. l->line_y = l->y;
  1836. l->line_h = 0;
  1837. }
  1838. {
  1839. struct lay_run *r = &l->runs[l->nruns++];
  1840. int gap = l->line_x - l->run_x;
  1841. if (gap < 0)
  1842. gap = 0;
  1843. r->gap = (unsigned short)gap;
  1844. r->off = 0;
  1845. r->len = 0;
  1846. r->color = 0;
  1847. r->href = href;
  1848. /* Inline replaced elements honour their vertical margins; this
  1849. * is how Bootstrap's negative logo margins centre the wordmark. */
  1850. r->dy = st->mt;
  1851. r->has_lit = 0;
  1852. r->lit[0] = '\0';
  1853. r->img = (short)idx;
  1854. r->iw = (unsigned short)dw;
  1855. r->ih = (unsigned short)dh;
  1856. r->w = (unsigned short)dw;
  1857. r->font_px = st->font_px;
  1858. r->bold = st->bold;
  1859. r->italic = st->italic;
  1860. r->mono = st->mono;
  1861. r->underline = 0;
  1862. }
  1863. l->line_x += dw;
  1864. l->run_x = l->line_x;
  1865. if (l->line_h < dh)
  1866. l->line_h = dh;
  1867. }
  1868. static int text_width(struct lay *l, const char *s, unsigned int n,
  1869. const struct br_style *st)
  1870. {
  1871. return (int)ngui_text_width_px(l->ui, s, n, st->font_px,
  1872. st->bold, st->italic, st->mono);
  1873. }
  1874. /* Longest prefix that fits in maxw, at least one byte. */
  1875. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  1876. const struct br_style *st, int maxw)
  1877. {
  1878. unsigned int take = 0;
  1879. while (take < n) {
  1880. if (text_width(l, s, take + 1, st) > maxw)
  1881. break;
  1882. take++;
  1883. }
  1884. return take ? take : 1;
  1885. }
  1886. static void emit_word(struct lay *l, const char *s, unsigned int start,
  1887. unsigned int n, unsigned int base,
  1888. const struct br_style *st, unsigned short href)
  1889. {
  1890. int avail = l->right - l->left;
  1891. int w = text_width(l, s + start, n, st);
  1892. unsigned int off = start;
  1893. if (l->line_x + w > l->right &&
  1894. (l->nruns > 0 || l->line_x > l->left))
  1895. flush_line(l);
  1896. if (w <= avail) {
  1897. if (n)
  1898. add_run(l, (unsigned short)(base + start),
  1899. (unsigned short)n, st, href, 0);
  1900. return;
  1901. }
  1902. while (n > 0) {
  1903. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  1904. add_run(l, (unsigned short)(base + off),
  1905. (unsigned short)take, st, href, 0);
  1906. off += take;
  1907. n -= take;
  1908. if (n)
  1909. flush_line(l);
  1910. }
  1911. }
  1912. static void emit_text(struct lay *l, const char *s, unsigned int len,
  1913. const struct br_style *st, unsigned short href, int pre)
  1914. {
  1915. unsigned int i = 0;
  1916. unsigned int base;
  1917. int space_w = (int)ngui_text_width_px(l->ui, " ", 1, st->font_px,
  1918. st->bold, st->italic, st->mono);
  1919. if (!s || !len)
  1920. return;
  1921. if (space_w <= 0)
  1922. space_w = 8;
  1923. base = (unsigned int)(s - doc.text);
  1924. if (st->uppercase) {
  1925. char *p = (char *)s;
  1926. unsigned int j;
  1927. for (j = 0; j < len; j++)
  1928. if (p[j] >= 'a' && p[j] <= 'z')
  1929. p[j] = (char)(p[j] - 'a' + 'A');
  1930. }
  1931. if (pre) {
  1932. while (i < len) {
  1933. unsigned int start;
  1934. if (s[i] == '\n') {
  1935. flush_line(l);
  1936. i++;
  1937. continue;
  1938. }
  1939. if (s[i] == ' ') {
  1940. if (l->line_x + space_w > l->right &&
  1941. (l->nruns > 0 || l->line_x > l->left))
  1942. flush_line(l);
  1943. else
  1944. l->line_x += space_w;
  1945. i++;
  1946. continue;
  1947. }
  1948. start = i;
  1949. while (i < len && s[i] != ' ' && s[i] != '\n')
  1950. i++;
  1951. emit_word(l, s, start, i - start, base, st, href);
  1952. }
  1953. return;
  1954. }
  1955. while (i < len) {
  1956. unsigned int start, n;
  1957. if (s[i] == ' ') {
  1958. l->space_pending = 1;
  1959. i++;
  1960. continue;
  1961. }
  1962. start = i;
  1963. while (i < len && s[i] != ' ')
  1964. i++;
  1965. n = i - start;
  1966. if (l->space_pending &&
  1967. (l->nruns > 0 || l->line_x > l->left)) {
  1968. if (l->line_x + space_w <= l->right)
  1969. l->line_x += space_w;
  1970. }
  1971. l->space_pending = 0;
  1972. emit_word(l, s, start, n, base, st, href);
  1973. }
  1974. }
  1975. static int list_index(unsigned int parent, unsigned int node)
  1976. {
  1977. unsigned int n = 0, i;
  1978. for (i = doc.nodes[parent].first; i && i != node;
  1979. i = doc.nodes[i].next)
  1980. if (doc.nodes[i].tag == BR_TAG_LI)
  1981. n++;
  1982. return (int)n + 1;
  1983. }
  1984. static const char *form_text(unsigned int node)
  1985. {
  1986. const char *v = br_value(&doc, node);
  1987. const char *p = br_placeholder(&doc, node);
  1988. const char *t = br_type(&doc, node);
  1989. if (s_eq(t, "hidden"))
  1990. return 0;
  1991. if (s_eq(t, "submit") || s_eq(t, "button") || s_eq(t, "reset"))
  1992. return v[0] ? v : "Button";
  1993. if (v[0])
  1994. return v;
  1995. if (p[0])
  1996. return p;
  1997. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  1998. return "Text";
  1999. if (doc.nodes[node].tag == BR_TAG_SELECT)
  2000. return "Select";
  2001. return "Search";
  2002. }
  2003. static void add_form_run(struct lay *l, unsigned int node,
  2004. const struct br_style *st, unsigned short href)
  2005. {
  2006. const char *text = form_text(node);
  2007. struct lay_run *r;
  2008. int tw, w, h, i;
  2009. if (!text)
  2010. return;
  2011. tw = (int)ngui_text_width_px(l->ui, text, s_len(text), st->font_px,
  2012. st->bold, st->italic, st->mono);
  2013. h = ngui_text_line_height(l->ui, st->font_px, st->mono) + 4;
  2014. if (h < 20)
  2015. h = 20;
  2016. if (st->width_kind == 1)
  2017. w = st->width;
  2018. else if (st->width_kind == 2)
  2019. w = (l->right - l->left) * (int)st->width / 100;
  2020. else
  2021. w = tw + 18;
  2022. if (w < 64)
  2023. w = 64;
  2024. if (w > l->right - l->left)
  2025. w = l->right - l->left;
  2026. if (w < 8)
  2027. w = 8;
  2028. if (l->line_x + w > l->right &&
  2029. (l->nruns > 0 || l->line_x > l->left))
  2030. flush_line(l);
  2031. if (l->nruns >= 96)
  2032. return;
  2033. r = &l->runs[l->nruns++];
  2034. r->gap = (unsigned short)(l->line_x - l->run_x);
  2035. r->off = r->len = 0;
  2036. r->color = st->color;
  2037. r->href = href;
  2038. r->dy = 0;
  2039. r->has_lit = 1;
  2040. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  2041. r->lit[i] = text[i];
  2042. r->lit[i] = '\0';
  2043. r->img = -2;
  2044. r->iw = (unsigned short)w;
  2045. r->ih = (unsigned short)h;
  2046. r->w = (unsigned short)w;
  2047. r->font_px = st->font_px;
  2048. r->bold = st->bold;
  2049. r->italic = st->italic;
  2050. r->mono = st->mono;
  2051. r->underline = 0;
  2052. l->line_x += w;
  2053. l->run_x = l->line_x;
  2054. if (l->line_h < h)
  2055. l->line_h = h;
  2056. }
  2057. /* A poster wrapper is absolutely positioned over the media slot; the
  2058. * measured height of its picture is normally added back to the flow. When a
  2059. * loading-skeleton sibling already reserves that slot, adding both doubles
  2060. * the media height and pushes the article text a full screen down. */
  2061. static int has_skeleton_sibling(unsigned int node)
  2062. {
  2063. unsigned int p = doc.nodes[node].parent, c;
  2064. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  2065. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  2066. continue;
  2067. if (doc.nodes[c].class_off &&
  2068. contains_ci(doc.attrs + doc.nodes[c].class_off,
  2069. "skeleton"))
  2070. return 1;
  2071. }
  2072. return 0;
  2073. }
  2074. static void layout_children(struct lay *l, unsigned int parent,
  2075. const struct br_style *pst, int depth,
  2076. unsigned short link);
  2077. static void layout_flex_children(struct lay *l, unsigned int parent,
  2078. const struct br_style *pst, int depth,
  2079. unsigned short link);
  2080. static void layout_grid_children(struct lay *l, unsigned int parent,
  2081. const struct br_style *pst, int depth,
  2082. unsigned short link);
  2083. static void layout_grid_auto(struct lay *l, unsigned int parent,
  2084. const struct br_style *pst, int depth,
  2085. unsigned short link);
  2086. static int flex_item_width(struct lay *l, unsigned int n,
  2087. const struct br_style *cs, int avail);
  2088. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  2089. const struct br_style *pst, int depth,
  2090. unsigned short link);
  2091. static void layout_table_row(struct lay *l, unsigned int row,
  2092. const struct br_style *pst, int depth,
  2093. unsigned short link);
  2094. /* A flex container whose items are only inline spans is usually just a
  2095. * heading/icon pair. Our flex row positions such items without emitting
  2096. * their inline text in some deep page contexts; normal inline flow renders
  2097. * the same content correctly. */
  2098. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  2099. {
  2100. unsigned int c;
  2101. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2102. struct br_node *nd = &doc.nodes[c];
  2103. struct br_style cs;
  2104. if (nd->type == BR_NODE_TEXT)
  2105. continue;
  2106. br_style_for(&doc, c, pst, &cs);
  2107. if (cs.display == BR_DISPLAY_NONE)
  2108. continue;
  2109. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  2110. cs.width_kind || cs.has_bg || cs.border_w ||
  2111. nd->tag == BR_TAG_IMG)
  2112. return 1;
  2113. }
  2114. return 0;
  2115. }
  2116. static int css_radius(const struct br_style *st, int corner,
  2117. int w, int h)
  2118. {
  2119. int r = st->radius[corner];
  2120. if (r <= 0)
  2121. return 0;
  2122. if (r > w / 2)
  2123. r = w / 2;
  2124. if (r > h / 2)
  2125. r = h / 2;
  2126. return r;
  2127. }
  2128. static void svg_viewbox(unsigned node, int *vw, int *vh)
  2129. {
  2130. struct br_node *nd = &doc.nodes[node];
  2131. if (nd->width_attr && nd->height_attr) {
  2132. *vw = nd->width_attr;
  2133. *vh = nd->height_attr;
  2134. } else {
  2135. *vw = 300;
  2136. *vh = 150;
  2137. }
  2138. if (*vw < 1)
  2139. *vw = 1;
  2140. if (*vh < 1)
  2141. *vh = 1;
  2142. }
  2143. static int svg_num(const char **pp)
  2144. {
  2145. const char *p = *pp;
  2146. int neg = 0, v = 0, frac = 0, scale = 1;
  2147. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2148. *p == '\n' || *p == '\r')
  2149. p++;
  2150. if (*p == '-') {
  2151. neg = 1;
  2152. p++;
  2153. } else if (*p == '+') {
  2154. p++;
  2155. }
  2156. while (*p >= '0' && *p <= '9') {
  2157. v = v * 10 + (*p - '0');
  2158. p++;
  2159. }
  2160. if (*p == '.') {
  2161. p++;
  2162. while (*p >= '0' && *p <= '9' && scale < 1000) {
  2163. frac = frac * 10 + (*p - '0');
  2164. scale *= 10;
  2165. p++;
  2166. }
  2167. }
  2168. v += frac / scale;
  2169. *pp = p;
  2170. return neg ? -v : v;
  2171. }
  2172. static void svg_path(struct ngui *ui, const char *d,
  2173. int ox, int oy, int dw, int dh, int vw, int vh,
  2174. unsigned short color)
  2175. {
  2176. int cx = 0, cy = 0, sx = 0, sy = 0;
  2177. char cmd = 0;
  2178. const char *p = d;
  2179. while (p && *p) {
  2180. int rel, nx, ny;
  2181. char c;
  2182. while (*p == ' ' || *p == ',' || *p == '\t' ||
  2183. *p == '\n' || *p == '\r')
  2184. p++;
  2185. if (!*p)
  2186. break;
  2187. if ((*p >= 'A' && *p <= 'Z') ||
  2188. (*p >= 'a' && *p <= 'z'))
  2189. cmd = *p++;
  2190. else if (!cmd) {
  2191. p++;
  2192. continue;
  2193. }
  2194. rel = cmd >= 'a' && cmd <= 'z';
  2195. c = rel ? (char)(cmd - 'a' + 'A') : cmd;
  2196. if (c == 'Z') {
  2197. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2198. ox + sx * dw / vw, oy + sy * dh / vh,
  2199. color);
  2200. cx = sx;
  2201. cy = sy;
  2202. cmd = 0;
  2203. continue;
  2204. }
  2205. if (c == 'H' || c == 'V') {
  2206. const char *save = p;
  2207. int a = svg_num(&p);
  2208. if (p == save) {
  2209. p++;
  2210. continue;
  2211. }
  2212. nx = cx;
  2213. ny = cy;
  2214. if (c == 'H')
  2215. nx = rel ? cx + a : a;
  2216. else
  2217. ny = rel ? cy + a : a;
  2218. } else {
  2219. const char *save = p;
  2220. int a = svg_num(&p);
  2221. int b = svg_num(&p);
  2222. if (p == save) {
  2223. p++;
  2224. continue;
  2225. }
  2226. if (c == 'M') {
  2227. nx = rel ? cx + a : a;
  2228. ny = rel ? cy + b : b;
  2229. cx = sx = nx;
  2230. cy = sy = ny;
  2231. cmd = rel ? 'l' : 'L';
  2232. continue;
  2233. }
  2234. if (c != 'L')
  2235. break;
  2236. nx = rel ? cx + a : a;
  2237. ny = rel ? cy + b : b;
  2238. }
  2239. ngui_line(ui, ox + cx * dw / vw, oy + cy * dh / vh,
  2240. ox + nx * dw / vw, oy + ny * dh / vh, color);
  2241. cx = nx;
  2242. cy = ny;
  2243. }
  2244. }
  2245. static void draw_svg(struct ngui *ui, unsigned node,
  2246. int ox, int oy, int dw, int dh, int vw, int vh,
  2247. const struct br_style *pst)
  2248. {
  2249. unsigned int c;
  2250. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  2251. struct br_node *nd = &doc.nodes[c];
  2252. struct br_style st;
  2253. const char *nm;
  2254. if (nd->type != BR_NODE_ELEM || !nd->name_off)
  2255. continue;
  2256. nm = doc.attrs + nd->name_off;
  2257. br_style_for(&doc, c, pst, &st);
  2258. if (s_eq(nm, "rect")) {
  2259. struct ngui_rect r;
  2260. int rx = (int)nd->svg_rx * dw / vw;
  2261. r.x = ox + (int)nd->svg_x * dw / vw;
  2262. r.y = oy + (int)nd->svg_y * dh / vh;
  2263. r.w = (int)nd->width_attr * dw / vw;
  2264. r.h = (int)nd->height_attr * dh / vh;
  2265. if (r.w < 1)
  2266. r.w = 1;
  2267. if (r.h < 1)
  2268. r.h = 1;
  2269. if (rx > r.w / 2)
  2270. rx = r.w / 2;
  2271. if (rx > r.h / 2)
  2272. rx = r.h / 2;
  2273. if (st.has_bg) {
  2274. if (rx)
  2275. ngui_fill_round_rect(ui, r, rx, rx,
  2276. rx, rx, st.bg);
  2277. else
  2278. ngui_fill_rect(ui, r, st.bg);
  2279. }
  2280. if (st.border_w) {
  2281. if (rx)
  2282. ngui_frame_round(ui, r, rx, rx, rx, rx,
  2283. st.border_w,
  2284. st.border_color);
  2285. else
  2286. ngui_frame(ui, r, st.border_color);
  2287. }
  2288. } else if (s_eq(nm, "line")) {
  2289. if (st.border_w)
  2290. ngui_line(ui,
  2291. ox + (int)nd->svg_x * dw / vw,
  2292. oy + (int)nd->svg_y * dh / vh,
  2293. ox + (int)nd->width_attr * dw / vw,
  2294. oy + (int)nd->height_attr * dh / vh,
  2295. st.border_color);
  2296. } else if (s_eq(nm, "path")) {
  2297. if (st.border_w && nd->src_off)
  2298. svg_path(ui, doc.attrs + nd->src_off,
  2299. ox, oy, dw, dh, vw, vh,
  2300. st.border_color);
  2301. } else if (s_eq(nm, "text")) {
  2302. unsigned int t = nd->first;
  2303. const char *s;
  2304. unsigned int n, tw;
  2305. int px = st.font_px ? st.font_px : 16;
  2306. int tx, ty, anchor;
  2307. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  2308. continue;
  2309. s = doc.text + doc.nodes[t].text_off;
  2310. n = doc.nodes[t].text_len;
  2311. tw = ngui_text_width_px(ui, s, n, px, st.bold,
  2312. st.italic, st.mono);
  2313. tx = ox + (int)nd->svg_x * dw / vw;
  2314. ty = oy + (int)nd->svg_y * dh / vh -
  2315. ngui_text_ascent(ui, px, st.mono);
  2316. anchor = st.align;
  2317. if (nd->attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  2318. anchor = BR_ALIGN_CENTER;
  2319. else if (nd->attr_flags & BR_ATTR_ANCHOR_END)
  2320. anchor = BR_ALIGN_RIGHT;
  2321. if (anchor == BR_ALIGN_CENTER)
  2322. tx -= (int)tw / 2;
  2323. else if (anchor == BR_ALIGN_RIGHT)
  2324. tx -= (int)tw;
  2325. ngui_text_px(ui, tx, ty, s, n, st.color, px,
  2326. st.bold, st.italic, st.mono);
  2327. }
  2328. }
  2329. }
  2330. static void layout_block(struct lay *l, unsigned int node,
  2331. const struct br_style *st, int depth,
  2332. unsigned short link)
  2333. {
  2334. int old_left = l->left, old_right = l->right, old_align = l->align;
  2335. int top, l0, r0;
  2336. int flow_y, flow_left, flow_right, positioned;
  2337. if (depth > 24 || st->display == BR_DISPLAY_NONE)
  2338. return;
  2339. flow_y = l->y;
  2340. flow_left = l->left;
  2341. flow_right = l->right;
  2342. positioned = st->pos;
  2343. if (positioned) {
  2344. if (st->pos == 2) {
  2345. l->y = page_rect.y + (st->top_set ? st->top : 0);
  2346. l->left = page_rect.x;
  2347. l->right = page_rect.x + page_rect.w - 12;
  2348. } else {
  2349. l->y = flow_y + (st->top_set ? st->top : 0);
  2350. l->left = flow_left + (st->left_set ? st->left : 0);
  2351. l->right = flow_right + (st->left_set ? st->left : 0);
  2352. }
  2353. old_left = l->left;
  2354. old_right = l->right;
  2355. }
  2356. if (doc.nodes[node].tag == BR_TAG_INPUT ||
  2357. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  2358. doc.nodes[node].tag == BR_TAG_SELECT) {
  2359. if (!(doc.nodes[node].tag == BR_TAG_INPUT &&
  2360. s_eq(br_type(&doc, node), "hidden")))
  2361. add_form_run(l, node, st, link);
  2362. l->y += 20;
  2363. return;
  2364. }
  2365. flush_line(l);
  2366. l->y += st->mt;
  2367. top = l->y;
  2368. l0 = old_left + st->ml;
  2369. r0 = old_right - st->mr;
  2370. if (r0 < l0 + 16)
  2371. r0 = l0 + 16;
  2372. if (l->draw && block_h[node] &&
  2373. top < page_rect.y + page_rect.h &&
  2374. top + block_h[node] > page_rect.y) {
  2375. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  2376. int rtl = css_radius(st, 0, box.w, box.h);
  2377. int rtr = css_radius(st, 1, box.w, box.h);
  2378. int rbr = css_radius(st, 2, box.w, box.h);
  2379. int rbl = css_radius(st, 3, box.w, box.h);
  2380. if (rtl || rtr || rbr || rbl) {
  2381. if (st->has_bg) {
  2382. int bw = st->border_w;
  2383. if (bw > 0 && st->border_color != st->bg &&
  2384. box.w > bw * 2 && box.h > bw * 2) {
  2385. struct ngui_rect inner = {
  2386. box.x + bw, box.y + bw,
  2387. box.w - bw * 2, box.h - bw * 2
  2388. };
  2389. int itl = rtl > bw ? rtl - bw : 0;
  2390. int itr = rtr > bw ? rtr - bw : 0;
  2391. int ibr = rbr > bw ? rbr - bw : 0;
  2392. int ibl = rbl > bw ? rbl - bw : 0;
  2393. ngui_fill_round_rect(l->ui, box, rtl,
  2394. rtr, rbr, rbl,
  2395. st->border_color);
  2396. ngui_fill_round_rect(l->ui, inner,
  2397. itl, itr, ibr,
  2398. ibl, st->bg);
  2399. } else {
  2400. ngui_fill_round_rect(l->ui, box, rtl,
  2401. rtr, rbr, rbl,
  2402. st->bg);
  2403. }
  2404. } else if (st->border_w) {
  2405. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  2406. rbl, st->border_w,
  2407. st->border_color);
  2408. }
  2409. } else {
  2410. if (st->has_bg)
  2411. ngui_fill_rect(l->ui, box, st->bg);
  2412. if (st->border_w)
  2413. ngui_frame(l->ui, box, st->border_color);
  2414. }
  2415. }
  2416. l->left = l0 + st->pl;
  2417. l->right = r0 - st->pr;
  2418. if (l->right < l->left + 8)
  2419. l->right = l->left + 8;
  2420. l->align = st->align;
  2421. l->y += st->pt;
  2422. if (doc.nodes[node].tag == BR_TAG_HR) {
  2423. if (l->draw)
  2424. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  2425. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  2426. l->y += 8;
  2427. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  2428. int vw = l->right - l->left;
  2429. int vh;
  2430. if (doc.nodes[node].width_pct)
  2431. vw = vw * doc.nodes[node].width_attr / 100;
  2432. else if (doc.nodes[node].width_attr)
  2433. vw = doc.nodes[node].width_attr;
  2434. if (vw > l->right - l->left)
  2435. vw = l->right - l->left;
  2436. if (vw < 8)
  2437. vw = 8;
  2438. vh = vw * 9 / 16;
  2439. if (vh > 240)
  2440. vh = 240;
  2441. if (vh < 80)
  2442. vh = 80;
  2443. if (l->draw) {
  2444. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  2445. vw, vh}, 0xD69A);
  2446. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  2447. vw, vh}, 0x8410);
  2448. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  2449. 0x4208);
  2450. }
  2451. l->y += vh + 4;
  2452. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  2453. int vw, vh, dw = l->right - l->left;
  2454. int dh;
  2455. svg_viewbox(node, &vw, &vh);
  2456. if (dw < 8)
  2457. dw = 8;
  2458. dh = dw * vh / vw;
  2459. if (dh < 8)
  2460. dh = 8;
  2461. if (dh > 1400)
  2462. dh = 1400;
  2463. if (l->draw) {
  2464. struct ngui_rect clip = {l->left, l->y, dw, dh};
  2465. ngui_push_clip(l->ui, clip);
  2466. draw_svg(l->ui, node, l->left, l->y, dw, dh,
  2467. vw, vh, st);
  2468. ngui_pop_clip(l->ui);
  2469. }
  2470. l->y += dh;
  2471. } else {
  2472. if (doc.nodes[node].tag == BR_TAG_LI && !st->no_bullet) {
  2473. char *m = li_marker[node];
  2474. if (!m[0]) {
  2475. unsigned int parent = doc.nodes[node].parent;
  2476. if (parent &&
  2477. doc.nodes[parent].tag == BR_TAG_OL) {
  2478. int idx = list_index(parent, node);
  2479. unsigned int n = 0;
  2480. s_append_dec(m, &n, (unsigned int)idx, 6);
  2481. s_append(m, &n, ".", 6);
  2482. } else {
  2483. s_copy(m, "-", 6);
  2484. }
  2485. }
  2486. if (l->draw) {
  2487. int mw = (int)ngui_text_width_ui(l->ui, m);
  2488. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  2489. st->color);
  2490. }
  2491. }
  2492. if (doc.nodes[node].tag == BR_TAG_TR)
  2493. layout_table_row(l, node, st, depth + 1, link);
  2494. else if (st->grid_auto)
  2495. layout_grid_auto(l, node, st, depth + 1, link);
  2496. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  2497. st->grid_gap > 0)
  2498. layout_grid_children(l, node, st, depth + 1, link);
  2499. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  2500. flex_wants_row(node, st))
  2501. layout_flex_children(l, node, st, depth + 1, link);
  2502. else
  2503. layout_children(l, node, st, depth + 1, link);
  2504. }
  2505. flush_line(l);
  2506. l->y += st->pb;
  2507. /* Honour an explicit CSS height. Fixed-height header/icon boxes often
  2508. * contain only absolutely positioned children, so their flow height
  2509. * would otherwise collapse to zero. */
  2510. if (st->height_kind == 1 && st->height > 0 &&
  2511. l->y < top + st->height)
  2512. l->y = top + st->height;
  2513. l->left = old_left;
  2514. l->right = old_right;
  2515. l->align = old_align;
  2516. l->y += st->mb;
  2517. if (!l->draw) {
  2518. /* block_h is the element box, not the flow advance: the bottom
  2519. * margin must not be painted as part of the background. */
  2520. int h = l->y - st->mb - top;
  2521. if (h < 0)
  2522. h = 0;
  2523. if (h > 65535)
  2524. h = 65535;
  2525. block_h[node] = (unsigned short)h;
  2526. }
  2527. if (positioned) {
  2528. l->y = flow_y;
  2529. l->left = flow_left;
  2530. l->right = flow_right;
  2531. }
  2532. }
  2533. static int text_node_blank(const struct br_node *nd)
  2534. {
  2535. const char *t = doc.text + nd->text_off;
  2536. unsigned int i;
  2537. for (i = 0; i < nd->text_len; i++)
  2538. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  2539. t[i] != '\r')
  2540. return 0;
  2541. return 1;
  2542. }
  2543. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  2544. * text/image widths in the subtree, plus padding and margins. This keeps
  2545. * Bootstrap's floated nav items on one line instead of giving each the whole
  2546. * row. */
  2547. static int text_space(char c)
  2548. {
  2549. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  2550. }
  2551. static int intrinsic_width(struct ngui *ui, unsigned int node,
  2552. const struct br_style *pst, int depth)
  2553. {
  2554. unsigned int c;
  2555. int w = 0;
  2556. if (depth > 12)
  2557. return 0;
  2558. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  2559. struct br_node *nd = &doc.nodes[c];
  2560. struct br_style cs;
  2561. if (nd->type == BR_NODE_TEXT) {
  2562. const char *t = doc.text + nd->text_off;
  2563. unsigned int tn = nd->text_len;
  2564. if (doc.nodes[node].tag == BR_TAG_PRE) {
  2565. w += (int)ngui_text_width_px(ui, t, tn,
  2566. pst->font_px, pst->bold, pst->italic,
  2567. pst->mono);
  2568. } else {
  2569. unsigned int ti = 0;
  2570. int first = 1;
  2571. int lead = w > 0 && tn > 0 && text_space(t[0]);
  2572. int sp = (int)ngui_text_width_px(ui, " ", 1,
  2573. pst->font_px, pst->bold, pst->italic,
  2574. pst->mono);
  2575. while (ti < tn) {
  2576. unsigned int ts;
  2577. while (ti < tn && text_space(t[ti]))
  2578. ti++;
  2579. ts = ti;
  2580. while (ti < tn && !text_space(t[ti]))
  2581. ti++;
  2582. if (ti == ts)
  2583. break;
  2584. if (!first || lead)
  2585. w += sp;
  2586. lead = 0;
  2587. w += (int)ngui_text_width_px(ui,
  2588. t + ts, ti - ts,
  2589. pst->font_px, pst->bold,
  2590. pst->italic, pst->mono);
  2591. first = 0;
  2592. }
  2593. }
  2594. continue;
  2595. }
  2596. br_style_for(&doc, c, pst, &cs);
  2597. if (cs.display == BR_DISPLAY_NONE)
  2598. continue;
  2599. if (nd->tag == BR_TAG_BR) {
  2600. w += 8;
  2601. continue;
  2602. }
  2603. if (nd->tag == BR_TAG_IMG) {
  2604. /* Measure the image as layout will draw it: a CSS or
  2605. * attribute height keeps the intrinsic aspect ratio, and
  2606. * a CSS width overrides the native pixel width. Bootstrap
  2607. * sizes the Cloudron logo with height:40px only. */
  2608. int idx = nd->img_index;
  2609. int iw = 0, ih = 0;
  2610. if (idx >= 0 && idx < image_count &&
  2611. images[idx].state == 1) {
  2612. iw = (int)images[idx].native_w;
  2613. ih = (int)images[idx].native_h;
  2614. if (iw <= 0 || ih <= 0) {
  2615. iw = (int)images[idx].img.w;
  2616. ih = (int)images[idx].img.h;
  2617. }
  2618. }
  2619. if (cs.width_kind == 1) {
  2620. w += cs.width;
  2621. } else if (cs.width_kind == 2) {
  2622. w += 64;
  2623. } else if (nd->width_attr) {
  2624. w += nd->width_attr;
  2625. } else if (nd->height_attr && iw && ih) {
  2626. w += iw * (int)nd->height_attr / ih;
  2627. } else if (cs.height_kind == 1 && iw && ih) {
  2628. w += iw * (int)cs.height / ih;
  2629. } else if (iw) {
  2630. w += iw;
  2631. } else {
  2632. w += 64;
  2633. }
  2634. continue;
  2635. }
  2636. w += cs.pl + cs.pr + cs.ml + cs.mr;
  2637. w += intrinsic_width(ui, c, &cs, depth + 1);
  2638. if (w > 4096)
  2639. break;
  2640. }
  2641. return w;
  2642. }
  2643. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  2644. * the main user: .row > .col-md-* with float:left and a percentage width.
  2645. * Each column is laid out with its own left/right edge and the row advances
  2646. * to the tallest column. Returns the first child not consumed. */
  2647. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  2648. const struct br_style *pst, int depth,
  2649. unsigned short link)
  2650. {
  2651. unsigned int n = first;
  2652. int row_left = l->left, row_right = l->right;
  2653. int row_top, row_bottom, xl, xr, any = 0;
  2654. flush_line(l);
  2655. row_top = l->y;
  2656. row_bottom = l->y;
  2657. xl = row_left;
  2658. xr = row_right;
  2659. while (n) {
  2660. struct br_node *nd = &doc.nodes[n];
  2661. struct br_style cs;
  2662. unsigned short lk = link;
  2663. int colw, right;
  2664. if (nd->type == BR_NODE_TEXT) {
  2665. if (text_node_blank(nd)) {
  2666. n = nd->next;
  2667. continue;
  2668. }
  2669. break;
  2670. }
  2671. br_style_for(&doc, n, pst, &cs);
  2672. if (cs.display == BR_DISPLAY_NONE) {
  2673. n = nd->next;
  2674. continue;
  2675. }
  2676. /* A float blockifies its box: Bootstrap floats inline
  2677. * anchors too (the navbar brand and its text links), and
  2678. * their padding must be honoured. */
  2679. if (!cs.float_left)
  2680. break;
  2681. if (nd->tag == BR_TAG_A && nd->href_off)
  2682. lk = (unsigned short)n;
  2683. right = cs.float_left == 2;
  2684. if (cs.width_kind == 2)
  2685. colw = (row_right - row_left) * (int)cs.width / 100;
  2686. else if (cs.width_kind == 1)
  2687. colw = (int)cs.width;
  2688. else {
  2689. colw = intrinsic_width(l->ui, n, &cs, 0) +
  2690. cs.pl + cs.pr + cs.ml + cs.mr;
  2691. if (colw < 8)
  2692. colw = 8;
  2693. }
  2694. if (colw < 8)
  2695. colw = 8;
  2696. if (colw > row_right - row_left)
  2697. colw = row_right - row_left;
  2698. if (right) {
  2699. if (any && xr - colw < xl) {
  2700. row_top = row_bottom;
  2701. row_bottom = row_top;
  2702. xl = row_left;
  2703. xr = row_right;
  2704. }
  2705. if (xr - colw < xl)
  2706. colw = xr - xl;
  2707. if (colw < 8)
  2708. colw = 8;
  2709. l->left = xr - colw;
  2710. if (l->left < row_left)
  2711. l->left = row_left;
  2712. l->right = xr;
  2713. xr = l->left;
  2714. } else {
  2715. if (any && xl + colw > xr) {
  2716. row_top = row_bottom;
  2717. row_bottom = row_top;
  2718. xl = row_left;
  2719. xr = row_right;
  2720. }
  2721. l->left = xl;
  2722. l->right = xl + colw;
  2723. xl += colw;
  2724. }
  2725. if (l->right < l->left + 8)
  2726. l->right = l->left + 8;
  2727. l->y = row_top;
  2728. l->line_x = l->left;
  2729. l->run_x = l->left;
  2730. l->line_y = l->y;
  2731. l->line_h = 0;
  2732. l->nruns = 0;
  2733. l->space_pending = 0;
  2734. l->align = cs.align;
  2735. layout_block(l, n, &cs, depth + 1, lk);
  2736. if (l->y > row_bottom)
  2737. row_bottom = l->y;
  2738. any = 1;
  2739. n = nd->next;
  2740. }
  2741. l->left = row_left;
  2742. l->right = row_right;
  2743. l->y = row_bottom;
  2744. l->line_x = l->left;
  2745. l->run_x = l->left;
  2746. l->line_y = l->y;
  2747. l->line_h = 0;
  2748. l->nruns = 0;
  2749. l->space_pending = 0;
  2750. return n;
  2751. }
  2752. static int flex_item_width(struct lay *l, unsigned int n,
  2753. const struct br_style *cs, int avail)
  2754. {
  2755. struct br_node *nd = &doc.nodes[n];
  2756. (void)l;
  2757. int w;
  2758. if (cs->width_kind == 2)
  2759. w = avail * (int)cs->width / 100;
  2760. else if (cs->width_kind == 1)
  2761. w = (int)cs->width;
  2762. else if (nd->tag == BR_TAG_IMG) {
  2763. int idx = nd->img_index;
  2764. if (idx >= 0 && idx < image_count &&
  2765. images[idx].state == 1)
  2766. w = (int)images[idx].img.w;
  2767. else if (nd->width_attr)
  2768. w = (int)nd->width_attr;
  2769. else
  2770. w = 64;
  2771. } else {
  2772. w = intrinsic_width(l->ui, n, cs, 0);
  2773. w += cs->pl + cs->pr + cs->ml + cs->mr;
  2774. }
  2775. if (w < 24)
  2776. w = 24;
  2777. if (w > avail)
  2778. w = avail;
  2779. return w;
  2780. }
  2781. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  2782. * on one line, not one full-width block each. Place intrinsic widths from
  2783. * left to right and wrap when the row is full. */
  2784. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  2785. const struct br_style *pst, int depth,
  2786. unsigned short link)
  2787. {
  2788. unsigned int n = first;
  2789. int row_left = l->left, row_right = l->right;
  2790. int avail = row_right - row_left;
  2791. int x = row_left, y = l->y, row_h = 0, any = 0;
  2792. flush_line(l);
  2793. y = l->y;
  2794. while (n) {
  2795. struct br_node *nd = &doc.nodes[n];
  2796. struct br_style cs;
  2797. unsigned short lk = link;
  2798. int colw, h;
  2799. if (nd->type == BR_NODE_TEXT) {
  2800. if (!text_node_blank(nd))
  2801. break;
  2802. if (any)
  2803. x += 4;
  2804. n = nd->next;
  2805. continue;
  2806. }
  2807. br_style_for(&doc, n, pst, &cs);
  2808. if (cs.display == BR_DISPLAY_NONE) {
  2809. n = nd->next;
  2810. continue;
  2811. }
  2812. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  2813. break;
  2814. if (nd->tag == BR_TAG_A && nd->href_off)
  2815. lk = (unsigned short)n;
  2816. colw = flex_item_width(l, n, &cs, avail);
  2817. /* A few pixels of slack keep a single long token (boot.S)
  2818. * from wrapping at the exact content width. */
  2819. colw += 8;
  2820. if (colw > avail)
  2821. colw = avail;
  2822. if (any && x + colw > row_right) {
  2823. y += row_h + 2;
  2824. x = row_left;
  2825. row_h = 0;
  2826. any = 0;
  2827. }
  2828. if (any && x > row_left)
  2829. x += 4;
  2830. l->left = x;
  2831. l->right = x + colw;
  2832. if (l->right < l->left + 8)
  2833. l->right = l->left + 8;
  2834. l->y = y;
  2835. l->line_x = l->left;
  2836. l->run_x = l->left;
  2837. l->line_y = l->y;
  2838. l->line_h = 0;
  2839. l->nruns = 0;
  2840. l->space_pending = 0;
  2841. l->align = cs.align;
  2842. layout_block(l, n, &cs, depth + 1, lk);
  2843. h = l->y - y;
  2844. if (h > row_h)
  2845. row_h = h;
  2846. x += colw;
  2847. any = 1;
  2848. n = nd->next;
  2849. }
  2850. if (any)
  2851. y += row_h;
  2852. l->left = row_left;
  2853. l->right = row_right;
  2854. l->y = y;
  2855. l->line_x = l->left;
  2856. l->run_x = l->left;
  2857. l->line_y = l->y;
  2858. l->line_h = 0;
  2859. l->nruns = 0;
  2860. l->space_pending = 0;
  2861. return n;
  2862. }
  2863. static void layout_flex_children(struct lay *l, unsigned int parent,
  2864. const struct br_style *pst, int depth,
  2865. unsigned short link)
  2866. {
  2867. unsigned int n, c;
  2868. int row_left = l->left, row_right = l->right;
  2869. int avail = row_right - row_left;
  2870. int grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  2871. int x = row_left, row_top = l->y, row_bottom = l->y, any = 0;
  2872. if (avail < 160 || depth > 24) {
  2873. layout_children(l, parent, pst, depth, link);
  2874. return;
  2875. }
  2876. /* If direct text is not just whitespace, normal block flow handles it
  2877. * better than pretending it is a flex item. */
  2878. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2879. struct br_node *nd = &doc.nodes[c];
  2880. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  2881. layout_children(l, parent, pst, depth, link);
  2882. return;
  2883. }
  2884. }
  2885. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  2886. struct br_node *nd = &doc.nodes[c];
  2887. struct br_style cs;
  2888. if (nd->type == BR_NODE_TEXT)
  2889. continue;
  2890. br_style_for(&doc, c, pst, &cs);
  2891. if (cs.display == BR_DISPLAY_NONE)
  2892. continue;
  2893. if (cs.flex_grow && !cs.width_kind)
  2894. grow_count++;
  2895. else
  2896. fixed += flex_item_width(l, c, &cs, avail);
  2897. }
  2898. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  2899. if (grow_w < 96)
  2900. grow_w = 96;
  2901. n = doc.nodes[parent].first;
  2902. while (n) {
  2903. struct br_node *nd = &doc.nodes[n];
  2904. struct br_style cs;
  2905. unsigned short lk = link;
  2906. int colw;
  2907. if (nd->type == BR_NODE_TEXT) {
  2908. n = nd->next;
  2909. continue;
  2910. }
  2911. br_style_for(&doc, n, pst, &cs);
  2912. if (cs.display == BR_DISPLAY_NONE) {
  2913. n = nd->next;
  2914. continue;
  2915. }
  2916. if (nd->tag == BR_TAG_A && nd->href_off)
  2917. lk = (unsigned short)n;
  2918. if (cs.flex_grow && !cs.width_kind)
  2919. colw = grow_w;
  2920. else
  2921. colw = flex_item_width(l, n, &cs, avail);
  2922. if (colw > row_right - row_left)
  2923. colw = row_right - row_left;
  2924. if (any && x + colw > row_right) {
  2925. if (pst->flex_wrap == 2) {
  2926. if (colw > row_right - x)
  2927. colw = row_right - x;
  2928. } else {
  2929. row_top = row_bottom;
  2930. row_bottom = row_top;
  2931. x = row_left;
  2932. }
  2933. }
  2934. if (any && gap && x > row_left)
  2935. x += gap;
  2936. l->left = x;
  2937. l->right = x + colw;
  2938. if (l->right < l->left + 8)
  2939. l->right = l->left + 8;
  2940. l->y = row_top;
  2941. l->line_x = l->left;
  2942. l->run_x = l->left;
  2943. l->line_y = l->y;
  2944. l->line_h = 0;
  2945. l->nruns = 0;
  2946. l->space_pending = 0;
  2947. l->align = cs.align;
  2948. layout_block(l, n, &cs, depth + 1, lk);
  2949. if (l->y > row_bottom)
  2950. row_bottom = l->y;
  2951. x += colw;
  2952. any++;
  2953. n = nd->next;
  2954. }
  2955. l->left = row_left;
  2956. l->right = row_right;
  2957. l->y = row_bottom;
  2958. l->line_x = l->left;
  2959. l->run_x = l->left;
  2960. l->line_y = l->y;
  2961. l->line_h = 0;
  2962. l->nruns = 0;
  2963. l->space_pending = 0;
  2964. }
  2965. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  2966. * plus the grid-area hints used by site shells (site notice/footer full
  2967. * width, column-start left, page-content right). Anything more elaborate
  2968. * falls back to normal block flow. */
  2969. static int grid_track_width(unsigned char kind, unsigned short val,
  2970. int avail, int other)
  2971. {
  2972. if (kind == 2)
  2973. return avail * (int)val / 100;
  2974. if (kind == 1)
  2975. return val;
  2976. return other;
  2977. }
  2978. static void layout_grid_children(struct lay *l, unsigned int parent,
  2979. const struct br_style *pst, int depth,
  2980. unsigned short link)
  2981. {
  2982. unsigned int n;
  2983. int row_left = l->left, row_right = l->right;
  2984. int avail = row_right - row_left;
  2985. int gap = pst->grid_gap;
  2986. int track_total = avail - gap;
  2987. int col0, col1, x0, x1;
  2988. int row_y, row_bottom, have_left = 0, have_right = 0;
  2989. unsigned int c;
  2990. if (avail < 32 || depth > 24)
  2991. return;
  2992. if (track_total < 16)
  2993. track_total = 16;
  2994. col0 = grid_track_width((unsigned char)(pst->width_kind),
  2995. pst->width, track_total, 0);
  2996. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  2997. pst->max_width, track_total, 0);
  2998. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  2999. int w0 = pst->width ? pst->width : 1;
  3000. int w1 = pst->max_width ? pst->max_width : 1;
  3001. col0 = track_total * w0 / (w0 + w1);
  3002. col1 = track_total - col0;
  3003. } else if (pst->width_kind == 3) {
  3004. col0 = track_total - col1;
  3005. if (col0 < 24)
  3006. col0 = 24;
  3007. } else if (pst->max_width_kind == 3) {
  3008. col1 = track_total - col0;
  3009. if (col1 < 24)
  3010. col1 = 24;
  3011. }
  3012. if (col0 < 24)
  3013. col0 = 24;
  3014. if (col1 < 24)
  3015. col1 = 24;
  3016. if (col0 + col1 > track_total) {
  3017. col1 = track_total - col0;
  3018. if (col1 < 24)
  3019. col1 = 24;
  3020. }
  3021. x0 = row_left;
  3022. x1 = row_left + col0 + gap;
  3023. /* Direct text makes a grid ambiguous; use block flow instead. */
  3024. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3025. struct br_node *nd = &doc.nodes[c];
  3026. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3027. layout_children(l, parent, pst, depth, link);
  3028. return;
  3029. }
  3030. }
  3031. row_y = row_bottom = l->y;
  3032. n = doc.nodes[parent].first;
  3033. while (n) {
  3034. struct br_node *nd = &doc.nodes[n];
  3035. struct br_style cs;
  3036. unsigned short lk = link;
  3037. int slot, x, w;
  3038. if (nd->type == BR_NODE_TEXT) {
  3039. n = nd->next;
  3040. continue;
  3041. }
  3042. br_style_for(&doc, n, pst, &cs);
  3043. if (cs.display == BR_DISPLAY_NONE) {
  3044. n = nd->next;
  3045. continue;
  3046. }
  3047. if (nd->tag == BR_TAG_A && nd->href_off)
  3048. lk = (unsigned short)n;
  3049. slot = cs.grid_slot;
  3050. if (!slot) {
  3051. if (!have_left)
  3052. slot = 2;
  3053. else if (!have_right)
  3054. slot = 3;
  3055. else
  3056. slot = 2;
  3057. }
  3058. if (slot == 1) {
  3059. if (have_left || have_right) {
  3060. row_y = row_bottom;
  3061. have_left = have_right = 0;
  3062. }
  3063. x = row_left;
  3064. w = avail;
  3065. } else if (slot == 2) {
  3066. if (have_left) {
  3067. row_y = row_bottom;
  3068. have_left = have_right = 0;
  3069. }
  3070. x = x0;
  3071. w = col0;
  3072. have_left = 1;
  3073. } else {
  3074. if (have_right) {
  3075. row_y = row_bottom;
  3076. have_left = have_right = 0;
  3077. }
  3078. x = x1;
  3079. w = col1;
  3080. have_right = 1;
  3081. }
  3082. l->left = x;
  3083. l->right = x + w;
  3084. if (l->right < l->left + 8)
  3085. l->right = l->left + 8;
  3086. l->y = row_y;
  3087. l->line_x = l->left;
  3088. l->run_x = l->left;
  3089. l->line_y = l->y;
  3090. l->line_h = 0;
  3091. l->nruns = 0;
  3092. l->space_pending = 0;
  3093. l->align = cs.align;
  3094. layout_block(l, n, &cs, depth + 1, lk);
  3095. if (l->y > row_bottom)
  3096. row_bottom = l->y;
  3097. n = nd->next;
  3098. }
  3099. l->left = row_left;
  3100. l->right = row_right;
  3101. l->y = row_bottom;
  3102. l->line_x = l->left;
  3103. l->run_x = l->left;
  3104. l->line_y = l->y;
  3105. l->line_h = 0;
  3106. l->nruns = 0;
  3107. l->space_pending = 0;
  3108. }
  3109. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  3110. * capped at four. Used by the project docs' card grids. */
  3111. static void layout_grid_auto(struct lay *l, unsigned int parent,
  3112. const struct br_style *pst, int depth,
  3113. unsigned short link)
  3114. {
  3115. unsigned int n, c;
  3116. int row_left = l->left, row_right = l->right;
  3117. int avail = row_right - row_left;
  3118. int gap = pst->grid_gap;
  3119. int minw = pst->width_kind == 1 ? pst->width : 200;
  3120. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  3121. if (avail < 32 || depth > 24) {
  3122. layout_children(l, parent, pst, depth, link);
  3123. return;
  3124. }
  3125. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  3126. struct br_node *nd = &doc.nodes[c];
  3127. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  3128. layout_children(l, parent, pst, depth, link);
  3129. return;
  3130. }
  3131. }
  3132. if (minw < 80)
  3133. minw = 80;
  3134. ncols = (avail + gap) / (minw + gap);
  3135. if (ncols < 1)
  3136. ncols = 1;
  3137. if (ncols > 4)
  3138. ncols = 4;
  3139. colw = (avail - gap * (ncols - 1)) / ncols;
  3140. if (colw < 24)
  3141. colw = 24;
  3142. x = row_left;
  3143. n = doc.nodes[parent].first;
  3144. while (n) {
  3145. struct br_node *nd = &doc.nodes[n];
  3146. struct br_style cs;
  3147. unsigned short lk = link;
  3148. int h;
  3149. if (nd->type == BR_NODE_TEXT) {
  3150. n = nd->next;
  3151. continue;
  3152. }
  3153. br_style_for(&doc, n, pst, &cs);
  3154. if (cs.display == BR_DISPLAY_NONE) {
  3155. n = nd->next;
  3156. continue;
  3157. }
  3158. if (nd->tag == BR_TAG_A && nd->href_off)
  3159. lk = (unsigned short)n;
  3160. l->left = x;
  3161. l->right = x + colw;
  3162. if (l->right < l->left + 8)
  3163. l->right = l->left + 8;
  3164. l->y = y;
  3165. l->line_x = l->left;
  3166. l->run_x = l->left;
  3167. l->line_y = l->y;
  3168. l->line_h = 0;
  3169. l->nruns = 0;
  3170. l->space_pending = 0;
  3171. l->align = cs.align;
  3172. layout_block(l, n, &cs, depth + 1, lk);
  3173. h = l->y - y;
  3174. if (h > row_h)
  3175. row_h = h;
  3176. col++;
  3177. n = nd->next;
  3178. if (col == ncols) {
  3179. y += row_h + gap;
  3180. x = row_left;
  3181. row_h = 0;
  3182. col = 0;
  3183. } else {
  3184. x += colw + gap;
  3185. }
  3186. }
  3187. if (col)
  3188. y += row_h;
  3189. else if (y > start_y)
  3190. y -= gap;
  3191. l->left = row_left;
  3192. l->right = row_right;
  3193. l->y = y;
  3194. l->line_x = l->left;
  3195. l->run_x = l->left;
  3196. l->line_y = l->y;
  3197. l->line_h = 0;
  3198. l->nruns = 0;
  3199. l->space_pending = 0;
  3200. }
  3201. /* Column widths are the widest cell in each column across every row, so all
  3202. * rows line up. The table model is still deliberately basic: no colspan,
  3203. * border-collapse or percentage columns. */
  3204. static void table_columns(struct lay *l, unsigned int table,
  3205. const struct br_style *pst, int *raw, int maxcols,
  3206. int *out_cols, int *out_total)
  3207. {
  3208. unsigned int r, c;
  3209. int cols = 0, total = 0;
  3210. for (c = 0; c < (unsigned int)maxcols; c++)
  3211. raw[c] = 0;
  3212. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  3213. struct br_node *rn = &doc.nodes[r];
  3214. int col = 0;
  3215. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  3216. continue;
  3217. for (c = rn->first; c; c = doc.nodes[c].next) {
  3218. struct br_node *cn = &doc.nodes[c];
  3219. struct br_style cs;
  3220. int w;
  3221. if (cn->type != BR_NODE_ELEM ||
  3222. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  3223. continue;
  3224. if (col >= maxcols)
  3225. break;
  3226. br_style_for(&doc, c, pst, &cs);
  3227. if (cs.display == BR_DISPLAY_NONE)
  3228. continue;
  3229. w = intrinsic_width(l->ui, c, &cs, 0) + cs.pl + cs.pr +
  3230. cs.ml + cs.mr;
  3231. if (w < 24)
  3232. w = 24;
  3233. if (w > raw[col])
  3234. raw[col] = w;
  3235. if (col + 1 > cols)
  3236. cols = col + 1;
  3237. col++;
  3238. }
  3239. }
  3240. for (c = 0; c < (unsigned int)cols; c++)
  3241. total += raw[c];
  3242. *out_cols = cols;
  3243. *out_total = total;
  3244. }
  3245. static void layout_table_row(struct lay *l, unsigned int row,
  3246. const struct br_style *pst, int depth,
  3247. unsigned short link)
  3248. {
  3249. unsigned int n, cell[12];
  3250. int raw[12], ncell = 0, total = 0, cols = 0;
  3251. int row_left = l->left, row_right = l->right;
  3252. int avail = row_right - row_left;
  3253. int x = row_left, y = l->y, bottom = l->y;
  3254. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  3255. struct br_node *nd = &doc.nodes[n];
  3256. struct br_style cs;
  3257. if (nd->type == BR_NODE_TEXT) {
  3258. if (text_node_blank(nd))
  3259. continue;
  3260. layout_children(l, row, pst, depth, link);
  3261. return;
  3262. }
  3263. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  3264. layout_children(l, row, pst, depth, link);
  3265. return;
  3266. }
  3267. br_style_for(&doc, n, pst, &cs);
  3268. if (cs.display == BR_DISPLAY_NONE)
  3269. continue;
  3270. if (ncell >= 12) {
  3271. layout_children(l, row, pst, depth, link);
  3272. return;
  3273. }
  3274. cell[ncell] = n;
  3275. ncell++;
  3276. }
  3277. if (ncell < 2 || avail < 32) {
  3278. layout_children(l, row, pst, depth, link);
  3279. return;
  3280. }
  3281. table_columns(l, doc.nodes[row].parent, pst, raw, 12, &cols, &total);
  3282. if (cols < 2 || total <= 0) {
  3283. int c;
  3284. for (c = 0; c < ncell; c++) {
  3285. struct br_style cs;
  3286. br_style_for(&doc, cell[c], pst, &cs);
  3287. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0) +
  3288. cs.pl + cs.pr + cs.ml + cs.mr;
  3289. if (raw[c] < 24)
  3290. raw[c] = 24;
  3291. total += raw[c];
  3292. }
  3293. }
  3294. for (n = 0; n < (unsigned int)ncell; n++) {
  3295. struct br_style cs;
  3296. int w = (int)((long)raw[n] * avail / total);
  3297. br_style_for(&doc, cell[n], pst, &cs);
  3298. if (w < 24)
  3299. w = 24;
  3300. if (w < 8)
  3301. w = 8;
  3302. l->left = x;
  3303. l->right = x + w;
  3304. l->y = y;
  3305. l->line_x = l->left;
  3306. l->run_x = l->left;
  3307. l->line_y = l->y;
  3308. l->line_h = 0;
  3309. l->nruns = 0;
  3310. l->space_pending = 0;
  3311. l->align = cs.align;
  3312. layout_block(l, cell[n], &cs, depth + 1, link);
  3313. if (l->y > bottom)
  3314. bottom = l->y;
  3315. x += w;
  3316. }
  3317. l->left = row_left;
  3318. l->right = row_right;
  3319. l->y = bottom;
  3320. l->line_x = l->left;
  3321. l->run_x = l->left;
  3322. l->line_y = l->y;
  3323. l->line_h = 0;
  3324. l->nruns = 0;
  3325. l->space_pending = 0;
  3326. }
  3327. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  3328. * flow so they sit above it, like CSS painting order. Their flow origin is
  3329. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  3330. struct br_deferred {
  3331. unsigned int node;
  3332. int flow_y, flow_left, flow_right;
  3333. unsigned short link;
  3334. };
  3335. static struct br_deferred deferred[16];
  3336. static int ndeferred;
  3337. static void layout_children(struct lay *l, unsigned int parent,
  3338. const struct br_style *pst, int depth,
  3339. unsigned short link)
  3340. {
  3341. unsigned int n;
  3342. if (depth > 24)
  3343. return;
  3344. n = doc.nodes[parent].first;
  3345. while (n) {
  3346. struct br_node *nd = &doc.nodes[n];
  3347. struct br_style cs;
  3348. unsigned short lk = link;
  3349. if (nd->type == BR_NODE_TEXT) {
  3350. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  3351. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  3352. n = nd->next;
  3353. continue;
  3354. }
  3355. br_style_for(&doc, n, pst, &cs);
  3356. if (cs.display == BR_DISPLAY_NONE) {
  3357. n = nd->next;
  3358. continue;
  3359. }
  3360. if (nd->tag == BR_TAG_A && nd->href_off)
  3361. lk = (unsigned short)n;
  3362. if (cs.pos) {
  3363. if (l->draw && ndeferred < 16) {
  3364. deferred[ndeferred].node = n;
  3365. deferred[ndeferred].flow_y = l->y;
  3366. deferred[ndeferred].flow_left = l->left;
  3367. deferred[ndeferred].flow_right = l->right;
  3368. deferred[ndeferred].link = lk;
  3369. ndeferred++;
  3370. } else {
  3371. layout_block(l, n, &cs, depth + 1, lk);
  3372. }
  3373. if (cs.pos == 1 && block_h[n] &&
  3374. doc.nodes[n].class_off) {
  3375. const char *cl = doc.attrs +
  3376. doc.nodes[n].class_off;
  3377. if ((contains_ci(cl, "poster-wrapper") ||
  3378. contains_ci(cl, "ts-picture")) &&
  3379. !has_skeleton_sibling(n))
  3380. l->y += block_h[n];
  3381. }
  3382. n = nd->next;
  3383. continue;
  3384. }
  3385. if (nd->tag == BR_TAG_BR) {
  3386. flush_line(l);
  3387. n = nd->next;
  3388. continue;
  3389. }
  3390. if (nd->tag == BR_TAG_HR) {
  3391. flush_line(l);
  3392. if (l->draw)
  3393. ngui_fill_rect(l->ui,
  3394. (struct ngui_rect){l->left, l->y + 2,
  3395. l->right - l->left, 1}, BR_GRAY);
  3396. l->y += 8;
  3397. n = nd->next;
  3398. continue;
  3399. }
  3400. if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  3401. nd->tag == BR_TAG_SELECT) {
  3402. if (!(nd->tag == BR_TAG_INPUT &&
  3403. s_eq(br_type(&doc, n), "hidden")))
  3404. add_form_run(l, n, &cs, lk);
  3405. n = nd->next;
  3406. continue;
  3407. }
  3408. if (nd->tag == BR_TAG_IMG) {
  3409. add_image_run(l, n, &cs, lk);
  3410. n = nd->next;
  3411. continue;
  3412. }
  3413. if (nd->tag == BR_TAG_VIDEO) {
  3414. layout_block(l, n, &cs, depth + 1, lk);
  3415. n = nd->next;
  3416. continue;
  3417. }
  3418. if (cs.float_left) {
  3419. n = layout_float_group(l, n, pst, depth, lk);
  3420. continue;
  3421. }
  3422. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  3423. n = layout_inline_blocks(l, n, pst, depth, link);
  3424. continue;
  3425. }
  3426. if (cs.display == BR_DISPLAY_BLOCK || br_tag_is_block(nd->tag))
  3427. layout_block(l, n, &cs, depth + 1, lk);
  3428. else {
  3429. layout_children(l, n, &cs, depth + 1, lk);
  3430. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  3431. l->space_pending = 1;
  3432. }
  3433. n = nd->next;
  3434. }
  3435. }
  3436. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  3437. * runs and a recursive page can otherwise overflow the stack. */
  3438. static struct lay layout_state;
  3439. static int measure_page(int left, int right)
  3440. {
  3441. struct lay *l = &layout_state;
  3442. struct br_style base = base_style();
  3443. unsigned int i;
  3444. for (i = 0; i < BR_MAX_NODES; i++) {
  3445. block_h[i] = 0;
  3446. img_top[i] = 0;
  3447. img_h[i] = 0;
  3448. }
  3449. l->draw = 0;
  3450. l->ui = 0;
  3451. l->left = left;
  3452. l->right = right;
  3453. l->y = 0;
  3454. l->line_x = left;
  3455. l->run_x = left;
  3456. l->line_y = 0;
  3457. l->line_h = 0;
  3458. l->align = BR_ALIGN_LEFT;
  3459. l->depth = 0;
  3460. l->nruns = 0;
  3461. l->space_pending = 0;
  3462. layout_children(l, doc.root, &base, 0, 0);
  3463. return l->y + 8;
  3464. }
  3465. static void render_page(int left, int right, int y0)
  3466. {
  3467. struct lay *l = &layout_state;
  3468. struct br_style base = base_style();
  3469. l->draw = 1;
  3470. l->ui = &ui;
  3471. l->left = left;
  3472. l->right = right;
  3473. l->y = y0;
  3474. l->line_x = left;
  3475. l->run_x = left;
  3476. l->line_y = y0;
  3477. l->line_h = 0;
  3478. l->align = BR_ALIGN_LEFT;
  3479. l->depth = 0;
  3480. l->nruns = 0;
  3481. l->space_pending = 0;
  3482. nhits = 0;
  3483. ndeferred = 0;
  3484. layout_children(l, doc.root, &base, 0, 0);
  3485. {
  3486. int i;
  3487. for (i = 0; i < ndeferred; i++) {
  3488. struct br_style st;
  3489. br_style_for(&doc, deferred[i].node, &base, &st);
  3490. if (st.display == BR_DISPLAY_NONE)
  3491. continue;
  3492. l->draw = 1;
  3493. l->left = deferred[i].flow_left;
  3494. l->right = deferred[i].flow_right;
  3495. l->y = deferred[i].flow_y;
  3496. l->line_x = l->left;
  3497. l->run_x = l->left;
  3498. l->line_y = l->y;
  3499. l->line_h = 0;
  3500. l->nruns = 0;
  3501. l->space_pending = 0;
  3502. l->align = st.align;
  3503. if (st.pos == 2 && block_h[deferred[i].node]) {
  3504. struct ngui_rect clip;
  3505. int ch = block_h[deferred[i].node] + 24;
  3506. clip.x = page_rect.x;
  3507. clip.y = page_rect.y;
  3508. clip.w = page_rect.w - 12;
  3509. if (ch > page_rect.h)
  3510. ch = page_rect.h;
  3511. clip.h = ch;
  3512. ngui_push_clip(&ui, clip);
  3513. if (st.has_bg)
  3514. ngui_fill_rect(&ui, clip, st.bg);
  3515. layout_block(l, deferred[i].node, &st, 0,
  3516. deferred[i].link);
  3517. ngui_pop_clip(&ui);
  3518. } else {
  3519. layout_block(l, deferred[i].node, &st, 0,
  3520. deferred[i].link);
  3521. }
  3522. }
  3523. }
  3524. }
  3525. /* ---- UI ---- */
  3526. static int find_hit(int x, int y)
  3527. {
  3528. int i;
  3529. for (i = nhits - 1; i >= 0; i--) {
  3530. struct hit *h = &hits[i];
  3531. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  3532. y < h->y + h->h)
  3533. return (int)h->node;
  3534. }
  3535. return 0;
  3536. }
  3537. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  3538. {
  3539. int x = r.x + 4, y = r.y + 4, h = 22;
  3540. int compact = r.w < 560;
  3541. int go_w = r.w < 420 ? 32 : 42;
  3542. int in_x, in_w, res;
  3543. ngui_fill_rect(&ui, r, ui.theme.panel);
  3544. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  3545. ui.theme.border);
  3546. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  3547. NGUI_ICON_CHEVRON_LEFT))
  3548. *action |= ACT_BACK;
  3549. x += 32;
  3550. if (!compact) {
  3551. if (ngui_icon_button(&ui, ID_FORWARD,
  3552. (struct ngui_rect){x, y, 28, h},
  3553. NGUI_ICON_CHEVRON_RIGHT))
  3554. *action |= ACT_FORWARD;
  3555. x += 32;
  3556. }
  3557. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  3558. NGUI_ICON_REFRESH))
  3559. *action |= ACT_RELOAD;
  3560. x += 32;
  3561. if (!compact) {
  3562. if (ngui_icon_button(&ui, ID_HOME,
  3563. (struct ngui_rect){x, y, 28, h},
  3564. NGUI_ICON_HOME))
  3565. *action |= ACT_HOME;
  3566. x += 32;
  3567. }
  3568. in_x = x + 2;
  3569. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  3570. if (in_w < 60)
  3571. in_w = 60;
  3572. res = ngui_text_input(&ui, ID_URL,
  3573. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  3574. if (res & NGUI_INPUT_SUBMIT)
  3575. *action |= ACT_NAV;
  3576. if (res & NGUI_INPUT_CANCEL)
  3577. ngui_set_focus(&ui, 0);
  3578. if (ngui_button(&ui, ID_GO,
  3579. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  3580. "Go"))
  3581. *action |= ACT_NAV;
  3582. }
  3583. static int page_hover_node(void)
  3584. {
  3585. if (!ui.inside)
  3586. return 0;
  3587. if (ui.mouse_x < page_rect.x ||
  3588. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  3589. ui.mouse_y < page_rect.y ||
  3590. ui.mouse_y >= page_rect.y + page_rect.h)
  3591. return 0;
  3592. return find_hit(ui.mouse_x, ui.mouse_y);
  3593. }
  3594. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  3595. {
  3596. int x, y, w = page.w, h = page.h;
  3597. if (!src || w <= 0 || h <= 0)
  3598. return;
  3599. for (y = 0; y < h; y++) {
  3600. unsigned short *s = src + (page.y + y) * sw + page.x;
  3601. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  3602. for (x = 0; x + 1 < w; x += 2) {
  3603. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  3604. }
  3605. if (x < w)
  3606. d[x] = s[x];
  3607. }
  3608. }
  3609. static void draw_page(struct ngui_rect page)
  3610. {
  3611. int left, right, ch;
  3612. int old_panel, old_dim;
  3613. unsigned short *saved_px;
  3614. int saved_w, saved_h, use_buf;
  3615. page_rect = page;
  3616. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  3617. page_cache_valid && layout_valid &&
  3618. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  3619. page_scroll.offset == page_cache_scroll &&
  3620. page_cache_nnode == doc.nnode &&
  3621. page_cache_x == page.x && page_cache_y == page.y &&
  3622. page_cache_w == page.w && page_cache_h == page.h) {
  3623. blit_page(page, page_backbuf, pagebuf_w);
  3624. return;
  3625. }
  3626. ngui_fill_rect(&ui, page, ui.theme.bg);
  3627. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  3628. const char *s = page_loading ? "Loading..." : "No page";
  3629. int w = (int)ngui_text_width_ui(&ui, s);
  3630. ngui_text(&ui, page.x + (page.w - w) / 2,
  3631. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  3632. page_scroll.content_h = 0;
  3633. page_scroll.view_h = page.h;
  3634. page_cache_valid = 0;
  3635. return;
  3636. }
  3637. if (page.w < 40 || page.h < 40) {
  3638. page_cache_valid = 0;
  3639. return;
  3640. }
  3641. saved_px = ui.px;
  3642. saved_w = ui.w;
  3643. saved_h = ui.h;
  3644. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  3645. if (use_buf) {
  3646. ui.px = page_backbuf;
  3647. ui.w = pagebuf_w;
  3648. ui.h = pagebuf_h;
  3649. ngui_fill_rect(&ui, page, ui.theme.bg);
  3650. }
  3651. left = page.x + 8;
  3652. right = page.x + page.w - 16;
  3653. if (!layout_valid || left != layout_left || right != layout_right ||
  3654. layout_nnode != doc.nnode) {
  3655. layout_content_h = measure_page(left, right);
  3656. layout_valid = 1;
  3657. layout_left = left;
  3658. layout_right = right;
  3659. layout_nnode = doc.nnode;
  3660. }
  3661. ch = layout_content_h;
  3662. page_scroll.content_h = ch;
  3663. page_scroll.view_h = page.h;
  3664. ngui_scroll_begin(&ui, page, &page_scroll);
  3665. render_page(left, right, page.y + 4 - page_scroll.offset);
  3666. old_panel = ui.theme.panel_alt;
  3667. old_dim = ui.theme.text_dim;
  3668. ui.theme.panel_alt = 0xC618;
  3669. ui.theme.text_dim = 0x8410;
  3670. ngui_scroll_end(&ui, page, &page_scroll);
  3671. ui.theme.panel_alt = old_panel;
  3672. ui.theme.text_dim = old_dim;
  3673. if (use_buf) {
  3674. ui.px = saved_px;
  3675. ui.w = saved_w;
  3676. ui.h = saved_h;
  3677. blit_page(page, page_backbuf, pagebuf_w);
  3678. page_cache_valid = 1;
  3679. page_cache_scroll = page_scroll.offset;
  3680. page_cache_nnode = doc.nnode;
  3681. page_cache_x = page.x;
  3682. page_cache_y = page.y;
  3683. page_cache_w = page.w;
  3684. page_cache_h = page.h;
  3685. } else {
  3686. page_cache_valid = 0;
  3687. }
  3688. }
  3689. static void draw_status(struct ngui_rect r)
  3690. {
  3691. char msg[BR_URL_MAX + 32];
  3692. unsigned int n = 0;
  3693. int hover = page_hover_node();
  3694. unsigned short color;
  3695. const char *kind;
  3696. ngui_fill_rect(&ui, r, ui.theme.panel);
  3697. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  3698. ui.theme.border);
  3699. if (hover) {
  3700. const char *href = br_href(&doc, (unsigned int)hover);
  3701. char url[BR_URL_MAX];
  3702. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  3703. s_append(msg, &n, "Link: ", sizeof(msg));
  3704. s_append(msg, &n, url, sizeof(msg));
  3705. } else {
  3706. s_copy(msg, "Link", sizeof(msg));
  3707. }
  3708. color = ui.theme.accent;
  3709. } else if (status_text[0]) {
  3710. s_copy(msg, status_text, sizeof(msg));
  3711. color = status_error ? ui.theme.error : ui.theme.text;
  3712. } else if (page_title[0]) {
  3713. s_copy(msg, page_title, sizeof(msg));
  3714. color = ui.theme.text;
  3715. } else {
  3716. s_copy(msg, "Ready", sizeof(msg));
  3717. color = ui.theme.text_dim;
  3718. }
  3719. kind = s_eq(page_url, "about:home") ? "HOME" :
  3720. page_is_local ? "FILE" :
  3721. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  3722. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  3723. {
  3724. int kw = (int)ngui_text_width_ui(&ui, kind);
  3725. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  3726. ui.theme.text_dim);
  3727. }
  3728. }
  3729. static void draw(unsigned int *action)
  3730. {
  3731. struct ngui_rect r = {0, 0, ui.w, ui.h};
  3732. struct ngui_rect toolbar, status, page;
  3733. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  3734. status = ngui_cut_bottom(&r, BR_STATUS_H);
  3735. page = r;
  3736. draw_toolbar(toolbar, action);
  3737. draw_page(page);
  3738. draw_status(status);
  3739. }
  3740. static void redraw_now(void)
  3741. {
  3742. unsigned int action = 0;
  3743. ngui_begin(&ui);
  3744. draw(&action);
  3745. ngui_end(&ui);
  3746. }
  3747. static void handle_keys(unsigned int *action)
  3748. {
  3749. int k, scrolled = 0;
  3750. /* Batch queued page keys: a slow full-page render must not make a
  3751. * held Page Down advance only once every few frames. */
  3752. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  3753. scrolled++;
  3754. if (scrolled)
  3755. ngui_invalidate(&ui);
  3756. if (ngui_focus(&ui))
  3757. return;
  3758. while ((k = ngui_key(&ui)) != 0) {
  3759. switch (k) {
  3760. case NGUI_KEY_ESC:
  3761. *action |= ACT_CLOSE;
  3762. break;
  3763. case NGUI_KEY_TAB:
  3764. case 0x0C: /* Ctrl+L */
  3765. ngui_set_focus(&ui, ID_URL);
  3766. break;
  3767. case 0x12: /* Ctrl+R */
  3768. *action |= ACT_RELOAD;
  3769. break;
  3770. case NGUI_KEY_BACKSPACE:
  3771. *action |= ACT_BACK;
  3772. break;
  3773. case NGUI_KEY_UP:
  3774. ngui_scroll_to(&page_scroll,
  3775. page_scroll.offset - 24);
  3776. ngui_invalidate(&ui);
  3777. break;
  3778. case NGUI_KEY_DOWN:
  3779. ngui_scroll_to(&page_scroll,
  3780. page_scroll.offset + 24);
  3781. ngui_invalidate(&ui);
  3782. break;
  3783. case NGUI_KEY_HOME:
  3784. ngui_scroll_to(&page_scroll, 0);
  3785. ngui_invalidate(&ui);
  3786. break;
  3787. case NGUI_KEY_END:
  3788. ngui_scroll_to(&page_scroll,
  3789. page_scroll.content_h -
  3790. page_scroll.view_h);
  3791. ngui_invalidate(&ui);
  3792. break;
  3793. default:
  3794. break;
  3795. }
  3796. }
  3797. }
  3798. static void handle_page_click(unsigned int *action)
  3799. {
  3800. int node;
  3801. char url[BR_URL_MAX];
  3802. if (!ui.pressed)
  3803. return;
  3804. if (ui.press_x < page_rect.x ||
  3805. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  3806. ui.press_y < page_rect.y ||
  3807. ui.press_y >= page_rect.y + page_rect.h)
  3808. return;
  3809. node = find_hit(ui.press_x, ui.press_y);
  3810. if (!node)
  3811. return;
  3812. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  3813. sizeof(url)) != 0)
  3814. return;
  3815. s_copy(click_url, url, sizeof(click_url));
  3816. *action |= ACT_NAV;
  3817. }
  3818. void _start(const char *arg)
  3819. {
  3820. struct win_info wi;
  3821. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  3822. u_win_create(960, 640, "Browser", &wi) != 0 &&
  3823. u_win_create(780, 540, "Browser", &wi) != 0) {
  3824. u_puts("browser: no graphics window\n");
  3825. u_exit(1);
  3826. }
  3827. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  3828. url_in.placeholder = "http://...";
  3829. br_doc_init(&doc);
  3830. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  3831. ui.theme.accent);
  3832. br_set_viewport(wi.width);
  3833. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  3834. s_copy(cwd, "/", sizeof(cwd));
  3835. heap_clear();
  3836. page_scroll.offset = 0;
  3837. page_scroll.content_h = 0;
  3838. if (arg && arg[0]) {
  3839. navigate(arg, 1);
  3840. } else {
  3841. load_home(1);
  3842. /* Start ready to type: keep the home page, but leave the address
  3843. * bar empty instead of showing "about:home". */
  3844. ngui_input_set(&url_in, "");
  3845. ngui_set_focus(&ui, ID_URL);
  3846. }
  3847. for (;;) {
  3848. unsigned int action = 0;
  3849. unsigned int now;
  3850. click_url[0] = '\0';
  3851. if (pending_action) {
  3852. action |= pending_action & ACT_WAIT_NAV;
  3853. if (pending_url[0])
  3854. s_copy(click_url, pending_url, sizeof(click_url));
  3855. pending_action = 0;
  3856. pending_url[0] = '\0';
  3857. cancel_fetch = 0;
  3858. } else if (preload_active) {
  3859. if (preload_wait)
  3860. preload_wait = 0;
  3861. else
  3862. preload_step();
  3863. } else if (preload_pending &&
  3864. page_scroll.offset != preload_scroll) {
  3865. preload_scroll = page_scroll.offset;
  3866. preload_pending = 0;
  3867. preload_node = 0;
  3868. preload_active = 1;
  3869. }
  3870. now = u_ticks_ms();
  3871. if (status_until && (int)(now - status_until) >= 0) {
  3872. status_text[0] = '\0';
  3873. status_until = 0;
  3874. status_error = 0;
  3875. ngui_invalidate(&ui);
  3876. }
  3877. if (!ngui_begin(&ui)) {
  3878. /* A queued navigation (e.g. Enter in the URL bar during
  3879. * a slow fetch) must be handled even when this frame
  3880. * needs no redraw. */
  3881. if (!action) {
  3882. u_sleep_ms(10);
  3883. continue;
  3884. }
  3885. } else {
  3886. draw(&action);
  3887. handle_keys(&action);
  3888. handle_page_click(&action);
  3889. ngui_end(&ui);
  3890. }
  3891. if (action & ACT_NAV) {
  3892. if (click_url[0]) {
  3893. navigate(click_url, 1);
  3894. click_url[0] = '\0';
  3895. } else {
  3896. navigate(url_in.text, 1);
  3897. }
  3898. }
  3899. if (action & ACT_BACK) {
  3900. if (hist_pos > 0) {
  3901. hist_pos--;
  3902. navigate(history[hist_pos], 0);
  3903. }
  3904. }
  3905. if (action & ACT_FORWARD) {
  3906. if (hist_pos + 1 < hist_len) {
  3907. hist_pos++;
  3908. navigate(history[hist_pos], 0);
  3909. }
  3910. }
  3911. if (action & ACT_RELOAD) {
  3912. if (s_eq(page_url, "about:home"))
  3913. load_home(0);
  3914. else
  3915. navigate(page_url, 0);
  3916. }
  3917. if (action & ACT_HOME)
  3918. load_home(1);
  3919. if (action & ACT_CLOSE)
  3920. quit = 1;
  3921. if (quit)
  3922. break;
  3923. if (pending_action)
  3924. continue;
  3925. u_sleep_ms(10);
  3926. }
  3927. fetch_helper_stop();
  3928. u_win_close();
  3929. u_exit(0);
  3930. }