browser.c 117 KB

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