browser.c 107 KB

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