browser.c 110 KB

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