browser.c 362 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. #define BR_MAX_SHEETS 6
  71. #define BR_HISTORY 16
  72. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  73. #define BR_STATUS_MAX 200
  74. #define BR_IMG_RGB565(r, g, b) \
  75. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  76. #define BR_GRAY 0x8410
  77. enum {
  78. ID_URL = 1,
  79. ID_GO,
  80. ID_BACK,
  81. ID_FORWARD,
  82. ID_RELOAD,
  83. ID_HOME
  84. };
  85. #define ACT_NAV (1u << 0)
  86. #define ACT_BACK (1u << 1)
  87. #define ACT_FORWARD (1u << 2)
  88. #define ACT_RELOAD (1u << 3)
  89. #define ACT_HOME (1u << 4)
  90. #define ACT_CLOSE (1u << 5)
  91. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  92. ACT_HOME | ACT_CLOSE)
  93. struct br_image {
  94. int state; /* 0 empty, 1 ready */
  95. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  96. int native_w, native_h;
  97. unsigned int url_hash; /* <img> source, 0 = not shareable */
  98. char err[32];
  99. /* Display-size cache: the box an image is actually painted in. The
  100. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  101. * window resize can re-scale it; the cached copy is exactly dw x dh,
  102. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  103. struct img_image disp;
  104. unsigned int disp_pixels;
  105. unsigned int disp_last;
  106. };
  107. static struct ngui ui;
  108. static struct ngui_input url_in;
  109. static struct ngui_scroll page_scroll;
  110. static struct br_doc doc;
  111. static struct br_image images[BR_MAX_IMAGES];
  112. static int image_count;
  113. static unsigned int image_pixels;
  114. static unsigned int image_disp_pixels;
  115. static unsigned int image_disp_clock;
  116. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  117. * numbers are what decides whether the next work is network, decode or
  118. * display; keep them cheap (one tick read per phase). */
  119. static unsigned int img_stat_start;
  120. static unsigned int img_stat_wall;
  121. static unsigned int img_stat_net;
  122. static unsigned int img_stat_open;
  123. static unsigned int img_stat_first;
  124. static unsigned int img_stat_io;
  125. static unsigned int img_stat_dec;
  126. static unsigned int img_stat_scale;
  127. static unsigned int img_stat_paint;
  128. static unsigned int img_stat_reflow;
  129. static unsigned int img_stat_bytes;
  130. static int img_stat_n;
  131. static unsigned int img_last_dec_ms;
  132. static unsigned int img_last_scale_ms;
  133. static char img_stat_log[BR_IMG_STAT_LOG];
  134. static unsigned int img_stat_log_len;
  135. static unsigned int img_repaint_ms;
  136. static int img_repaint_pending;
  137. /* Painted border boxes, in page/screen coordinates (layout starts at
  138. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  139. struct br_layout_box {
  140. int x, y;
  141. int w, h;
  142. unsigned char valid;
  143. };
  144. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  145. /* Images are loaded one per main-loop iteration so the parsed page stays
  146. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  147. static int preload_active;
  148. static int preload_max_jobs;
  149. static int preload_pending;
  150. static int preload_wait;
  151. static unsigned int preload_node;
  152. static int preload_loaded;
  153. static int preload_scroll;
  154. static int preload_rescan;
  155. static char post_status_text[BR_STATUS_MAX];
  156. static int post_status_error;
  157. static unsigned int post_status_ttl;
  158. /* Content-relative position/height of each <img>, recorded by the measure
  159. * pass so image loading can be deferred until it is near the viewport. */
  160. static unsigned short img_top[BR_MAX_NODES];
  161. static unsigned short img_h[BR_MAX_NODES];
  162. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  163. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  164. * body. Decode arenas are allocated per image instead of living here. */
  165. static unsigned char *image_io_buf;
  166. static struct ufont_face *font_faces[BR_MAX_FACES];
  167. #define image_file_buf (image_io_buf)
  168. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  169. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  170. static struct inflate image_inflate_ws;
  171. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  172. #error "CSS scratch must fit in image_io_buf"
  173. #endif
  174. static char page_url[BR_URL_MAX];
  175. static char page_title[BR_TITLE_MAX];
  176. static char cwd[64];
  177. static int page_is_local;
  178. static int page_loading;
  179. static char status_text[BR_STATUS_MAX];
  180. static unsigned int status_until;
  181. static int status_error;
  182. static char history[BR_HISTORY][BR_URL_MAX];
  183. static int hist_len, hist_pos;
  184. static char click_url[BR_URL_MAX];
  185. static char pending_url[BR_URL_MAX];
  186. #define BR_POST_MAX 4096
  187. static char pending_post[BR_POST_MAX];
  188. static unsigned int pending_post_len;
  189. /* The pending navigation is a POST even when its body is empty (a form
  190. * without fields, e.g. the OIDC consent auto-submit). */
  191. static int pending_post_is;
  192. /* window "resize" bookkeeping: the page width the last event was for. */
  193. static int resize_sent_w = -1;
  194. static int resize_pending;
  195. static unsigned int pending_action;
  196. static int cancel_fetch;
  197. static int quit;
  198. static struct ngui_rect page_rect;
  199. static unsigned short *page_backbuf;
  200. static int pagebuf_w, pagebuf_h;
  201. static int page_cache_valid;
  202. static int page_cache_scroll;
  203. static unsigned int page_cache_nnode;
  204. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  205. static int layout_valid, layout_left, layout_right;
  206. /* Height of the page viewport: what html/body height:100% resolves to. */
  207. static int layout_view_h;
  208. static unsigned int layout_nnode;
  209. static int layout_content_h;
  210. /* layout output */
  211. struct lay_run {
  212. unsigned int off;
  213. unsigned short len;
  214. unsigned short gap;
  215. unsigned short color;
  216. unsigned short href;
  217. char lit[28];
  218. short img;
  219. signed short dy; /* inline image vertical offset */
  220. unsigned short iw, ih;
  221. unsigned short w;
  222. unsigned char font_px, bold, italic, mono, underline, strike;
  223. unsigned char overline, font_face;
  224. unsigned char transform_scale;
  225. unsigned char origin_x_kind, origin_y_kind;
  226. signed short scale_x, scale_y, rotate_x100;
  227. signed short origin_x, origin_y;
  228. unsigned char has_lit;
  229. unsigned int form; /* node + 1, 0 = not a control */
  230. unsigned char form_kind;
  231. unsigned char form_disabled;
  232. /* RUN_PBOX: background colour, background image and its placement
  233. * inside the iw x ih box (relative offsets, drawn size). */
  234. unsigned char pb_has_bg;
  235. unsigned short pb_bg;
  236. short pb_img;
  237. short pb_x, pb_y, pb_w, pb_h;
  238. };
  239. struct lay {
  240. int draw;
  241. struct ngui *ui;
  242. int left, right;
  243. int y;
  244. int line_x, line_y, line_h;
  245. int line_left, line_right;
  246. int parent_top;
  247. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  248. int cb_h; /* definite content height of the containing block for
  249. * percentage heights; 0 = indefinite (auto) */
  250. int run_x;
  251. int align;
  252. int depth;
  253. int space_pending;
  254. unsigned char float_active;
  255. int float_left, float_right, float_bottom;
  256. struct lay_run runs[96];
  257. int nruns;
  258. };
  259. struct hit {
  260. int x, y, w, h;
  261. unsigned short node;
  262. };
  263. /* Live form state; the DOM attributes stay the initial/default value. */
  264. #define FORM_MAX 64
  265. #define FORM_VALUE_MAX 63
  266. enum {
  267. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  268. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  269. };
  270. struct form_state {
  271. unsigned int node;
  272. char value[FORM_VALUE_MAX + 1];
  273. unsigned char len, caret, checked, selected, used;
  274. };
  275. static struct form_state form_states[FORM_MAX];
  276. static unsigned int form_focus;
  277. static unsigned int form_dirty;
  278. static int form_descendant(unsigned int node, unsigned int form);
  279. static int form_submit_form(unsigned int node, int fire_event);
  280. static int link_fragment_nav(unsigned int node);
  281. static void history_push(const char *url);
  282. static void form_reset_event(unsigned int form);
  283. static unsigned int s_len(const char *s);
  284. static int s_eq(const char *a, const char *b);
  285. static void form_key(int k);
  286. static void form_click(unsigned int node);
  287. static void style_for_node(unsigned int node, struct br_style *out);
  288. static int form_author_styled(const struct br_style *st);
  289. static int css_radius(const struct br_style *st, int corner, int w, int h);
  290. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  291. const struct br_style *st, int focused);
  292. static int form_disabled(unsigned int node)
  293. {
  294. struct br_node *n = &doc.nodes[node];
  295. if (n->attr_flags & BR_ATTR_DISABLED)
  296. return 1;
  297. return br_find_attr(&doc, node, "disabled") != 0;
  298. }
  299. static int form_kind_of(unsigned int node)
  300. {
  301. const char *type = br_type(&doc, node);
  302. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  303. return FORM_TEXTAREA;
  304. if (doc.nodes[node].tag == BR_TAG_SELECT)
  305. return FORM_SELECT;
  306. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  307. if (s_eq(type, "reset"))
  308. return FORM_RESET;
  309. if (s_eq(type, "button"))
  310. return FORM_BUTTON;
  311. return FORM_SUBMIT;
  312. }
  313. if (s_eq(type, "password"))
  314. return FORM_PASSWORD;
  315. if (s_eq(type, "checkbox"))
  316. return FORM_CHECKBOX;
  317. if (s_eq(type, "radio"))
  318. return FORM_RADIO;
  319. if (s_eq(type, "submit"))
  320. return FORM_SUBMIT;
  321. if (s_eq(type, "reset"))
  322. return FORM_RESET;
  323. if (s_eq(type, "button"))
  324. return FORM_BUTTON;
  325. return FORM_TEXT;
  326. }
  327. static unsigned int form_option_count(unsigned int node)
  328. {
  329. unsigned int c, n = 0;
  330. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  331. if (doc.nodes[c].type == BR_NODE_ELEM &&
  332. doc.nodes[c].tag == BR_TAG_OPTION)
  333. n++;
  334. return n;
  335. }
  336. static unsigned int form_option_selected(unsigned int node)
  337. {
  338. unsigned int c, i = 0;
  339. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  340. if (doc.nodes[c].type != BR_NODE_ELEM ||
  341. doc.nodes[c].tag != BR_TAG_OPTION)
  342. continue;
  343. if (br_find_attr(&doc, c, "selected"))
  344. return i;
  345. i++;
  346. }
  347. return 0;
  348. }
  349. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  350. char *out, unsigned int cap)
  351. {
  352. unsigned int c, i = 0;
  353. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  354. if (doc.nodes[c].type != BR_NODE_ELEM ||
  355. doc.nodes[c].tag != BR_TAG_OPTION)
  356. continue;
  357. if (i == idx)
  358. return br_text_content(&doc, c, out, cap);
  359. i++;
  360. }
  361. return 0;
  362. }
  363. static int form_is_control(unsigned int node);
  364. static struct form_state *form_get(unsigned int node, int create)
  365. {
  366. struct form_state *slot = 0;
  367. unsigned int i;
  368. for (i = 0; i < FORM_MAX; i++) {
  369. if (form_states[i].used) {
  370. if (form_states[i].node == node)
  371. return &form_states[i];
  372. } else if (!slot) {
  373. slot = &form_states[i];
  374. }
  375. }
  376. if (create && !slot) {
  377. /* Full: a client-side router (Docusaurus' React Router)
  378. * replaces page content without a navigation, so slots of
  379. * controls that left the document pile up until no new
  380. * control can be drawn or focused.
  381. * Reuse those first, then slots of nodes that are no longer
  382. * controls. */
  383. for (i = 0; i < FORM_MAX && !slot; i++)
  384. if (form_states[i].node != form_focus &&
  385. br_node_detached(&doc, form_states[i].node))
  386. slot = &form_states[i];
  387. for (i = 0; i < FORM_MAX && !slot; i++)
  388. if (form_states[i].node != form_focus &&
  389. !form_is_control(form_states[i].node))
  390. slot = &form_states[i];
  391. }
  392. if (!create || !slot)
  393. return 0;
  394. slot->node = node;
  395. slot->len = 0;
  396. slot->caret = 0;
  397. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  398. slot->selected = form_option_selected(node);
  399. slot->used = 1;
  400. {
  401. unsigned int n = 0;
  402. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  403. n = br_text_content(&doc, node, slot->value,
  404. FORM_VALUE_MAX + 1);
  405. } else {
  406. const char *v = br_value(&doc, node);
  407. if (v) {
  408. n = s_len(v);
  409. if (n > FORM_VALUE_MAX)
  410. n = FORM_VALUE_MAX;
  411. for (unsigned int j = 0; j < n; j++)
  412. slot->value[j] = v[j];
  413. }
  414. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  415. n = br_text_content(&doc, node, slot->value,
  416. FORM_VALUE_MAX + 1);
  417. }
  418. if (n > FORM_VALUE_MAX)
  419. n = FORM_VALUE_MAX;
  420. slot->value[n] = '\0';
  421. slot->len = (unsigned char)n;
  422. slot->caret = (unsigned char)n;
  423. }
  424. return slot;
  425. }
  426. static void form_reset_state(void)
  427. {
  428. unsigned int i;
  429. for (i = 0; i < FORM_MAX; i++)
  430. form_states[i].used = 0;
  431. form_focus = 0;
  432. }
  433. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  434. * is laid out like a normal element so that content shows; only a text or
  435. * empty button is drawn as a native control. Clicks still reach it
  436. * through the box hit test. */
  437. static int button_has_elements(unsigned int node)
  438. {
  439. unsigned int c;
  440. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  441. return 0;
  442. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  443. if (doc.nodes[c].type == BR_NODE_ELEM)
  444. return 1;
  445. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  446. * sidebar caret) is laid out as an element so the box is drawn. */
  447. if (!doc.nodes[node].first && doc.npe_rules) {
  448. struct br_style st, ps;
  449. char buf[8];
  450. int pe;
  451. style_for_node(node, &st);
  452. for (pe = 1; pe <= 2; pe++)
  453. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  454. sizeof(buf)) &&
  455. ps.content == BR_CONTENT_EMPTY &&
  456. ps.display != BR_DISPLAY_NONE)
  457. return 1;
  458. }
  459. return 0;
  460. }
  461. static int form_is_control(unsigned int node)
  462. {
  463. unsigned int tag;
  464. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  465. return 0;
  466. tag = doc.nodes[node].tag;
  467. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  468. tag == BR_TAG_SELECT ||
  469. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  470. }
  471. #define HIT_MAX 96
  472. static struct hit hits[HIT_MAX];
  473. static int nhits;
  474. static unsigned short block_h[BR_MAX_NODES];
  475. /* Border-box height a flex container stretches an item to (align-items:
  476. * stretch in a row with a taller line or a definite height), 0 = none.
  477. * Written by the measure pass, read by both. */
  478. static unsigned short flex_stretch_h[BR_MAX_NODES];
  479. /* Measure-pass top of each block, in the same document coordinates as
  480. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  481. * paint, so it cannot drive the lazy background loader). */
  482. static unsigned short block_top[BR_MAX_NODES];
  483. static char li_marker[BR_MAX_NODES][12];
  484. /* one connection object; the browser fetches one resource at a time */
  485. /* ---- tiny strings ---- */
  486. static unsigned int s_len(const char *s)
  487. {
  488. unsigned int n = 0;
  489. while (s && s[n])
  490. n++;
  491. return n;
  492. }
  493. static void s_copy(char *d, const char *s, unsigned int cap)
  494. {
  495. unsigned int i = 0;
  496. if (!cap)
  497. return;
  498. while (s && s[i] && i + 1 < cap) {
  499. d[i] = s[i];
  500. i++;
  501. }
  502. d[i] = '\0';
  503. }
  504. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  505. {
  506. while (s && *s && *n + 1 < cap)
  507. d[(*n)++] = *s++;
  508. d[*n] = '\0';
  509. }
  510. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  511. unsigned int cap)
  512. {
  513. char tmp[12];
  514. unsigned int i = 0, j;
  515. do {
  516. tmp[i++] = (char)('0' + v % 10);
  517. v /= 10;
  518. } while (v && i < sizeof(tmp));
  519. for (j = 0; j < i && *n + 1 < cap; j++)
  520. d[(*n)++] = tmp[i - 1 - j];
  521. d[*n] = '\0';
  522. }
  523. static int s_eq(const char *a, const char *b)
  524. {
  525. while (*a && *b) {
  526. if (*a != *b)
  527. return 0;
  528. a++;
  529. b++;
  530. }
  531. return *a == *b;
  532. }
  533. static int starts_with(const char *s, const char *p)
  534. {
  535. unsigned int i = 0;
  536. while (p[i]) {
  537. if (s[i] != p[i])
  538. return 0;
  539. i++;
  540. }
  541. return 1;
  542. }
  543. static int contains_ci(const char *s, const char *p)
  544. {
  545. unsigned int i, j;
  546. for (i = 0; s[i]; i++) {
  547. for (j = 0; p[j]; j++) {
  548. char a = s[i + j];
  549. if (a >= 'A' && a <= 'Z')
  550. a = (char)(a - 'A' + 'a');
  551. if (a != p[j])
  552. break;
  553. }
  554. if (!p[j])
  555. return 1;
  556. }
  557. return 0;
  558. }
  559. static char *trim(char *s)
  560. {
  561. unsigned int n;
  562. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  563. s++;
  564. n = s_len(s);
  565. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  566. s[n - 1] == '\r' || s[n - 1] == '\n'))
  567. s[--n] = '\0';
  568. return s;
  569. }
  570. /* ---- per-process heap ---- */
  571. static int heap_start(void)
  572. {
  573. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  574. if (!image_io_buf)
  575. return -1;
  576. page_backbuf = (unsigned short *)malloc(
  577. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  578. pagebuf_w = page_backbuf ? ui.w : 0;
  579. pagebuf_h = page_backbuf ? ui.h : 0;
  580. page_cache_valid = 0;
  581. return 0;
  582. }
  583. static void heap_clear(void)
  584. {
  585. memset(font_faces, 0, sizeof(font_faces));
  586. ngui_font_detach(&ui);
  587. svg_cache_clear();
  588. decode_arena = 0; /* lives in the page heap too */
  589. decode_arena_size = 0;
  590. heap_reset();
  591. /* The document arenas live in that heap; drop the stale pointers so
  592. * the next br_parse_plain() allocates fresh ones. */
  593. doc.nodes = 0;
  594. doc.text = 0;
  595. doc.attrs = 0;
  596. image_io_buf = 0;
  597. page_backbuf = 0;
  598. pagebuf_w = pagebuf_h = 0;
  599. page_cache_valid = 0;
  600. }
  601. static void browser_rules_alloc(void)
  602. {
  603. struct br_rule *rules;
  604. rules = (struct br_rule *)malloc(
  605. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  606. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  607. }
  608. /* ---- status ---- */
  609. static void set_status(const char *s, int err, unsigned int ttl_ms)
  610. {
  611. s_copy(status_text, s, sizeof(status_text));
  612. status_error = err;
  613. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  614. ngui_invalidate(&ui);
  615. }
  616. /* Update the status text without forcing a frame; the throttled image
  617. * repaint picks it up. Starting one helper per image used to invalidate the
  618. * whole page before every decode. */
  619. static void set_status_quiet(const char *s)
  620. {
  621. s_copy(status_text, s, sizeof(status_text));
  622. status_error = 0;
  623. status_until = 0;
  624. }
  625. /* ---- JavaScript ---- */
  626. static int resolve_link(const char *base, const char *href, char *out,
  627. unsigned int cap);
  628. static char js_last_status[BR_STATUS_MAX];
  629. static int js_last_error;
  630. static void js_host_status(const char *msg, int error)
  631. {
  632. s_copy(js_last_status, msg, sizeof(js_last_status));
  633. js_last_error = error;
  634. set_status(msg, error, 6000);
  635. }
  636. static void js_host_report(const char *msg)
  637. {
  638. u_puts("[js] ");
  639. u_puts(msg);
  640. u_putc('\n');
  641. s_copy(js_last_status, msg, sizeof(js_last_status));
  642. js_last_error = 1;
  643. set_status(msg, 1, 8000);
  644. }
  645. static void js_host_navigate(const char *url)
  646. {
  647. char resolved[BR_URL_MAX];
  648. if (!url || !url[0])
  649. return;
  650. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  651. return;
  652. s_copy(pending_url, resolved, sizeof(pending_url));
  653. pending_action |= ACT_NAV;
  654. cancel_fetch = 1;
  655. }
  656. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  657. * back/forward between fragments): the page URL, address bar and history
  658. * follow, nothing is reloaded. `push` adds a history entry. */
  659. static int page_set_fragment(const char *url, int push)
  660. {
  661. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  662. return -1;
  663. s_copy(page_url, url, sizeof(page_url));
  664. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  665. url_in.len = s_len(url_in.text);
  666. url_in.cursor = url_in.len;
  667. url_in.scroll = 0;
  668. if (push)
  669. history_push(page_url);
  670. ngui_invalidate(&ui);
  671. return 0;
  672. }
  673. static int js_host_set_hash(const char *url)
  674. {
  675. return page_set_fragment(url, 1);
  676. }
  677. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  678. * the page, so a hash router can react). */
  679. static int same_doc_fragment(const char *url)
  680. {
  681. unsigned int a = 0, b = 0;
  682. if (!js_browser_active() || !url)
  683. return 0;
  684. while (url[a] && url[a] != '#')
  685. a++;
  686. while (page_url[b] && page_url[b] != '#')
  687. b++;
  688. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  689. !s_eq(url, page_url);
  690. }
  691. static void js_host_changed(void)
  692. {
  693. /* Class/style/attribute mutations change computed styles, not just the
  694. * text: drop the per-node style cache before the next layout. */
  695. br_reset_styles(&doc);
  696. layout_valid = 0;
  697. /* Script-built content (Angular's ng-repeat cards) brings new images
  698. * and inline background styles: rescan once the main loop is idle. */
  699. preload_rescan = 1;
  700. ngui_invalidate(&ui);
  701. }
  702. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  703. {
  704. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  705. return 0;
  706. *x = layout_boxes[node].x - page_rect.x;
  707. *y = layout_boxes[node].y - page_rect.y;
  708. *w = layout_boxes[node].w;
  709. *h = layout_boxes[node].h;
  710. return 1;
  711. }
  712. static void form_copy_out(const char *s, char *buf, int cap)
  713. {
  714. int i = 0;
  715. if (!buf || cap <= 0)
  716. return;
  717. while (s && s[i] && i + 1 < cap) {
  718. buf[i] = s[i];
  719. i++;
  720. }
  721. buf[i] = '\0';
  722. }
  723. static int js_host_form_value(unsigned int node, char *buf, int cap)
  724. {
  725. struct form_state *fs;
  726. int kind;
  727. if (!form_is_control(node))
  728. return 0;
  729. kind = form_kind_of(node);
  730. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  731. return 0;
  732. if (kind == FORM_SELECT) {
  733. char opt[64] = "";
  734. unsigned int c, i = 0;
  735. fs = form_get(node, 1);
  736. if (!fs)
  737. return 0;
  738. form_option_text(node, fs->selected, opt, sizeof(opt));
  739. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  740. if (doc.nodes[c].type != BR_NODE_ELEM ||
  741. doc.nodes[c].tag != BR_TAG_OPTION)
  742. continue;
  743. if (i == fs->selected) {
  744. const char *v = br_value(&doc, c);
  745. if (v && v[0])
  746. form_copy_out(v, buf, cap);
  747. else
  748. form_copy_out(opt, buf, cap);
  749. return 1;
  750. }
  751. i++;
  752. }
  753. form_copy_out(opt, buf, cap);
  754. return 1;
  755. }
  756. fs = form_get(node, 1);
  757. if (!fs)
  758. return 0;
  759. form_copy_out(fs->value, buf, cap);
  760. return 1;
  761. }
  762. static int js_host_form_checked(unsigned int node)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return -1;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return -1;
  771. fs = form_get(node, 1);
  772. return fs ? fs->checked : 0;
  773. }
  774. static int js_host_form_selected(unsigned int node)
  775. {
  776. struct form_state *fs;
  777. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  778. return -1;
  779. fs = form_get(node, 1);
  780. return fs ? fs->selected : 0;
  781. }
  782. static int js_host_form_set_value(unsigned int node, const char *value)
  783. {
  784. struct form_state *fs;
  785. unsigned int n;
  786. if (!form_is_control(node))
  787. return 0;
  788. fs = form_get(node, 1);
  789. if (!fs)
  790. return 0;
  791. n = s_len(value ? value : "");
  792. if (n > FORM_VALUE_MAX)
  793. n = FORM_VALUE_MAX;
  794. for (unsigned int i = 0; i < n; i++)
  795. fs->value[i] = value[i];
  796. fs->value[n] = '\0';
  797. fs->len = (unsigned char)n;
  798. fs->caret = (unsigned char)n;
  799. layout_valid = 0;
  800. ngui_invalidate(&ui);
  801. return 1;
  802. }
  803. static int js_host_form_set_checked(unsigned int node, int checked)
  804. {
  805. struct form_state *fs;
  806. int kind;
  807. if (!form_is_control(node))
  808. return 0;
  809. kind = form_kind_of(node);
  810. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  811. return 0;
  812. fs = form_get(node, 1);
  813. if (!fs)
  814. return 0;
  815. fs->checked = (unsigned char)(checked != 0);
  816. layout_valid = 0;
  817. ngui_invalidate(&ui);
  818. return 1;
  819. }
  820. static int js_host_form_set_selected(unsigned int node, int index)
  821. {
  822. struct form_state *fs;
  823. unsigned int n;
  824. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  825. return 0;
  826. fs = form_get(node, 1);
  827. if (!fs)
  828. return 0;
  829. n = form_option_count(node);
  830. if (index < 0)
  831. index = 0;
  832. if (n && (unsigned int)index >= n)
  833. index = (int)n - 1;
  834. fs->selected = (unsigned char)index;
  835. layout_valid = 0;
  836. ngui_invalidate(&ui);
  837. return 1;
  838. }
  839. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  840. {
  841. unsigned int i;
  842. int n = 0;
  843. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  844. doc.nodes[form].tag != BR_TAG_FORM)
  845. return 0;
  846. for (i = 0; i < doc.nnode && n < cap; i++) {
  847. struct br_node *nd = &doc.nodes[i];
  848. if (i == form || nd->type != BR_NODE_ELEM)
  849. continue;
  850. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  851. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  852. continue;
  853. if (!form_descendant(i, form))
  854. continue;
  855. out[n++] = i;
  856. }
  857. return n;
  858. }
  859. static int js_host_form_submit(unsigned int form)
  860. {
  861. form_submit_form(form, 0);
  862. return 1;
  863. }
  864. static int js_host_form_reset(unsigned int form)
  865. {
  866. form_reset_event(form);
  867. return 1;
  868. }
  869. static void css_computed_name(const char *p, char *out, int cap)
  870. {
  871. int n = 0;
  872. for (; p && *p && n + 2 < cap; p++) {
  873. char c = *p;
  874. if (c >= 'A' && c <= 'Z') {
  875. out[n++] = '-';
  876. c = (char)(c - 'A' + 'a');
  877. } else if (c == '_') {
  878. c = '-';
  879. } else if (c >= 'a' && c <= 'z') {
  880. /* keep */
  881. }
  882. out[n++] = c;
  883. }
  884. out[n] = '\0';
  885. if (!strcmp(out, "css-float"))
  886. strcpy(out, "float");
  887. }
  888. static void css_rgb(unsigned short c, char *buf, int cap)
  889. {
  890. int r = ((c >> 11) & 31) * 255 / 31;
  891. int g = ((c >> 5) & 63) * 255 / 63;
  892. int b = (c & 31) * 255 / 31;
  893. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  894. }
  895. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  896. int font_px)
  897. {
  898. if (unit == 4) {
  899. snprintf(buf, cap, "auto");
  900. } else if (unit == 0) {
  901. snprintf(buf, cap, "%dpx", raw);
  902. } else if (unit == 1) {
  903. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  904. } else if (unit == 2) {
  905. /* Chrome's getComputedStyle() reports used pixel values. */
  906. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  907. } else if (unit == 3) {
  908. snprintf(buf, cap, "%dpx",
  909. (int)br_root_font_px() * raw / 100);
  910. } else {
  911. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  912. raw / 100, raw % 100, px);
  913. }
  914. }
  915. static int js_host_computed(unsigned int node, const char *property,
  916. char *buf, int cap)
  917. {
  918. struct br_style st;
  919. char name[40];
  920. /* Node 0 is a real element when the page starts with <html>. */
  921. if (!buf || cap <= 0 || node >= doc.nnode ||
  922. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  923. return 0;
  924. buf[0] = '\0';
  925. css_computed_name(property, name, sizeof(name));
  926. style_for_node(node, &st);
  927. if (!strcmp(name, "display")) {
  928. const char *v = "inline";
  929. if (st.display == BR_DISPLAY_BLOCK)
  930. v = "block";
  931. else if (st.display == BR_DISPLAY_NONE)
  932. v = "none";
  933. else if (st.display == BR_DISPLAY_FLEX)
  934. v = "flex";
  935. else if (st.display == BR_DISPLAY_GRID)
  936. v = "grid";
  937. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  938. v = "inline-block";
  939. snprintf(buf, cap, "%s", v);
  940. } else if (!strcmp(name, "position")) {
  941. static const char *pos[] = {
  942. "static", "absolute", "fixed", "relative", "sticky"
  943. };
  944. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  945. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  946. int is_w = name[0] == 'w';
  947. int kind = is_w ? st.width_kind : st.height_kind;
  948. int val = is_w ? st.width : st.height;
  949. if (kind == 3) {
  950. if (is_w)
  951. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  952. st.width_calc_pct / 100,
  953. st.width_calc_pct % 100,
  954. st.width_calc_px);
  955. else
  956. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  957. st.height_calc_pct / 100,
  958. st.height_calc_pct % 100,
  959. st.height_calc_px);
  960. } else if (kind == 1) {
  961. snprintf(buf, cap, "%dpx", val);
  962. } else if (kind == 2) {
  963. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  964. } else {
  965. snprintf(buf, cap, "auto");
  966. }
  967. } else if (!strcmp(name, "color") ||
  968. !strcmp(name, "background-color")) {
  969. if (!strcmp(name, "background-color") && !st.has_bg)
  970. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  971. else
  972. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  973. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  974. int is_fill = name[0] == 'f';
  975. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  976. if (mode == BR_PAINT_COLOR)
  977. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  978. else if (mode == BR_PAINT_CURRENT)
  979. css_rgb(st.color, buf, cap);
  980. else if (mode == BR_PAINT_UNSET && is_fill)
  981. snprintf(buf, cap, "rgb(0, 0, 0)");
  982. else if (mode == BR_PAINT_URL)
  983. snprintf(buf, cap, "url()");
  984. else
  985. snprintf(buf, cap, "none");
  986. } else if (!strcmp(name, "font-size")) {
  987. snprintf(buf, cap, "%dpx", st.font_px);
  988. } else if (!strcmp(name, "font-weight")) {
  989. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  990. } else if (!strcmp(name, "font-style")) {
  991. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  992. } else if (!strcmp(name, "font-family")) {
  993. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  994. br_font_face_family(st.font_face)[0])
  995. snprintf(buf, cap, "%s",
  996. br_font_face_family(st.font_face));
  997. else
  998. snprintf(buf, cap, "%s",
  999. st.mono ? "monospace" : "sans-serif");
  1000. } else if (!strcmp(name, "text-align")) {
  1001. static const char *al[] = { "left", "center", "right", "justify" };
  1002. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1003. } else if (!strcmp(name, "float")) {
  1004. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1005. st.float_left == 2 ? "right" : "none");
  1006. } else if (!strcmp(name, "clear")) {
  1007. static const char *cl[] = { "none", "left", "right", "both" };
  1008. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1009. } else if (!strcmp(name, "opacity")) {
  1010. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1011. } else if (!strcmp(name, "visibility")) {
  1012. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1013. } else if (!strcmp(name, "overflow")) {
  1014. snprintf(buf, cap, "%s",
  1015. st.overflow_hidden ? "hidden" : "visible");
  1016. } else if (!strcmp(name, "white-space")) {
  1017. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1018. } else if (!strcmp(name, "text-transform")) {
  1019. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1020. } else if (!strcmp(name, "box-sizing")) {
  1021. snprintf(buf, cap, "%s",
  1022. st.box_sizing ? "border-box" : "content-box");
  1023. } else if (!strcmp(name, "line-height")) {
  1024. if (st.line_h_px)
  1025. snprintf(buf, cap, "%dpx", st.line_h_px);
  1026. else if (st.line_h_pct)
  1027. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1028. else
  1029. snprintf(buf, cap, "normal");
  1030. } else if (!strcmp(name, "z-index")) {
  1031. if (st.z_set)
  1032. snprintf(buf, cap, "%d", st.z_index);
  1033. else
  1034. snprintf(buf, cap, "auto");
  1035. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1036. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1037. int set = name[0] == 't' ? st.top_set :
  1038. name[0] == 'l' ? st.left_set :
  1039. name[0] == 'r' ? st.right_set : st.bottom_set;
  1040. int v = name[0] == 't' ? st.top :
  1041. name[0] == 'l' ? st.left :
  1042. name[0] == 'r' ? st.right : st.bottom;
  1043. if (set)
  1044. snprintf(buf, cap, "%dpx", v);
  1045. else
  1046. snprintf(buf, cap, "auto");
  1047. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1048. !strcmp(name, "margin-bottom") ||
  1049. !strcmp(name, "margin-left") ||
  1050. !strcmp(name, "padding-top") ||
  1051. !strcmp(name, "padding-right") ||
  1052. !strcmp(name, "padding-bottom") ||
  1053. !strcmp(name, "padding-left")) {
  1054. int is_pad = name[0] == 'p';
  1055. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1056. name[strlen(name) - 1] == 't' ? 1 :
  1057. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1058. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1059. if (!strcmp(name, "margin-right") ||
  1060. !strcmp(name, "padding-right"))
  1061. side = 1;
  1062. else if (!strcmp(name, "margin-bottom") ||
  1063. !strcmp(name, "padding-bottom"))
  1064. side = 2;
  1065. else if (!strcmp(name, "margin-left") ||
  1066. !strcmp(name, "padding-left"))
  1067. side = 3;
  1068. else
  1069. side = 0;
  1070. side += is_pad ? 4 : 0;
  1071. css_mp_value(buf, cap,
  1072. side == 0 ? st.mt : side == 1 ? st.mr :
  1073. side == 2 ? st.mb : side == 3 ? st.ml :
  1074. side == 4 ? st.pt : side == 5 ? st.pr :
  1075. side == 6 ? st.pb : st.pl,
  1076. st.mp_unit[side], st.mp_calc_px[side],
  1077. st.font_px);
  1078. } else if (!strcmp(name, "border-top-width") ||
  1079. !strcmp(name, "border-right-width") ||
  1080. !strcmp(name, "border-bottom-width") ||
  1081. !strcmp(name, "border-left-width")) {
  1082. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1083. name[7] == 'b' ? 2 : 3;
  1084. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1085. } else if (!strcmp(name, "border-top-color") ||
  1086. !strcmp(name, "border-right-color") ||
  1087. !strcmp(name, "border-bottom-color") ||
  1088. !strcmp(name, "border-left-color")) {
  1089. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1090. name[7] == 'b' ? 2 : 3;
  1091. if (st.border_w[side] && !st.border_t[side])
  1092. css_rgb(st.border_c[side], buf, cap);
  1093. else
  1094. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1095. } else if (!strcmp(name, "background-image")) {
  1096. if (st.bg_image)
  1097. snprintf(buf, cap, "url(\"%s\")",
  1098. br_bg_image_url(st.bg_image - 1));
  1099. else
  1100. snprintf(buf, cap, "none");
  1101. } else if (!strcmp(name, "background-repeat")) {
  1102. static const char *rp[] = {
  1103. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1104. };
  1105. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1106. st.bg_repeat : 0]);
  1107. } else if (!strcmp(name, "background-position")) {
  1108. if (st.bg_pos_x_kind == 1)
  1109. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1110. st.bg_pos_y);
  1111. else
  1112. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1113. st.bg_pos_y);
  1114. } else if (!strcmp(name, "background-size")) {
  1115. if (st.bg_size_kind == 3)
  1116. snprintf(buf, cap, "cover");
  1117. else if (st.bg_size_kind == 4)
  1118. snprintf(buf, cap, "contain");
  1119. else if (st.bg_size_kind == 1)
  1120. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1121. st.bg_size_h);
  1122. else if (st.bg_size_kind == 2)
  1123. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1124. st.bg_size_h);
  1125. else
  1126. snprintf(buf, cap, "auto");
  1127. } else if (!strcmp(name, "transform")) {
  1128. char tmp[128];
  1129. unsigned int n = 0;
  1130. if (!st.transform_set) {
  1131. snprintf(buf, cap, "none");
  1132. } else {
  1133. tmp[0] = '\0';
  1134. if (st.tx || st.ty) {
  1135. snprintf(tmp + n, sizeof(tmp) - n,
  1136. "translate(%dpx, %dpx)", st.tx, st.ty);
  1137. n = (unsigned int)strlen(tmp);
  1138. }
  1139. if (st.transform_scale) {
  1140. snprintf(tmp + n, sizeof(tmp) - n,
  1141. "%sscale(%d.%02d, %d.%02d)",
  1142. n ? " " : "", st.scale_x / 100,
  1143. st.scale_x % 100, st.scale_y / 100,
  1144. st.scale_y % 100);
  1145. n = (unsigned int)strlen(tmp);
  1146. if (st.rotate_x100) {
  1147. snprintf(tmp + n, sizeof(tmp) - n,
  1148. " rotate(%d.%02ddeg)",
  1149. st.rotate_x100 / 100,
  1150. st.rotate_x100 % 100);
  1151. }
  1152. } else if (st.rotate_x100) {
  1153. snprintf(tmp + n, sizeof(tmp) - n,
  1154. "%srotate(%d.%02ddeg)",
  1155. n ? " " : "", st.rotate_x100 / 100,
  1156. st.rotate_x100 % 100);
  1157. }
  1158. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1159. }
  1160. } else {
  1161. return 0;
  1162. }
  1163. return buf[0] != '\0';
  1164. }
  1165. static int js_host_click(unsigned int node)
  1166. {
  1167. char url[BR_URL_MAX];
  1168. const char *href;
  1169. if (node >= doc.nnode)
  1170. return 0;
  1171. if (form_is_control(node)) {
  1172. form_click(node); /* dispatches its own click event */
  1173. return 1;
  1174. }
  1175. /* element.click() fires a bubbling, cancelable click before the
  1176. * default action, like a real click (delegated list handlers). */
  1177. if (!js_browser_event(node, "click", 1, 1))
  1178. return 1;
  1179. if (link_fragment_nav(node))
  1180. return 1;
  1181. href = br_href(&doc, node);
  1182. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1183. return 0;
  1184. s_copy(pending_url, url, sizeof(pending_url));
  1185. pending_action |= ACT_NAV;
  1186. cancel_fetch = 1;
  1187. ngui_invalidate(&ui);
  1188. return 1;
  1189. }
  1190. static int fetch_script_text(const char *url, unsigned char **out,
  1191. unsigned int *outlen, char *err,
  1192. unsigned int errcap);
  1193. struct fetch_worker;
  1194. static struct fetch_worker *fetch_worker_alloc(void);
  1195. static void fetch_worker_release(struct fetch_worker *w);
  1196. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1197. unsigned int cap, const char *post,
  1198. unsigned int post_len, unsigned int node,
  1199. int bg, char *err, unsigned int errcap);
  1200. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1201. unsigned int errcap);
  1202. static int fetch_worker_read_body(struct fetch_worker *w,
  1203. unsigned char *plain,
  1204. unsigned int plaincap,
  1205. unsigned char *comp,
  1206. unsigned int compcap,
  1207. int *truncated, char *err,
  1208. unsigned int errcap);
  1209. static void fetch_workers_stop_all(void);
  1210. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1211. unsigned int cap, const char *method,
  1212. const char *ctype, const char *post,
  1213. unsigned int post_len, unsigned int node,
  1214. int bg, unsigned int dec_w,
  1215. unsigned int dec_h, char *err,
  1216. unsigned int errcap);
  1217. static int script_cache_has(const char *url);
  1218. static void script_cache_put(const char *url, const unsigned char *data,
  1219. unsigned int len);
  1220. static unsigned int script_cache_hash(const char *s);
  1221. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1222. unsigned int errcap);
  1223. static void fetch_workers_cancel_busy(void);
  1224. static void worker_wait_ui(void);
  1225. static int fetch_worker_status(const struct fetch_worker *w);
  1226. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1227. * module load: the wait must not pump input, or a click would dispatch DOM
  1228. * events into the middle of the running script. */
  1229. static int fetch_wait_passive;
  1230. static void script_error(const char *what, const char *url, const char *why)
  1231. {
  1232. char msg[192];
  1233. unsigned int n = 0;
  1234. s_append(msg, &n, what, sizeof(msg));
  1235. if (url && url[0]) {
  1236. s_append(msg, &n, " ", sizeof(msg));
  1237. s_append(msg, &n, url, sizeof(msg));
  1238. }
  1239. if (why && why[0]) {
  1240. s_append(msg, &n, ": ", sizeof(msg));
  1241. s_append(msg, &n, why, sizeof(msg));
  1242. }
  1243. js_host_report(msg);
  1244. }
  1245. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1246. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1247. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1248. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1249. #define JS_HTTP_POST_MAX (16u * 1024u)
  1250. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1251. static int js_worker_http(const char *method, const char *url,
  1252. const char *ctype, const char *body,
  1253. unsigned int body_len, struct js_http_resp *r,
  1254. char *err, int errcap);
  1255. static int js_host_http(const char *method, const char *url,
  1256. const char *ctype, const char *body,
  1257. unsigned int body_len, struct js_http_resp *r,
  1258. char *err, int errcap)
  1259. {
  1260. if (pending_action) {
  1261. s_copy(err, "page is navigating", (unsigned int)errcap);
  1262. return -1;
  1263. }
  1264. if (url[0] == '/') {
  1265. /* Local file: GET only. */
  1266. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1267. int rv;
  1268. if (!buf) {
  1269. s_copy(err, "out of memory", (unsigned int)errcap);
  1270. return -1;
  1271. }
  1272. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1273. (int)JS_HTTP_MAX);
  1274. r->status = rv < 0 ? 404 : 200;
  1275. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1276. buf[r->len] = '\0';
  1277. r->body = (char *)buf;
  1278. s_copy(r->url, url, sizeof(r->url));
  1279. if (contains_ci(url, ".json"))
  1280. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1281. return 0;
  1282. }
  1283. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1284. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1285. return -1;
  1286. }
  1287. if (body_len > JS_HTTP_POST_MAX) {
  1288. s_copy(err, "request body too large", (unsigned int)errcap);
  1289. return -1;
  1290. }
  1291. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1292. errcap);
  1293. }
  1294. /* Module source for the engine's loader: the boot script cache first, then
  1295. * one blocking fetch with input pumping disabled (the loader runs inside
  1296. * JavaScript). */
  1297. static char *js_host_load_script(const char *url, unsigned int *len)
  1298. {
  1299. unsigned char *data = 0;
  1300. char err[64];
  1301. int rv;
  1302. fetch_wait_passive++;
  1303. set_status("Loading module...", 0, 0);
  1304. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1305. fetch_wait_passive--;
  1306. if (rv != 0) {
  1307. script_error("Cannot load module", url,
  1308. rv == FETCH_ABORT ? "navigation" : err);
  1309. return 0;
  1310. }
  1311. return (char *)data;
  1312. }
  1313. /* Web Storage lives in /share, outside the page heap that every navigation
  1314. * resets: localStorage per origin for the boot, sessionStorage per origin
  1315. * and browser window. */
  1316. #define JS_ORIGIN_MAX 160
  1317. /* scheme://host[:port] of the page (a local page's whole path). */
  1318. static void js_page_origin(char *origin, unsigned int cap)
  1319. {
  1320. unsigned int i = 0, slashes = 0;
  1321. while (page_url[i] && i + 1 < cap) {
  1322. if (page_url[i] == '/' && ++slashes == 3)
  1323. break;
  1324. origin[i] = page_url[i];
  1325. i++;
  1326. }
  1327. origin[i] = '\0';
  1328. }
  1329. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1330. {
  1331. unsigned int n = 0;
  1332. s_append(out, &n, "/share/bls", cap);
  1333. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1334. }
  1335. static void js_storage_path(int kind, char *out, unsigned int cap)
  1336. {
  1337. char origin[JS_ORIGIN_MAX];
  1338. unsigned int n = 0;
  1339. js_page_origin(origin, sizeof(origin));
  1340. if (!kind) {
  1341. js_origin_path(origin, out, cap);
  1342. return;
  1343. }
  1344. s_append(out, &n, "/share/bss", cap);
  1345. if (kind) {
  1346. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1347. s_append(out, &n, "-", cap);
  1348. }
  1349. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1350. }
  1351. static void persist_mark_origin(const char *origin);
  1352. static int persist_store_lookup(const char *origin, char *out, int cap);
  1353. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1354. {
  1355. char path[48], origin[JS_ORIGIN_MAX];
  1356. int rv;
  1357. js_storage_path(kind, path, sizeof(path));
  1358. if (set) {
  1359. if (kind) {
  1360. if (!set[0] || !strcmp(set, "{}")) {
  1361. u_syscall1(SYS_UNLINK, (int)path);
  1362. return 0;
  1363. }
  1364. } else {
  1365. /* localStorage keeps an explicit "{}" rather than no
  1366. * file: a missing /share file means "not loaded from
  1367. * /data yet", and a cleared store must not come back
  1368. * from the disk copy before it is flushed. */
  1369. if (!set[0])
  1370. set = "{}";
  1371. js_page_origin(origin, sizeof(origin));
  1372. persist_mark_origin(origin);
  1373. }
  1374. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1375. (int)strlen(set)) < 0 ? -1 : 0;
  1376. }
  1377. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1378. if (rv < 0 && !kind) {
  1379. /* First use this boot: the persistent copy on /data. */
  1380. js_page_origin(origin, sizeof(origin));
  1381. rv = persist_store_lookup(origin, out, cap);
  1382. if (rv >= 0)
  1383. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1384. }
  1385. if (rv < 0)
  1386. return -1;
  1387. out[rv] = '\0';
  1388. return rv;
  1389. }
  1390. /* ---- persistence on /data ----
  1391. *
  1392. * /share is the working copy (RAM, shared by every helper and window); the
  1393. * installed disk's /data volume keeps the cookie jar and localStorage
  1394. * across reboots when it is mounted. The browser owns the disk copies: at
  1395. * start it restores the jar into /share, and its main loop writes back
  1396. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1397. * setItem updates costs one FAT write. The helpers only touch /share (they
  1398. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1399. * /data mount every disk access simply fails. Both files are plaintext
  1400. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1401. #define PERSIST_MS 3000u
  1402. #define SHARE_COOKIES "/share/bcookies"
  1403. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1404. #define DATA_STORE "/data/BSTORE.DAT"
  1405. #define DATA_STORE_MAGIC "NBLS1\n"
  1406. #define DATA_STORE_MAX (192u * 1024u)
  1407. #define PERSIST_DIRTY_MAX 8
  1408. static unsigned int persist_due;
  1409. static unsigned int cookie_sum_saved;
  1410. static int cookie_sum_valid;
  1411. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1412. static int persist_ndirty;
  1413. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1414. {
  1415. unsigned int h = 2166136261u, i;
  1416. for (i = 0; i < n; i++)
  1417. h = (h ^ p[i]) * 16777619u;
  1418. return h;
  1419. }
  1420. /* Called once at startup, before any helper runs. */
  1421. static void persist_restore(void)
  1422. {
  1423. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1424. int n;
  1425. if (!jar)
  1426. return;
  1427. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1428. (int)sizeof(struct uhttp_jar));
  1429. if (n != (int)sizeof(struct uhttp_jar)) {
  1430. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1431. (int)sizeof(struct uhttp_jar));
  1432. if (n == (int)sizeof(struct uhttp_jar)) {
  1433. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1434. (int)jar, n);
  1435. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1436. cookie_sum_valid = 1;
  1437. }
  1438. }
  1439. free(jar);
  1440. persist_due = u_ticks_ms() + PERSIST_MS;
  1441. }
  1442. static void persist_mark_origin(const char *origin)
  1443. {
  1444. int i;
  1445. for (i = 0; i < persist_ndirty; i++)
  1446. if (s_eq(persist_dirty[i], origin))
  1447. return;
  1448. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1449. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1450. }
  1451. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1452. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1453. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1454. unsigned int *o_off, unsigned int *o_len,
  1455. unsigned int *d_off, unsigned int *d_len,
  1456. unsigned int *rec_end)
  1457. {
  1458. unsigned int p = *pos, v = 0;
  1459. if (p >= len)
  1460. return 0;
  1461. *o_off = p;
  1462. while (p < len && buf[p] != '\n')
  1463. p++;
  1464. if (p >= len)
  1465. return 0;
  1466. *o_len = p - *o_off;
  1467. p++;
  1468. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1469. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1470. if (p >= len || buf[p] != '\n')
  1471. return 0;
  1472. p++;
  1473. if (v > len - p)
  1474. return 0;
  1475. *d_off = p;
  1476. *d_len = v;
  1477. p += v;
  1478. if (p < len && buf[p] == '\n')
  1479. p++;
  1480. *rec_end = p;
  1481. *pos = p;
  1482. return 1;
  1483. }
  1484. static int store_load(char **out)
  1485. {
  1486. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1487. int n;
  1488. *out = buf;
  1489. if (!buf)
  1490. return -1;
  1491. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1492. (int)DATA_STORE_MAX);
  1493. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1494. !starts_with(buf, DATA_STORE_MAGIC))
  1495. return 0;
  1496. return n;
  1497. }
  1498. static int persist_store_lookup(const char *origin, char *out, int cap)
  1499. {
  1500. char *buf;
  1501. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1502. unsigned int olen = s_len(origin);
  1503. int n = store_load(&buf), rv = -1;
  1504. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1505. &dl, &e)) {
  1506. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1507. if ((int)dl < cap) {
  1508. memcpy(out, buf + d, dl);
  1509. out[dl] = '\0';
  1510. rv = (int)dl;
  1511. }
  1512. break;
  1513. }
  1514. }
  1515. free(buf);
  1516. return rv;
  1517. }
  1518. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1519. static void persist_store_flush(void)
  1520. {
  1521. char *old, *nb, path[48];
  1522. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1523. int n = store_load(&old), i, w;
  1524. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1525. if (n < 0 || !nb) {
  1526. free(old);
  1527. free(nb);
  1528. return;
  1529. }
  1530. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1531. /* Untouched origins first, in their old order. */
  1532. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1533. &dl, &e)) {
  1534. int dirty = 0;
  1535. for (i = 0; i < persist_ndirty; i++)
  1536. if (s_len(persist_dirty[i]) == ol &&
  1537. !memcmp(persist_dirty[i], old + oo, ol))
  1538. dirty = 1;
  1539. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1540. continue;
  1541. memcpy(nb + nn, old + oo, e - oo);
  1542. nn += e - oo;
  1543. }
  1544. /* Then the changed ones (an emptied store is dropped). */
  1545. for (i = 0; i < persist_ndirty; i++) {
  1546. char num[12];
  1547. unsigned int k = 0;
  1548. js_origin_path(persist_dirty[i], path, sizeof(path));
  1549. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1550. (int)DATA_STORE_MAX);
  1551. if (w <= 2) /* missing or "{}" */
  1552. continue;
  1553. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1554. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1555. DATA_STORE_MAX) {
  1556. set_status("Saved site data is full; a site's "
  1557. "localStorage was not saved", 1, 6000);
  1558. continue;
  1559. }
  1560. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1561. nb[nn++] = '\n';
  1562. s_append(nb, &nn, num, DATA_STORE_MAX);
  1563. nb[nn++] = '\n';
  1564. memcpy(nb + nn, old, (unsigned int)w);
  1565. nn += (unsigned int)w;
  1566. nb[nn++] = '\n';
  1567. }
  1568. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1569. persist_ndirty = 0;
  1570. free(old);
  1571. free(nb);
  1572. }
  1573. static void persist_cookies_flush(void)
  1574. {
  1575. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1576. unsigned int sum;
  1577. int n;
  1578. if (!jar)
  1579. return;
  1580. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1581. (int)sizeof(struct uhttp_jar));
  1582. if (n == (int)sizeof(struct uhttp_jar)) {
  1583. sum = persist_sum(jar, (unsigned int)n);
  1584. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1585. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1586. (int)jar, n) >= 0) {
  1587. cookie_sum_saved = sum;
  1588. cookie_sum_valid = 1;
  1589. }
  1590. }
  1591. }
  1592. free(jar);
  1593. }
  1594. /* ---- visit history (URL-bar autocomplete) ----
  1595. *
  1596. * Every page that finishes loading is recorded with its title, a visit
  1597. * count and a stamp: a counter that only grows and travels with the file,
  1598. * so it orders visits across windows and boots without a wall clock. The
  1599. * table lives in BSS, because the page heap is reset on every navigation.
  1600. * The boot's browser windows share it through /share/bhist (rewritten on
  1601. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1602. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1603. * /share/bhist and merges it first, so two windows add to one history
  1604. * instead of overwriting each other. File format: "NBHIST1\n", then
  1605. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1606. * other browser state on /data. */
  1607. #define HIST_MAX 128
  1608. #define HIST_URL_MAX 512
  1609. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1610. #define HIST_MAGIC "NBHIST1\n"
  1611. #define SHARE_HIST "/share/bhist"
  1612. #define DATA_HIST "/data/BHIST.DAT"
  1613. #define HIST_FORGET_MAX 16
  1614. struct hist_ent {
  1615. unsigned int visits;
  1616. unsigned int stamp;
  1617. char url[HIST_URL_MAX];
  1618. char title[BR_TITLE_MAX];
  1619. };
  1620. static struct hist_ent hist_tab[HIST_MAX];
  1621. static int hist_n;
  1622. static int hist_share_dirty, hist_data_dirty;
  1623. /* URLs removed in this process: a merge must not bring them back. */
  1624. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1625. static int hist_nforgot;
  1626. static unsigned int hist_hash(const char *s)
  1627. {
  1628. return persist_sum((const unsigned char *)s, s_len(s));
  1629. }
  1630. static int hist_is_forgotten(const char *url)
  1631. {
  1632. unsigned int h = hist_hash(url);
  1633. int i;
  1634. for (i = 0; i < hist_nforgot; i++)
  1635. if (hist_forgot[i] == h)
  1636. return 1;
  1637. return 0;
  1638. }
  1639. static int hist_find(const char *url)
  1640. {
  1641. int i;
  1642. for (i = 0; i < hist_n; i++)
  1643. if (s_eq(hist_tab[i].url, url))
  1644. return i;
  1645. return -1;
  1646. }
  1647. static unsigned int hist_next_stamp(void)
  1648. {
  1649. unsigned int m = 0;
  1650. int i;
  1651. for (i = 0; i < hist_n; i++)
  1652. if (hist_tab[i].stamp > m)
  1653. m = hist_tab[i].stamp;
  1654. return m + 1;
  1655. }
  1656. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1657. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1658. {
  1659. unsigned int i;
  1660. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1661. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1662. d[i] = '\0';
  1663. }
  1664. /* Insert or update an entry; the newer stamp wins the title, the larger
  1665. * visit count is kept. A full table evicts the least recent entry, unless
  1666. * the new one is older still. Returns NULL when nothing was stored. */
  1667. static struct hist_ent *hist_put(const char *url, const char *title,
  1668. unsigned int visits, unsigned int stamp)
  1669. {
  1670. struct hist_ent *e;
  1671. int i = hist_find(url);
  1672. if (i < 0) {
  1673. if (hist_n < HIST_MAX) {
  1674. i = hist_n++;
  1675. } else {
  1676. int j;
  1677. i = 0;
  1678. for (j = 1; j < hist_n; j++)
  1679. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1680. i = j;
  1681. if (hist_tab[i].stamp >= stamp)
  1682. return 0;
  1683. }
  1684. e = &hist_tab[i];
  1685. e->visits = 0;
  1686. e->stamp = 0;
  1687. e->title[0] = '\0';
  1688. s_copy(e->url, url, sizeof(e->url));
  1689. }
  1690. e = &hist_tab[i];
  1691. if (visits > e->visits)
  1692. e->visits = visits;
  1693. if (stamp >= e->stamp) {
  1694. e->stamp = stamp;
  1695. if (title && title[0])
  1696. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1697. } else if (!e->title[0] && title) {
  1698. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1699. }
  1700. return e;
  1701. }
  1702. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1703. {
  1704. unsigned int v = 0;
  1705. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1706. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1707. return v;
  1708. }
  1709. static void hist_merge_buf(const char *b, int n)
  1710. {
  1711. int pos = (int)s_len(HIST_MAGIC);
  1712. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1713. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1714. return;
  1715. while (pos < n) {
  1716. unsigned int visits, stamp, ul = 0;
  1717. int t0, t1;
  1718. visits = hist_parse_dec(b, n, &pos);
  1719. if (pos < n && b[pos] == ' ')
  1720. pos++;
  1721. stamp = hist_parse_dec(b, n, &pos);
  1722. if (pos < n && b[pos] == ' ')
  1723. pos++;
  1724. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1725. if (ul + 1 < sizeof(url))
  1726. url[ul++] = b[pos];
  1727. pos++;
  1728. }
  1729. url[ul] = '\0';
  1730. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1731. while (t1 < n && b[t1] != '\n')
  1732. t1++;
  1733. pos = t1 + 1;
  1734. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1735. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1736. hist_put(url, title, visits, stamp);
  1737. }
  1738. }
  1739. static int hist_serialize(char *b, unsigned int cap)
  1740. {
  1741. unsigned int n = 0;
  1742. int i;
  1743. s_append(b, &n, HIST_MAGIC, cap);
  1744. for (i = 0; i < hist_n; i++) {
  1745. struct hist_ent *e = &hist_tab[i];
  1746. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1747. break;
  1748. s_append_dec(b, &n, e->visits, cap);
  1749. b[n++] = ' ';
  1750. s_append_dec(b, &n, e->stamp, cap);
  1751. b[n++] = ' ';
  1752. s_append(b, &n, e->url, cap);
  1753. b[n++] = '\t';
  1754. s_append(b, &n, e->title, cap);
  1755. b[n++] = '\n';
  1756. }
  1757. return (int)n;
  1758. }
  1759. /* Merge /share/bhist, then write it back (and /data when asked). */
  1760. static void hist_sync(int to_data)
  1761. {
  1762. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1763. int n;
  1764. if (!b)
  1765. return;
  1766. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1767. (int)HIST_FILE_MAX);
  1768. if (n > 0)
  1769. hist_merge_buf(b, n);
  1770. n = hist_serialize(b, HIST_FILE_MAX);
  1771. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1772. hist_share_dirty = 0;
  1773. if (to_data) {
  1774. /* No /data mount: the write fails, and there is nothing to
  1775. * retry until the next visit. */
  1776. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1777. hist_data_dirty = 0;
  1778. }
  1779. free(b);
  1780. }
  1781. /* Startup: the boot's shared copy, else the saved one from /data. */
  1782. static void hist_load(void)
  1783. {
  1784. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1785. int n;
  1786. if (!b)
  1787. return;
  1788. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1789. (int)HIST_FILE_MAX);
  1790. if (n <= 0) {
  1791. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1792. (int)HIST_FILE_MAX);
  1793. if (n > 0)
  1794. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1795. }
  1796. if (n > 0)
  1797. hist_merge_buf(b, n);
  1798. free(b);
  1799. }
  1800. static void hist_visit(const char *url, const char *title)
  1801. {
  1802. struct hist_ent *e;
  1803. unsigned int i;
  1804. if (!url[0] || starts_with(url, "about:") ||
  1805. s_len(url) >= HIST_URL_MAX)
  1806. return;
  1807. for (i = 0; url[i]; i++)
  1808. if ((unsigned char)url[i] < 0x20)
  1809. return;
  1810. e = hist_put(url, title, 0, hist_next_stamp());
  1811. if (!e)
  1812. return;
  1813. e->visits++;
  1814. hist_data_dirty = 1;
  1815. hist_sync(0);
  1816. }
  1817. static void hist_forget(int i)
  1818. {
  1819. if (i < 0 || i >= hist_n)
  1820. return;
  1821. if (hist_nforgot < HIST_FORGET_MAX)
  1822. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1823. hist_n--;
  1824. for (; i < hist_n; i++)
  1825. hist_tab[i] = hist_tab[i + 1];
  1826. hist_data_dirty = 1;
  1827. hist_sync(0);
  1828. }
  1829. static void hist_tick(void)
  1830. {
  1831. if (hist_share_dirty || hist_data_dirty)
  1832. hist_sync(hist_data_dirty);
  1833. }
  1834. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1835. static void persist_tick(void)
  1836. {
  1837. unsigned int now = u_ticks_ms();
  1838. if ((int)(now - persist_due) < 0)
  1839. return;
  1840. persist_due = now + PERSIST_MS;
  1841. persist_cookies_flush();
  1842. if (persist_ndirty)
  1843. persist_store_flush();
  1844. hist_tick();
  1845. }
  1846. /* <link rel="modulepreload">: download the page's module graph on all
  1847. * helpers at once into the boot script cache, before any script runs. The
  1848. * engine's module loader is sequential (one blocking fetch per import), so
  1849. * without this a Vite app with a dozen chunks pays every round trip in a
  1850. * row. Failures are ignored; the loader fetches what is missing. */
  1851. #define MODULE_PRELOAD_MAX 24
  1852. static void prefetch_module_preloads(void)
  1853. {
  1854. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1855. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1856. unsigned int count = 0, next = 0, done = 0, i;
  1857. char err[64];
  1858. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1859. struct br_node *nd = &doc.nodes[i];
  1860. const char *rel, *href;
  1861. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1862. continue;
  1863. rel = br_rel(&doc, i);
  1864. href = br_href(&doc, i);
  1865. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1866. continue;
  1867. if (resolve_link(page_url, href, urls[count],
  1868. sizeof(urls[count])) != 0 ||
  1869. urls[count][0] == '/' || script_cache_has(urls[count]))
  1870. continue;
  1871. slot[count++] = 0;
  1872. }
  1873. if (!count)
  1874. return;
  1875. set_status("Loading modules...", 0, 0);
  1876. while (done < count) {
  1877. struct fetch_worker *w;
  1878. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1879. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1880. 0, 0, 0, err,
  1881. sizeof(err)) != 0) {
  1882. fetch_worker_release(w);
  1883. done++;
  1884. } else {
  1885. slot[next] = w;
  1886. }
  1887. next++;
  1888. }
  1889. worker_wait_ui();
  1890. if (cancel_fetch || pending_action) {
  1891. fetch_workers_cancel_busy();
  1892. return;
  1893. }
  1894. for (i = 0; i < next; i++) {
  1895. unsigned char *body;
  1896. int rv, tr = 0;
  1897. if (!slot[i])
  1898. continue;
  1899. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1900. if (rv == 0)
  1901. continue;
  1902. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1903. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1904. if (body) {
  1905. rv = fetch_worker_read_body(slot[i], body,
  1906. BR_SCRIPT_MAX, image_io_buf,
  1907. BR_PAGE_COMP_MAX, &tr, err,
  1908. sizeof(err));
  1909. if (rv > 0 && !tr)
  1910. script_cache_put(urls[i], body,
  1911. (unsigned int)rv);
  1912. free(body);
  1913. }
  1914. fetch_worker_release(slot[i]);
  1915. slot[i] = 0;
  1916. done++;
  1917. }
  1918. u_sleep_ms(10);
  1919. }
  1920. }
  1921. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1922. * submitted to helper workers ahead of time, but scripts still execute in
  1923. * document order. */
  1924. #define SCRIPT_INLINE 0
  1925. #define SCRIPT_LOCAL 1
  1926. #define SCRIPT_REMOTE 2
  1927. #define SCRIPT_ERROR 3
  1928. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1929. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1930. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1931. static void script_submit_window(unsigned int *next, char *err,
  1932. unsigned int errcap)
  1933. {
  1934. while (*next < doc.nscripts) {
  1935. struct fetch_worker *w;
  1936. if (script_kind[*next] != SCRIPT_REMOTE) {
  1937. (*next)++;
  1938. continue;
  1939. }
  1940. w = fetch_worker_alloc();
  1941. if (!w)
  1942. return;
  1943. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1944. 0, 0, 0, 0, err, errcap) != 0) {
  1945. fetch_worker_release(w);
  1946. script_kind[*next] = SCRIPT_ERROR;
  1947. (*next)++;
  1948. continue;
  1949. }
  1950. script_slot[*next] = w;
  1951. (*next)++;
  1952. }
  1953. }
  1954. /* Run the page's scripts in document order. External bodies are prefetched
  1955. * in parallel so downloading script N+1 overlaps executing script N; inline
  1956. * bodies are copied because the engine needs NUL-terminated text. */
  1957. static void run_page_scripts(void)
  1958. {
  1959. struct js_browser_host host;
  1960. unsigned int i, next = 0;
  1961. char err[64], ferr[64];
  1962. if (!doc.nscripts)
  1963. return;
  1964. host.status = js_host_status;
  1965. host.report = js_host_report;
  1966. host.navigate = js_host_navigate;
  1967. host.changed = js_host_changed;
  1968. host.rect = js_host_rect;
  1969. host.form_value = js_host_form_value;
  1970. host.form_checked = js_host_form_checked;
  1971. host.form_selected = js_host_form_selected;
  1972. host.form_set_value = js_host_form_set_value;
  1973. host.form_set_checked = js_host_form_set_checked;
  1974. host.form_set_selected = js_host_form_set_selected;
  1975. host.form_elements = js_host_form_elements;
  1976. host.form_submit = js_host_form_submit;
  1977. host.form_reset = js_host_form_reset;
  1978. host.click = js_host_click;
  1979. host.computed = js_host_computed;
  1980. host.http = js_host_http;
  1981. host.load_script = js_host_load_script;
  1982. host.storage = js_host_storage;
  1983. host.set_hash = js_host_set_hash;
  1984. host.page_url = page_url;
  1985. host.width = ui.w;
  1986. host.height = ui.h;
  1987. if (js_browser_start(&doc, &host) != 0) {
  1988. js_host_status("JavaScript: out of memory", 1);
  1989. return;
  1990. }
  1991. resize_sent_w = -1;
  1992. resize_pending = 0;
  1993. prefetch_module_preloads();
  1994. for (i = 0; i < doc.nscripts; i++) {
  1995. struct br_script *script = &doc.scripts[i];
  1996. const char *src_attr = script->src_off ?
  1997. doc.attrs + script->src_off : "";
  1998. script_slot[i] = 0;
  1999. if (!script->src_off) {
  2000. script_kind[i] = SCRIPT_INLINE;
  2001. continue;
  2002. }
  2003. if (!src_attr[0] ||
  2004. resolve_link(page_url, src_attr, script_urls[i],
  2005. sizeof(script_urls[i])) != 0) {
  2006. script_urls[i][0] = '\0';
  2007. script_kind[i] = SCRIPT_ERROR;
  2008. continue;
  2009. }
  2010. if (script_urls[i][0] == '/' ||
  2011. script_cache_has(script_urls[i]))
  2012. script_kind[i] = SCRIPT_LOCAL;
  2013. else
  2014. script_kind[i] = SCRIPT_REMOTE;
  2015. }
  2016. script_submit_window(&next, ferr, sizeof(ferr));
  2017. for (i = 0; i < doc.nscripts; i++) {
  2018. struct br_script *script = &doc.scripts[i];
  2019. /* document.currentScript for classic scripts (null for modules) */
  2020. js_browser_set_current_script(script->module ? 0 : script->node);
  2021. if (script_kind[i] == SCRIPT_INLINE) {
  2022. unsigned int off = script->off;
  2023. unsigned int len = script->len;
  2024. unsigned int k;
  2025. char *src = (char *)malloc(len + 1);
  2026. if (!src) {
  2027. js_host_status("JavaScript: out of memory", 1);
  2028. break;
  2029. }
  2030. for (k = 0; k < len; k++)
  2031. src[k] = doc.script_src[off + k];
  2032. src[len] = '\0';
  2033. if (script->module) {
  2034. /* A distinct module name per inline module
  2035. * (QuickJS registers modules by name); the
  2036. * fragment keeps relative imports resolving
  2037. * against the page. */
  2038. char mname[BR_URL_MAX + 16];
  2039. unsigned int mn = 0;
  2040. s_append(mname, &mn, page_url, sizeof(mname));
  2041. s_append(mname, &mn, "#module", sizeof(mname));
  2042. s_append_dec(mname, &mn, i, sizeof(mname));
  2043. js_browser_run_module(src, mname);
  2044. } else {
  2045. js_browser_run(src, page_url);
  2046. }
  2047. free(src);
  2048. } else if (script->src_off) {
  2049. const char *src_attr = doc.attrs + script->src_off;
  2050. if (script_kind[i] == SCRIPT_ERROR) {
  2051. script_error("Cannot load script", src_attr,
  2052. script_urls[i][0] ?
  2053. "network busy" :
  2054. "unsupported URL");
  2055. continue;
  2056. }
  2057. if (script_kind[i] == SCRIPT_LOCAL) {
  2058. unsigned char *data = 0;
  2059. unsigned int len = 0;
  2060. int rv;
  2061. set_status("Loading script...", 0, 0);
  2062. rv = fetch_script_text(script_urls[i], &data,
  2063. &len, err, sizeof(err));
  2064. if (rv == FETCH_ABORT)
  2065. break;
  2066. if (rv != 0) {
  2067. script_error("Cannot load script",
  2068. script_urls[i], err);
  2069. continue;
  2070. }
  2071. if (script->module)
  2072. js_browser_run_module(
  2073. (const char *)data,
  2074. script_urls[i]);
  2075. else
  2076. js_browser_run((const char *)data,
  2077. script_urls[i]);
  2078. free(data);
  2079. } else {
  2080. struct fetch_worker *w = script_slot[i];
  2081. unsigned char *body = 0;
  2082. int tr = 0, rv;
  2083. if (!w) {
  2084. w = fetch_worker_alloc();
  2085. if (!w)
  2086. continue;
  2087. if (fetch_worker_submit(w,
  2088. script_urls[i],
  2089. BR_SCRIPT_MAX,
  2090. 0, 0, 0, 0, err,
  2091. sizeof(err)) != 0) {
  2092. fetch_worker_release(w);
  2093. script_kind[i] = SCRIPT_ERROR;
  2094. if (i == next)
  2095. next++;
  2096. continue;
  2097. }
  2098. script_slot[i] = w;
  2099. if (i == next)
  2100. next++;
  2101. }
  2102. set_status("Loading script...", 0, 0);
  2103. rv = fetch_worker_wait(w, err, sizeof(err));
  2104. if (rv == FETCH_ABORT) {
  2105. fetch_workers_stop_all();
  2106. break;
  2107. }
  2108. /* The body gets its own buffer (scripts are up
  2109. * to 2 MB); image_io_buf takes the gzip
  2110. * stream. */
  2111. body = rv == 0 ? (unsigned char *)malloc(
  2112. BR_SCRIPT_MAX + 1) : 0;
  2113. if (body)
  2114. rv = fetch_worker_read_body(w, body,
  2115. BR_SCRIPT_MAX, image_io_buf,
  2116. BR_PAGE_COMP_MAX, &tr, err,
  2117. sizeof(err));
  2118. else {
  2119. if (rv == 0)
  2120. s_copy(err, "out of memory",
  2121. sizeof(err));
  2122. rv = -1;
  2123. }
  2124. fetch_worker_release(w);
  2125. script_slot[i] = 0;
  2126. script_submit_window(&next, ferr, sizeof(ferr));
  2127. if (rv <= 0)
  2128. script_error("Cannot load script",
  2129. script_urls[i], err);
  2130. else if (tr || (unsigned int)rv >=
  2131. BR_SCRIPT_MAX)
  2132. script_error("Cannot load script",
  2133. script_urls[i],
  2134. "script is too large");
  2135. else {
  2136. body[rv] = '\0';
  2137. script_cache_put(script_urls[i], body,
  2138. (unsigned int)rv);
  2139. if (script->module)
  2140. js_browser_run_module(
  2141. (const char *)body,
  2142. script_urls[i]);
  2143. else
  2144. js_browser_run(
  2145. (const char *)body,
  2146. script_urls[i]);
  2147. }
  2148. free(body);
  2149. }
  2150. }
  2151. if (pending_action)
  2152. break;
  2153. }
  2154. js_browser_set_current_script(0);
  2155. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2156. * load_home() stop it before the next navigation. */
  2157. if (doc.scripts_truncated && !js_last_error)
  2158. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2159. 1);
  2160. }
  2161. /* ---- images ---- */
  2162. /* data: images that failed to decode (key = data_img_key()), so a layout
  2163. * pass does not retry them on every frame. */
  2164. #define DATA_IMG_FAIL_MAX 32
  2165. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2166. static int data_img_nfail;
  2167. static void image_reset(void)
  2168. {
  2169. int i;
  2170. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2171. images[i].state = 0;
  2172. images[i].native_w = images[i].native_h = 0;
  2173. images[i].err[0] = '\0';
  2174. /* heap_clear() ran before us, so these pointers are stale: drop
  2175. * them without calling free(). */
  2176. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2177. images[i].disp_pixels = 0;
  2178. images[i].disp_last = 0;
  2179. }
  2180. image_count = 0;
  2181. data_img_nfail = 0;
  2182. image_pixels = 0;
  2183. image_disp_pixels = 0;
  2184. image_disp_clock = 0;
  2185. memset(img_stat_log, 0, sizeof(img_stat_log));
  2186. img_stat_log_len = 0;
  2187. img_stat_start = 0;
  2188. img_stat_wall = 0;
  2189. img_stat_net = img_stat_open = img_stat_first = 0;
  2190. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2191. img_stat_paint = img_stat_reflow = 0;
  2192. img_stat_bytes = 0;
  2193. img_stat_n = 0;
  2194. img_last_dec_ms = img_last_scale_ms = 0;
  2195. img_repaint_ms = 0;
  2196. img_repaint_pending = 0;
  2197. preload_active = 0;
  2198. preload_pending = 0;
  2199. preload_wait = 0;
  2200. preload_node = 0;
  2201. preload_loaded = 0;
  2202. }
  2203. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2204. * are arriving. The main loop draws once per dirty frame; without this a
  2205. * page of N images did N full layout+paint passes. */
  2206. static void image_repaint(void)
  2207. {
  2208. unsigned int now = u_ticks_ms();
  2209. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2210. img_repaint_ms = now;
  2211. img_repaint_pending = 0;
  2212. ngui_invalidate(&ui);
  2213. } else {
  2214. img_repaint_pending = 1;
  2215. }
  2216. }
  2217. static void image_disp_drop(struct br_image *bi)
  2218. {
  2219. if (bi->disp.px)
  2220. free(bi->disp.px);
  2221. if (bi->disp.alpha)
  2222. free(bi->disp.alpha);
  2223. memset(&bi->disp, 0, sizeof(bi->disp));
  2224. if (bi->disp_pixels) {
  2225. if (image_disp_pixels >= bi->disp_pixels)
  2226. image_disp_pixels -= bi->disp_pixels;
  2227. bi->disp_pixels = 0;
  2228. }
  2229. }
  2230. /* Free the least recently used display caches until need pixels fit. The
  2231. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2232. static int image_disp_room(unsigned int need)
  2233. {
  2234. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2235. unsigned int oldest = ~0u;
  2236. int i, victim = -1;
  2237. for (i = 0; i < image_count; i++) {
  2238. if (!images[i].disp.px)
  2239. continue;
  2240. if (images[i].disp_last < oldest) {
  2241. oldest = images[i].disp_last;
  2242. victim = i;
  2243. }
  2244. }
  2245. if (victim < 0)
  2246. return -1;
  2247. image_disp_drop(&images[victim]);
  2248. }
  2249. return 0;
  2250. }
  2251. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2252. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2253. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2254. {
  2255. struct img_blit b;
  2256. unsigned int px;
  2257. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2258. return 0;
  2259. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2260. return &bi->img;
  2261. if (dw > 4096 || dh > 4096)
  2262. return &bi->img;
  2263. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2264. bi->disp.h == (unsigned int)dh) {
  2265. bi->disp_last = ++image_disp_clock;
  2266. return &bi->disp;
  2267. }
  2268. px = (unsigned int)dw * (unsigned int)dh;
  2269. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2270. return &bi->img;
  2271. image_disp_drop(bi);
  2272. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2273. if (!bi->disp.px)
  2274. return &bi->img;
  2275. if (bi->img.alpha) {
  2276. bi->disp.alpha = (unsigned char *)malloc(px);
  2277. if (!bi->disp.alpha) {
  2278. free(bi->disp.px);
  2279. bi->disp.px = 0;
  2280. return &bi->img;
  2281. }
  2282. }
  2283. bi->disp.w = (unsigned int)dw;
  2284. bi->disp.h = (unsigned int)dh;
  2285. bi->disp.format = bi->img.format;
  2286. bi->disp.flags = 0;
  2287. memset(&b, 0, sizeof(b));
  2288. b.dst = bi->disp.px;
  2289. b.dst_w = dw;
  2290. b.dst_h = dh;
  2291. b.clip_w = dw;
  2292. b.clip_h = dh;
  2293. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2294. b.dst_a = bi->disp.alpha;
  2295. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2296. img_draw(&bi->img, &b);
  2297. bi->disp_pixels = px;
  2298. image_disp_pixels += px;
  2299. bi->disp_last = ++image_disp_clock;
  2300. return &bi->disp;
  2301. }
  2302. /* Decode into the shared arena, then copy/scale the result into a display
  2303. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2304. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2305. * pixels. Transparent edges are composited over white. */
  2306. /* One decode scratch arena per page, reused across images. Allocating and
  2307. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2308. * each small display bitmap landed in the hole the previous arena left, so
  2309. * the next arena no longer fit and the heap ratcheted up until an app
  2310. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2311. * still released right after their one image. */
  2312. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2313. static unsigned char *decode_arena_get(unsigned int bytes)
  2314. {
  2315. if (decode_arena && decode_arena_size >= bytes)
  2316. return decode_arena;
  2317. free(decode_arena);
  2318. decode_arena = (unsigned char *)malloc(bytes);
  2319. decode_arena_size = decode_arena ? bytes : 0;
  2320. return decode_arena;
  2321. }
  2322. static void decode_arena_put(void)
  2323. {
  2324. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2325. free(decode_arena);
  2326. decode_arena = 0;
  2327. decode_arena_size = 0;
  2328. }
  2329. }
  2330. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2331. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2332. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2333. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2334. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2335. struct br_image *bi, int box_w, int box_h);
  2336. static int decode_image_data(const unsigned char *data, unsigned int len,
  2337. struct br_image *bi, int box_w, int box_h,
  2338. int fit_w, int fit_h)
  2339. {
  2340. struct img_info info;
  2341. struct img_options opt;
  2342. struct img_mem mem;
  2343. struct img_image decoded;
  2344. unsigned char *arena;
  2345. unsigned int est, bytes, i;
  2346. unsigned int t0;
  2347. unsigned short *px;
  2348. unsigned char *alpha = 0;
  2349. int dw, dh, r;
  2350. bi->url_hash = 0;
  2351. img_last_dec_ms = 0;
  2352. img_last_scale_ms = 0;
  2353. if (img_sniff(data, len, &info) != 0) {
  2354. if (svg_text_sniff(data, len))
  2355. return svg_decode_image(data, len, bi,
  2356. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2357. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2358. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2359. return -1;
  2360. }
  2361. est = img_estimate(&info);
  2362. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2363. s_copy(bi->err, "image too large", sizeof(bi->err));
  2364. return -1;
  2365. }
  2366. arena = decode_arena_get(est);
  2367. if (!arena) {
  2368. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2369. return -1;
  2370. }
  2371. img_mem_init(&mem, arena, est);
  2372. opt.max_pixels = BR_IMG_PIX_MAX;
  2373. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2374. (box_w > 0 ? (unsigned int)box_w : 0);
  2375. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2376. (box_h > 0 ? (unsigned int)box_h : 0);
  2377. t0 = u_ticks_ms();
  2378. r = img_decode(data, len, &opt, &mem, &decoded);
  2379. img_last_dec_ms = u_ticks_ms() - t0;
  2380. if (r != 0) {
  2381. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2382. goto fail;
  2383. }
  2384. if (decoded.w == 0 || decoded.h == 0) {
  2385. s_copy(bi->err, "empty image", sizeof(bi->err));
  2386. goto fail;
  2387. }
  2388. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2389. * needs the intrinsic dimensions from the header. */
  2390. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2391. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2392. dw = (int)decoded.w;
  2393. dh = (int)decoded.h;
  2394. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2395. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2396. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2397. * axes with one scale so the aspect ratio is preserved. */
  2398. if (fit_w > 0 || fit_h > 0) {
  2399. unsigned int scw = fit_w > 0 ?
  2400. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2401. unsigned int sch = fit_h > 0 ?
  2402. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2403. unsigned int sc = scw < sch ? scw : sch;
  2404. if (sc < 0x10000u) {
  2405. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2406. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2407. if (dw < 1)
  2408. dw = 1;
  2409. if (dh < 1)
  2410. dh = 1;
  2411. }
  2412. }
  2413. if (box_w > 0 && box_h > 0) {
  2414. /* cover: scale so both box sides are filled, never up */
  2415. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2416. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2417. unsigned int sc = sw > sh ? sw : sh;
  2418. if (sc < 0x10000u) {
  2419. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2420. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2421. }
  2422. }
  2423. if (dw > BR_IMG_LAYOUT_W) {
  2424. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2425. dw = BR_IMG_LAYOUT_W;
  2426. }
  2427. if (dh < 1)
  2428. dh = 1;
  2429. if (dw < 1)
  2430. dw = 1;
  2431. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2432. BR_IMG_PIXEL_BUDGET) {
  2433. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2434. goto fail;
  2435. }
  2436. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2437. px = (unsigned short *)malloc(bytes);
  2438. if (!px) {
  2439. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2440. goto fail;
  2441. }
  2442. /* Keep the alpha plane for the scaled image so transparent logos and
  2443. * icons composite over the page instead of the browser's dark theme
  2444. * background. Very large alpha images stay flattened to bound the
  2445. * heap use. */
  2446. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2447. alpha = (unsigned char *)malloc((unsigned int)dw *
  2448. (unsigned int)dh);
  2449. if (alpha) {
  2450. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2451. alpha[i] = 255;
  2452. }
  2453. }
  2454. /* With an alpha plane the colour under transparent pixels only shows
  2455. * through partially covered edge pixels of the downscale: use white,
  2456. * as documented above, not the dark browser theme (which left a dark
  2457. * fringe around scaled app icons). */
  2458. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2459. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2460. {
  2461. struct img_blit b;
  2462. b.dst = px;
  2463. b.dst_w = dw;
  2464. b.dst_h = dh;
  2465. b.clip_x = 0;
  2466. b.clip_y = 0;
  2467. b.clip_w = dw;
  2468. b.clip_h = dh;
  2469. b.x = 0;
  2470. b.y = 0;
  2471. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2472. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2473. b.bg2 = b.bg;
  2474. b.dst_a = alpha;
  2475. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2476. t0 = u_ticks_ms();
  2477. img_draw(&decoded, &b);
  2478. img_last_scale_ms = u_ticks_ms() - t0;
  2479. }
  2480. bi->img.format = decoded.format;
  2481. bi->img.w = (unsigned int)dw;
  2482. bi->img.h = (unsigned int)dh;
  2483. bi->img.px = px;
  2484. bi->img.alpha = alpha;
  2485. bi->img.flags = 0;
  2486. bi->state = 1;
  2487. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2488. decode_arena_put();
  2489. return 0;
  2490. fail:
  2491. decode_arena_put();
  2492. return -1;
  2493. }
  2494. /* ---- URL / local path handling ---- */
  2495. static int is_http(const char *s)
  2496. {
  2497. return starts_with(s, "http://") || starts_with(s, "https://");
  2498. }
  2499. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2500. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2501. {
  2502. char seg[64];
  2503. unsigned int i = 0, o = 1;
  2504. int depth = 0;
  2505. int trailing;
  2506. if (!in || in[0] != '/' || cap < 2)
  2507. return -1;
  2508. trailing = 0;
  2509. {
  2510. unsigned int n = s_len(in);
  2511. if (n > 1 && in[n - 1] == '/')
  2512. trailing = 1;
  2513. }
  2514. out[0] = '/';
  2515. while (in[i]) {
  2516. unsigned int n = 0;
  2517. while (in[i] == '/')
  2518. i++;
  2519. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2520. if (n + 1 < sizeof(seg))
  2521. seg[n++] = in[i];
  2522. i++;
  2523. }
  2524. seg[n] = '\0';
  2525. if (n == 0)
  2526. break;
  2527. if (s_eq(seg, "."))
  2528. continue;
  2529. if (s_eq(seg, "..")) {
  2530. if (depth > 0) {
  2531. while (o > 1 && out[o - 1] != '/')
  2532. o--;
  2533. if (o > 1)
  2534. o--;
  2535. depth--;
  2536. }
  2537. continue;
  2538. }
  2539. if (o > 1) {
  2540. if (o + 1 >= cap)
  2541. return -1;
  2542. out[o++] = '/';
  2543. }
  2544. if (o + n + 1 >= cap)
  2545. return -1;
  2546. {
  2547. unsigned int j;
  2548. for (j = 0; j < n; j++)
  2549. out[o++] = seg[j];
  2550. }
  2551. depth++;
  2552. }
  2553. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2554. if (o + 1 >= cap)
  2555. return -1;
  2556. out[o++] = '/';
  2557. }
  2558. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2559. if (in[i] == '?' || in[i] == '#') {
  2560. while (in[i]) {
  2561. if (o + 1 >= cap)
  2562. return -1;
  2563. out[o++] = in[i++];
  2564. }
  2565. }
  2566. out[o] = '\0';
  2567. return 0;
  2568. }
  2569. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2570. {
  2571. char joined[BR_URL_MAX];
  2572. if (!in || !in[0]) {
  2573. s_copy(out, cwd[0] ? cwd : "/", cap);
  2574. return;
  2575. }
  2576. if (in[0] == '/') {
  2577. if (normalize_abs(in, out, cap) != 0)
  2578. s_copy(out, in, cap);
  2579. return;
  2580. }
  2581. {
  2582. unsigned int n = 0;
  2583. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2584. s_append(joined, &n, "/", sizeof(joined));
  2585. s_append(joined, &n, in, sizeof(joined));
  2586. }
  2587. if (normalize_abs(joined, out, cap) != 0)
  2588. s_copy(out, joined, cap);
  2589. }
  2590. /* ---- canonical origin cache ---- *
  2591. *
  2592. * Sites commonly redirect http://host to https://host and then to
  2593. * https://www.host. Remember the final scheme/host of the last navigation so
  2594. * a bare domain typed again goes straight there instead of paying for two
  2595. * more connections and TLS handshakes. Only default-port requests are
  2596. * rewritten; explicit ports are left alone. */
  2597. #define ORIGIN_CACHE_MAX 8
  2598. #define ORIGIN_FILE "/share/borigins"
  2599. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2600. UHTTP_HOST_MAX + 2))
  2601. struct origin_cache_entry {
  2602. char host[UHTTP_HOST_MAX];
  2603. char origin[UHTTP_HOST_MAX + 16];
  2604. };
  2605. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2606. static int origin_count;
  2607. static char origin_buf[ORIGIN_BUF_SIZE];
  2608. static int default_port(const struct uhttp_url *u)
  2609. {
  2610. return u->secure ? u->port == 443 : u->port == 80;
  2611. }
  2612. static void url_origin(const struct uhttp_url *u, char *out,
  2613. unsigned int cap)
  2614. {
  2615. unsigned int n = 0;
  2616. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2617. s_append(out, &n, u->host, cap);
  2618. if (!default_port(u)) {
  2619. s_append(out, &n, ":", cap);
  2620. s_append_dec(out, &n, u->port, cap);
  2621. }
  2622. }
  2623. static void origin_cache_apply(char *url, unsigned int cap)
  2624. {
  2625. struct uhttp_url u;
  2626. char out[BR_URL_MAX];
  2627. unsigned int n = 0;
  2628. int i;
  2629. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2630. return;
  2631. for (i = 0; i < origin_count; i++) {
  2632. if (!s_eq(u.host, origins[i].host))
  2633. continue;
  2634. s_append(out, &n, origins[i].origin, sizeof(out));
  2635. s_append(out, &n, u.path, sizeof(out));
  2636. s_copy(url, out, cap);
  2637. return;
  2638. }
  2639. }
  2640. static void origin_cache_save(void)
  2641. {
  2642. unsigned int n = 0;
  2643. int i;
  2644. for (i = 0; i < origin_count; i++) {
  2645. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2646. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2647. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2648. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2649. }
  2650. if (n)
  2651. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2652. (int)origin_buf, (int)n);
  2653. }
  2654. static void origin_cache_load(void)
  2655. {
  2656. char *p;
  2657. int rn;
  2658. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2659. (int)(sizeof(origin_buf) - 1));
  2660. if (rn <= 0)
  2661. return;
  2662. origin_buf[rn] = '\0';
  2663. p = origin_buf;
  2664. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2665. char *line = p, *origin;
  2666. while (*p && *p != '\n')
  2667. p++;
  2668. if (*p)
  2669. *p++ = '\0';
  2670. if (!line[0])
  2671. continue;
  2672. origin = line;
  2673. while (*origin && *origin != ' ')
  2674. origin++;
  2675. if (!*origin)
  2676. continue;
  2677. *origin++ = '\0';
  2678. if (!line[0] || !is_http(origin))
  2679. continue;
  2680. {
  2681. struct uhttp_url uo;
  2682. if (uhttp_parse_url(origin, &uo) != 0 ||
  2683. !s_eq(uo.path, "/"))
  2684. continue;
  2685. }
  2686. s_copy(origins[origin_count].host, line,
  2687. sizeof(origins[origin_count].host));
  2688. s_copy(origins[origin_count].origin, origin,
  2689. sizeof(origins[origin_count].origin));
  2690. origin_count++;
  2691. }
  2692. }
  2693. static int host_is_www_of(const char *host, const char *base)
  2694. {
  2695. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2696. host[3] == '.' && s_eq(host + 4, base);
  2697. }
  2698. static void origin_cache_learn(const char *requested, const char *final)
  2699. {
  2700. struct uhttp_url from, to;
  2701. char origin[UHTTP_HOST_MAX + 16];
  2702. int i;
  2703. if (!is_http(requested) || !is_http(final))
  2704. return;
  2705. if (uhttp_parse_url(requested, &from) != 0 ||
  2706. uhttp_parse_url(final, &to) != 0)
  2707. return;
  2708. if (!default_port(&from))
  2709. return;
  2710. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2711. from.port == to.port)
  2712. return;
  2713. /* Only remember origin-level canonicalisation: the same path, and
  2714. * either the same host or its www./apex sibling. A path- or
  2715. * host-specific redirect (a shortener, a login page) must not poison
  2716. * every request to the typed host. */
  2717. if (!s_eq(from.path, to.path))
  2718. return;
  2719. if (!s_eq(from.host, to.host) &&
  2720. !host_is_www_of(to.host, from.host) &&
  2721. !host_is_www_of(from.host, to.host))
  2722. return;
  2723. url_origin(&to, origin, sizeof(origin));
  2724. for (i = 0; i < origin_count; i++) {
  2725. if (s_eq(origins[i].host, from.host)) {
  2726. if (!s_eq(origins[i].origin, origin)) {
  2727. s_copy(origins[i].origin, origin,
  2728. sizeof(origins[i].origin));
  2729. origin_cache_save();
  2730. }
  2731. return;
  2732. }
  2733. }
  2734. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2735. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2736. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2737. origin_cache_save();
  2738. }
  2739. static int path_dir(const char *path, char *out, unsigned int cap)
  2740. {
  2741. unsigned int i, last = 0;
  2742. for (i = 0; path[i]; i++)
  2743. if (path[i] == '/')
  2744. last = i;
  2745. if (last == 0) {
  2746. if (cap < 2)
  2747. return -1;
  2748. out[0] = '/';
  2749. out[1] = '\0';
  2750. return 0;
  2751. }
  2752. if (last + 1 >= cap)
  2753. return -1;
  2754. {
  2755. unsigned int j;
  2756. for (j = 0; j < last; j++)
  2757. out[j] = path[j];
  2758. out[last] = '\0';
  2759. }
  2760. return 0;
  2761. }
  2762. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2763. static int resolve_link(const char *base, const char *href, char *out,
  2764. unsigned int cap)
  2765. {
  2766. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2767. if (!href || !href[0] || href[0] == '#')
  2768. return -1;
  2769. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2770. starts_with(href, "data:") || starts_with(href, "tel:"))
  2771. return -1;
  2772. if (starts_with(href, "about:")) {
  2773. s_copy(out, href, cap);
  2774. return 0;
  2775. }
  2776. if (is_http(href)) {
  2777. s_copy(out, href, cap);
  2778. return 0;
  2779. }
  2780. if (starts_with(href, "//")) {
  2781. if (is_http(base)) {
  2782. unsigned int n = 0;
  2783. s_append(out, &n, starts_with(base, "https:") ?
  2784. "https:" : "http:", cap);
  2785. s_append(out, &n, href, cap);
  2786. return 0;
  2787. }
  2788. return -1;
  2789. }
  2790. if (is_http(base)) {
  2791. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2792. }
  2793. /* local page */
  2794. if (href[0] == '/') {
  2795. if (normalize_abs(href, out, cap) != 0)
  2796. return -1;
  2797. return 0;
  2798. }
  2799. {
  2800. static char dir[BR_URL_MAX];
  2801. unsigned int n = 0;
  2802. if (s_eq(base, "about:home"))
  2803. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2804. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2805. s_copy(dir, "/", sizeof(dir));
  2806. s_append(joined, &n, dir, sizeof(joined));
  2807. if (n == 0 || joined[n - 1] != '/')
  2808. s_append(joined, &n, "/", sizeof(joined));
  2809. s_append(joined, &n, href, sizeof(joined));
  2810. }
  2811. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2812. }
  2813. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2814. * rest instead of failing when a page or stylesheet is larger than the
  2815. * buffer. The stream is still walked to the end, so a normal page is
  2816. * verified; a truncated compressed input still returns whatever was decoded
  2817. * so far. */
  2818. struct trunc_buf {
  2819. unsigned char *dst;
  2820. unsigned int cap, pos;
  2821. int full;
  2822. };
  2823. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2824. {
  2825. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2826. if (len > m->cap - m->pos) {
  2827. unsigned int room = m->cap - m->pos;
  2828. if (room) {
  2829. unsigned int i;
  2830. for (i = 0; i < room; i++)
  2831. m->dst[m->pos + i] = data[i];
  2832. m->pos += room;
  2833. }
  2834. m->full = 1;
  2835. return 0;
  2836. }
  2837. {
  2838. unsigned int i;
  2839. for (i = 0; i < len; i++)
  2840. m->dst[m->pos + i] = data[i];
  2841. }
  2842. m->pos += len;
  2843. return 0;
  2844. }
  2845. static void worker_wait_ui(void);
  2846. static void inflate_ui_pump(void *ctx)
  2847. {
  2848. static unsigned int last;
  2849. unsigned int now = u_ticks_ms();
  2850. (void)ctx;
  2851. if ((int)(now - last) >= 50) {
  2852. last = now;
  2853. worker_wait_ui();
  2854. }
  2855. }
  2856. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2857. unsigned char *dst, unsigned int cap,
  2858. unsigned int *outlen, int gzip, int *truncated)
  2859. {
  2860. struct inflate_src in;
  2861. struct inflate_sink sink;
  2862. struct trunc_buf m;
  2863. unsigned int got = 0;
  2864. int r;
  2865. in.p = src;
  2866. in.len = len;
  2867. in.more = 0;
  2868. in.ctx = 0;
  2869. m.dst = dst;
  2870. m.cap = cap;
  2871. m.pos = 0;
  2872. m.full = 0;
  2873. sink.write = trunc_write;
  2874. sink.ctx = &m;
  2875. inflate_init(&image_inflate_ws, &in, &sink);
  2876. image_inflate_ws.progress = inflate_ui_pump;
  2877. image_inflate_ws.progress_ctx = 0;
  2878. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2879. inflate_zlib(&image_inflate_ws, &got);
  2880. *outlen = m.pos;
  2881. *truncated = m.full || r != 0;
  2882. if (r != 0 && m.pos == 0)
  2883. return -1;
  2884. return 0;
  2885. }
  2886. /* ---- headless fetch workers ------------------------------------------ *
  2887. *
  2888. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2889. * writes the raw response, a small metadata file and a done marker under
  2890. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2891. * or a multi-megabyte body never freezes the UI and images download in
  2892. * parallel.
  2893. */
  2894. struct fetch_meta {
  2895. int status;
  2896. int error;
  2897. int trunc;
  2898. unsigned int len;
  2899. unsigned int open_ms;
  2900. unsigned int first_ms;
  2901. unsigned int total_ms;
  2902. /* Optional decoded bitmap produced by the helper (image jobs). */
  2903. unsigned int dw, dh, nw, nh;
  2904. unsigned int alpha;
  2905. unsigned int px_len;
  2906. unsigned int dec_ms;
  2907. int dec_err;
  2908. char encoding[16];
  2909. char ctype[64];
  2910. char final[BR_URL_MAX];
  2911. };
  2912. static void draw(unsigned int *action);
  2913. static void handle_keys(unsigned int *action);
  2914. static void handle_page_click(unsigned int *action);
  2915. #define FETCH_WORKERS 4
  2916. #define FETCH_PATH_MAX 32
  2917. /* One long-lived curl __serve helper per worker. Each worker has its own
  2918. * request/body/meta/done files under /share so several downloads can be in
  2919. * flight at once; the keep-alive connection stays in the helper process, so
  2920. * tls.c's per-process state remains valid. */
  2921. struct fetch_worker {
  2922. int pid;
  2923. int slot;
  2924. int busy;
  2925. int ready;
  2926. int image_job;
  2927. unsigned int seq;
  2928. unsigned int deadline;
  2929. int retried;
  2930. unsigned int dec_w, dec_h;
  2931. int dec_retried;
  2932. char req[FETCH_PATH_MAX];
  2933. char body[FETCH_PATH_MAX];
  2934. char meta[FETCH_PATH_MAX];
  2935. char done[FETCH_PATH_MAX];
  2936. char post[FETCH_PATH_MAX];
  2937. char px[FETCH_PATH_MAX];
  2938. /* Optional preload job attached to this worker. */
  2939. unsigned int node;
  2940. int bg;
  2941. char url[BR_URL_MAX];
  2942. struct fetch_meta m;
  2943. };
  2944. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2945. static int fetch_tty = -2;
  2946. static void fetch_tty_drain(void);
  2947. static unsigned int fetch_session;
  2948. static unsigned int fetch_seq;
  2949. static struct fetch_meta fetch_meta;
  2950. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2951. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2952. static int fetch_last_error;
  2953. static unsigned int meta_uint(char **pp)
  2954. {
  2955. char *p = *pp;
  2956. unsigned int v = 0;
  2957. while (*p >= '0' && *p <= '9') {
  2958. v = v * 10 + (unsigned int)(*p - '0');
  2959. p++;
  2960. }
  2961. while (*p && *p != '\n')
  2962. p++;
  2963. if (*p == '\n')
  2964. p++;
  2965. *pp = p;
  2966. return v;
  2967. }
  2968. static void meta_str(char **pp, char *out, unsigned int cap)
  2969. {
  2970. char *p = *pp;
  2971. unsigned int n = 0;
  2972. while (*p && *p != '\n' && n + 1 < cap)
  2973. out[n++] = *p++;
  2974. out[n] = '\0';
  2975. while (*p && *p != '\n')
  2976. p++;
  2977. if (*p == '\n')
  2978. p++;
  2979. *pp = p;
  2980. }
  2981. static void worker_wait_ui(void)
  2982. {
  2983. unsigned int action = 0;
  2984. if (!ngui_begin(&ui))
  2985. return;
  2986. draw(&action);
  2987. handle_keys(&action);
  2988. handle_page_click(&action);
  2989. if (action & ACT_WAIT_NAV) {
  2990. pending_action |= action & ACT_WAIT_NAV;
  2991. if ((action & ACT_NAV) && click_url[0])
  2992. s_copy(pending_url, click_url, sizeof(pending_url));
  2993. click_url[0] = '\0';
  2994. cancel_fetch = 1;
  2995. }
  2996. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2997. ngui_invalidate(&ui);
  2998. ngui_end(&ui);
  2999. }
  3000. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3001. unsigned int session, int slot)
  3002. {
  3003. unsigned int n = 0;
  3004. s_append(out, &n, "/share/bf", cap);
  3005. s_append_dec(out, &n, session, cap);
  3006. s_append(out, &n, "_", cap);
  3007. s_append_dec(out, &n, (unsigned int)slot, cap);
  3008. s_append(out, &n, kind, cap);
  3009. }
  3010. static void fetch_pool_init(void)
  3011. {
  3012. static int ready;
  3013. int i;
  3014. if (ready)
  3015. return;
  3016. ready = 1;
  3017. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3018. (u_ticks_ms() & 0xFFFFu);
  3019. if (!fetch_session)
  3020. fetch_session = 1;
  3021. for (i = 0; i < FETCH_WORKERS; i++) {
  3022. struct fetch_worker *w = &fetch_workers[i];
  3023. w->pid = -1;
  3024. w->slot = i;
  3025. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3026. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3027. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3028. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3029. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3030. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3031. }
  3032. }
  3033. static void fetch_worker_stop(struct fetch_worker *w)
  3034. {
  3035. int i;
  3036. /* An abandoned image job leaves its node loadable again. */
  3037. if (w->busy && w->image_job && w->node < doc.nnode) {
  3038. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3039. doc.nodes[w->node].bg_img_index = -1;
  3040. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3041. doc.nodes[w->node].img_index = -1;
  3042. }
  3043. if (w->pid > 0) {
  3044. u_kill((unsigned int)w->pid);
  3045. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3046. u_sleep_ms(5);
  3047. /* Let the reaper close the socket before we reuse the slot. */
  3048. u_sleep_ms(10);
  3049. }
  3050. w->pid = -1;
  3051. w->busy = 0;
  3052. w->ready = 0;
  3053. w->image_job = 0;
  3054. if (w->req[0]) {
  3055. u_syscall1(SYS_UNLINK, (int)w->done);
  3056. u_syscall1(SYS_UNLINK, (int)w->meta);
  3057. u_syscall1(SYS_UNLINK, (int)w->body);
  3058. u_syscall1(SYS_UNLINK, (int)w->post);
  3059. u_syscall1(SYS_UNLINK, (int)w->req);
  3060. }
  3061. }
  3062. static void fetch_workers_stop_all(void)
  3063. {
  3064. int i;
  3065. for (i = 0; i < FETCH_WORKERS; i++)
  3066. fetch_worker_stop(&fetch_workers[i]);
  3067. }
  3068. /* Abandon the transfers of the current page but keep idle helpers and their
  3069. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3070. * because its response would otherwise land in a reused /share slot. */
  3071. static void fetch_workers_cancel_busy(void)
  3072. {
  3073. int i;
  3074. for (i = 0; i < FETCH_WORKERS; i++)
  3075. if (fetch_workers[i].busy)
  3076. fetch_worker_stop(&fetch_workers[i]);
  3077. }
  3078. static void fetch_workers_prepare_nav(const char *url)
  3079. {
  3080. int i;
  3081. (void)url;
  3082. for (i = 0; i < FETCH_WORKERS; i++) {
  3083. struct fetch_worker *w = &fetch_workers[i];
  3084. if (w->pid <= 0)
  3085. continue;
  3086. /* Only an in-flight transfer must be aborted. Idle helpers
  3087. * stay warm across origins: there are just FETCH_WORKERS of
  3088. * them, and uhttp_open drops the old connection when the
  3089. * next job is for another host. Killing and respawning all
  3090. * four on every navigation churned processes and sockets
  3091. * while images were still loading. */
  3092. if (w->busy)
  3093. fetch_worker_stop(w);
  3094. }
  3095. }
  3096. /* The browser is no longer the active window and no fetch is running: give
  3097. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3098. static void fetch_workers_stop_if_unfocused(void)
  3099. {
  3100. int i;
  3101. fetch_tty_drain();
  3102. if (ui.focused || page_loading || preload_active)
  3103. return;
  3104. for (i = 0; i < FETCH_WORKERS; i++)
  3105. if (fetch_workers[i].pid > 0) {
  3106. fetch_workers_stop_all();
  3107. return;
  3108. }
  3109. }
  3110. /* The helpers (and this process, since u_tty_create() rebinds our own
  3111. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3112. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3113. * a dozen TLS connections every helper hung in its next log line, so the
  3114. * following cross-origin navigation sat at "Loading..." until it timed out.
  3115. * Drain and discard it from every wait/poll loop. */
  3116. static void fetch_tty_drain(void)
  3117. {
  3118. char sink[512];
  3119. int i;
  3120. if (fetch_tty <= 0)
  3121. return;
  3122. for (i = 0; i < 16; i++)
  3123. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3124. break;
  3125. }
  3126. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3127. unsigned int errcap)
  3128. {
  3129. char arg[40];
  3130. unsigned int n = 0;
  3131. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3132. return 0;
  3133. w->pid = -1;
  3134. fetch_pool_init();
  3135. if (fetch_tty == -2) {
  3136. int t = u_tty_create();
  3137. fetch_tty = t > 0 ? t : 0;
  3138. }
  3139. s_append(arg, &n, "__serve ", sizeof(arg));
  3140. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3141. s_append(arg, &n, " ", sizeof(arg));
  3142. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3143. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3144. if (w->pid <= 0) {
  3145. w->pid = -1;
  3146. s_copy(err, "cannot start network helper", errcap);
  3147. return -1;
  3148. }
  3149. return 0;
  3150. }
  3151. static struct fetch_worker *fetch_worker_alloc(void)
  3152. {
  3153. int i;
  3154. fetch_pool_init();
  3155. for (i = 0; i < FETCH_WORKERS; i++)
  3156. if (!fetch_workers[i].busy)
  3157. return &fetch_workers[i];
  3158. return 0;
  3159. }
  3160. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3161. unsigned int cap, const char *method,
  3162. const char *ctype, const char *post,
  3163. unsigned int post_len, unsigned int node,
  3164. int bg, unsigned int dec_w,
  3165. unsigned int dec_h, char *err,
  3166. unsigned int errcap);
  3167. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3168. unsigned int cap, const char *post,
  3169. unsigned int post_len, unsigned int node,
  3170. int bg, char *err, unsigned int errcap)
  3171. {
  3172. /* A body pointer with no bytes is still a POST: the classic request
  3173. * line would turn it into a GET. */
  3174. if (post && !post_len)
  3175. return fetch_worker_submit_req(w, url, cap, "POST",
  3176. "application/x-www-form-urlencoded", post, 0, node,
  3177. bg, 0, 0, err, errcap);
  3178. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3179. node, bg, 0, 0, err, errcap);
  3180. }
  3181. /* Image job: ask the helper to decode at these display bounds as well. */
  3182. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3183. unsigned int cap, unsigned int node,
  3184. int bg, unsigned int dec_w,
  3185. unsigned int dec_h, char *err,
  3186. unsigned int errcap)
  3187. {
  3188. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3189. dec_w, dec_h, err, errcap);
  3190. }
  3191. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3192. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3193. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3194. unsigned int cap, const char *method,
  3195. const char *ctype, const char *post,
  3196. unsigned int post_len, unsigned int node,
  3197. int bg, unsigned int dec_w,
  3198. unsigned int dec_h, char *err,
  3199. unsigned int errcap)
  3200. {
  3201. static char req[BR_URL_MAX + 256];
  3202. unsigned int n = 0;
  3203. fetch_seq++;
  3204. if (!fetch_seq)
  3205. fetch_seq = 1;
  3206. w->seq = fetch_seq;
  3207. w->ready = 0;
  3208. w->image_job = 0;
  3209. w->retried = 0;
  3210. w->m.error = 0;
  3211. w->node = node;
  3212. w->bg = bg;
  3213. w->dec_w = dec_w;
  3214. w->dec_h = dec_h;
  3215. w->dec_retried = 0;
  3216. s_copy(w->url, url, sizeof(w->url));
  3217. s_append_dec(req, &n, w->seq, sizeof(req));
  3218. s_append(req, &n, " ", sizeof(req));
  3219. s_append_dec(req, &n, cap, sizeof(req));
  3220. s_append(req, &n, " ", sizeof(req));
  3221. if (dec_w || dec_h) {
  3222. s_append(req, &n, "D ", sizeof(req));
  3223. s_append_dec(req, &n, dec_w, sizeof(req));
  3224. s_append(req, &n, " ", sizeof(req));
  3225. s_append_dec(req, &n, dec_h, sizeof(req));
  3226. s_append(req, &n, " ", sizeof(req));
  3227. } else if (method) {
  3228. unsigned int k;
  3229. s_append(req, &n, "X ", sizeof(req));
  3230. s_append(req, &n, method, sizeof(req));
  3231. s_append(req, &n, " ", sizeof(req));
  3232. s_append_dec(req, &n, post_len, sizeof(req));
  3233. s_append(req, &n, " ", sizeof(req));
  3234. if (!ctype || !ctype[0])
  3235. s_append(req, &n, "-", sizeof(req));
  3236. /* One token on the request line: drop the spaces
  3237. * ("application/json; charset=utf-8" stays valid). */
  3238. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3239. if (ctype[k] != ' ')
  3240. req[n++] = ctype[k];
  3241. req[n] = '\0';
  3242. s_append(req, &n, " ", sizeof(req));
  3243. } else if (post_len) {
  3244. s_append(req, &n, "POST ", sizeof(req));
  3245. s_append_dec(req, &n, post_len, sizeof(req));
  3246. s_append(req, &n, " ", sizeof(req));
  3247. }
  3248. s_append(req, &n, url, sizeof(req));
  3249. s_append(req, &n, "\n", sizeof(req));
  3250. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3251. (int)post, (int)post_len) < 0) {
  3252. s_copy(err, "cannot queue form body", errcap);
  3253. return -1;
  3254. }
  3255. u_syscall1(SYS_UNLINK, (int)w->done);
  3256. u_syscall1(SYS_UNLINK, (int)w->meta);
  3257. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3258. s_copy(err, "cannot queue network request", errcap);
  3259. return -1;
  3260. }
  3261. if (fetch_worker_start(w, err, errcap) != 0)
  3262. return -1;
  3263. w->busy = 1;
  3264. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3265. return 0;
  3266. }
  3267. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3268. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3269. unsigned int errcap)
  3270. {
  3271. static char meta[BR_URL_MAX + 1024];
  3272. char *p;
  3273. int rn, mseq;
  3274. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3275. (int)(sizeof(meta) - 1));
  3276. if (rn <= 0) {
  3277. s_copy(err, "network helper failed", errcap);
  3278. return -1;
  3279. }
  3280. meta[rn] = '\0';
  3281. p = meta;
  3282. mseq = (int)meta_uint(&p);
  3283. if (mseq != (int)w->seq) {
  3284. s_copy(err, "stale network response", errcap);
  3285. return -1;
  3286. }
  3287. w->m.status = (int)meta_uint(&p);
  3288. w->m.error = (int)meta_uint(&p);
  3289. w->m.trunc = (int)meta_uint(&p);
  3290. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3291. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3292. meta_str(&p, w->m.final, sizeof(w->m.final));
  3293. w->m.len = meta_uint(&p);
  3294. w->m.open_ms = 0;
  3295. w->m.first_ms = 0;
  3296. w->m.total_ms = 0;
  3297. if (*p) {
  3298. w->m.open_ms = meta_uint(&p);
  3299. w->m.first_ms = meta_uint(&p);
  3300. w->m.total_ms = meta_uint(&p);
  3301. }
  3302. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3303. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3304. w->m.dec_err = 0;
  3305. if (*p) {
  3306. w->m.dw = meta_uint(&p);
  3307. w->m.dh = meta_uint(&p);
  3308. w->m.nw = meta_uint(&p);
  3309. w->m.nh = meta_uint(&p);
  3310. w->m.alpha = meta_uint(&p);
  3311. w->m.px_len = meta_uint(&p);
  3312. w->m.dec_err = (int)meta_uint(&p);
  3313. w->m.dec_ms = meta_uint(&p);
  3314. }
  3315. if (w->m.error) {
  3316. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3317. return -1;
  3318. }
  3319. w->ready = 1;
  3320. return 0;
  3321. }
  3322. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3323. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3324. unsigned int errcap)
  3325. {
  3326. static char done[24];
  3327. char *p;
  3328. int rn, mseq;
  3329. fetch_tty_drain();
  3330. if (!w->busy)
  3331. return -1;
  3332. if (w->ready)
  3333. return 1;
  3334. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3335. (int)(sizeof(done) - 1));
  3336. if (rn > 0) {
  3337. done[rn] = '\0';
  3338. p = done;
  3339. mseq = (int)meta_uint(&p);
  3340. if (mseq == (int)w->seq) {
  3341. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3342. fetch_worker_stop(w);
  3343. return -1;
  3344. }
  3345. return 1;
  3346. }
  3347. }
  3348. if (!u_alive((unsigned int)w->pid)) {
  3349. w->pid = -1;
  3350. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3351. w->retried = 1;
  3352. return 0;
  3353. }
  3354. s_copy(err, "network helper stopped", errcap);
  3355. fetch_worker_stop(w);
  3356. return -1;
  3357. }
  3358. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3359. s_copy(err, "network request timed out", errcap);
  3360. fetch_worker_stop(w);
  3361. return -1;
  3362. }
  3363. return 0;
  3364. }
  3365. /* Copy the completed body, inflating it if the server ignored our identity
  3366. * request. Mirrors the old fetch_remote body path. */
  3367. static int fetch_worker_read_body(struct fetch_worker *w,
  3368. unsigned char *plain,
  3369. unsigned int plaincap,
  3370. unsigned char *comp,
  3371. unsigned int compcap,
  3372. int *truncated, char *err,
  3373. unsigned int errcap)
  3374. {
  3375. int rv, zr, was_trunc;
  3376. if (contains_ci(w->m.encoding, "gzip") ||
  3377. contains_ci(w->m.encoding, "deflate")) {
  3378. unsigned int comp_len = 0, plen = 0;
  3379. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3380. (int)compcap);
  3381. if (rv < 0) {
  3382. s_copy(err, "empty response", errcap);
  3383. return -1;
  3384. }
  3385. comp_len = (unsigned int)rv;
  3386. if (comp_len < w->m.len) {
  3387. s_copy(err, "compressed response is too large", errcap);
  3388. return -1;
  3389. }
  3390. if (contains_ci(w->m.encoding, "deflate"))
  3391. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3392. &plen, 0, &was_trunc);
  3393. else
  3394. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3395. &plen, 1, &was_trunc);
  3396. if (zr != 0) {
  3397. s_copy(err, "compressed response is corrupt", errcap);
  3398. return -1;
  3399. }
  3400. *truncated = w->m.trunc || was_trunc;
  3401. return (int)plen;
  3402. }
  3403. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3404. if (rv < 0) {
  3405. s_copy(err, "empty response", errcap);
  3406. return -1;
  3407. }
  3408. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3409. return rv;
  3410. }
  3411. static void fetch_worker_release(struct fetch_worker *w)
  3412. {
  3413. u_syscall1(SYS_UNLINK, (int)w->done);
  3414. u_syscall1(SYS_UNLINK, (int)w->meta);
  3415. u_syscall1(SYS_UNLINK, (int)w->body);
  3416. u_syscall1(SYS_UNLINK, (int)w->post);
  3417. u_syscall1(SYS_UNLINK, (int)w->px);
  3418. u_syscall1(SYS_UNLINK, (int)w->req);
  3419. w->busy = 0;
  3420. w->ready = 0;
  3421. w->image_job = 0;
  3422. w->dec_w = 0;
  3423. w->dec_h = 0;
  3424. w->dec_retried = 0;
  3425. }
  3426. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3427. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3428. unsigned int errcap)
  3429. {
  3430. for (;;) {
  3431. int rv;
  3432. if (!fetch_wait_passive)
  3433. worker_wait_ui();
  3434. if (cancel_fetch || pending_action) {
  3435. fetch_workers_cancel_busy();
  3436. return FETCH_ABORT;
  3437. }
  3438. rv = fetch_worker_poll(w, err, errcap);
  3439. if (rv != 0)
  3440. return rv == 1 ? 0 : -1;
  3441. u_sleep_ms(10);
  3442. }
  3443. }
  3444. static int fetch_remote(const char *url, unsigned int cap,
  3445. const char *post, unsigned int post_len,
  3446. unsigned char *plain, unsigned int plaincap,
  3447. unsigned char *comp, unsigned int compcap,
  3448. struct fetch_meta *m, int *truncated,
  3449. char *err, unsigned int errcap)
  3450. {
  3451. struct fetch_worker *w = fetch_worker_alloc();
  3452. int rv;
  3453. fetch_last_error = 0;
  3454. if (!w) {
  3455. s_copy(err, "network busy", errcap);
  3456. return -1;
  3457. }
  3458. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3459. err, errcap) != 0) {
  3460. fetch_worker_release(w);
  3461. return -1;
  3462. }
  3463. rv = fetch_worker_wait(w, err, errcap);
  3464. if (rv == FETCH_ABORT) {
  3465. fetch_worker_release(w);
  3466. return FETCH_ABORT;
  3467. }
  3468. if (rv != 0) {
  3469. fetch_last_error = w->m.error;
  3470. fetch_worker_release(w);
  3471. return -1;
  3472. }
  3473. *m = w->m;
  3474. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3475. truncated, err, errcap);
  3476. fetch_worker_release(w);
  3477. if (rv >= 0 && (cancel_fetch || pending_action))
  3478. return FETCH_ABORT;
  3479. return rv;
  3480. }
  3481. static int fetch_worker_status(const struct fetch_worker *w)
  3482. {
  3483. return w->m.status;
  3484. }
  3485. /* fetch()/XHR through a helper: one request, the status and body come back
  3486. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3487. static int js_worker_http(const char *method, const char *url,
  3488. const char *ctype, const char *body,
  3489. unsigned int body_len, struct js_http_resp *r,
  3490. char *err, int errcap)
  3491. {
  3492. struct fetch_worker *w = fetch_worker_alloc();
  3493. unsigned char *plain;
  3494. int rv, tr = 0;
  3495. if (!w) {
  3496. s_copy(err, "network busy", (unsigned int)errcap);
  3497. return -1;
  3498. }
  3499. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3500. body_len, 0, 0, 0, 0, err,
  3501. (unsigned int)errcap) != 0) {
  3502. fetch_worker_release(w);
  3503. return -1;
  3504. }
  3505. fetch_wait_passive++;
  3506. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3507. fetch_wait_passive--;
  3508. if (rv != 0) {
  3509. if (rv == FETCH_ABORT)
  3510. s_copy(err, "page is navigating", (unsigned int)errcap);
  3511. fetch_worker_release(w);
  3512. return -1;
  3513. }
  3514. r->status = w->m.status;
  3515. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3516. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3517. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3518. if (!plain) {
  3519. fetch_worker_release(w);
  3520. s_copy(err, "out of memory", (unsigned int)errcap);
  3521. return -1;
  3522. }
  3523. if (w->m.len == 0) {
  3524. rv = 0; /* 204, an empty 200: no body file */
  3525. } else {
  3526. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3527. image_io_buf, BR_PAGE_COMP_MAX,
  3528. &tr, err, (unsigned int)errcap);
  3529. }
  3530. fetch_worker_release(w);
  3531. if (rv < 0) {
  3532. free(plain);
  3533. return -1;
  3534. }
  3535. plain[rv] = '\0';
  3536. r->body = (char *)plain;
  3537. r->len = (unsigned int)rv;
  3538. return 0;
  3539. }
  3540. /* ---- HTTP / file fetch ---- */
  3541. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3542. unsigned int *outlen, int *is_local, char *ctype,
  3543. unsigned int ctcap, char *final, unsigned int finalcap,
  3544. char *err, unsigned int errcap, int *truncated,
  3545. const char *post, unsigned int post_len)
  3546. {
  3547. unsigned char *buf;
  3548. unsigned int len;
  3549. int tr = 0;
  3550. int rv;
  3551. *out = 0;
  3552. *outlen = 0;
  3553. *truncated = 0;
  3554. if (final && finalcap)
  3555. final[0] = '\0';
  3556. if (ctype && ctcap)
  3557. ctype[0] = '\0';
  3558. if (url[0] == '/') {
  3559. char pathbuf[BR_URL_MAX];
  3560. const char *open_url = url;
  3561. unsigned int i = 0;
  3562. /* A local form GET keeps ?query in the address bar but the
  3563. * file lookup uses the path alone, like a real browser. */
  3564. while (url[i] && url[i] != '?' && url[i] != '#')
  3565. i++;
  3566. if (url[i]) {
  3567. s_copy(pathbuf, url, i + 1);
  3568. open_url = pathbuf;
  3569. }
  3570. buf = (unsigned char *)malloc(cap);
  3571. if (!buf) {
  3572. s_copy(err, "out of memory", errcap);
  3573. return -1;
  3574. }
  3575. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3576. if (rv < 0) {
  3577. free(buf);
  3578. s_copy(err, "file not found", errcap);
  3579. return -1;
  3580. }
  3581. *out = buf;
  3582. *outlen = (unsigned int)rv;
  3583. *is_local = 1;
  3584. if (ctype)
  3585. s_copy(ctype, "text/html", ctcap);
  3586. if (final)
  3587. s_copy(final, url, finalcap);
  3588. if ((unsigned int)rv == cap)
  3589. *truncated = 1;
  3590. return 0;
  3591. }
  3592. buf = (unsigned char *)malloc(cap);
  3593. if (!buf) {
  3594. s_copy(err, "out of memory", errcap);
  3595. return -1;
  3596. }
  3597. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3598. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3599. if (rv == FETCH_ABORT) {
  3600. free(buf);
  3601. return FETCH_ABORT;
  3602. }
  3603. if (rv < 0) {
  3604. free(buf);
  3605. return -1;
  3606. }
  3607. len = (unsigned int)rv;
  3608. if (len == 0) {
  3609. free(buf);
  3610. s_copy(err, "empty response", errcap);
  3611. return -1;
  3612. }
  3613. if (ctype)
  3614. s_copy(ctype, fetch_meta.ctype, ctcap);
  3615. if (final && fetch_meta.final[0])
  3616. s_copy(final, fetch_meta.final, finalcap);
  3617. *is_local = 0;
  3618. *out = buf;
  3619. *outlen = len;
  3620. *truncated = tr;
  3621. return 0;
  3622. }
  3623. /* Load every @font-face the parser registered. Local files go through
  3624. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3625. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3626. * to the built-in regular/bold/italic/mono set. */
  3627. static void load_font_faces(void)
  3628. {
  3629. unsigned int i;
  3630. memset(font_faces, 0, sizeof(font_faces));
  3631. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3632. i <= BR_MAX_FACES; i++) {
  3633. const char *url = br_font_face_url((int)i);
  3634. const char *base = br_font_face_base((int)i);
  3635. char abs[BR_URL_MAX];
  3636. if (!url || !url[0])
  3637. continue;
  3638. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3639. sizeof(abs)) != 0)
  3640. continue;
  3641. if (abs[0] == '/') {
  3642. font_faces[i - 1] = ufont_face_open_path(abs);
  3643. } else if (is_http(abs)) {
  3644. unsigned char *buf;
  3645. char err[64];
  3646. int rv, tr = 0;
  3647. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3648. if (!buf)
  3649. continue;
  3650. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3651. UFONT_MAX_FILE, image_io_buf,
  3652. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3653. err, sizeof(err));
  3654. if (rv > 0)
  3655. font_faces[i - 1] = ufont_face_open_mem(buf,
  3656. rv);
  3657. free(buf);
  3658. }
  3659. }
  3660. }
  3661. /* Remote scripts are cached under /share for the current boot, like the
  3662. * stylesheet cache, so reloads and later visits skip the network. */
  3663. static int script_cache_count;
  3664. static unsigned int script_cache_hash(const char *s)
  3665. {
  3666. unsigned int h = 2166136261u;
  3667. while (*s) {
  3668. h ^= (unsigned char)*s++;
  3669. h *= 16777619u;
  3670. }
  3671. return h;
  3672. }
  3673. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3674. {
  3675. unsigned int n = 0;
  3676. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3677. s_append_dec(out, &n, script_cache_hash(url), cap);
  3678. }
  3679. static void script_cache_clear(void)
  3680. {
  3681. struct sys_dirent d;
  3682. char path[96];
  3683. for (;;) {
  3684. int i, found = 0;
  3685. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3686. (int)&d) == 1; i++) {
  3687. unsigned int n = 0;
  3688. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3689. continue;
  3690. s_append(path, &n, "/share/", sizeof(path));
  3691. s_append(path, &n, d.name, sizeof(path));
  3692. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3693. return;
  3694. found = 1;
  3695. break;
  3696. }
  3697. if (!found)
  3698. break;
  3699. }
  3700. script_cache_count = 0;
  3701. }
  3702. static void script_cache_init(void)
  3703. {
  3704. struct sys_dirent d;
  3705. int i, count = 0;
  3706. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3707. (int)&d) == 1; i++)
  3708. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3709. count++;
  3710. if (count >= SCRIPT_CACHE_MAX) {
  3711. script_cache_clear();
  3712. return;
  3713. }
  3714. script_cache_count = count;
  3715. }
  3716. static int script_cache_get(const char *url, unsigned char **out,
  3717. unsigned int *outlen)
  3718. {
  3719. char path[96];
  3720. struct sys_stat st;
  3721. unsigned char *buf;
  3722. int rn;
  3723. script_cache_path(url, path, sizeof(path));
  3724. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3725. st.size >= SCRIPT_CACHE_FILE_MAX)
  3726. return 0;
  3727. buf = (unsigned char *)malloc(st.size + 1);
  3728. if (!buf)
  3729. return 0;
  3730. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3731. if (rn != (int)st.size) {
  3732. free(buf);
  3733. return 0;
  3734. }
  3735. buf[st.size] = '\0';
  3736. *out = buf;
  3737. *outlen = st.size;
  3738. return 1;
  3739. }
  3740. static void script_cache_put(const char *url, const unsigned char *data,
  3741. unsigned int len)
  3742. {
  3743. char path[96];
  3744. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3745. len >= SCRIPT_CACHE_FILE_MAX)
  3746. return;
  3747. script_cache_path(url, path, sizeof(path));
  3748. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3749. (int)len) >= 0)
  3750. script_cache_count++;
  3751. }
  3752. static int script_cache_has(const char *url)
  3753. {
  3754. char path[96];
  3755. struct sys_stat st;
  3756. script_cache_path(url, path, sizeof(path));
  3757. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3758. st.size < SCRIPT_CACHE_FILE_MAX;
  3759. }
  3760. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3761. static int fetch_script_text(const char *url, unsigned char **out,
  3762. unsigned int *outlen, char *err,
  3763. unsigned int errcap)
  3764. {
  3765. unsigned char *buf;
  3766. unsigned int len;
  3767. int local, truncated = 0;
  3768. char ctype[64], final[BR_URL_MAX];
  3769. int rv;
  3770. *out = 0;
  3771. *outlen = 0;
  3772. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3773. return 0;
  3774. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3775. sizeof(ctype), final, sizeof(final), err, errcap,
  3776. &truncated, 0, 0);
  3777. if (rv != 0)
  3778. return rv;
  3779. if (truncated || len >= BR_SCRIPT_MAX) {
  3780. free(buf);
  3781. s_copy(err, "script is too large", errcap);
  3782. return -1;
  3783. }
  3784. buf[len] = '\0';
  3785. if (!local)
  3786. script_cache_put(url, buf, len);
  3787. *out = buf;
  3788. *outlen = len;
  3789. return 0;
  3790. }
  3791. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3792. * the heap, so images must not allocate their file body from it as well. */
  3793. static int fetch_image(const char *url, unsigned int cap,
  3794. unsigned char **out, unsigned int *outlen,
  3795. char *err, unsigned int errcap)
  3796. {
  3797. unsigned int len;
  3798. int tr = 0;
  3799. int rv;
  3800. *out = 0;
  3801. *outlen = 0;
  3802. if (cap > BR_IMG_FILE_MAX)
  3803. cap = BR_IMG_FILE_MAX;
  3804. if (url[0] == '/') {
  3805. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3806. (int)cap);
  3807. if (rv < 0) {
  3808. s_copy(err, "file not found", errcap);
  3809. return -1;
  3810. }
  3811. *out = image_file_buf;
  3812. *outlen = (unsigned int)rv;
  3813. return 0;
  3814. }
  3815. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3816. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3817. if (rv == FETCH_ABORT)
  3818. return FETCH_ABORT;
  3819. if (rv < 0)
  3820. return -1;
  3821. len = (unsigned int)rv;
  3822. if (len == 0) {
  3823. s_copy(err, "empty image", errcap);
  3824. return -1;
  3825. }
  3826. *out = image_file_buf;
  3827. *outlen = len;
  3828. return 0;
  3829. }
  3830. /* Remote stylesheets are immutable enough for the current boot: keep
  3831. * successful responses under /share so a reload, a second visit or a fresh
  3832. * browser launch does not fetch the same five sheets over the network again.
  3833. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3834. static int css_cache_count;
  3835. static unsigned int css_cache_hash(const char *s)
  3836. {
  3837. unsigned int h = 2166136261u;
  3838. while (*s) {
  3839. h ^= (unsigned char)*s++;
  3840. h *= 16777619u;
  3841. }
  3842. return h;
  3843. }
  3844. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3845. {
  3846. unsigned int n = 0;
  3847. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3848. s_append_dec(out, &n, css_cache_hash(url), cap);
  3849. }
  3850. static void css_cache_clear(void)
  3851. {
  3852. struct sys_dirent d;
  3853. char path[96];
  3854. for (;;) {
  3855. int i, found = 0;
  3856. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3857. (int)&d) == 1; i++) {
  3858. unsigned int n = 0;
  3859. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3860. continue;
  3861. s_append(path, &n, "/share/", sizeof(path));
  3862. s_append(path, &n, d.name, sizeof(path));
  3863. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3864. return;
  3865. found = 1;
  3866. break;
  3867. }
  3868. if (!found)
  3869. break;
  3870. }
  3871. css_cache_count = 0;
  3872. }
  3873. static void css_cache_init(void)
  3874. {
  3875. struct sys_dirent d;
  3876. int i, count = 0;
  3877. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3878. (int)&d) == 1; i++)
  3879. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3880. count++;
  3881. if (count >= CSS_CACHE_MAX) {
  3882. css_cache_clear();
  3883. return;
  3884. }
  3885. css_cache_count = count;
  3886. }
  3887. static int css_cache_get(const char *url, unsigned char **out,
  3888. unsigned int *outlen)
  3889. {
  3890. char path[96];
  3891. int rn;
  3892. css_cache_path(url, path, sizeof(path));
  3893. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3894. (int)CSS_CACHE_FILE_MAX);
  3895. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3896. return 0;
  3897. *out = image_io_buf;
  3898. *outlen = (unsigned int)rn;
  3899. return 1;
  3900. }
  3901. static void css_cache_put(const char *url, const unsigned char *data,
  3902. unsigned int len)
  3903. {
  3904. char path[96];
  3905. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3906. len >= CSS_CACHE_FILE_MAX)
  3907. return;
  3908. css_cache_path(url, path, sizeof(path));
  3909. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3910. (int)len) >= 0)
  3911. css_cache_count++;
  3912. }
  3913. static int css_cache_has(const char *url)
  3914. {
  3915. char path[96];
  3916. struct sys_stat st;
  3917. css_cache_path(url, path, sizeof(path));
  3918. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3919. st.size < CSS_CACHE_FILE_MAX;
  3920. }
  3921. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3922. * immediately, so it does not need the page heap; this leaves the heap for
  3923. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3924. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3925. char *err, unsigned int errcap)
  3926. {
  3927. unsigned int len;
  3928. int tr = 0;
  3929. int rv;
  3930. *out = 0;
  3931. *outlen = 0;
  3932. if (url[0] == '/') {
  3933. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3934. (int)BR_CSS_MAX);
  3935. if (rv < 0) {
  3936. s_copy(err, "stylesheet not found", errcap);
  3937. return -1;
  3938. }
  3939. *out = image_io_buf;
  3940. *outlen = (unsigned int)rv;
  3941. return 0;
  3942. }
  3943. if (css_cache_get(url, out, outlen))
  3944. return 0;
  3945. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3946. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3947. &fetch_meta, &tr, err, errcap);
  3948. if (rv == FETCH_ABORT)
  3949. return FETCH_ABORT;
  3950. if (rv < 0)
  3951. return -1;
  3952. len = (unsigned int)rv;
  3953. if (len == 0) {
  3954. s_copy(err, "empty stylesheet", errcap);
  3955. return -1;
  3956. }
  3957. *out = image_io_buf;
  3958. *outlen = len;
  3959. css_cache_put(url, image_io_buf, len);
  3960. return 0;
  3961. }
  3962. static void redraw_now(void);
  3963. static char error_page[1024];
  3964. static void show_error(const char *title, const char *detail)
  3965. {
  3966. char *page = error_page;
  3967. unsigned int n = 0;
  3968. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3969. s_append(page, &n, title, sizeof(error_page));
  3970. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3971. {
  3972. const char *p = detail;
  3973. while (*p && n + 1 < sizeof(error_page)) {
  3974. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3975. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3976. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3977. else page[n++] = *p;
  3978. p++;
  3979. }
  3980. }
  3981. page[n] = '\0';
  3982. s_append(page, &n, "</p><p>", sizeof(error_page));
  3983. s_append(page, &n, page_url, sizeof(error_page));
  3984. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3985. sizeof(error_page));
  3986. br_parse(&doc, page, n);
  3987. layout_valid = 0;
  3988. preload_active = 0;
  3989. preload_pending = 0;
  3990. preload_wait = 0;
  3991. fetch_workers_cancel_busy();
  3992. s_copy(page_title, title, sizeof(page_title));
  3993. page_loading = 0;
  3994. set_status(title, 1, 0);
  3995. ngui_invalidate(&ui);
  3996. }
  3997. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3998. unsigned int node)
  3999. {
  4000. if (image_count >= BR_MAX_IMAGES)
  4001. return -1;
  4002. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4003. return -1;
  4004. doc.nodes[node].img_index = 0;
  4005. image_count = 1;
  4006. return 0;
  4007. }
  4008. static int ancestor_is(unsigned int node, unsigned int tag)
  4009. {
  4010. unsigned int p = doc.nodes[node].parent;
  4011. while (p) {
  4012. if (doc.nodes[p].tag == tag)
  4013. return 1;
  4014. p = doc.nodes[p].parent;
  4015. }
  4016. return 0;
  4017. }
  4018. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4019. * parallel but parsed in document order, so the cascade is unchanged. */
  4020. static int load_stylesheets(void)
  4021. {
  4022. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4023. static unsigned char remote[BR_MAX_SHEETS];
  4024. struct fetch_worker *slot[BR_MAX_SHEETS];
  4025. unsigned int i, n = 0, next = 0, k;
  4026. char err[64];
  4027. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4028. struct br_node *nd = &doc.nodes[i];
  4029. const char *rel, *href;
  4030. char url[BR_URL_MAX];
  4031. int dup = 0;
  4032. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4033. continue;
  4034. rel = br_rel(&doc, i);
  4035. if (!contains_ci(rel, "stylesheet"))
  4036. continue;
  4037. href = br_href(&doc, i);
  4038. if (!href[0])
  4039. continue;
  4040. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4041. continue;
  4042. for (k = 0; k < n; k++)
  4043. if (s_eq(urls[k], url)) {
  4044. dup = 1;
  4045. break;
  4046. }
  4047. if (dup)
  4048. continue;
  4049. s_copy(urls[n], url, BR_URL_MAX);
  4050. remote[n] = url[0] != '/' && !css_cache_has(url);
  4051. n++;
  4052. }
  4053. for (i = 0; i < BR_MAX_SHEETS; i++)
  4054. slot[i] = 0;
  4055. /* Start as many remote sheets as there are free workers. */
  4056. for (; next < n; next++) {
  4057. struct fetch_worker *w;
  4058. if (!remote[next])
  4059. continue;
  4060. w = fetch_worker_alloc();
  4061. if (!w)
  4062. break;
  4063. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4064. err, sizeof(err)) != 0) {
  4065. fetch_worker_release(w);
  4066. remote[next] = 0;
  4067. continue;
  4068. }
  4069. slot[next] = w;
  4070. }
  4071. for (i = 0; i < n; i++) {
  4072. unsigned char *data = 0;
  4073. unsigned int len = 0;
  4074. int rv;
  4075. if (!remote[i]) {
  4076. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4077. if (rv == FETCH_ABORT) {
  4078. fetch_workers_stop_all();
  4079. return FETCH_ABORT;
  4080. }
  4081. if (rv != 0 || !len)
  4082. continue;
  4083. } else {
  4084. struct fetch_worker *w = slot[i];
  4085. int tr = 0;
  4086. if (!w) {
  4087. w = fetch_worker_alloc();
  4088. if (!w) {
  4089. rv = -1;
  4090. goto css_failed;
  4091. }
  4092. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4093. 0, 0, 0, 0, err,
  4094. sizeof(err)) != 0) {
  4095. fetch_worker_release(w);
  4096. remote[i] = 0;
  4097. if (i == next)
  4098. next++;
  4099. continue;
  4100. }
  4101. slot[i] = w;
  4102. if (i == next)
  4103. next++;
  4104. }
  4105. rv = fetch_worker_wait(w, err, sizeof(err));
  4106. if (rv == FETCH_ABORT) {
  4107. fetch_workers_stop_all();
  4108. return FETCH_ABORT;
  4109. }
  4110. if (rv == 0)
  4111. rv = fetch_worker_read_body(w, image_io_buf,
  4112. BR_CSS_MAX,
  4113. image_io_buf + BR_CSS_MAX,
  4114. BR_CSS_COMP_MAX, &tr,
  4115. err, sizeof(err));
  4116. else
  4117. rv = -1;
  4118. fetch_worker_release(w);
  4119. slot[i] = 0;
  4120. /* Refill the worker window before parsing this sheet. */
  4121. for (; next < n; next++) {
  4122. struct fetch_worker *nw;
  4123. if (!remote[next])
  4124. continue;
  4125. nw = fetch_worker_alloc();
  4126. if (!nw)
  4127. break;
  4128. if (fetch_worker_submit(nw, urls[next],
  4129. BR_CSS_MAX, 0, 0, 0, 0,
  4130. err, sizeof(err)) != 0) {
  4131. fetch_worker_release(nw);
  4132. remote[next] = 0;
  4133. continue;
  4134. }
  4135. slot[next] = nw;
  4136. }
  4137. css_failed:
  4138. if (rv <= 0) {
  4139. /* One synchronous retry: a dropped sheet leaves the
  4140. * whole page unstyled (seen intermittently on
  4141. * arstechnica's CDN). */
  4142. u_puts("[css] retry ");
  4143. u_puts(urls[i]);
  4144. u_puts(": ");
  4145. u_puts(err[0] ? err : "no worker/empty body");
  4146. u_putc('\n');
  4147. err[0] = '\0';
  4148. rv = fetch_css(urls[i], &data, &len, err,
  4149. sizeof(err));
  4150. if (rv == FETCH_ABORT) {
  4151. fetch_workers_stop_all();
  4152. return FETCH_ABORT;
  4153. }
  4154. if (rv != 0 || !len) {
  4155. u_puts("[css] failed: ");
  4156. u_puts(err);
  4157. u_putc('\n');
  4158. continue;
  4159. }
  4160. } else {
  4161. len = (unsigned int)rv;
  4162. data = image_io_buf;
  4163. css_cache_put(urls[i], data, len);
  4164. }
  4165. }
  4166. if (len) {
  4167. br_set_font_base(urls[i]);
  4168. br_parse_css_text(&doc, (const char *)data, len);
  4169. }
  4170. }
  4171. br_set_font_base(page_url);
  4172. br_parse_inline_css(&doc);
  4173. load_font_faces();
  4174. br_reset_styles(&doc);
  4175. layout_valid = 0;
  4176. return 0;
  4177. }
  4178. static void preload_begin(void)
  4179. {
  4180. preload_active = 1;
  4181. preload_pending = 0;
  4182. preload_wait = 1;
  4183. preload_max_jobs = FETCH_WORKERS;
  4184. preload_node = 0;
  4185. preload_loaded = 0;
  4186. preload_scroll = 0;
  4187. img_stat_start = u_ticks_ms();
  4188. img_stat_wall = 0;
  4189. img_stat_net = img_stat_open = img_stat_first = 0;
  4190. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4191. img_stat_paint = img_stat_reflow = 0;
  4192. img_stat_bytes = 0;
  4193. img_stat_n = 0;
  4194. img_stat_log_len = 0;
  4195. if (img_stat_log[0])
  4196. img_stat_log[0] = '\0';
  4197. img_repaint_ms = 0;
  4198. img_repaint_pending = 0;
  4199. }
  4200. /* Styles are computed top-down during layout, but images inside a hidden
  4201. * menu/carousel are never visited and keep img_top == 0. Without this check
  4202. * the preloader walks the DOM in node order and spends the whole image
  4203. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4204. static struct br_style base_style(void);
  4205. static int node_hidden(unsigned int node)
  4206. {
  4207. unsigned int path[32], n = 0, p = node, i;
  4208. struct br_style st, parent;
  4209. while (p && n < sizeof(path) / sizeof(path[0])) {
  4210. path[n++] = p;
  4211. p = doc.nodes[p].parent;
  4212. }
  4213. /* Node 0 is the <html> element when the page starts with one: it
  4214. * is an ancestor too. Styles are cached per node, so the chain
  4215. * must start from the same base as style_for_node(); seeding it
  4216. * with a zeroed style left <body> cached with black text and no
  4217. * line-height once an image job ran (docs.cloudron.io). */
  4218. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4219. doc.nodes[0].type == BR_NODE_ELEM &&
  4220. doc.nodes[0].tag == BR_TAG_HTML &&
  4221. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4222. path[n++] = 0;
  4223. parent = base_style();
  4224. for (i = n; i > 0; i--) {
  4225. br_style_for(&doc, path[i - 1], &parent, &st);
  4226. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4227. st.opacity_hidden)
  4228. return 1;
  4229. parent = st;
  4230. }
  4231. return 0;
  4232. }
  4233. static struct br_style base_style(void);
  4234. static int style_width_px(const struct br_style *st, int base);
  4235. static int style_height_px(const struct br_style *st, int base);
  4236. static void style_for_node(unsigned int node, struct br_style *out)
  4237. {
  4238. unsigned int p = doc.nodes[node].parent;
  4239. struct br_style parent;
  4240. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4241. * starts with one (see root_style()), but also the parent field of a
  4242. * detached subtree root. */
  4243. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4244. doc.nodes[0].tag == BR_TAG_HTML &&
  4245. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4246. style_for_node(p, &parent);
  4247. br_style_for(&doc, node, &parent, out);
  4248. } else {
  4249. parent = base_style();
  4250. br_style_for(&doc, node, &parent, out);
  4251. }
  4252. }
  4253. /* ---- parallel image preloading ---- *
  4254. *
  4255. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4256. * preload_step() only starts jobs and harvests completed ones; the browser
  4257. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4258. */
  4259. static int preload_active_jobs(void)
  4260. {
  4261. int i, n = 0;
  4262. for (i = 0; i < FETCH_WORKERS; i++)
  4263. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4264. n++;
  4265. return n;
  4266. }
  4267. static void preload_job_error(struct fetch_worker *w)
  4268. {
  4269. if (w->node < doc.nnode) {
  4270. if (w->bg)
  4271. doc.nodes[w->node].bg_img_index = -2;
  4272. else
  4273. doc.nodes[w->node].img_index = -2;
  4274. image_repaint();
  4275. }
  4276. }
  4277. /* Is the image's box anywhere near the visible page? A decode below the
  4278. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4279. * so it does not need a repaint. top/h come from the last layout; treat an
  4280. * unknown box as visible to stay safe. */
  4281. static int image_preload_visible(unsigned int node, int bg)
  4282. {
  4283. int top, h, scroll;
  4284. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4285. return 1;
  4286. if (bg) {
  4287. top = (int)block_top[node];
  4288. h = (int)block_h[node];
  4289. } else {
  4290. top = (int)img_top[node];
  4291. h = (int)img_h[node];
  4292. }
  4293. if (!top && !h)
  4294. return 1;
  4295. scroll = (int)page_scroll.offset;
  4296. if (top > scroll + page_rect.h + 160)
  4297. return 0;
  4298. if (top + h + 160 < scroll)
  4299. return 0;
  4300. return 1;
  4301. }
  4302. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4303. * decode_image_data applies one scale to both axes so the aspect ratio is
  4304. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4305. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4306. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4307. {
  4308. struct br_style st;
  4309. struct br_node *nd;
  4310. unsigned int p;
  4311. int cw, w = 0, h = 0;
  4312. *out_w = *out_h = 0;
  4313. if (node >= doc.nnode)
  4314. return;
  4315. nd = &doc.nodes[node];
  4316. style_for_node(node, &st);
  4317. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4318. p = doc.nodes[node].parent;
  4319. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4320. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4321. cw = layout_boxes[p].w;
  4322. if (st.width_kind)
  4323. w = style_width_px(&st, cw);
  4324. else if (nd->width_attr)
  4325. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4326. (int)nd->width_attr;
  4327. if (st.height_kind)
  4328. h = style_height_px(&st, cw);
  4329. else if (nd->height_attr)
  4330. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4331. (int)nd->height_attr;
  4332. if (st.max_width_kind) {
  4333. int mw = st.max_width_kind == 3 ?
  4334. cw * st.max_width_calc_pct / 100 +
  4335. st.max_width_calc_px :
  4336. st.max_width_kind == 2 ?
  4337. cw * (int)st.max_width / 100 :
  4338. (int)st.max_width;
  4339. if (mw > 0 && (w == 0 || w > mw))
  4340. w = mw;
  4341. }
  4342. if (st.max_height_kind) {
  4343. int mh = st.max_height_kind == 3 ?
  4344. cw * st.max_height_calc_pct / 100 +
  4345. st.max_height_calc_px :
  4346. st.max_height_kind == 2 ?
  4347. cw * (int)st.max_height / 100 :
  4348. (int)st.max_height;
  4349. if (mh > 0 && (h == 0 || h > mh))
  4350. h = mh;
  4351. }
  4352. if (w > BR_IMG_LAYOUT_W)
  4353. w = BR_IMG_LAYOUT_W;
  4354. if (h > 4096)
  4355. h = 4096;
  4356. if (w < 0)
  4357. w = 0;
  4358. if (h < 0)
  4359. h = 0;
  4360. *out_w = w;
  4361. *out_h = h;
  4362. }
  4363. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4364. {
  4365. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4366. * same source reuses it (heise repeats one comment icon 85 times).
  4367. * Backgrounds are scaled to their box and are not shared. */
  4368. images[image_count].url_hash =
  4369. !bg && url ? script_cache_hash(url) | 1u : 0;
  4370. if (bg)
  4371. doc.nodes[node].bg_img_index = (short)image_count;
  4372. else
  4373. doc.nodes[node].img_index = (short)image_count;
  4374. image_count++;
  4375. preload_loaded++;
  4376. /* A background bitmap never changes its box, so keep the (expensive)
  4377. * measured layout and only repaint the pixels. */
  4378. if (bg)
  4379. page_cache_valid = 0;
  4380. else
  4381. layout_valid = 0;
  4382. if (image_preload_visible(node, bg))
  4383. image_repaint();
  4384. }
  4385. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4386. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4387. * on the UI thread instead of a decode. */
  4388. static int preload_store_helper(unsigned int node, int bg,
  4389. unsigned char *px, unsigned int pxlen,
  4390. unsigned int dw, unsigned int dh,
  4391. int alpha, unsigned int nw, unsigned int nh,
  4392. const char *url)
  4393. {
  4394. struct br_image *bi;
  4395. unsigned int npx;
  4396. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4397. dw > 4096 || dh > 4096) {
  4398. free(px);
  4399. return -1;
  4400. }
  4401. npx = dw * dh;
  4402. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4403. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4404. free(px);
  4405. return -1;
  4406. }
  4407. bi = &images[image_count];
  4408. bi->img.format = 0;
  4409. bi->img.w = dw;
  4410. bi->img.h = dh;
  4411. bi->img.px = (unsigned short *)px;
  4412. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4413. bi->img.flags = 0;
  4414. bi->native_w = nw ? (int)nw : (int)dw;
  4415. bi->native_h = nh ? (int)nh : (int)dh;
  4416. bi->state = 1;
  4417. image_pixels += npx;
  4418. preload_accept_image(node, bg, url);
  4419. return 0;
  4420. }
  4421. static void preload_decode(unsigned int node, int bg,
  4422. const unsigned char *data, unsigned int len,
  4423. const char *url)
  4424. {
  4425. int fit_w = 0, fit_h = 0;
  4426. if (image_count >= BR_MAX_IMAGES) {
  4427. if (bg)
  4428. doc.nodes[node].bg_img_index = -2;
  4429. else
  4430. doc.nodes[node].img_index = -2;
  4431. return;
  4432. }
  4433. if (!bg)
  4434. image_fit_size(node, &fit_w, &fit_h);
  4435. if (decode_image_data(data, len, &images[image_count],
  4436. bg && node < BR_MAX_NODES &&
  4437. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4438. bg && node < BR_MAX_NODES &&
  4439. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4440. fit_w, fit_h) == 0) {
  4441. preload_accept_image(node, bg, url);
  4442. } else {
  4443. if (bg)
  4444. doc.nodes[node].bg_img_index = -2;
  4445. else
  4446. doc.nodes[node].img_index = -2;
  4447. layout_valid = 0;
  4448. }
  4449. if (image_preload_visible(node, bg))
  4450. image_repaint();
  4451. }
  4452. /* ---- data: URLs ----
  4453. *
  4454. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4455. * (the caller frees them). The payload is percent-decoded, then base64-
  4456. * decoded when the header says so. Infima's menu chevron and many icon
  4457. * fonts' fallbacks are inline SVGs written this way. */
  4458. static int b64_val(int c)
  4459. {
  4460. if (c >= 'A' && c <= 'Z') return c - 'A';
  4461. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4462. if (c >= '0' && c <= '9') return c - '0' + 52;
  4463. if (c == '+' || c == '-') return 62;
  4464. if (c == '/' || c == '_') return 63;
  4465. return -1;
  4466. }
  4467. static int hex_val(int c)
  4468. {
  4469. if (c >= '0' && c <= '9') return c - '0';
  4470. c |= 32;
  4471. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4472. return -1;
  4473. }
  4474. static int data_url_decode(const char *url, unsigned char **out,
  4475. unsigned int *out_len)
  4476. {
  4477. const char *comma, *p;
  4478. unsigned int n = 0, len, i;
  4479. unsigned char *buf;
  4480. int base64 = 0;
  4481. *out = 0;
  4482. *out_len = 0;
  4483. if (!starts_with(url, "data:"))
  4484. return -1;
  4485. comma = url + 5;
  4486. while (*comma && *comma != ',')
  4487. comma++;
  4488. if (!*comma)
  4489. return -1;
  4490. for (p = url + 5; p + 7 <= comma; p++)
  4491. if (!strncmp(p, ";base64", 7))
  4492. base64 = 1;
  4493. len = s_len(comma + 1);
  4494. buf = (unsigned char *)malloc(len + 1);
  4495. if (!buf)
  4496. return -1;
  4497. for (i = 0, p = comma + 1; i < len; i++) {
  4498. int c = (unsigned char)p[i];
  4499. if (c == '%' && i + 2 < len &&
  4500. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4501. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4502. i += 2;
  4503. }
  4504. buf[n++] = (unsigned char)c;
  4505. }
  4506. if (base64) {
  4507. unsigned int acc = 0, o = 0;
  4508. int bits = 0;
  4509. for (i = 0; i < n; i++) {
  4510. int v = b64_val(buf[i]);
  4511. if (v < 0)
  4512. continue; /* padding, whitespace */
  4513. acc = (acc << 6) | (unsigned int)v;
  4514. bits += 6;
  4515. if (bits >= 8) {
  4516. bits -= 8;
  4517. buf[o++] = (unsigned char)(acc >> bits);
  4518. }
  4519. }
  4520. n = o;
  4521. }
  4522. buf[n] = 0;
  4523. *out = buf;
  4524. *out_len = n;
  4525. return 0;
  4526. }
  4527. static unsigned int data_img_key(const char *url, int w, int h)
  4528. {
  4529. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4530. ((unsigned int)h * 40503u)) | 1u;
  4531. }
  4532. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4533. * rasterized at that size), decoding it on first use; -1 on failure.
  4534. * Decoded bitmaps are found again through url_hash, which is distinct
  4535. * from the <img> sharing hash because it mixes in the size. */
  4536. static int data_url_image(const char *url, int w, int h)
  4537. {
  4538. unsigned int key, len;
  4539. unsigned char *data;
  4540. int i;
  4541. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4542. return -1;
  4543. key = data_img_key(url, w, h);
  4544. for (i = 0; i < image_count; i++)
  4545. if (images[i].state == 1 && images[i].url_hash == key)
  4546. return i;
  4547. for (i = 0; i < data_img_nfail; i++)
  4548. if (data_img_fail[i] == key)
  4549. return -1;
  4550. if (image_count < BR_MAX_IMAGES &&
  4551. data_url_decode(url, &data, &len) == 0) {
  4552. int r = decode_image_data(data, len, &images[image_count],
  4553. w, h, w, h);
  4554. free(data);
  4555. if (r == 0) {
  4556. images[image_count].url_hash = key;
  4557. return image_count++;
  4558. }
  4559. }
  4560. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4561. data_img_fail[data_img_nfail++] = key;
  4562. return -1;
  4563. }
  4564. /* A local file image bypasses the helpers: count its decode so a page opened
  4565. * from /share or /data still produces the same timing breakdown. */
  4566. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4567. {
  4568. img_stat_n++;
  4569. img_stat_bytes += bytes;
  4570. img_stat_io += io_ms;
  4571. if (image_count > before) {
  4572. struct br_image *bi = &images[image_count - 1];
  4573. img_stat_dec += img_last_dec_ms;
  4574. img_stat_scale += img_last_scale_ms;
  4575. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4576. unsigned int n = img_stat_log_len;
  4577. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4578. s_append_dec(img_stat_log, &n, bytes,
  4579. sizeof(img_stat_log));
  4580. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4581. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4582. sizeof(img_stat_log));
  4583. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4584. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4585. sizeof(img_stat_log));
  4586. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4587. s_append_dec(img_stat_log, &n,
  4588. (unsigned int)bi->native_w,
  4589. sizeof(img_stat_log));
  4590. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4591. s_append_dec(img_stat_log, &n,
  4592. (unsigned int)bi->native_h,
  4593. sizeof(img_stat_log));
  4594. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4595. s_append_dec(img_stat_log, &n, bi->img.w,
  4596. sizeof(img_stat_log));
  4597. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4598. s_append_dec(img_stat_log, &n, bi->img.h,
  4599. sizeof(img_stat_log));
  4600. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4601. s_append_dec(img_stat_log, &n,
  4602. bi->img.alpha ? 1u : 0u,
  4603. sizeof(img_stat_log));
  4604. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4605. img_stat_log_len = n;
  4606. }
  4607. }
  4608. }
  4609. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4610. static int preload_finish_worker(struct fetch_worker *w)
  4611. {
  4612. char err[64];
  4613. int rv, tr = 0;
  4614. unsigned int t0, io_ms;
  4615. int before;
  4616. int used_px = 0;
  4617. rv = fetch_worker_poll(w, err, sizeof(err));
  4618. if (rv < 0) {
  4619. /* A helper from an older pack does not understand the image
  4620. * decode request; retry once without it and decode in-process. */
  4621. if (w->image_job && w->dec_w && !w->dec_retried &&
  4622. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4623. 0, 0, 0, 0, w->node, w->bg,
  4624. 0, 0, err, sizeof(err)) == 0) {
  4625. w->image_job = 1;
  4626. w->dec_retried = 1;
  4627. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4628. return 0;
  4629. }
  4630. preload_job_error(w);
  4631. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4632. unsigned int n = img_stat_log_len;
  4633. char u[48];
  4634. s_copy(u, w->url, sizeof(u));
  4635. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4636. s_append(img_stat_log, &n, " error\n",
  4637. sizeof(img_stat_log));
  4638. img_stat_log_len = n;
  4639. }
  4640. img_stat_n++;
  4641. fetch_worker_release(w);
  4642. return 1;
  4643. }
  4644. if (rv == 0)
  4645. return 0;
  4646. t0 = u_ticks_ms();
  4647. rv = -1;
  4648. before = image_count;
  4649. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4650. w->m.px_len <= 8u * 1024u * 1024u) {
  4651. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4652. int pr = -1;
  4653. if (px)
  4654. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4655. (int)w->m.px_len);
  4656. if (pr == (int)w->m.px_len) {
  4657. if (preload_store_helper(w->node, w->bg, px,
  4658. w->m.px_len, w->m.dw,
  4659. w->m.dh, (int)w->m.alpha,
  4660. w->m.nw, w->m.nh,
  4661. w->url) == 0) {
  4662. rv = (int)w->m.len;
  4663. img_last_dec_ms = w->m.dec_ms;
  4664. img_last_scale_ms = 0;
  4665. used_px = 1;
  4666. } else {
  4667. px = 0; /* the helper freed it */
  4668. }
  4669. }
  4670. if (px && !(pr == (int)w->m.px_len))
  4671. free(px);
  4672. }
  4673. io_ms = u_ticks_ms() - t0;
  4674. if (rv < 0) {
  4675. t0 = u_ticks_ms();
  4676. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4677. image_comp_buf, BR_IMG_FILE_MAX,
  4678. &tr, err, sizeof(err));
  4679. io_ms += u_ticks_ms() - t0;
  4680. before = image_count;
  4681. if (rv >= 0)
  4682. preload_decode(w->node, w->bg, image_file_buf,
  4683. (unsigned int)rv, w->url);
  4684. else
  4685. preload_job_error(w);
  4686. }
  4687. img_stat_n++;
  4688. img_stat_net += w->m.total_ms;
  4689. img_stat_open += w->m.open_ms;
  4690. img_stat_first += w->m.first_ms;
  4691. img_stat_io += io_ms;
  4692. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4693. img_stat_dec += w->m.dec_ms;
  4694. if (rv >= 0 && !used_px) {
  4695. img_stat_dec += img_last_dec_ms;
  4696. img_stat_scale += img_last_scale_ms;
  4697. }
  4698. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4699. unsigned int n = img_stat_log_len;
  4700. char u[48];
  4701. s_copy(u, w->url, sizeof(u));
  4702. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4703. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4704. s_append_dec(img_stat_log, &n,
  4705. rv > 0 ? (unsigned int)rv : 0,
  4706. sizeof(img_stat_log));
  4707. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4708. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4709. sizeof(img_stat_log));
  4710. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4711. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4712. sizeof(img_stat_log));
  4713. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4714. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4715. sizeof(img_stat_log));
  4716. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4717. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4718. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4719. s_append_dec(img_stat_log, &n,
  4720. rv >= 0 ? img_last_dec_ms : 0,
  4721. sizeof(img_stat_log));
  4722. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4723. s_append_dec(img_stat_log, &n,
  4724. rv >= 0 ? img_last_scale_ms : 0,
  4725. sizeof(img_stat_log));
  4726. if (image_count > before) {
  4727. struct br_image *bi = &images[image_count - 1];
  4728. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4729. s_append_dec(img_stat_log, &n,
  4730. (unsigned int)bi->native_w,
  4731. sizeof(img_stat_log));
  4732. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4733. s_append_dec(img_stat_log, &n,
  4734. (unsigned int)bi->native_h,
  4735. sizeof(img_stat_log));
  4736. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4737. s_append_dec(img_stat_log, &n, bi->img.w,
  4738. sizeof(img_stat_log));
  4739. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4740. s_append_dec(img_stat_log, &n, bi->img.h,
  4741. sizeof(img_stat_log));
  4742. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4743. s_append_dec(img_stat_log, &n,
  4744. bi->img.alpha ? 1u : 0u,
  4745. sizeof(img_stat_log));
  4746. }
  4747. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4748. img_stat_log_len = n;
  4749. }
  4750. fetch_worker_release(w);
  4751. return 1;
  4752. }
  4753. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4754. * the number of jobs started. */
  4755. static int preload_fill_jobs(void)
  4756. {
  4757. int started = 0;
  4758. char err[64];
  4759. while (preload_active && preload_node < doc.nnode) {
  4760. unsigned int i = preload_node;
  4761. struct br_node *nd = &doc.nodes[i];
  4762. const char *src;
  4763. char url[BR_URL_MAX];
  4764. struct fetch_worker *w;
  4765. if (preload_active_jobs() >= preload_max_jobs)
  4766. break;
  4767. if (nd->type != BR_NODE_ELEM) {
  4768. preload_node++;
  4769. continue;
  4770. }
  4771. if (nd->tag != BR_TAG_IMG) {
  4772. if (nd->bg_img_index == -1) {
  4773. struct br_style bs;
  4774. style_for_node(i, &bs);
  4775. if (bs.display != BR_DISPLAY_NONE &&
  4776. !bs.vis_hidden && bs.bg_image) {
  4777. const char *bsrc =
  4778. br_bg_image_url(bs.bg_image - 1);
  4779. /* Lazy like <img>: a background box
  4780. * below the viewport (or not laid
  4781. * out yet) waits for the next scan. */
  4782. if (bsrc[0] &&
  4783. (!layout_boxes[i].valid ||
  4784. block_top[i] >
  4785. (unsigned int)(page_scroll.offset +
  4786. page_rect.h + 160))) {
  4787. preload_pending = 1;
  4788. preload_node++;
  4789. continue;
  4790. }
  4791. if (starts_with(bsrc, "data:")) {
  4792. /* Inline image: decode now,
  4793. * no fetch helper. */
  4794. unsigned char *data;
  4795. unsigned int len;
  4796. preload_node = i + 1;
  4797. if (data_url_decode(bsrc, &data,
  4798. &len) == 0) {
  4799. preload_decode(i, 1, data,
  4800. len, 0);
  4801. free(data);
  4802. } else {
  4803. nd->bg_img_index = -2;
  4804. }
  4805. continue;
  4806. }
  4807. if (bsrc[0] &&
  4808. resolve_link(page_url, bsrc, url,
  4809. sizeof(url)) == 0) {
  4810. if (image_count +
  4811. preload_active_jobs() >=
  4812. BR_MAX_IMAGES) {
  4813. preload_node = doc.nnode;
  4814. break;
  4815. }
  4816. if (url[0] == '/') {
  4817. unsigned char *data = 0;
  4818. unsigned int len = 0;
  4819. unsigned int t0;
  4820. int before;
  4821. preload_node = i + 1;
  4822. before = image_count;
  4823. t0 = u_ticks_ms();
  4824. if (fetch_image(url,
  4825. BR_IMG_FILE_MAX,
  4826. &data, &len,
  4827. err,
  4828. sizeof(err)) == 0) {
  4829. preload_decode(i, 1, data, len, 0);
  4830. img_stat_local(before, len,
  4831. u_ticks_ms() - t0);
  4832. } else {
  4833. nd->bg_img_index = -2;
  4834. }
  4835. continue;
  4836. }
  4837. w = fetch_worker_alloc();
  4838. if (!w)
  4839. return started;
  4840. preload_node = i + 1;
  4841. if (fetch_worker_submit(w, url,
  4842. BR_IMG_FILE_MAX,
  4843. 0, 0, i, 1,
  4844. err,
  4845. sizeof(err)) != 0) {
  4846. nd->bg_img_index = -2;
  4847. fetch_worker_release(w);
  4848. continue;
  4849. }
  4850. w->image_job = 1;
  4851. w->deadline = u_ticks_ms() +
  4852. BR_IMG_JOB_TIMEOUT_MS;
  4853. /* in flight: rescans skip it */
  4854. nd->bg_img_index = -3;
  4855. started++;
  4856. continue;
  4857. }
  4858. }
  4859. nd->bg_img_index = -2;
  4860. }
  4861. preload_node++;
  4862. continue;
  4863. }
  4864. if (nd->img_index != -1) {
  4865. preload_node++;
  4866. continue;
  4867. }
  4868. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4869. preload_node++;
  4870. continue;
  4871. }
  4872. src = br_src(&doc, i);
  4873. if (starts_with(src, "data:")) {
  4874. unsigned char *data;
  4875. unsigned int len;
  4876. preload_node = i + 1;
  4877. if (data_url_decode(src, &data, &len) == 0) {
  4878. preload_decode(i, 0, data, len, 0);
  4879. free(data);
  4880. } else {
  4881. doc.nodes[i].img_index = -2;
  4882. }
  4883. continue;
  4884. }
  4885. if (!src[0]) {
  4886. preload_node++;
  4887. continue;
  4888. }
  4889. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4890. preload_node++;
  4891. continue;
  4892. }
  4893. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4894. preload_node = doc.nnode;
  4895. break;
  4896. }
  4897. /* Do not stop at the first below-fold image: DOM order is
  4898. * not visual order, and a footer/ad image early in the DOM
  4899. * used to hide every later article image from the loader. */
  4900. if (img_top[i] >
  4901. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4902. preload_pending = 1;
  4903. preload_node++;
  4904. continue;
  4905. }
  4906. {
  4907. unsigned int uh = script_cache_hash(url) | 1u;
  4908. int k;
  4909. for (k = 0; k < image_count; k++)
  4910. if (images[k].state == 1 &&
  4911. images[k].url_hash == uh)
  4912. break;
  4913. if (k < image_count) {
  4914. nd->img_index = (short)k;
  4915. layout_valid = 0;
  4916. preload_node = i + 1;
  4917. image_repaint();
  4918. continue;
  4919. }
  4920. }
  4921. if (url[0] == '/') {
  4922. unsigned char *data = 0;
  4923. unsigned int len = 0;
  4924. unsigned int t0;
  4925. int before;
  4926. preload_node = i + 1;
  4927. before = image_count;
  4928. t0 = u_ticks_ms();
  4929. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4930. err, sizeof(err)) == 0) {
  4931. preload_decode(i, 0, data, len, url);
  4932. img_stat_local(before, len, u_ticks_ms() - t0);
  4933. } else {
  4934. nd->img_index = -2;
  4935. }
  4936. continue;
  4937. }
  4938. w = fetch_worker_alloc();
  4939. if (!w)
  4940. return started;
  4941. preload_node = i + 1;
  4942. {
  4943. char msg[64];
  4944. unsigned int n = 0;
  4945. s_append(msg, &n, "Loading images ", sizeof(msg));
  4946. s_append_dec(msg, &n,
  4947. (unsigned int)preload_loaded + 1,
  4948. sizeof(msg));
  4949. s_append(msg, &n, "...", sizeof(msg));
  4950. set_status_quiet(msg);
  4951. image_repaint();
  4952. }
  4953. {
  4954. int fit_w = 0, fit_h = 0;
  4955. image_fit_size(i, &fit_w, &fit_h);
  4956. if (!fit_w)
  4957. fit_w = BR_IMG_LAYOUT_W;
  4958. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4959. i, 0,
  4960. (unsigned int)fit_w,
  4961. (unsigned int)fit_h,
  4962. err, sizeof(err)) != 0) {
  4963. nd->img_index = -2;
  4964. fetch_worker_release(w);
  4965. continue;
  4966. }
  4967. }
  4968. w->image_job = 1;
  4969. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4970. nd->img_index = -3; /* in flight: rescans skip it */
  4971. started++;
  4972. }
  4973. return started;
  4974. }
  4975. /* Report where the image batch spent its time: status bar for the headline,
  4976. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4977. static void img_stats_report(void)
  4978. {
  4979. char msg[80];
  4980. static char out[BR_IMG_STAT_LOG + 512];
  4981. unsigned int n = 0, o = 0;
  4982. if (!img_stat_n)
  4983. return;
  4984. img_stat_wall = img_stat_start ?
  4985. u_ticks_ms() - img_stat_start : 1;
  4986. if (!img_stat_wall)
  4987. img_stat_wall = 1;
  4988. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4989. s_append(msg, &n, "img ", sizeof(msg));
  4990. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4991. s_append(msg, &n, " ", sizeof(msg));
  4992. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4993. s_append(msg, &n, "ms net ", sizeof(msg));
  4994. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4995. s_append(msg, &n, " dec ", sizeof(msg));
  4996. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4997. s_append(msg, &n, " sc ", sizeof(msg));
  4998. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4999. s_append(msg, &n, " paint ", sizeof(msg));
  5000. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5001. /* Keep the page's phase breakdown and append the image summary when
  5002. * it fits; never hide a JS error or a truncation notice. */
  5003. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5004. unsigned int plen = s_len(post_status_text);
  5005. if (!plen) {
  5006. s_copy(post_status_text, msg, sizeof(post_status_text));
  5007. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5008. unsigned int pn = plen;
  5009. s_append(post_status_text, &pn, " | ",
  5010. sizeof(post_status_text));
  5011. s_append(post_status_text, &pn, msg,
  5012. sizeof(post_status_text));
  5013. } else {
  5014. s_copy(post_status_text, msg, sizeof(post_status_text));
  5015. }
  5016. post_status_ttl = 12000;
  5017. }
  5018. s_append(out, &o, "browser image stats\n", sizeof(out));
  5019. s_append(out, &o, "n=", sizeof(out));
  5020. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5021. s_append(out, &o, " wall=", sizeof(out));
  5022. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5023. s_append(out, &o, " net=", sizeof(out));
  5024. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5025. s_append(out, &o, " open=", sizeof(out));
  5026. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5027. s_append(out, &o, " first=", sizeof(out));
  5028. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5029. s_append(out, &o, " io=", sizeof(out));
  5030. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5031. s_append(out, &o, " dec=", sizeof(out));
  5032. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5033. s_append(out, &o, " scale=", sizeof(out));
  5034. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5035. s_append(out, &o, " paint=", sizeof(out));
  5036. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5037. s_append(out, &o, " reflow=", sizeof(out));
  5038. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5039. s_append(out, &o, " bytes=", sizeof(out));
  5040. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5041. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5042. sizeof(out));
  5043. s_append(out, &o, img_stat_log, sizeof(out));
  5044. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5045. (int)s_len(out));
  5046. }
  5047. static void preload_step(void)
  5048. {
  5049. int i;
  5050. unsigned int t0;
  5051. if (!preload_active)
  5052. return;
  5053. if (cancel_fetch || pending_action) {
  5054. preload_active = 0;
  5055. preload_pending = 0;
  5056. fetch_workers_cancel_busy();
  5057. return;
  5058. }
  5059. preload_fill_jobs();
  5060. /* Decode completed images in a short batch instead of one per pass.
  5061. * A pass used to decode one image and then sleep 10 ms, so a page of
  5062. * small icons trickled in at the decode rate. The budget keeps a
  5063. * single huge JPEG from monopolising the UI while small images
  5064. * finish together. */
  5065. t0 = u_ticks_ms();
  5066. for (i = 0; i < FETCH_WORKERS; i++) {
  5067. if (!fetch_workers[i].busy)
  5068. continue;
  5069. if (preload_finish_worker(&fetch_workers[i]) &&
  5070. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5071. break;
  5072. }
  5073. if (preload_active && preload_node >= doc.nnode &&
  5074. preload_active_jobs() == 0) {
  5075. preload_active = 0;
  5076. if (preload_pending)
  5077. preload_scroll = page_scroll.offset;
  5078. else
  5079. preload_pending = 0;
  5080. /* Keep the now idle helpers and their connections; a later
  5081. * navigation reuses them. They exit after ten idle seconds,
  5082. * and losing window focus stops them at once. */
  5083. if (img_repaint_pending) {
  5084. img_repaint_pending = 0;
  5085. ngui_invalidate(&ui);
  5086. }
  5087. img_stats_report();
  5088. set_status(post_status_text, post_status_error, post_status_ttl);
  5089. ngui_invalidate(&ui);
  5090. }
  5091. }
  5092. /* Set by navigate() when it turned a typed bare host into https://; the next
  5093. * load_page() consumes it and may retry over http. */
  5094. static int nav_https_upgraded;
  5095. /* Errors that mean "https is not served here" rather than "the site is
  5096. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5097. static int https_fallback_error(int e)
  5098. {
  5099. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5100. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5101. e == UHTTP_ERR_RESET;
  5102. }
  5103. static void history_push(const char *url)
  5104. {
  5105. if (!url || !url[0])
  5106. return;
  5107. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5108. s_eq(history[hist_pos], url))
  5109. return;
  5110. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5111. hist_len = hist_pos + 1;
  5112. if (hist_len < BR_HISTORY) {
  5113. s_copy(history[hist_len], url, BR_URL_MAX);
  5114. hist_pos = hist_len;
  5115. hist_len++;
  5116. } else {
  5117. int i;
  5118. for (i = 1; i < BR_HISTORY; i++)
  5119. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5120. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5121. hist_pos = BR_HISTORY - 1;
  5122. }
  5123. }
  5124. static void load_page(const char *url, int local, int push)
  5125. {
  5126. unsigned char *body = 0;
  5127. unsigned int len = 0;
  5128. int truncated = 0;
  5129. struct img_info image_info;
  5130. char ctype[64];
  5131. char final[BR_URL_MAX];
  5132. char err[80];
  5133. const char *detail = 0;
  5134. const char *post = pending_post_is ? pending_post : 0;
  5135. unsigned int post_len = pending_post_len;
  5136. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5137. /* Phase timings for the status line: where a slow load spends it. */
  5138. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5139. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5140. int upgraded = nav_https_upgraded;
  5141. int retried = 0;
  5142. int rv;
  5143. nav_https_upgraded = 0;
  5144. final[0] = '\0';
  5145. pending_post_len = 0;
  5146. pending_post_is = 0;
  5147. cancel_fetch = 0;
  5148. preload_active = 0;
  5149. preload_pending = 0;
  5150. fetch_workers_prepare_nav(url);
  5151. js_browser_stop();
  5152. js_last_status[0] = '\0';
  5153. js_last_error = 0;
  5154. heap_clear();
  5155. image_reset();
  5156. form_reset_state();
  5157. layout_valid = 0;
  5158. page_scroll.offset = 0;
  5159. page_scroll.dragging = 0;
  5160. page_title[0] = '\0';
  5161. page_loading = 1;
  5162. page_is_local = local;
  5163. s_copy(page_url, url, sizeof(page_url));
  5164. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5165. url_in.len = s_len(url_in.text);
  5166. url_in.cursor = url_in.len;
  5167. url_in.scroll = 0;
  5168. ngui_set_focus(&ui, 0);
  5169. if (final[0])
  5170. final[0] = '\0';
  5171. if (push)
  5172. history_push(url);
  5173. set_status("Loading...", 0, 0);
  5174. ngui_invalidate(&ui);
  5175. /* heap_clear() detaches the fonts, so attach them again before the
  5176. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5177. if (heap_start() != 0) {
  5178. show_error("Out of memory", "Cannot allocate the page buffer");
  5179. return;
  5180. }
  5181. br_parse_plain(&doc, "", 0); /* blank while loading */
  5182. ngui_font_attach(&ui);
  5183. redraw_now();
  5184. browser_rules_alloc();
  5185. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5186. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5187. &truncated, post, post_len);
  5188. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5189. fetch_last_error == UHTTP_ERR_DNS) {
  5190. /* A busy previous page can leave the receiver ring full just
  5191. * long enough to lose a DNS reply. Tear the old helpers down
  5192. * and try once more before giving up. */
  5193. retried = 1;
  5194. fetch_workers_stop_all();
  5195. u_sleep_ms(500);
  5196. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5197. sizeof(ctype), final, sizeof(final), err,
  5198. sizeof(err), &truncated, post, post_len);
  5199. }
  5200. if (rv == FETCH_ABORT)
  5201. return;
  5202. t_fetch = u_ticks_ms() - t_start;
  5203. /* Capture the page timing before CSS/script/image fetches overwrite the
  5204. * shared fetch_meta block. */
  5205. if (rv == 0 && !local) {
  5206. page_open_ms = fetch_meta.open_ms;
  5207. page_first_ms = fetch_meta.first_ms;
  5208. page_total_ms = fetch_meta.total_ms;
  5209. }
  5210. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5211. https_fallback_error(fetch_last_error)) {
  5212. char http_url[BR_URL_MAX];
  5213. unsigned int n = 0;
  5214. s_append(http_url, &n, "http://", sizeof(http_url));
  5215. s_append(http_url, &n, url + 8, sizeof(http_url));
  5216. /* Replace the https entry instead of adding a second one. */
  5217. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5218. s_eq(history[hist_pos], url))
  5219. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5220. load_page(http_url, 0, 0);
  5221. return;
  5222. }
  5223. if (rv != 0) {
  5224. detail = err;
  5225. show_error("Cannot load this page", detail);
  5226. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5227. url_in.len = s_len(url_in.text);
  5228. url_in.cursor = url_in.len;
  5229. url_in.scroll = 0;
  5230. return;
  5231. }
  5232. if (!local)
  5233. origin_cache_learn(url, final[0] ? final : url);
  5234. page_is_local = local;
  5235. if (final[0]) {
  5236. s_copy(page_url, final, sizeof(page_url));
  5237. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5238. url_in.len = s_len(url_in.text);
  5239. url_in.cursor = url_in.len;
  5240. url_in.scroll = 0;
  5241. }
  5242. if (contains_ci(ctype, "text/plain")) {
  5243. br_parse_plain(&doc, (const char *)body, len);
  5244. } else if (contains_ci(ctype, "image/") ||
  5245. (!contains_ci(ctype, "text/html") &&
  5246. img_sniff(body, len, &image_info) == 0)) {
  5247. unsigned int node = br_parse_image_doc(&doc, page_url);
  5248. if (node)
  5249. decode_direct_image(body, len, node);
  5250. s_copy(page_title, "Image", sizeof(page_title));
  5251. } else {
  5252. br_set_viewport(ui.w);
  5253. t_mark = u_ticks_ms();
  5254. br_parse(&doc, (const char *)body, len);
  5255. t_parse = u_ticks_ms() - t_mark;
  5256. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5257. sizeof(page_title));
  5258. t_mark = u_ticks_ms();
  5259. if (load_stylesheets() == FETCH_ABORT)
  5260. return;
  5261. t_css = u_ticks_ms() - t_mark;
  5262. if (pending_action)
  5263. return;
  5264. }
  5265. preload_begin();
  5266. page_loading = 0;
  5267. hist_visit(page_url, page_title);
  5268. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5269. url_in.len = s_len(url_in.text);
  5270. url_in.cursor = url_in.len;
  5271. url_in.scroll = 0;
  5272. ngui_set_focus(&ui, 0);
  5273. /* Paint the parsed page before fetching/running scripts. A slow
  5274. * remote <script src> then does not hide the page behind the loading
  5275. * screen; the fetch helper pumps this UI while it waits. */
  5276. set_status("Loading scripts...", 0, 0);
  5277. t_mark = u_ticks_ms();
  5278. redraw_now();
  5279. t_paint = u_ticks_ms() - t_mark;
  5280. /* Start one image download before the scripts. The other workers
  5281. * fetch the external script bodies in parallel, and the remaining
  5282. * images start as soon as the script phase ends. */
  5283. preload_max_jobs = 1;
  5284. preload_fill_jobs();
  5285. preload_wait = 0;
  5286. t_mark = u_ticks_ms();
  5287. run_page_scripts();
  5288. t_js = u_ticks_ms() - t_mark;
  5289. preload_max_jobs = FETCH_WORKERS;
  5290. if (pending_action)
  5291. return;
  5292. post_status_text[0] = '\0';
  5293. post_status_error = 0;
  5294. post_status_ttl = 0;
  5295. if (js_last_status[0]) {
  5296. s_copy(post_status_text, js_last_status,
  5297. sizeof(post_status_text));
  5298. post_status_error = js_last_error;
  5299. post_status_ttl = 8000;
  5300. } else if (truncated) {
  5301. s_copy(post_status_text, "Page truncated at the buffer limit",
  5302. sizeof(post_status_text));
  5303. post_status_ttl = 6000;
  5304. } else if (doc.truncated) {
  5305. s_copy(post_status_text, "Page truncated by the parser",
  5306. sizeof(post_status_text));
  5307. post_status_ttl = 6000;
  5308. } else if (page_total_ms) {
  5309. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5310. * paint 220, js 1750" -- the phases of this load. */
  5311. unsigned int n = 0;
  5312. static const char *const names[] = {
  5313. ", parse ", ", css ", ", paint ", ", js "
  5314. };
  5315. unsigned int vals[4];
  5316. int k;
  5317. vals[0] = t_parse;
  5318. vals[1] = t_css;
  5319. vals[2] = t_paint;
  5320. vals[3] = t_js;
  5321. (void)page_first_ms;
  5322. if (starts_with(page_url, "https://"))
  5323. s_append(post_status_text, &n,
  5324. "HTTPS (not verified), ",
  5325. sizeof(post_status_text));
  5326. s_append(post_status_text, &n, "Loaded in ",
  5327. sizeof(post_status_text));
  5328. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5329. sizeof(post_status_text));
  5330. s_append(post_status_text, &n, " ms: page ",
  5331. sizeof(post_status_text));
  5332. s_append_dec(post_status_text, &n, t_fetch,
  5333. sizeof(post_status_text));
  5334. s_append(post_status_text, &n, " (headers ",
  5335. sizeof(post_status_text));
  5336. s_append_dec(post_status_text, &n, page_open_ms,
  5337. sizeof(post_status_text));
  5338. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5339. for (k = 0; k < 4; k++) {
  5340. s_append(post_status_text, &n, names[k],
  5341. sizeof(post_status_text));
  5342. s_append_dec(post_status_text, &n, vals[k],
  5343. sizeof(post_status_text));
  5344. }
  5345. post_status_ttl = 12000;
  5346. } else if (starts_with(page_url, "https://")) {
  5347. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5348. sizeof(post_status_text));
  5349. post_status_ttl = 6000;
  5350. }
  5351. set_status(post_status_text, post_status_error, post_status_ttl);
  5352. ngui_invalidate(&ui);
  5353. }
  5354. static void load_home(int push)
  5355. {
  5356. pending_post_len = 0;
  5357. pending_post_is = 0;
  5358. cancel_fetch = 0;
  5359. preload_active = 0;
  5360. preload_pending = 0;
  5361. js_browser_stop();
  5362. js_last_status[0] = '\0';
  5363. js_last_error = 0;
  5364. heap_clear();
  5365. image_reset();
  5366. form_reset_state();
  5367. layout_valid = 0;
  5368. page_scroll.offset = 0;
  5369. page_scroll.dragging = 0;
  5370. page_loading = 1;
  5371. page_is_local = 0;
  5372. s_copy(page_url, "about:home", sizeof(page_url));
  5373. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5374. url_in.len = s_len(url_in.text);
  5375. url_in.cursor = url_in.len;
  5376. url_in.scroll = 0;
  5377. ngui_set_focus(&ui, 0);
  5378. if (push)
  5379. history_push(page_url);
  5380. ngui_invalidate(&ui);
  5381. /* See load_page(): reattach the fonts before the first redraw. */
  5382. if (heap_start() != 0) {
  5383. show_error("Out of memory", "Cannot allocate the browser heap");
  5384. return;
  5385. }
  5386. br_parse_plain(&doc, "", 0);
  5387. ngui_font_attach(&ui);
  5388. redraw_now();
  5389. browser_rules_alloc();
  5390. {
  5391. static const char home[] =
  5392. "<html><head><title>NebOS Browser</title><style>"
  5393. "body { margin: 10px; color: #e4e6f0; }"
  5394. "h1 { color: #7fb0ff; }"
  5395. ".box { background-color: #262b3a; margin: 12px; "
  5396. "padding: 10px; }"
  5397. "a { color: #7fb0ff; }"
  5398. "pre { background-color: #32384a; }"
  5399. "</style></head><body>"
  5400. "<h1>NebOS Browser</h1>"
  5401. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5402. "shared HTTP client and the image library.</p>"
  5403. "<div class=\"box\"><b>Try:</b>"
  5404. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5405. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5406. "<li><a href=\"/floppy1/JS.HTM\">/"
  5407. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5408. "<li><a href=\"http://10.0.2.2:8000/\">"
  5409. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5410. "<li><a href=\"https://example.com/\">"
  5411. "https://example.com/</a> (TLS, not verified)</li>"
  5412. "</ul></div>"
  5413. "<p>Type a URL in the bar above. Esc closes the "
  5414. "window, Ctrl+L focuses the address bar.</p>"
  5415. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5416. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5417. "</body></html>";
  5418. br_set_viewport(ui.w);
  5419. br_parse(&doc, home, sizeof(home) - 1);
  5420. br_parse_inline_css(&doc);
  5421. br_reset_styles(&doc);
  5422. s_copy(page_title, doc.title, sizeof(page_title));
  5423. }
  5424. post_status_text[0] = '\0';
  5425. post_status_error = 0;
  5426. post_status_ttl = 0;
  5427. page_loading = 0;
  5428. set_status("", 0, 0);
  5429. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5430. url_in.len = s_len(url_in.text);
  5431. url_in.cursor = url_in.len;
  5432. url_in.scroll = 0;
  5433. ngui_set_focus(&ui, 0);
  5434. ngui_invalidate(&ui);
  5435. }
  5436. /* Extensions the browser opens from the local filesystem. A dotted input
  5437. * with one of these still resolves relative to the cwd. */
  5438. static int local_file_ext(const char *s)
  5439. {
  5440. static const char *const exts[] = {
  5441. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5442. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5443. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5444. "cfg", "conf", 0
  5445. };
  5446. unsigned int i = 0, start = 0, len = 0, e;
  5447. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5448. s[i] != '#') {
  5449. if (s[i] == '.') {
  5450. start = i + 1;
  5451. len = 0;
  5452. } else if (start) {
  5453. len++;
  5454. }
  5455. i++;
  5456. }
  5457. if (!len)
  5458. return 0;
  5459. for (e = 0; exts[e]; e++) {
  5460. const char *x = exts[e];
  5461. unsigned int xn = s_len(x), k;
  5462. if (xn != len)
  5463. continue;
  5464. for (k = 0; k < len; k++) {
  5465. char a = s[start + k];
  5466. if (a >= 'A' && a <= 'Z')
  5467. a = (char)(a - 'A' + 'a');
  5468. if (a != x[k])
  5469. break;
  5470. }
  5471. if (k == len)
  5472. return 1;
  5473. }
  5474. return 0;
  5475. }
  5476. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5477. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5478. * Enter to the first network request. */
  5479. static int looks_like_host(const char *s)
  5480. {
  5481. unsigned int i = 0;
  5482. int dot = 0;
  5483. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5484. s[i] != ':') {
  5485. char c = s[i];
  5486. if (c == '.') {
  5487. dot = 1;
  5488. } else if (!((c >= 'a' && c <= 'z') ||
  5489. (c >= 'A' && c <= 'Z') ||
  5490. (c >= '0' && c <= '9') ||
  5491. c == '-' || c == '_')) {
  5492. return 0;
  5493. }
  5494. i++;
  5495. }
  5496. return dot && i > 0 && !local_file_ext(s);
  5497. }
  5498. static void load_remote(const char *url, int push)
  5499. {
  5500. char canon[BR_URL_MAX];
  5501. s_copy(canon, url, sizeof(canon));
  5502. origin_cache_apply(canon, sizeof(canon));
  5503. load_page(canon, 0, push);
  5504. }
  5505. static void navigate(const char *input, int push)
  5506. {
  5507. char target[BR_URL_MAX];
  5508. char *t;
  5509. if (!input)
  5510. return;
  5511. s_copy(target, input, sizeof(target));
  5512. t = trim(target);
  5513. if (!t[0])
  5514. return;
  5515. if (s_eq(t, "about:home")) {
  5516. load_home(push);
  5517. return;
  5518. }
  5519. if (starts_with(t, "file://")) {
  5520. make_abs_local(t + 7, target, sizeof(target));
  5521. load_page(target, 1, push);
  5522. return;
  5523. }
  5524. if (is_http(t)) {
  5525. load_remote(t, push);
  5526. return;
  5527. }
  5528. if (t[0] == '/') {
  5529. make_abs_local(t, target, sizeof(target));
  5530. load_page(target, 1, push);
  5531. return;
  5532. }
  5533. if (!looks_like_host(t)) {
  5534. struct sys_stat st;
  5535. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5536. make_abs_local(t, target, sizeof(target));
  5537. load_page(target, 1, push);
  5538. return;
  5539. }
  5540. }
  5541. {
  5542. /* A typed bare host tries https first: nearly every site
  5543. * redirects http -> https anyway, and that hop costs a whole
  5544. * extra connection. load_page() falls back to http when the
  5545. * https connection itself fails. */
  5546. char with_scheme[BR_URL_MAX];
  5547. unsigned int n = 0;
  5548. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5549. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5550. nav_https_upgraded = 1;
  5551. load_remote(with_scheme, push);
  5552. }
  5553. }
  5554. /* ---- layout ---- */
  5555. static struct ufont_face *style_face(const struct br_style *st)
  5556. {
  5557. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5558. return font_faces[st->font_face - 1];
  5559. return 0;
  5560. }
  5561. static struct ufont_face *run_face(const struct lay_run *r)
  5562. {
  5563. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5564. return font_faces[r->font_face - 1];
  5565. return 0;
  5566. }
  5567. static unsigned int face_text_width(struct ngui *gui,
  5568. const struct br_style *st,
  5569. const char *s, unsigned int n)
  5570. {
  5571. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5572. st->bold, st->italic, st->mono);
  5573. }
  5574. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5575. {
  5576. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5577. st->mono);
  5578. }
  5579. static unsigned int run_text_width(struct ngui *gui,
  5580. const struct lay_run *r,
  5581. const char *s, unsigned int n)
  5582. {
  5583. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5584. r->bold, r->italic, r->mono);
  5585. }
  5586. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5587. {
  5588. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5589. r->mono);
  5590. }
  5591. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5592. {
  5593. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5594. }
  5595. static struct br_style base_style(void)
  5596. {
  5597. struct br_style s = { 0 };
  5598. s.color = ui.theme.text;
  5599. s.bg = ui.theme.bg;
  5600. s.has_bg = 0;
  5601. for (int i = 0; i < 4; i++) {
  5602. s.border_c[i] = 0;
  5603. s.border_w[i] = 0;
  5604. s.border_s[i] = BR_BORDER_SOLID;
  5605. }
  5606. s.font_px = 16;
  5607. s.bold = 0;
  5608. s.italic = 0;
  5609. s.mono = 0;
  5610. s.underline = 0;
  5611. s.strike = 0;
  5612. s.overline = 0;
  5613. s.align = BR_ALIGN_LEFT;
  5614. s.display = BR_DISPLAY_BLOCK;
  5615. s.no_bullet = 0;
  5616. s.list_style = BR_LIST_AUTO;
  5617. s.uppercase = 0;
  5618. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5619. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5620. s.width = s.max_width = s.min_width = 0;
  5621. s.height = s.min_height = s.max_height = 0;
  5622. s.box_sizing = 0;
  5623. s.ml_auto = s.mr_auto = 0;
  5624. s.line_h_pct = 0;
  5625. s.line_h_px = 0;
  5626. s.mt = s.mb = s.ml = s.mr = 0;
  5627. s.pt = s.pb = s.pl = s.pr = 0;
  5628. return s;
  5629. }
  5630. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5631. * a minified page that starts `<!doctype html><html ...>` makes it the
  5632. * <html> element itself, and the layout walks only its children, so its
  5633. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5634. * colour and font there) used to be skipped and the theme defaults showed
  5635. * through. Only inherited properties are taken: the root's box (margins,
  5636. * display, background) is not a container style for its children here. */
  5637. static struct br_style root_style(void)
  5638. {
  5639. struct br_style base = base_style(), st;
  5640. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5641. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5642. return base;
  5643. br_style_for(&doc, doc.root, &base, &st);
  5644. base.color = st.color;
  5645. base.font_px = st.font_px;
  5646. base.bold = st.bold;
  5647. base.italic = st.italic;
  5648. base.mono = st.mono;
  5649. base.font_face = st.font_face;
  5650. base.align = st.align;
  5651. base.line_h_pct = st.line_h_pct;
  5652. base.line_h_px = st.line_h_px;
  5653. base.nowrap = st.nowrap;
  5654. base.uppercase = st.uppercase;
  5655. base.cursor = st.cursor;
  5656. base.vis_hidden = st.vis_hidden;
  5657. base.fill_mode = st.fill_mode;
  5658. base.fill = st.fill;
  5659. base.stroke_mode = st.stroke_mode;
  5660. base.stroke = st.stroke;
  5661. base.stroke_w = st.stroke_w;
  5662. base.fill_evenodd = st.fill_evenodd;
  5663. return base;
  5664. }
  5665. /* Resolve a margin/padding raw value. Percentages use the containing
  5666. * block width for all four sides, as CSS specifies. */
  5667. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5668. {
  5669. if (unit == 1)
  5670. return base * v / 10000;
  5671. if (unit == 2)
  5672. return st->font_px * v / 100;
  5673. if (unit == 3)
  5674. return (int)br_root_font_px() * v / 100;
  5675. if (unit == 4)
  5676. return 0;
  5677. return v;
  5678. }
  5679. static int mp_px(const struct br_style *st, int side, int base)
  5680. {
  5681. int raw;
  5682. switch (side) {
  5683. case 0: raw = st->mt; break;
  5684. case 1: raw = st->mr; break;
  5685. case 2: raw = st->mb; break;
  5686. case 3: raw = st->ml; break;
  5687. case 4: raw = st->pt; break;
  5688. case 5: raw = st->pr; break;
  5689. case 6: raw = st->pb; break;
  5690. default: raw = st->pl; break;
  5691. }
  5692. if (st->mp_unit[side] == 5)
  5693. return base * raw / 100 + st->mp_calc_px[side];
  5694. return css_mp_px(st, raw, st->mp_unit[side], base);
  5695. }
  5696. static int style_width_px(const struct br_style *st, int base)
  5697. {
  5698. if (st->width_kind == 1)
  5699. return st->width;
  5700. if (st->width_kind == 2)
  5701. return base * (int)st->width / 100;
  5702. if (st->width_kind == 3)
  5703. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5704. return 0;
  5705. }
  5706. static int style_height_px(const struct br_style *st, int base)
  5707. {
  5708. if (st->height_kind == 1)
  5709. return st->height;
  5710. if (st->height_kind == 2)
  5711. return base * (int)st->height / 100;
  5712. if (st->height_kind == 3)
  5713. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5714. return 0;
  5715. }
  5716. static int css_size(unsigned char kind, int val, int base)
  5717. {
  5718. if (kind == 1)
  5719. return val;
  5720. if (kind == 2)
  5721. return base * val / 100;
  5722. return -1;
  5723. }
  5724. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5725. int thick, int horizontal, unsigned short color,
  5726. unsigned char style)
  5727. {
  5728. int pos;
  5729. if (len <= 0 || thick <= 0)
  5730. return;
  5731. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5732. if (horizontal)
  5733. ngui_fill_rect(ui, (struct ngui_rect){
  5734. x, y, len, thick}, color);
  5735. else
  5736. ngui_fill_rect(ui, (struct ngui_rect){
  5737. x, y, thick, len}, color);
  5738. return;
  5739. }
  5740. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5741. int seg = len - pos;
  5742. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5743. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5744. if (horizontal)
  5745. ngui_fill_rect(ui, (struct ngui_rect){
  5746. x + pos, y, seg, thick}, color);
  5747. else
  5748. ngui_fill_rect(ui, (struct ngui_rect){
  5749. x, y + pos, thick, seg}, color);
  5750. }
  5751. }
  5752. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5753. const struct br_style *st)
  5754. {
  5755. int top = st->border_w[0], right = st->border_w[1];
  5756. int bottom = st->border_w[2], left = st->border_w[3];
  5757. if (r.w <= 0 || r.h <= 0)
  5758. return;
  5759. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5760. int i;
  5761. for (i = 0; i < 4; i++)
  5762. if (st->border_w[i] && !st->border_t[i]) {
  5763. ngui_fill_rect(ui, r, st->border_c[i]);
  5764. break;
  5765. }
  5766. return;
  5767. }
  5768. if (top && !st->border_t[0])
  5769. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5770. st->border_c[0], st->border_s[0]);
  5771. if (bottom && !st->border_t[2])
  5772. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5773. st->border_c[2], st->border_s[2]);
  5774. if (left && !st->border_t[3])
  5775. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5776. left, 0, st->border_c[3], st->border_s[3]);
  5777. if (right && !st->border_t[1])
  5778. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5779. r.h - top - bottom, right, 0,
  5780. st->border_c[1], st->border_s[1]);
  5781. }
  5782. static void transform_origin(const struct br_style *st, int w, int h,
  5783. int *ox, int *oy)
  5784. {
  5785. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5786. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5787. }
  5788. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5789. unsigned int a)
  5790. {
  5791. unsigned int dr, dg, db, sr, sg, sb;
  5792. if (a >= 255)
  5793. return s;
  5794. dr = (d >> 11) & 31;
  5795. dg = (d >> 5) & 63;
  5796. db = d & 31;
  5797. sr = (s >> 11) & 31;
  5798. sg = (s >> 5) & 63;
  5799. sb = s & 31;
  5800. dr = (dr * (255 - a) + sr * a) / 255;
  5801. dg = (dg * (255 - a) + sg * a) / 255;
  5802. db = (db * (255 - a) + sb * a) / 255;
  5803. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5804. }
  5805. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5806. * transforms the element's own background box; text and descendants keep
  5807. * their layout (documented approximation). */
  5808. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5809. unsigned short color,
  5810. const struct br_style *st)
  5811. {
  5812. double sx = st->scale_x / 100.0;
  5813. double sy = st->scale_y / 100.0;
  5814. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5815. double c = cos(th), sn = sin(th);
  5816. int ox, oy, minx, miny, maxx, maxy, x, y;
  5817. double ax, ay;
  5818. double px[4], py[4];
  5819. int cx1, cy1, cx2, cy2, i;
  5820. if (sx == 0)
  5821. sx = 0.01;
  5822. if (sy == 0)
  5823. sy = 0.01;
  5824. transform_origin(st, box.w, box.h, &ox, &oy);
  5825. ax = box.x + ox;
  5826. ay = box.y + oy;
  5827. px[0] = -ox; py[0] = -oy;
  5828. px[1] = box.w - ox; py[1] = -oy;
  5829. px[2] = box.w - ox; py[2] = box.h - oy;
  5830. px[3] = -ox; py[3] = box.h - oy;
  5831. minx = miny = 1000000;
  5832. maxx = maxy = -1000000;
  5833. for (i = 0; i < 4; i++) {
  5834. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5835. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5836. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5837. if (dx < minx) minx = dx;
  5838. if (dx > maxx) maxx = dx;
  5839. if (dy < miny) miny = dy;
  5840. if (dy > maxy) maxy = dy;
  5841. }
  5842. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5843. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5844. cx2 = page_rect.x + page_rect.w - 12;
  5845. cy2 = page_rect.y + page_rect.h;
  5846. if (cx2 > gui->w) cx2 = gui->w;
  5847. if (cy2 > gui->h) cy2 = gui->h;
  5848. if (minx < cx1) minx = cx1;
  5849. if (miny < cy1) miny = cy1;
  5850. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5851. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5852. for (y = miny; y <= maxy; y++) {
  5853. for (x = minx; x <= maxx; x++) {
  5854. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5855. double rx = dx * c + dy * sn;
  5856. double ry = -dx * sn + dy * c;
  5857. double bx = rx / sx + ox;
  5858. double by = ry / sy + oy;
  5859. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5860. gui->px[y * gui->w + x] = color;
  5861. }
  5862. }
  5863. }
  5864. static void draw_image_transformed(struct ngui *gui,
  5865. const struct img_image *im,
  5866. int x, int y, int w, int h,
  5867. int sx100, int sy100, int rot100,
  5868. int origin_x, int origin_y,
  5869. int origin_x_kind, int origin_y_kind)
  5870. {
  5871. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5872. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5873. double c = cos(th), sn = sin(th);
  5874. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5875. double ax, ay;
  5876. double bx[4], by[4];
  5877. int cx1, cy1, cx2, cy2;
  5878. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5879. return;
  5880. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5881. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5882. ax = x + ox;
  5883. ay = y + oy;
  5884. bx[0] = -ox; by[0] = -oy;
  5885. bx[1] = w - ox; by[1] = -oy;
  5886. bx[2] = w - ox; by[2] = h - oy;
  5887. bx[3] = -ox; by[3] = h - oy;
  5888. minx = miny = 1000000;
  5889. maxx = maxy = -1000000;
  5890. for (i = 0; i < 4; i++) {
  5891. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5892. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5893. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5894. if (dx < minx) minx = dx;
  5895. if (dx > maxx) maxx = dx;
  5896. if (dy < miny) miny = dy;
  5897. if (dy > maxy) maxy = dy;
  5898. }
  5899. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5900. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5901. cx2 = page_rect.x + page_rect.w - 12;
  5902. cy2 = page_rect.y + page_rect.h;
  5903. if (cx2 > gui->w) cx2 = gui->w;
  5904. if (cy2 > gui->h) cy2 = gui->h;
  5905. if (minx < cx1) minx = cx1;
  5906. if (miny < cy1) miny = cy1;
  5907. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5908. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5909. for (py = miny; py <= maxy; py++) {
  5910. for (px = minx; px <= maxx; px++) {
  5911. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5912. double rx = dx * c + dy * sn;
  5913. double ry = -dx * sn + dy * c;
  5914. double fx = rx / sx + ox;
  5915. double fy = ry / sy + oy;
  5916. int ix, iy;
  5917. unsigned int si, a;
  5918. unsigned short src;
  5919. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5920. continue;
  5921. ix = (int)(fx * (double)im->w / w);
  5922. iy = (int)(fy * (double)im->h / h);
  5923. if (ix < 0 || ix >= (int)im->w ||
  5924. iy < 0 || iy >= (int)im->h)
  5925. continue;
  5926. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5927. src = im->px[si];
  5928. a = im->alpha ? im->alpha[si] : 255;
  5929. gui->px[py * gui->w + px] =
  5930. a >= 255 ? src :
  5931. blend_rgb565(gui->px[py * gui->w + px],
  5932. src, a);
  5933. }
  5934. }
  5935. }
  5936. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5937. unsigned int node, const struct br_style *st);
  5938. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5939. * first and every pixel outside a corner's arc is restored afterwards. */
  5940. #define BG_ROUND_MAX 64
  5941. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5942. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5943. unsigned int node, const struct br_style *st,
  5944. int rtl, int rtr, int rbr, int rbl)
  5945. {
  5946. struct ngui *ui = l->ui;
  5947. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5948. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5949. if (ui->nclip > 0)
  5950. clip = ui->clip[ui->nclip - 1];
  5951. for (c = 0; c < 4; c++) {
  5952. if (r[c] > BG_ROUND_MAX)
  5953. r[c] = BG_ROUND_MAX;
  5954. if (r[c] > box.w / 2)
  5955. r[c] = box.w / 2;
  5956. if (r[c] > box.h / 2)
  5957. r[c] = box.h / 2;
  5958. }
  5959. for (c = 0; c < 4; c++) {
  5960. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5961. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5962. for (dy = 0; dy < r[c]; dy++)
  5963. for (dx = 0; dx < r[c]; dx++) {
  5964. int px = ox + dx, py = oy + dy;
  5965. if (px >= clip.x && py >= clip.y &&
  5966. px < clip.x + clip.w && py < clip.y + clip.h)
  5967. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5968. ui->px[py * ui->w + px];
  5969. }
  5970. }
  5971. draw_bg_image(l, box, node, st);
  5972. for (c = 0; c < 4; c++) {
  5973. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5974. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5975. /* arc centre, in corner-square coordinates */
  5976. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5977. int cy = (c >= 2) ? 0 : r[c];
  5978. for (dy = 0; dy < r[c]; dy++)
  5979. for (dx = 0; dx < r[c]; dx++) {
  5980. int px = ox + dx, py = oy + dy;
  5981. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5982. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5983. continue;
  5984. if (px >= clip.x && py >= clip.y &&
  5985. px < clip.x + clip.w && py < clip.y + clip.h)
  5986. ui->px[py * ui->w + px] =
  5987. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5988. }
  5989. }
  5990. }
  5991. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5992. unsigned int node, const struct br_style *st)
  5993. {
  5994. struct br_image *bi;
  5995. struct img_blit b;
  5996. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5997. unsigned int scale = 65536;
  5998. int legacy, tiles = 0, rows = 0;
  5999. int cx1, cy1, cx2, cy2;
  6000. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6001. return;
  6002. if (doc.nodes[node].bg_img_index < 0 ||
  6003. doc.nodes[node].bg_img_index >= image_count)
  6004. return;
  6005. bi = &images[doc.nodes[node].bg_img_index];
  6006. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6007. return;
  6008. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6009. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6010. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6011. if (legacy) {
  6012. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6013. tw = box.w;
  6014. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6015. x = box.x;
  6016. y = box.y;
  6017. rep_x = rep_y = 0;
  6018. } else {
  6019. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6020. unsigned int sx = ((unsigned int)box.w << 16) /
  6021. bi->img.w;
  6022. unsigned int sy = ((unsigned int)box.h << 16) /
  6023. bi->img.h;
  6024. scale = st->bg_size_kind == 3 ?
  6025. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6026. } else if (st->bg_size_kind == 1 ||
  6027. st->bg_size_kind == 2) {
  6028. int w = st->bg_size_w;
  6029. int h = st->bg_size_h;
  6030. if (st->bg_size_kind == 2) {
  6031. if (w)
  6032. w = box.w * w / 100;
  6033. if (h)
  6034. h = box.h * h / 100;
  6035. }
  6036. if (w)
  6037. scale = ((unsigned int)w << 16) / bi->img.w;
  6038. else if (h)
  6039. scale = ((unsigned int)h << 16) / bi->img.h;
  6040. }
  6041. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6042. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6043. if (tw < 1)
  6044. tw = 1;
  6045. if (th < 1)
  6046. th = 1;
  6047. posx = st->bg_pos_x_kind == 1 ?
  6048. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6049. posy = st->bg_pos_y_kind == 1 ?
  6050. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6051. x = box.x + posx;
  6052. y = box.y + posy;
  6053. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6054. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6055. if (rep_x) {
  6056. int m = (x - box.x) % tw;
  6057. if (m > 0)
  6058. m -= tw;
  6059. x = box.x + m;
  6060. }
  6061. if (rep_y) {
  6062. int m = (y - box.y) % th;
  6063. if (m > 0)
  6064. m -= th;
  6065. y = box.y + m;
  6066. }
  6067. }
  6068. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6069. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6070. cx2 = box.x + box.w;
  6071. cy2 = box.y + box.h;
  6072. if (cx2 > page_rect.x + page_rect.w - 12)
  6073. cx2 = page_rect.x + page_rect.w - 12;
  6074. if (cy2 > page_rect.y + page_rect.h)
  6075. cy2 = page_rect.y + page_rect.h;
  6076. if (cx1 >= cx2 || cy1 >= cy2)
  6077. return;
  6078. b.dst = l->ui->px;
  6079. b.dst_w = l->ui->w;
  6080. b.dst_h = l->ui->h;
  6081. b.clip_x = cx1;
  6082. b.clip_y = cy1;
  6083. b.clip_w = cx2 - cx1;
  6084. b.clip_h = cy2 - cy1;
  6085. b.bg = ui.theme.bg;
  6086. b.bg2 = ui.theme.bg;
  6087. b.dst_a = 0;
  6088. {
  6089. struct img_image *src = image_display_get(bi, tw, th);
  6090. int row_x;
  6091. if (!src)
  6092. src = &bi->img;
  6093. b.scale = ((unsigned int)tw << 16) / src->w;
  6094. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6095. row_x = x;
  6096. for (;;) {
  6097. for (;;) {
  6098. b.x = x;
  6099. b.y = y;
  6100. img_draw(src, &b);
  6101. if (!rep_x || ++tiles > 512)
  6102. break;
  6103. x += tw;
  6104. if (x >= box.x + box.w)
  6105. break;
  6106. }
  6107. if (!rep_y || ++rows > 64)
  6108. break;
  6109. y += th;
  6110. if (y >= box.y + box.h)
  6111. break;
  6112. x = row_x;
  6113. }
  6114. }
  6115. }
  6116. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6117. int *out_w, int *out_h);
  6118. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6119. const struct br_style *st, int x, int y, int w,
  6120. int h);
  6121. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6122. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6123. * ::before/::after box with a background (Infima's menu chevrons). */
  6124. #define RUN_SVG (-3)
  6125. #define RUN_PBOX (-4)
  6126. static int run_width(const struct lay_run *r)
  6127. {
  6128. if (r->img >= 0)
  6129. return r->iw;
  6130. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6131. return r->iw;
  6132. return (int)r->w;
  6133. }
  6134. static void start_line(struct lay *l, const struct br_style *st)
  6135. {
  6136. (void)st;
  6137. if (l->nruns == 0) {
  6138. l->line_y = l->y;
  6139. l->line_h = 0;
  6140. }
  6141. l->line_left = l->left;
  6142. l->line_right = l->right;
  6143. if (l->float_active && l->line_y < l->float_bottom) {
  6144. if (l->float_left > l->line_left)
  6145. l->line_left = l->float_left;
  6146. if (l->float_right < l->line_right)
  6147. l->line_right = l->float_right;
  6148. }
  6149. if (l->line_right < l->line_left + 8)
  6150. l->line_right = l->line_left + 8;
  6151. l->line_x = l->line_left;
  6152. l->run_x = l->line_left;
  6153. }
  6154. static void flush_line(struct lay *l)
  6155. {
  6156. int total, x, i, vis;
  6157. if (!l->nruns && l->line_x == l->line_left) {
  6158. l->line_h = 0;
  6159. return;
  6160. }
  6161. total = l->line_x - l->line_left;
  6162. x = l->line_left;
  6163. vis = 1;
  6164. if (l->draw) {
  6165. int lh = l->line_h ? l->line_h : 16;
  6166. vis = l->line_y + lh >= page_rect.y &&
  6167. l->line_y <= page_rect.y + page_rect.h;
  6168. }
  6169. if (l->align == BR_ALIGN_CENTER)
  6170. x += (l->line_right - l->line_left - total) / 2;
  6171. else if (l->align == BR_ALIGN_RIGHT)
  6172. x = l->line_right - total;
  6173. if (x < l->line_left)
  6174. x = l->line_left;
  6175. for (i = 0; i < l->nruns; i++) {
  6176. struct lay_run *r = &l->runs[i];
  6177. int w = run_width(r);
  6178. int ry = l->line_y + r->dy;
  6179. x += r->gap;
  6180. if (l->draw && vis) {
  6181. if (r->form) {
  6182. unsigned int node = r->form - 1;
  6183. struct form_state *fs = form_get(node, 1);
  6184. int hh = r->ih ? r->ih : 20;
  6185. int focused = form_focus == node;
  6186. int disabled = r->form_disabled;
  6187. unsigned short bg = l->ui->theme.panel_alt;
  6188. unsigned short fg = disabled ? 0x8410 : r->color;
  6189. struct ngui_rect box = {x, ry, w, hh};
  6190. if (r->form_kind == FORM_CHECKBOX ||
  6191. r->form_kind == FORM_RADIO) {
  6192. ngui_fill_rect(l->ui, box, bg);
  6193. ngui_frame(l->ui, box,
  6194. focused ? l->ui->theme.accent :
  6195. l->ui->theme.border);
  6196. if (fs && fs->checked) {
  6197. struct ngui_rect dot = {
  6198. x + 4, ry + 4,
  6199. w > 8 ? w - 8 : 1,
  6200. hh > 8 ? hh - 8 : 1
  6201. };
  6202. if (r->form_kind == FORM_RADIO)
  6203. ngui_fill_round_rect(
  6204. l->ui, dot, 4,
  6205. 4, 4, 4,
  6206. l->ui->theme.accent);
  6207. else
  6208. ngui_fill_rect(l->ui,
  6209. dot,
  6210. l->ui->theme.accent);
  6211. }
  6212. } else {
  6213. int editable =
  6214. r->form_kind == FORM_TEXT ||
  6215. r->form_kind == FORM_PASSWORD ||
  6216. r->form_kind == FORM_TEXTAREA;
  6217. int scroll = 0;
  6218. /* Editable fields draw the live value
  6219. * (r->lit is a short copy). */
  6220. static char shown[FORM_VALUE_MAX + 1];
  6221. const char *txt = r->lit;
  6222. unsigned int tl = s_len(r->lit);
  6223. if (editable && fs && fs->len) {
  6224. unsigned int k;
  6225. if (r->form_kind == FORM_PASSWORD) {
  6226. for (k = 0; k < fs->len; k++)
  6227. shown[k] = '*';
  6228. shown[k] = '\0';
  6229. txt = shown;
  6230. } else {
  6231. txt = fs->value;
  6232. }
  6233. tl = fs->len;
  6234. }
  6235. struct br_style fst;
  6236. int author, tx = x + 6, pr = 6;
  6237. style_for_node(node, &fst);
  6238. author = form_author_styled(&fst);
  6239. if (author) {
  6240. /* The page styled the control:
  6241. * its background, border, radius
  6242. * and text colour. */
  6243. form_paint_author(l->ui, box, &fst,
  6244. focused);
  6245. tx = x + fst.border_w[3] +
  6246. mp_px(&fst, 7, w);
  6247. pr = fst.border_w[1] +
  6248. mp_px(&fst, 5, w);
  6249. if (tx < x + 2 && !editable)
  6250. tx = x + 2;
  6251. if (!disabled)
  6252. fg = editable && fs &&
  6253. !fs->len ?
  6254. 0x8410 : fst.color;
  6255. if (!editable) {
  6256. int tw0 = (int)
  6257. run_text_width(l->ui,
  6258. r, txt, tl);
  6259. tx = x + (w - tw0) / 2;
  6260. }
  6261. } else {
  6262. /* The box is drawn in theme colours, so
  6263. * the text is too: the page's CSS colour
  6264. * (dark on a light page) would vanish on
  6265. * the dark field. */
  6266. if (!disabled)
  6267. fg = editable && fs && !fs->len ?
  6268. l->ui->theme.text_dim :
  6269. l->ui->theme.text;
  6270. ngui_fill_rect(l->ui, box, bg);
  6271. ngui_frame(l->ui, box,
  6272. focused ? l->ui->theme.accent :
  6273. l->ui->theme.border);
  6274. }
  6275. /* A value wider than the field shows its
  6276. * tail (where typing happens). */
  6277. if (editable && fs && fs->len &&
  6278. w > (tx - x) + pr) {
  6279. int tw = (int)run_text_width(l->ui,
  6280. r, txt, tl);
  6281. int room = w - (tx - x) - pr;
  6282. if (tw > room)
  6283. scroll = tw - room;
  6284. }
  6285. ngui_push_clip(l->ui, (struct ngui_rect){
  6286. x + 1, ry + 1,
  6287. w > 2 ? w - 2 : 1,
  6288. hh > 2 ? hh - 2 : 1 });
  6289. ngui_text_px_face(l->ui, run_face(r),
  6290. tx - scroll,
  6291. ry + (hh - r->font_px) / 2 - 1,
  6292. txt, tl, fg, r->font_px,
  6293. r->bold, r->italic, r->mono);
  6294. if (focused && fs && editable) {
  6295. int cw = 0;
  6296. if (fs->len && fs->caret)
  6297. cw = (int)run_text_width(
  6298. l->ui, r, txt,
  6299. fs->caret < fs->len ?
  6300. fs->caret : fs->len);
  6301. ngui_fill_rect(l->ui,
  6302. (struct ngui_rect){
  6303. tx + cw - scroll,
  6304. ry + 4, 1,
  6305. hh > 8 ? hh - 8 : 1
  6306. },
  6307. l->ui->theme.accent);
  6308. }
  6309. ngui_pop_clip(l->ui);
  6310. if (r->form_kind == FORM_SELECT) {
  6311. ngui_text_px(l->ui, x + w - 12,
  6312. ry + 2, "v", 1, fg,
  6313. r->font_px, 0, 0, 0);
  6314. }
  6315. }
  6316. } else if (r->img == RUN_PBOX) {
  6317. struct ngui_rect bx = { x, ry, w, r->ih };
  6318. ngui_push_clip(l->ui, bx);
  6319. if (r->pb_has_bg)
  6320. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6321. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6322. images[r->pb_img].state == 1) {
  6323. /* Rotate about the box centre: the
  6324. * image is centred in it here. */
  6325. draw_image_transformed(l->ui,
  6326. &images[r->pb_img].img,
  6327. x + r->pb_x, ry + r->pb_y,
  6328. r->pb_w, r->pb_h,
  6329. r->transform_scale ?
  6330. r->scale_x : 100,
  6331. r->transform_scale ?
  6332. r->scale_y : 100,
  6333. r->transform_scale ?
  6334. r->rotate_x100 : 0,
  6335. 50, 50, 1, 1);
  6336. }
  6337. ngui_pop_clip(l->ui);
  6338. } else if (r->img == RUN_SVG) {
  6339. struct br_style sst;
  6340. style_for_node(r->off, &sst);
  6341. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6342. r->ih);
  6343. } else if (r->img == -2) {
  6344. int hh = r->ih ? r->ih : 20;
  6345. ngui_fill_rect(l->ui,
  6346. (struct ngui_rect){x, ry, w, hh},
  6347. l->ui->theme.panel_alt);
  6348. ngui_frame(l->ui,
  6349. (struct ngui_rect){x, ry, w, hh},
  6350. l->ui->theme.border);
  6351. ngui_text_px_face(l->ui, run_face(r),
  6352. x + 6, ry + 2, r->lit,
  6353. s_len(r->lit), r->color,
  6354. r->font_px, r->bold, r->italic,
  6355. r->mono);
  6356. } else if (r->img >= 0) {
  6357. struct br_image *bi = &images[r->img];
  6358. if (bi->state == 1 && r->transform_scale) {
  6359. draw_image_transformed(l->ui, &bi->img,
  6360. x, ry, r->iw, r->ih,
  6361. r->scale_x, r->scale_y,
  6362. r->rotate_x100, r->origin_x,
  6363. r->origin_y, r->origin_x_kind,
  6364. r->origin_y_kind);
  6365. } else if (bi->state == 1) {
  6366. struct img_image *src =
  6367. image_display_get(bi, r->iw, r->ih);
  6368. struct img_blit b;
  6369. if (!src)
  6370. src = &bi->img;
  6371. b.dst = l->ui->px;
  6372. b.dst_w = l->ui->w;
  6373. b.dst_h = l->ui->h;
  6374. b.clip_x = page_rect.x;
  6375. b.clip_y = page_rect.y;
  6376. b.clip_w = page_rect.w - 12;
  6377. b.clip_h = page_rect.h;
  6378. b.x = x;
  6379. b.y = ry;
  6380. b.scale = ((unsigned int)r->iw << 16) /
  6381. src->w;
  6382. b.bg = ui.theme.bg;
  6383. b.bg2 = ui.theme.bg;
  6384. b.dst_a = 0;
  6385. b.flags = src->alpha ?
  6386. IMG_BLIT_OVER_DST : 0;
  6387. img_draw(src, &b);
  6388. }
  6389. } else {
  6390. const char *s = r->has_lit ? r->lit :
  6391. doc.text + r->off;
  6392. unsigned int n = r->has_lit ? s_len(r->lit) :
  6393. r->len;
  6394. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6395. s, n, r->color, r->font_px,
  6396. r->bold, r->italic, r->mono);
  6397. if (r->underline)
  6398. ngui_fill_rect(l->ui,
  6399. (struct ngui_rect){x,
  6400. ry + run_ascent(l->ui, r) + 2,
  6401. w, 1}, r->color);
  6402. if (r->strike)
  6403. ngui_fill_rect(l->ui,
  6404. (struct ngui_rect){x,
  6405. ry + run_ascent(l->ui, r) -
  6406. (r->font_px > 3 ?
  6407. r->font_px / 3 : 1),
  6408. w, 1}, r->color);
  6409. if (r->overline)
  6410. ngui_fill_rect(l->ui,
  6411. (struct ngui_rect){x, ry,
  6412. w, 1}, r->color);
  6413. }
  6414. if (r->form || r->href) {
  6415. if (nhits < HIT_MAX) {
  6416. struct hit *h = &hits[nhits];
  6417. unsigned int target = r->form ?
  6418. r->form - 1 : r->href;
  6419. int hh = (r->form || r->img >= 0 ||
  6420. r->img == RUN_SVG) ?
  6421. r->ih :
  6422. run_line_height(l->ui, r);
  6423. int merge = nhits > 0 &&
  6424. hits[nhits - 1].node == target &&
  6425. hits[nhits - 1].y == ry &&
  6426. hits[nhits - 1].h == hh &&
  6427. x <= hits[nhits - 1].x +
  6428. hits[nhits - 1].w + 2;
  6429. if (merge) {
  6430. struct hit *p = &hits[nhits - 1];
  6431. int end = x + w;
  6432. if (end > p->x + p->w)
  6433. p->w = end - p->x;
  6434. } else {
  6435. h->x = x;
  6436. h->y = ry;
  6437. h->w = w;
  6438. h->h = hh;
  6439. h->node = (unsigned short)target;
  6440. nhits++;
  6441. }
  6442. }
  6443. }
  6444. }
  6445. x += w;
  6446. }
  6447. l->y += l->line_h + 2;
  6448. if (l->float_active && l->y >= l->float_bottom)
  6449. l->float_active = 0;
  6450. l->nruns = 0;
  6451. l->line_x = l->left;
  6452. l->run_x = l->left;
  6453. l->line_left = l->left;
  6454. l->line_right = l->right;
  6455. l->line_h = 0;
  6456. l->space_pending = 0;
  6457. }
  6458. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6459. const struct br_style *st, unsigned short href,
  6460. const char *lit)
  6461. {
  6462. unsigned int n = lit ? s_len(lit) : len;
  6463. const char *tp = lit ? lit : doc.text + off;
  6464. int w = (int)face_text_width(l->ui, st, tp, n);
  6465. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6466. flush_line(l);
  6467. if (l->nruns == 0) {
  6468. l->line_y = l->y;
  6469. l->line_h = 0;
  6470. start_line(l, st);
  6471. }
  6472. {
  6473. struct lay_run *r = &l->runs[l->nruns++];
  6474. int gap = l->line_x - l->run_x;
  6475. if (gap < 0)
  6476. gap = 0;
  6477. r->gap = (unsigned short)gap;
  6478. r->off = off;
  6479. r->len = len;
  6480. r->color = st->color;
  6481. r->href = href;
  6482. r->dy = 0;
  6483. r->has_lit = 0;
  6484. r->form = 0;
  6485. r->form_kind = 0;
  6486. r->form_disabled = 0;
  6487. r->lit[0] = '\0';
  6488. if (lit && lit[0]) {
  6489. unsigned int i;
  6490. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6491. r->lit[i] = lit[i];
  6492. r->lit[i] = '\0';
  6493. r->has_lit = 1;
  6494. }
  6495. r->img = -1;
  6496. r->iw = r->ih = 0;
  6497. r->font_px = st->font_px;
  6498. r->bold = st->bold;
  6499. r->italic = st->italic;
  6500. r->mono = st->mono;
  6501. r->font_face = st->font_face;
  6502. /* A control with its own background is a button, not body copy;
  6503. * an inherited link underline would strike through the fill. */
  6504. r->underline = st->underline && !st->has_bg;
  6505. r->strike = st->strike && !st->has_bg;
  6506. r->overline = st->overline && !st->has_bg;
  6507. r->w = (unsigned short)w;
  6508. if (r->has_lit)
  6509. r->w = (unsigned short)run_text_width(
  6510. l->ui, r, r->lit, s_len(r->lit));
  6511. w = r->w;
  6512. }
  6513. l->line_x += w;
  6514. l->run_x = l->line_x;
  6515. {
  6516. int lh = face_line_height(l->ui, st);
  6517. if (st->line_h_px)
  6518. lh = st->line_h_px;
  6519. else if (st->line_h_pct)
  6520. lh = st->font_px * st->line_h_pct / 100;
  6521. if (lh < face_line_height(l->ui, st))
  6522. lh = face_line_height(l->ui, st);
  6523. if (l->line_h < lh)
  6524. l->line_h = lh;
  6525. }
  6526. }
  6527. static void add_image_run(struct lay *l, unsigned int node,
  6528. const struct br_style *st, unsigned short href)
  6529. {
  6530. struct br_image *bi = 0;
  6531. int idx = doc.nodes[node].img_index;
  6532. int dw, dh, maxw;
  6533. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6534. bi = &images[idx];
  6535. if (l->nruns == 0)
  6536. start_line(l, st);
  6537. if (l->space_pending &&
  6538. (l->nruns > 0 || l->line_x > l->line_left)) {
  6539. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6540. if (l->line_x + sp <= l->line_right)
  6541. l->line_x += sp;
  6542. }
  6543. l->space_pending = 0;
  6544. if (!bi) {
  6545. const char *alt = br_alt(&doc, node);
  6546. struct br_style gs = *st;
  6547. char tmp[96];
  6548. unsigned int n = 0;
  6549. int w;
  6550. gs.color = BR_GRAY;
  6551. gs.underline = 0;
  6552. s_append(tmp, &n, "[", sizeof(tmp));
  6553. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6554. s_append(tmp, &n, "]", sizeof(tmp));
  6555. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6556. if (l->line_x + w > l->line_right &&
  6557. (l->nruns > 0 || l->line_x > l->line_left))
  6558. flush_line(l);
  6559. add_run(l, 0, 0, &gs, href, tmp);
  6560. if (!l->draw) {
  6561. int t = l->line_y < 0 ? 0 : l->line_y;
  6562. int hh = face_line_height(l->ui, &gs);
  6563. if (t > 65535)
  6564. t = 65535;
  6565. if (hh > 65535)
  6566. hh = 65535;
  6567. img_top[node] = (unsigned short)t;
  6568. img_h[node] = (unsigned short)hh;
  6569. }
  6570. return;
  6571. }
  6572. maxw = l->line_right - l->line_left;
  6573. if (maxw < 8)
  6574. maxw = 8;
  6575. {
  6576. int iw = bi->native_w, ih = bi->native_h;
  6577. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6578. if (iw <= 0 || ih <= 0) {
  6579. iw = (int)bi->img.w;
  6580. ih = (int)bi->img.h;
  6581. }
  6582. dw = iw;
  6583. dh = ih;
  6584. if (doc.nodes[node].width_attr) {
  6585. int want = doc.nodes[node].width_attr;
  6586. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6587. have_w = 1;
  6588. }
  6589. if (doc.nodes[node].height_attr) {
  6590. int want = doc.nodes[node].height_attr;
  6591. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6592. have_h = 1;
  6593. }
  6594. if (have_w && !have_h)
  6595. dh = ih ? ih * dw / iw : 0;
  6596. if (have_h && !have_w)
  6597. dw = iw ? iw * dh / ih : 0;
  6598. if (st->width_kind) {
  6599. css_w = 1;
  6600. if (st->width_kind == 3)
  6601. dw = maxw * st->width_calc_pct / 100 +
  6602. st->width_calc_px;
  6603. else
  6604. dw = st->width_kind == 2 ?
  6605. maxw * (int)st->width / 100 :
  6606. (int)st->width;
  6607. }
  6608. /* Percentage heights resolve against the containing block's
  6609. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6610. * 2rem }` holding an `img { height: 100% }`), and are auto
  6611. * when it has none; they used to use the width. */
  6612. if (st->height_kind == 1 ||
  6613. ((st->height_kind == 2 || st->height_kind == 3) &&
  6614. l->cb_h > 0)) {
  6615. css_h = 1;
  6616. if (st->height_kind == 3)
  6617. dh = l->cb_h * st->height_calc_pct / 100 +
  6618. st->height_calc_px;
  6619. else
  6620. dh = st->height_kind == 2 ?
  6621. l->cb_h * (int)st->height / 100 :
  6622. (int)st->height;
  6623. }
  6624. if (css_w && !css_h)
  6625. dh = ih ? ih * dw / iw : 0;
  6626. if (css_h && !css_w)
  6627. dw = iw ? iw * dh / ih : 0;
  6628. if (st->max_width_kind) {
  6629. int mw = st->max_width_kind == 3 ?
  6630. maxw * st->max_width_calc_pct / 100 +
  6631. st->max_width_calc_px :
  6632. st->max_width_kind == 2 ?
  6633. maxw * (int)st->max_width / 100 :
  6634. (int)st->max_width;
  6635. if (mw > 0 && dw > mw) {
  6636. dh = iw ? ih * mw / iw : 0;
  6637. dw = mw;
  6638. }
  6639. }
  6640. }
  6641. if (dw < 8)
  6642. dw = 8;
  6643. if (dh < 8)
  6644. dh = 8;
  6645. if (dw > maxw) {
  6646. dh = dw ? dh * maxw / dw : dh;
  6647. dw = maxw;
  6648. }
  6649. if (!l->draw) {
  6650. int t = l->line_y < 0 ? 0 : l->line_y;
  6651. if (t > 65535)
  6652. t = 65535;
  6653. if (dh > 65535)
  6654. dh = 65535;
  6655. img_top[node] = (unsigned short)t;
  6656. img_h[node] = (unsigned short)dh;
  6657. }
  6658. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6659. l->line_x > l->line_left))
  6660. flush_line(l);
  6661. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6662. flush_line(l);
  6663. if (l->nruns == 0) {
  6664. l->line_y = l->y;
  6665. l->line_h = 0;
  6666. start_line(l, st);
  6667. }
  6668. {
  6669. struct lay_run *r = &l->runs[l->nruns++];
  6670. int gap = l->line_x - l->run_x;
  6671. if (gap < 0)
  6672. gap = 0;
  6673. r->gap = (unsigned short)gap;
  6674. r->off = 0;
  6675. r->len = 0;
  6676. r->color = 0;
  6677. r->href = href;
  6678. r->form = 0;
  6679. r->form_kind = 0;
  6680. r->form_disabled = 0;
  6681. /* Inline replaced elements honour their vertical margins; this
  6682. * is how Bootstrap's negative logo margins centre the wordmark. */
  6683. {
  6684. int idy = mp_px(st, 0, l->right - l->left);
  6685. if (idy < -2048)
  6686. idy = -2048;
  6687. if (idy > 2048)
  6688. idy = 2048;
  6689. r->dy = (signed short)idy;
  6690. }
  6691. r->has_lit = 0;
  6692. r->lit[0] = '\0';
  6693. r->img = (short)idx;
  6694. r->iw = (unsigned short)dw;
  6695. r->ih = (unsigned short)dh;
  6696. r->w = (unsigned short)dw;
  6697. r->font_px = st->font_px;
  6698. r->bold = st->bold;
  6699. r->italic = st->italic;
  6700. r->mono = st->mono;
  6701. r->font_face = st->font_face;
  6702. r->transform_scale = st->transform_scale;
  6703. r->scale_x = st->scale_x;
  6704. r->scale_y = st->scale_y;
  6705. r->rotate_x100 = st->rotate_x100;
  6706. r->origin_x = st->origin_x;
  6707. r->origin_y = st->origin_y;
  6708. r->origin_x_kind = st->origin_x_kind;
  6709. r->origin_y_kind = st->origin_y_kind;
  6710. r->underline = 0;
  6711. }
  6712. if (node < BR_MAX_NODES) {
  6713. layout_boxes[node].x = l->line_x;
  6714. layout_boxes[node].y = l->line_y +
  6715. mp_px(st, 0, l->right - l->left);
  6716. layout_boxes[node].w = dw;
  6717. layout_boxes[node].h = dh;
  6718. layout_boxes[node].valid = 1;
  6719. }
  6720. l->line_x += dw;
  6721. l->run_x = l->line_x;
  6722. if (l->line_h < dh)
  6723. l->line_h = dh;
  6724. }
  6725. /* An inline (or inline-block) <svg> is a replaced element in the text
  6726. * line, like an <img>: comment bubbles and arrows sit next to their label
  6727. * instead of starting a block of their own. */
  6728. static void add_svg_run(struct lay *l, unsigned int node,
  6729. const struct br_style *st, unsigned short href)
  6730. {
  6731. struct lay_run *r;
  6732. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6733. if (lw < 8)
  6734. lw = 8;
  6735. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6736. if (cw < 1)
  6737. cw = 1;
  6738. svg_size(node, st, cw, &dw, &dh);
  6739. if (dw > lw)
  6740. dw = lw;
  6741. ml = mp_px(st, 3, lw);
  6742. mr = mp_px(st, 1, lw);
  6743. if (ml < 0)
  6744. ml = 0;
  6745. if (mr < 0)
  6746. mr = 0;
  6747. if (l->line_x + ml + dw > l->line_right &&
  6748. (l->nruns > 0 || l->line_x > l->line_left))
  6749. flush_line(l);
  6750. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6751. flush_line(l);
  6752. if (l->nruns == 0) {
  6753. l->line_y = l->y;
  6754. l->line_h = 0;
  6755. start_line(l, st);
  6756. }
  6757. l->line_x += ml;
  6758. r = &l->runs[l->nruns++];
  6759. memset(r, 0, sizeof(*r));
  6760. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6761. l->line_x - l->run_x : 0);
  6762. r->off = node;
  6763. r->color = st->color;
  6764. r->href = href;
  6765. r->img = RUN_SVG;
  6766. r->iw = (unsigned short)dw;
  6767. r->ih = (unsigned short)dh;
  6768. r->w = (unsigned short)dw;
  6769. r->font_px = st->font_px;
  6770. if (node < BR_MAX_NODES) {
  6771. layout_boxes[node].x = l->line_x;
  6772. layout_boxes[node].y = l->line_y;
  6773. layout_boxes[node].w = dw;
  6774. layout_boxes[node].h = dh;
  6775. layout_boxes[node].valid = 1;
  6776. }
  6777. l->line_x += dw + mr;
  6778. l->run_x = l->line_x;
  6779. if (l->line_h < dh)
  6780. l->line_h = dh;
  6781. }
  6782. static int text_width(struct lay *l, const char *s, unsigned int n,
  6783. const struct br_style *st)
  6784. {
  6785. return (int)face_text_width(l->ui, st, s, n);
  6786. }
  6787. /* Longest prefix that fits in maxw, at least one byte. */
  6788. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6789. const struct br_style *st, int maxw)
  6790. {
  6791. unsigned int take = 0;
  6792. while (take < n) {
  6793. if (text_width(l, s, take + 1, st) > maxw)
  6794. break;
  6795. take++;
  6796. }
  6797. return take ? take : 1;
  6798. }
  6799. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6800. unsigned int n, unsigned int base,
  6801. const struct br_style *st, unsigned short href)
  6802. {
  6803. int avail;
  6804. int w = text_width(l, s + start, n, st);
  6805. unsigned int off = start;
  6806. if (l->nruns == 0)
  6807. start_line(l, st);
  6808. avail = l->line_right - l->line_left;
  6809. if (st->nowrap) {
  6810. if (n)
  6811. add_run(l, base + start,
  6812. (unsigned short)n, st, href, 0);
  6813. return;
  6814. }
  6815. /* A padded/bordered one-word button can be a few pixels wider than
  6816. * the content box; keep it on one line instead of splitting it. */
  6817. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6818. add_run(l, base + start,
  6819. (unsigned short)n, st, href, 0);
  6820. return;
  6821. }
  6822. if (l->line_x + w > l->line_right &&
  6823. (l->nruns > 0 || l->line_x > l->line_left)) {
  6824. flush_line(l);
  6825. start_line(l, st);
  6826. avail = l->line_right - l->line_left;
  6827. }
  6828. if (w <= avail) {
  6829. if (n)
  6830. add_run(l, base + start,
  6831. (unsigned short)n, st, href, 0);
  6832. return;
  6833. }
  6834. while (n > 0) {
  6835. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6836. add_run(l, base + off,
  6837. (unsigned short)take, st, href, 0);
  6838. off += take;
  6839. n -= take;
  6840. if (n) {
  6841. flush_line(l);
  6842. start_line(l, st);
  6843. avail = l->line_right - l->line_left;
  6844. }
  6845. }
  6846. }
  6847. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6848. const struct br_style *st, unsigned short href, int pre)
  6849. {
  6850. unsigned int i = 0;
  6851. unsigned int base;
  6852. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6853. if (!s || !len)
  6854. return;
  6855. if (space_w <= 0)
  6856. space_w = 8;
  6857. if (l->nruns == 0)
  6858. start_line(l, st);
  6859. base = (unsigned int)(s - doc.text);
  6860. if (st->uppercase) {
  6861. char *p = (char *)s;
  6862. unsigned int j;
  6863. for (j = 0; j < len; j++)
  6864. if (p[j] >= 'a' && p[j] <= 'z')
  6865. p[j] = (char)(p[j] - 'a' + 'A');
  6866. }
  6867. if (pre) {
  6868. while (i < len) {
  6869. unsigned int start;
  6870. if (s[i] == '\n') {
  6871. flush_line(l);
  6872. start_line(l, st);
  6873. i++;
  6874. continue;
  6875. }
  6876. if (s[i] == ' ') {
  6877. if (l->line_x + space_w > l->line_right &&
  6878. (l->nruns > 0 || l->line_x > l->line_left)) {
  6879. flush_line(l);
  6880. start_line(l, st);
  6881. } else {
  6882. l->line_x += space_w;
  6883. }
  6884. i++;
  6885. continue;
  6886. }
  6887. start = i;
  6888. while (i < len && s[i] != ' ' && s[i] != '\n')
  6889. i++;
  6890. emit_word(l, s, start, i - start, base, st, href);
  6891. }
  6892. return;
  6893. }
  6894. while (i < len) {
  6895. unsigned int start, n;
  6896. if (s[i] == ' ') {
  6897. l->space_pending = 1;
  6898. i++;
  6899. continue;
  6900. }
  6901. start = i;
  6902. while (i < len && s[i] != ' ')
  6903. i++;
  6904. n = i - start;
  6905. if (l->space_pending &&
  6906. (l->nruns > 0 || l->line_x > l->line_left)) {
  6907. if (st->nowrap ||
  6908. l->line_x + space_w <= l->line_right)
  6909. l->line_x += space_w;
  6910. }
  6911. l->space_pending = 0;
  6912. emit_word(l, s, start, n, base, st, href);
  6913. }
  6914. }
  6915. static int list_index(unsigned int parent, unsigned int node)
  6916. {
  6917. unsigned int n = 0, i;
  6918. for (i = doc.nodes[parent].first; i && i != node;
  6919. i = doc.nodes[i].next)
  6920. if (doc.nodes[i].tag == BR_TAG_LI)
  6921. n++;
  6922. return (int)n + 1;
  6923. }
  6924. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6925. unsigned int cap)
  6926. {
  6927. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6928. 50, 40, 10, 9, 5, 4, 1 };
  6929. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6930. "l", "xl", "x", "ix", "v", "iv", "i" };
  6931. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6932. "L", "XL", "X", "IX", "V", "IV", "I" };
  6933. unsigned int i;
  6934. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6935. while (v >= val[i] && *n + 1 < cap) {
  6936. const char *s = upper ? up[i] : lo[i];
  6937. while (*s && *n + 1 < cap)
  6938. m[(*n)++] = *s++;
  6939. v -= val[i];
  6940. }
  6941. }
  6942. }
  6943. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6944. {
  6945. unsigned int n = 0;
  6946. if (style == BR_LIST_DISC) {
  6947. m[n++] = '-';
  6948. } else if (style == BR_LIST_CIRCLE) {
  6949. m[n++] = 'o';
  6950. } else if (style == BR_LIST_SQUARE) {
  6951. m[n++] = '+';
  6952. } else if (style == BR_LIST_LOWER_ALPHA ||
  6953. style == BR_LIST_UPPER_ALPHA) {
  6954. if (idx >= 1 && idx <= 26)
  6955. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6956. 'A' : 'a') + idx - 1);
  6957. else
  6958. m[n++] = '?';
  6959. m[n++] = '.';
  6960. } else if (style == BR_LIST_LOWER_ROMAN ||
  6961. style == BR_LIST_UPPER_ROMAN) {
  6962. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6963. if (n + 1 < cap)
  6964. m[n++] = '.';
  6965. } else {
  6966. s_append_dec(m, &n, (unsigned int)idx, cap);
  6967. if (n + 1 < cap)
  6968. m[n++] = '.';
  6969. }
  6970. m[n] = '\0';
  6971. }
  6972. /* A control the page styled itself (background, border or radius in author
  6973. * CSS -- `background:transparent;border:none` counts) is painted with that
  6974. * style, sized from its padding/height and keeps the page's text colour.
  6975. * Unstyled controls keep the ngui theme look. */
  6976. static int form_author_styled(const struct br_style *st)
  6977. {
  6978. int i;
  6979. if (st->bg_set)
  6980. return 1;
  6981. for (i = 0; i < 4; i++)
  6982. if (st->border_w[i] || st->radius[i])
  6983. return 1;
  6984. return 0;
  6985. }
  6986. /* Set by the layout when the control is stretched to its line: a flex item
  6987. * (its box width was assigned by the flex row) or a child of a flex column,
  6988. * whose default align-items: stretch makes inputs full width. */
  6989. static int form_fill_line;
  6990. static void add_form_run(struct lay *l, unsigned int node,
  6991. const struct br_style *st, unsigned short href)
  6992. {
  6993. struct form_state *fs = form_get(node, 1);
  6994. char shown[FORM_VALUE_MAX + 1];
  6995. char opt[64];
  6996. const char *text = "";
  6997. struct lay_run *r;
  6998. int kind = form_kind_of(node);
  6999. int disabled = form_disabled(node);
  7000. int author = form_author_styled(st);
  7001. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7002. int ml = 0, mr = 0, mt = 0, mb = 0;
  7003. if (!fs)
  7004. return;
  7005. if (l->nruns == 0)
  7006. start_line(l, st);
  7007. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7008. text = "";
  7009. w = 16;
  7010. h = 16;
  7011. } else if (kind == FORM_SELECT) {
  7012. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7013. s_copy(opt, "Select", sizeof(opt));
  7014. text = opt;
  7015. w = 120;
  7016. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7017. kind == FORM_RESET) {
  7018. if (fs->len)
  7019. text = fs->value;
  7020. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7021. /* A <button>'s label is its content: an empty one
  7022. * (Docusaurus' sidebar caret, drawn by a CSS
  7023. * ::before icon) shows none. Only <input> buttons
  7024. * get the UA's default label. */
  7025. text = "";
  7026. else
  7027. text = kind == FORM_SUBMIT ? "Submit" :
  7028. kind == FORM_RESET ? "Reset" : "Button";
  7029. } else if (kind == FORM_PASSWORD) {
  7030. for (i = 0; i < fs->len; i++)
  7031. shown[i] = '*';
  7032. shown[fs->len] = '\0';
  7033. text = fs->len ? shown : br_placeholder(&doc, node);
  7034. } else {
  7035. if (fs->len)
  7036. text = fs->value;
  7037. else
  7038. text = br_placeholder(&doc, node);
  7039. if (kind == FORM_TEXTAREA) {
  7040. w = 180;
  7041. h = 40;
  7042. }
  7043. }
  7044. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7045. line_w = l->line_right - l->line_left;
  7046. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7047. st->border_w[1] + st->border_w[3];
  7048. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7049. st->border_w[0] + st->border_w[2];
  7050. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7051. /* Buttons are border-box in every UA stylesheet: an
  7052. * explicit width/height is the whole box. */
  7053. if (author || pad_x) {
  7054. w = tw + pad_x;
  7055. } else {
  7056. w = tw + 18;
  7057. if (w < 64)
  7058. w = 64;
  7059. }
  7060. if (st->width_kind)
  7061. w = style_width_px(st, line_w);
  7062. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7063. w = st->min_width;
  7064. if (st->height_kind == 1)
  7065. h = st->height;
  7066. else if (author)
  7067. h = st->font_px + 6 + pad_y;
  7068. else
  7069. h = 22;
  7070. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7071. kind == FORM_TEXTAREA) {
  7072. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7073. st->display == BR_DISPLAY_FLEX;
  7074. int boxed = st->box_sizing ? 0 : pad_x;
  7075. if (st->width_kind)
  7076. w = style_width_px(st, line_w) + boxed;
  7077. else if (fill)
  7078. w = line_w - (l->line_x - l->line_left);
  7079. else
  7080. w = kind == FORM_TEXTAREA ? 180 : 120;
  7081. if (kind == FORM_TEXTAREA) {
  7082. const char *ra = br_find_attr(&doc, node, "rows");
  7083. int rows = 0;
  7084. int lh = st->line_h_px ? st->line_h_px :
  7085. st->font_px * 5 / 4;
  7086. while (ra && *ra >= '0' && *ra <= '9')
  7087. rows = rows * 10 + (*ra++ - '0');
  7088. if (rows < 1 || rows > 40)
  7089. rows = 2;
  7090. h = author ? rows * lh + pad_y : 40;
  7091. } else if (author) {
  7092. h = st->font_px + 8 + pad_y;
  7093. } else if (st->font_px + 8 > h) {
  7094. /* Taller fields for large text (min-height/padding
  7095. * on login pages): keep the box around the glyphs. */
  7096. h = st->font_px + 8;
  7097. }
  7098. if (st->height_kind == 1)
  7099. h = st->height + (st->box_sizing ? 0 : pad_y);
  7100. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7101. h = st->min_height;
  7102. } else if (kind == FORM_SELECT) {
  7103. w = st->width_kind == 1 ? st->width : 120;
  7104. }
  7105. if (author) {
  7106. /* Inline margins (Google's `margin:11px 4px` between its
  7107. * two submit buttons). */
  7108. ml = mp_px(st, 3, line_w);
  7109. mr = mp_px(st, 1, line_w);
  7110. mt = mp_px(st, 0, line_w);
  7111. mb = mp_px(st, 2, line_w);
  7112. if (ml < 0 || ml > 64) ml = 0;
  7113. if (mr < 0 || mr > 64) mr = 0;
  7114. if (mt < 0 || mt > 64) mt = 0;
  7115. if (mb < 0 || mb > 64) mb = 0;
  7116. }
  7117. if (w > line_w - ml - mr)
  7118. w = line_w - ml - mr;
  7119. if (w < 8)
  7120. w = 8;
  7121. if (h > 400)
  7122. h = 400;
  7123. if (l->line_x + ml + w > l->line_right &&
  7124. (l->nruns > 0 || l->line_x > l->line_left))
  7125. flush_line(l);
  7126. if (l->nruns >= 96)
  7127. return;
  7128. if (l->nruns == 0) {
  7129. l->line_y = l->y;
  7130. l->line_h = 0;
  7131. start_line(l, st);
  7132. }
  7133. l->line_x += ml;
  7134. r = &l->runs[l->nruns++];
  7135. r->gap = (unsigned short)(l->line_x - l->run_x);
  7136. r->off = r->len = 0;
  7137. r->color = st->color;
  7138. r->href = href;
  7139. r->dy = (signed short)mt;
  7140. r->has_lit = 1;
  7141. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7142. r->lit[i] = text[i];
  7143. r->lit[i] = '\0';
  7144. r->img = -2;
  7145. r->iw = (unsigned short)w;
  7146. r->ih = (unsigned short)h;
  7147. r->w = (unsigned short)w;
  7148. r->font_px = st->font_px;
  7149. r->bold = st->bold;
  7150. r->italic = st->italic;
  7151. r->mono = st->mono;
  7152. r->font_face = st->font_face;
  7153. r->underline = 0;
  7154. r->form = node + 1;
  7155. r->form_kind = (unsigned char)kind;
  7156. r->form_disabled = (unsigned char)disabled;
  7157. if (node < BR_MAX_NODES) {
  7158. layout_boxes[node].x = l->line_x;
  7159. layout_boxes[node].y = l->line_y + mt;
  7160. layout_boxes[node].w = w;
  7161. layout_boxes[node].h = h;
  7162. layout_boxes[node].valid = 1;
  7163. }
  7164. l->line_x += w;
  7165. l->run_x = l->line_x;
  7166. l->line_x += mr;
  7167. if (l->line_h < h + mt + mb)
  7168. l->line_h = h + mt + mb;
  7169. }
  7170. /* Background, border and corner radius of an author-styled control, the
  7171. * same decoration rules as a block box. */
  7172. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7173. const struct br_style *st, int focused)
  7174. {
  7175. int rtl = css_radius(st, 0, box.w, box.h);
  7176. int rtr = css_radius(st, 1, box.w, box.h);
  7177. int rbr = css_radius(st, 2, box.w, box.h);
  7178. int rbl = css_radius(st, 3, box.w, box.h);
  7179. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7180. (void)focused;
  7181. if (box.w <= 0 || box.h <= 0)
  7182. return;
  7183. if (rtl || rtr || rbr || rbl) {
  7184. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7185. box.w > bw * 2 && box.h > bw * 2) {
  7186. struct ngui_rect in = { box.x + bw, box.y + bw,
  7187. box.w - bw * 2,
  7188. box.h - bw * 2 };
  7189. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7190. st->border_c[0]);
  7191. ngui_fill_round_rect(ui, in,
  7192. rtl > bw ? rtl - bw : 0,
  7193. rtr > bw ? rtr - bw : 0,
  7194. rbr > bw ? rbr - bw : 0,
  7195. rbl > bw ? rbl - bw : 0, st->bg);
  7196. } else if (st->has_bg) {
  7197. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7198. st->bg);
  7199. } else if (bw > 0) {
  7200. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7201. st->border_c[0]);
  7202. }
  7203. return;
  7204. }
  7205. if (st->has_bg)
  7206. ngui_fill_rect(ui, box, st->bg);
  7207. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7208. st->border_w[3])
  7209. draw_border_box(ui, box, st);
  7210. }
  7211. /* A poster wrapper is absolutely positioned over the media slot; the
  7212. * measured height of its picture is normally added back to the flow. When a
  7213. * loading-skeleton sibling already reserves that slot, adding both doubles
  7214. * the media height and pushes the article text a full screen down. */
  7215. static int has_skeleton_sibling(unsigned int node)
  7216. {
  7217. unsigned int p = doc.nodes[node].parent, c;
  7218. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7219. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7220. continue;
  7221. if (doc.nodes[c].class_off &&
  7222. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7223. "skeleton"))
  7224. return 1;
  7225. }
  7226. return 0;
  7227. }
  7228. static void layout_children(struct lay *l, unsigned int parent,
  7229. const struct br_style *pst, int depth,
  7230. unsigned short link);
  7231. static void layout_flex_children(struct lay *l, unsigned int parent,
  7232. const struct br_style *pst, int depth,
  7233. unsigned short link);
  7234. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7235. struct br_style *ps, int base);
  7236. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7237. const struct br_style *ps, unsigned short link);
  7238. static void layout_grid_children(struct lay *l, unsigned int parent,
  7239. const struct br_style *pst, int depth,
  7240. unsigned short link);
  7241. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7242. const struct br_style *pst, int depth,
  7243. unsigned short link);
  7244. static int flex_item_width(struct lay *l, unsigned int n,
  7245. const struct br_style *cs, int avail);
  7246. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7247. const struct br_style *pst, int depth,
  7248. unsigned short link);
  7249. static void layout_table_row(struct lay *l, unsigned int row,
  7250. const struct br_style *pst, int depth,
  7251. unsigned short link);
  7252. static int table_has_rowspan(unsigned int table);
  7253. static void layout_table(struct lay *l, unsigned int table,
  7254. const struct br_style *st, int depth,
  7255. unsigned short link);
  7256. /* A flex container whose items are only inline spans is usually just a
  7257. * heading/icon pair. Our flex row positions such items without emitting
  7258. * their inline text in some deep page contexts; normal inline flow renders
  7259. * the same content correctly. */
  7260. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7261. const struct br_style *cs, int depth,
  7262. unsigned short lk);
  7263. static void layout_flex_column(struct lay *l, unsigned int parent,
  7264. const struct br_style *pst, int depth,
  7265. unsigned short link);
  7266. static void emit_pseudo(struct lay *l, unsigned int node,
  7267. const struct br_style *st, int pe, unsigned short link);
  7268. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7269. {
  7270. unsigned int c;
  7271. int items = 0;
  7272. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7273. struct br_node *nd = &doc.nodes[c];
  7274. struct br_style cs;
  7275. if (nd->type == BR_NODE_TEXT)
  7276. continue;
  7277. br_style_for(&doc, c, pst, &cs);
  7278. if (cs.display == BR_DISPLAY_NONE)
  7279. continue;
  7280. /* `justify-content: space-between` spreads even two plain
  7281. * inline items (a "Password ... Reset password" label row)
  7282. * across the line; inline flow would set them side by side. */
  7283. if (++items >= 2 && pst->justify >= 3)
  7284. return 1;
  7285. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7286. cs.width_kind || cs.has_bg ||
  7287. cs.border_w[0] || cs.border_w[1] ||
  7288. cs.border_w[2] || cs.border_w[3] ||
  7289. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7290. return 1;
  7291. }
  7292. return 0;
  7293. }
  7294. static int css_radius(const struct br_style *st, int corner,
  7295. int w, int h)
  7296. {
  7297. int r = st->radius[corner];
  7298. if (r <= 0)
  7299. return 0;
  7300. if (r > w / 2)
  7301. r = w / 2;
  7302. if (r > h / 2)
  7303. r = h / 2;
  7304. return r;
  7305. }
  7306. /* ---- inline SVG ----
  7307. *
  7308. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7309. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7310. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7311. * opacity and solid paint; a gradient paints the average of its stops) and
  7312. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7313. #define SVG_CACHE_MAX 48
  7314. #define SVG_CACHE_PIXELS (640 * 1024)
  7315. #define SVG_MAX_POINTS 24576
  7316. struct svg_cache_ent {
  7317. unsigned int node;
  7318. int w, h;
  7319. unsigned short *px;
  7320. unsigned char *a;
  7321. unsigned int stamp;
  7322. };
  7323. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7324. static unsigned int svg_cache_pixels, svg_cache_clock;
  7325. static struct svgr svg_geom;
  7326. static void *svg_geom_buf;
  7327. /* Current viewport in user units: percentage lengths resolve against it
  7328. * (the viewBox size, not the device pixels). */
  7329. static double svg_vp_w = 300, svg_vp_h = 150;
  7330. /* The layers live in the page heap: forget them before heap_reset(). */
  7331. static void svg_cache_clear(void)
  7332. {
  7333. memset(svg_cache, 0, sizeof(svg_cache));
  7334. svg_cache_pixels = 0;
  7335. svg_geom_buf = 0;
  7336. }
  7337. static int svg_name_is(const char *a, const char *b)
  7338. {
  7339. while (*a && *b) {
  7340. char x = *a, y = *b;
  7341. if (x >= 'A' && x <= 'Z')
  7342. x = (char)(x - 'A' + 'a');
  7343. if (x != y)
  7344. return 0;
  7345. a++;
  7346. b++;
  7347. }
  7348. return *a == *b;
  7349. }
  7350. static const char *svg_elem_name(unsigned int node)
  7351. {
  7352. const struct br_node *nd = &doc.nodes[node];
  7353. if (nd->name_off)
  7354. return doc.attrs + nd->name_off;
  7355. return br_tag_name(nd->tag);
  7356. }
  7357. /* A numeric attribute; a percentage resolves against `base`. */
  7358. static double svg_attr_num(unsigned int node, const char *name, double def,
  7359. double base)
  7360. {
  7361. const char *v = br_find_attr(&doc, node, name);
  7362. const char *p = v;
  7363. int ok = 0;
  7364. double x;
  7365. if (!v)
  7366. return def;
  7367. x = svgr_num(&p, &ok);
  7368. if (!ok)
  7369. return def;
  7370. if (*p == '%')
  7371. x = x * base / 100.0;
  7372. return x;
  7373. }
  7374. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7375. static int svg_viewbox4(unsigned int node, double vb[4])
  7376. {
  7377. const char *v = br_find_attr(&doc, node, "viewbox");
  7378. const char *p = v;
  7379. int i, ok = 1;
  7380. if (!v)
  7381. return 0;
  7382. for (i = 0; i < 4 && ok; i++)
  7383. vb[i] = svgr_num(&p, &ok);
  7384. return ok && vb[2] > 0 && vb[3] > 0;
  7385. }
  7386. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7387. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7388. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7389. double w, double h, double m[6])
  7390. {
  7391. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7392. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7393. int ax = 1, ay = 1;
  7394. if (par && contains_ci(par, "none")) {
  7395. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7396. m[4] = -vb[0] * sx;
  7397. m[5] = -vb[1] * sy;
  7398. return;
  7399. }
  7400. if (par) {
  7401. if (contains_ci(par, "xmin"))
  7402. ax = 0;
  7403. else if (contains_ci(par, "xmax"))
  7404. ax = 2;
  7405. if (contains_ci(par, "ymin"))
  7406. ay = 0;
  7407. else if (contains_ci(par, "ymax"))
  7408. ay = 2;
  7409. }
  7410. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7411. (sx < sy ? sx : sy);
  7412. tx = (w - vb[2] * s) * ax / 2.0;
  7413. ty = (h - vb[3] * s) * ay / 2.0;
  7414. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7415. m[4] = tx - vb[0] * s;
  7416. m[5] = ty - vb[1] * s;
  7417. }
  7418. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7419. * the paint attribute, then average the gradient's stops. */
  7420. static int svg_url_paint(unsigned int node, const char *attr,
  7421. unsigned short *color, unsigned int *alpha)
  7422. {
  7423. const char *v = 0, *h;
  7424. char id[64];
  7425. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7426. for (k = 0; node && k < 32 && !v; k++) {
  7427. v = br_find_attr(&doc, node, attr);
  7428. if (!v) {
  7429. const char *style = br_find_attr(&doc, node, "style");
  7430. if (style && contains_ci(style, "url(#"))
  7431. v = strstr(style, "url(#");
  7432. }
  7433. if (v && !contains_ci(v, "url("))
  7434. v = 0;
  7435. node = doc.nodes[node].parent;
  7436. }
  7437. if (!v || !(h = strstr(v, "#")))
  7438. return 0;
  7439. h++;
  7440. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7441. id[n++] = *h++;
  7442. id[n] = '\0';
  7443. g = br_find_id(&doc, id);
  7444. /* Follow href chains (a gradient that only references another one's
  7445. * stops), at most a few hops. */
  7446. for (k = 0; g && k < 4; k++) {
  7447. unsigned int gi = g - 1;
  7448. const char *ref;
  7449. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7450. const char *nm, *sc, *so;
  7451. unsigned short col = 0;
  7452. double op = 1;
  7453. if (doc.nodes[c].type != BR_NODE_ELEM)
  7454. continue;
  7455. nm = svg_elem_name(c);
  7456. if (!svg_name_is(nm, "stop"))
  7457. continue;
  7458. sc = br_find_attr(&doc, c, "stop-color");
  7459. so = br_find_attr(&doc, c, "stop-opacity");
  7460. {
  7461. const char *st = br_find_attr(&doc, c, "style");
  7462. const char *q;
  7463. if (st && (q = strstr(st, "stop-color:")) != 0)
  7464. sc = q + 11;
  7465. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7466. so = q + 13;
  7467. }
  7468. if (sc) {
  7469. unsigned int L = 0;
  7470. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7471. L++;
  7472. if (!br_parse_color(sc, L, &col))
  7473. col = 0;
  7474. }
  7475. if (so) {
  7476. const char *p = so;
  7477. int ok = 0;
  7478. double x = svgr_num(&p, &ok);
  7479. if (ok)
  7480. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7481. }
  7482. sr += (col >> 11) & 31;
  7483. sg += (col >> 5) & 63;
  7484. sb += col & 31;
  7485. sa += (unsigned int)(op * 255);
  7486. cnt++;
  7487. }
  7488. if (cnt)
  7489. break;
  7490. ref = br_find_attr(&doc, gi, "href");
  7491. if (!ref)
  7492. ref = br_find_attr(&doc, gi, "xlink:href");
  7493. if (!ref || ref[0] != '#')
  7494. break;
  7495. g = br_find_id(&doc, ref + 1);
  7496. }
  7497. if (!cnt)
  7498. return 0;
  7499. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7500. (sb / cnt));
  7501. *alpha = sa / cnt;
  7502. return 1;
  7503. }
  7504. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7505. unsigned short *color, unsigned int *alpha)
  7506. {
  7507. int mode = fill ? st->fill_mode : st->stroke_mode;
  7508. const char *op = br_find_attr(&doc, node,
  7509. fill ? "fill-opacity" : "stroke-opacity");
  7510. *alpha = 255;
  7511. switch (mode) {
  7512. case BR_PAINT_UNSET:
  7513. if (!fill)
  7514. return 0;
  7515. *color = 0;
  7516. break;
  7517. case BR_PAINT_COLOR:
  7518. *color = fill ? st->fill : st->stroke;
  7519. break;
  7520. case BR_PAINT_CURRENT:
  7521. *color = st->color;
  7522. break;
  7523. case BR_PAINT_URL:
  7524. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7525. alpha))
  7526. return 0;
  7527. break;
  7528. default:
  7529. return 0;
  7530. }
  7531. if (op) {
  7532. const char *p = op;
  7533. int ok = 0;
  7534. double x = svgr_num(&p, &ok);
  7535. if (ok)
  7536. *alpha = (unsigned int)(*alpha *
  7537. (x < 0 ? 0 : x > 1 ? 1 : x));
  7538. }
  7539. return *alpha > 0;
  7540. }
  7541. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7542. const double m[6], const struct br_style *pst,
  7543. unsigned int alpha, int depth);
  7544. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7545. const double m[6], const struct br_style *st,
  7546. unsigned int alpha, int depth)
  7547. {
  7548. unsigned int c;
  7549. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7550. if (doc.nodes[c].type == BR_NODE_ELEM)
  7551. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7552. }
  7553. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7554. const double pm[6], const struct br_style *pst,
  7555. unsigned int alpha, int depth)
  7556. {
  7557. struct br_style st;
  7558. const char *nm = svg_elem_name(node);
  7559. const char *tf;
  7560. double m[6];
  7561. unsigned short color;
  7562. unsigned int pa;
  7563. int shape = 0, fillable = 1;
  7564. if (depth > 24 || !nm)
  7565. return;
  7566. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7567. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7568. svg_name_is(nm, "lineargradient") ||
  7569. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7570. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7571. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7572. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7573. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7574. svg_name_is(nm, "foreignobject"))
  7575. return;
  7576. br_style_for(&doc, node, pst, &st);
  7577. if (st.display == BR_DISPLAY_NONE)
  7578. return;
  7579. memcpy(m, pm, sizeof(m));
  7580. tf = br_find_attr(&doc, node, "transform");
  7581. if (tf)
  7582. svgr_transform(m, tf);
  7583. {
  7584. const char *op = br_find_attr(&doc, node, "opacity");
  7585. if (op) {
  7586. const char *p = op;
  7587. int ok = 0;
  7588. double x = svgr_num(&p, &ok);
  7589. if (ok)
  7590. alpha = (unsigned int)(alpha *
  7591. (x < 0 ? 0 :
  7592. x > 1 ? 1 : x));
  7593. }
  7594. }
  7595. if (!alpha)
  7596. return;
  7597. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7598. svg_name_is(nm, "switch")) {
  7599. svg_draw_children(L, node, m, &st, alpha, depth);
  7600. return;
  7601. }
  7602. if (svg_name_is(nm, "svg")) {
  7603. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7604. y = svg_attr_num(node, "y", 0, 0);
  7605. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7606. t[4] = x;
  7607. t[5] = y;
  7608. svgr_mat_mul(m, m, t);
  7609. double ow = svg_vp_w, oh = svg_vp_h;
  7610. if (svg_viewbox4(node, vb)) {
  7611. double w = svg_attr_num(node, "width", vb[2], ow);
  7612. double h = svg_attr_num(node, "height", vb[3], oh);
  7613. double vm[6];
  7614. svg_viewport_matrix(node, vb, w, h, vm);
  7615. svgr_mat_mul(m, m, vm);
  7616. svg_vp_w = vb[2];
  7617. svg_vp_h = vb[3];
  7618. }
  7619. svg_draw_children(L, node, m, &st, alpha, depth);
  7620. svg_vp_w = ow;
  7621. svg_vp_h = oh;
  7622. return;
  7623. }
  7624. if (svg_name_is(nm, "use")) {
  7625. const char *ref = br_find_attr(&doc, node, "href");
  7626. unsigned int tgt;
  7627. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7628. if (!ref)
  7629. ref = br_find_attr(&doc, node, "xlink:href");
  7630. if (!ref || ref[0] != '#')
  7631. return;
  7632. tgt = br_find_id(&doc, ref + 1);
  7633. if (!tgt || tgt - 1 == node)
  7634. return;
  7635. tgt--;
  7636. t[4] = svg_attr_num(node, "x", 0, 0);
  7637. t[5] = svg_attr_num(node, "y", 0, 0);
  7638. svgr_mat_mul(m, m, t);
  7639. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7640. double vb[4];
  7641. double ow = svg_vp_w, oh = svg_vp_h;
  7642. if (svg_viewbox4(tgt, vb)) {
  7643. /* A <use> without width/height sizes the
  7644. * symbol to 100% of the viewport: Docusaurus'
  7645. * 13.5px external-link icon references a
  7646. * 24-unit symbol and showed only its corner. */
  7647. double w = svg_attr_num(node, "width",
  7648. ow > 0 ? ow : vb[2], ow);
  7649. double h = svg_attr_num(node, "height",
  7650. oh > 0 ? oh : vb[3], oh);
  7651. double vm[6];
  7652. svg_viewport_matrix(tgt, vb, w, h, vm);
  7653. svgr_mat_mul(m, m, vm);
  7654. svg_vp_w = vb[2];
  7655. svg_vp_h = vb[3];
  7656. }
  7657. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7658. svg_vp_w = ow;
  7659. svg_vp_h = oh;
  7660. } else {
  7661. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7662. }
  7663. return;
  7664. }
  7665. svgr_reset(&svg_geom, m);
  7666. if (svg_name_is(nm, "path")) {
  7667. const char *d = br_find_attr(&doc, node, "d");
  7668. if (d) {
  7669. svgr_path(&svg_geom, d);
  7670. shape = 1;
  7671. }
  7672. } else if (svg_name_is(nm, "rect")) {
  7673. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7674. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7675. double rx = svg_attr_num(node, "rx", -1, w);
  7676. double ry = svg_attr_num(node, "ry", -1, h);
  7677. if (rx < 0)
  7678. rx = ry < 0 ? 0 : ry;
  7679. if (ry < 0)
  7680. ry = rx;
  7681. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7682. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7683. shape = 1;
  7684. } else if (svg_name_is(nm, "circle")) {
  7685. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7686. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7687. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7688. shape = 1;
  7689. } else if (svg_name_is(nm, "ellipse")) {
  7690. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7691. svg_attr_num(node, "cy", 0, svg_vp_h),
  7692. svg_attr_num(node, "rx", 0, svg_vp_w),
  7693. svg_attr_num(node, "ry", 0, svg_vp_h));
  7694. shape = 1;
  7695. } else if (svg_name_is(nm, "line")) {
  7696. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7697. svg_attr_num(node, "y1", 0, svg_vp_h));
  7698. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7699. svg_attr_num(node, "y2", 0, svg_vp_h));
  7700. shape = 1;
  7701. fillable = 0;
  7702. } else if (svg_name_is(nm, "polyline") ||
  7703. svg_name_is(nm, "polygon")) {
  7704. const char *pts = br_find_attr(&doc, node, "points");
  7705. if (pts) {
  7706. svgr_points(&svg_geom, pts,
  7707. svg_name_is(nm, "polygon"));
  7708. shape = 1;
  7709. }
  7710. }
  7711. if (!shape)
  7712. return;
  7713. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7714. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7715. st.fill_evenodd);
  7716. if (svg_paint(node, &st, 0, &color, &pa)) {
  7717. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7718. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7719. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7720. }
  7721. }
  7722. /* <text> elements: drawn straight onto the page every frame (the glyph
  7723. * renderer targets the ngui canvas, not a layer). x/y map through the
  7724. * accumulated transform; the font size scales with it. */
  7725. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7726. const double pm[6], const struct br_style *pst,
  7727. int ox, int oy, int depth)
  7728. {
  7729. unsigned int c;
  7730. if (depth > 24)
  7731. return;
  7732. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7733. struct br_style st;
  7734. const char *nm, *tf;
  7735. double m[6];
  7736. if (doc.nodes[c].type != BR_NODE_ELEM)
  7737. continue;
  7738. nm = svg_elem_name(c);
  7739. if (!nm || svg_name_is(nm, "defs") ||
  7740. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7741. svg_name_is(nm, "clippath"))
  7742. continue;
  7743. br_style_for(&doc, c, pst, &st);
  7744. if (st.display == BR_DISPLAY_NONE)
  7745. continue;
  7746. memcpy(m, pm, sizeof(m));
  7747. tf = br_find_attr(&doc, c, "transform");
  7748. if (tf)
  7749. svgr_transform(m, tf);
  7750. if (svg_name_is(nm, "text")) {
  7751. unsigned int t = doc.nodes[c].first;
  7752. const char *s;
  7753. unsigned int n, tw;
  7754. double x = svg_attr_num(c, "x", 0, 0),
  7755. y = svg_attr_num(c, "y", 0, 0);
  7756. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7757. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7758. int tx, ty, anchor;
  7759. unsigned short col;
  7760. unsigned int pa;
  7761. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7762. continue;
  7763. if (px < 6)
  7764. px = 6;
  7765. if (px > 72)
  7766. px = 72;
  7767. if (!svg_paint(c, &st, 1, &col, &pa))
  7768. continue;
  7769. s = doc.text + doc.nodes[t].text_off;
  7770. n = doc.nodes[t].text_len;
  7771. st.font_px = (unsigned char)px;
  7772. tw = face_text_width(ui, &st, s, n);
  7773. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7774. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7775. ngui_text_ascent_face(ui, style_face(&st), px,
  7776. st.mono);
  7777. anchor = st.align;
  7778. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7779. anchor = BR_ALIGN_CENTER;
  7780. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7781. anchor = BR_ALIGN_RIGHT;
  7782. if (anchor == BR_ALIGN_CENTER)
  7783. tx -= (int)tw / 2;
  7784. else if (anchor == BR_ALIGN_RIGHT)
  7785. tx -= (int)tw;
  7786. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7787. col, px, st.bold, st.italic,
  7788. st.mono);
  7789. } else {
  7790. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7791. }
  7792. }
  7793. }
  7794. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7795. {
  7796. double vb[4];
  7797. if (svg_viewbox4(node, vb)) {
  7798. svg_viewport_matrix(node, vb, w, h, m);
  7799. } else {
  7800. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7801. }
  7802. }
  7803. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7804. const struct br_style *st)
  7805. {
  7806. struct svg_cache_ent *e = 0;
  7807. struct svgr_layer L;
  7808. double m[6];
  7809. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7810. svg_cache_clock++;
  7811. for (i = 0; i < SVG_CACHE_MAX; i++)
  7812. if (svg_cache[i].px && svg_cache[i].node == node &&
  7813. svg_cache[i].w == w && svg_cache[i].h == h) {
  7814. svg_cache[i].stamp = svg_cache_clock;
  7815. return &svg_cache[i];
  7816. }
  7817. if (need > SVG_CACHE_PIXELS)
  7818. return 0;
  7819. /* Evict least recently used layers until this one fits. */
  7820. for (;;) {
  7821. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7822. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7823. if (!svg_cache[i].px) {
  7824. if (!free_slot)
  7825. free_slot = &svg_cache[i];
  7826. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7827. lru = &svg_cache[i];
  7828. }
  7829. }
  7830. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7831. e = free_slot;
  7832. break;
  7833. }
  7834. if (!lru)
  7835. return 0;
  7836. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7837. free(lru->px);
  7838. free(lru->a);
  7839. memset(lru, 0, sizeof(*lru));
  7840. }
  7841. if (!svg_geom_buf) {
  7842. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7843. if (!svg_geom_buf)
  7844. return 0;
  7845. }
  7846. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7847. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7848. e->a = (unsigned char *)calloc(need, 1);
  7849. if (!e->px || !e->a) {
  7850. free(e->px);
  7851. free(e->a);
  7852. memset(e, 0, sizeof(*e));
  7853. return 0;
  7854. }
  7855. e->node = node;
  7856. e->w = w;
  7857. e->h = h;
  7858. e->stamp = svg_cache_clock;
  7859. svg_cache_pixels += need;
  7860. L.px = e->px;
  7861. L.a = e->a;
  7862. L.w = w;
  7863. L.h = h;
  7864. svg_root_matrix(node, w, h, m);
  7865. {
  7866. double vb[4];
  7867. if (svg_viewbox4(node, vb)) {
  7868. svg_vp_w = vb[2];
  7869. svg_vp_h = vb[3];
  7870. } else {
  7871. svg_vp_w = w;
  7872. svg_vp_h = h;
  7873. }
  7874. }
  7875. svg_draw_children(&L, node, m, st, 255, 0);
  7876. return e;
  7877. }
  7878. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7879. *
  7880. * The markup is parsed into a detached subtree of the page document and
  7881. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7882. * bitmap, which then behaves like any decoded image. currentColor is
  7883. * black (an image has no inherited text colour); <text> is not drawn. */
  7884. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7885. {
  7886. unsigned int i = 0;
  7887. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7888. i = 3;
  7889. while (i < len) {
  7890. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7891. d[i] == '\r' || d[i] == '\n'))
  7892. i++;
  7893. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7894. return 1;
  7895. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7896. i += 4;
  7897. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7898. i++;
  7899. i += 3;
  7900. continue;
  7901. }
  7902. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7903. while (i < len && d[i] != '>')
  7904. i++;
  7905. i++;
  7906. continue;
  7907. }
  7908. return 0;
  7909. }
  7910. return 0;
  7911. }
  7912. static int svg_len_attr(unsigned int node, const char *name)
  7913. {
  7914. const char *v = br_find_attr(&doc, node, name);
  7915. int n = 0, any = 0;
  7916. if (!v)
  7917. return 0;
  7918. while (*v == ' ')
  7919. v++;
  7920. while (*v >= '0' && *v <= '9') {
  7921. n = n * 10 + (*v++ - '0');
  7922. any = 1;
  7923. }
  7924. if (*v == '.')
  7925. while (*++v >= '0' && *v <= '9')
  7926. ;
  7927. if (!any || *v == '%')
  7928. return 0;
  7929. return n;
  7930. }
  7931. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7932. struct br_image *bi, int box_w, int box_h)
  7933. {
  7934. unsigned int holder, svg = 0, c, need, i;
  7935. struct br_style base = base_style(), st;
  7936. struct svgr_layer L;
  7937. double vb[4], m[6];
  7938. int w, h, have_vb, nat_w, nat_h;
  7939. holder = br_create_element(&doc, "div", 3);
  7940. if (!holder) {
  7941. s_copy(bi->err, "page is full", sizeof(bi->err));
  7942. return -1;
  7943. }
  7944. holder--;
  7945. br_set_inner_html(&doc, holder, (const char *)data, len);
  7946. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7947. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7948. doc.nodes[c].tag == BR_TAG_SVG) {
  7949. svg = c;
  7950. break;
  7951. }
  7952. if (!svg) {
  7953. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7954. return -1;
  7955. }
  7956. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7957. w = svg_len_attr(svg, "width");
  7958. h = svg_len_attr(svg, "height");
  7959. if (box_w > 0 && box_h > 0) {
  7960. w = box_w;
  7961. h = box_h;
  7962. } else if (!w && !h) {
  7963. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7964. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7965. } else if (!w) {
  7966. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7967. } else if (!h) {
  7968. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7969. }
  7970. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7971. * so CSS scaling stays crisp. */
  7972. nat_w = w;
  7973. nat_h = h;
  7974. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7975. w *= 2;
  7976. h *= 2;
  7977. }
  7978. if (w > BR_IMG_LAYOUT_W) {
  7979. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7980. w = BR_IMG_LAYOUT_W;
  7981. }
  7982. if (h > 2048)
  7983. h = 2048;
  7984. if (w < 1)
  7985. w = 1;
  7986. if (h < 1)
  7987. h = 1;
  7988. need = (unsigned int)w * (unsigned int)h;
  7989. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7990. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7991. return -1;
  7992. }
  7993. if (!svg_geom_buf) {
  7994. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7995. if (!svg_geom_buf) {
  7996. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7997. return -1;
  7998. }
  7999. }
  8000. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8001. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8002. L.a = (unsigned char *)calloc(need, 1);
  8003. if (!L.px || !L.a) {
  8004. free(L.px);
  8005. free(L.a);
  8006. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8007. return -1;
  8008. }
  8009. for (i = 0; i < need; i++)
  8010. L.px[i] = 0xFFFF;
  8011. L.w = w;
  8012. L.h = h;
  8013. base.color = 0x0000;
  8014. br_style_for(&doc, svg, &base, &st);
  8015. svg_root_matrix(svg, w, h, m);
  8016. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8017. /* No viewBox: user units are CSS pixels of the natural size,
  8018. * so the up-to-4x raster (and a box size) must scale them.
  8019. * A 40x20 icon used to fill only the top-left quarter of its
  8020. * 160x80 bitmap and was drawn at a quarter of its size. */
  8021. m[0] = (double)w / nat_w;
  8022. m[3] = (double)h / nat_h;
  8023. }
  8024. svg_vp_w = have_vb ? vb[2] : nat_w;
  8025. svg_vp_h = have_vb ? vb[3] : nat_h;
  8026. svg_draw_children(&L, svg, m, &st, 255, 0);
  8027. bi->native_w = nat_w;
  8028. bi->native_h = nat_h;
  8029. bi->img.format = 0;
  8030. bi->img.w = (unsigned int)w;
  8031. bi->img.h = (unsigned int)h;
  8032. bi->img.px = L.px;
  8033. bi->img.alpha = L.a;
  8034. bi->img.flags = 0;
  8035. bi->state = 1;
  8036. image_pixels += need;
  8037. return 0;
  8038. }
  8039. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8040. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8041. int *out_w, int *out_h)
  8042. {
  8043. double vb[4];
  8044. int has_vb = svg_viewbox4(node, vb);
  8045. double aw = svg_attr_num(node, "width", -1, cw);
  8046. double ah = svg_attr_num(node, "height", -1, 0);
  8047. int w, h;
  8048. if (st->width_kind)
  8049. w = cw;
  8050. else if (aw > 0)
  8051. w = (int)(aw + 0.5);
  8052. else if (st->height_kind == 1 && has_vb)
  8053. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8054. else if (ah > 0 && has_vb)
  8055. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8056. else if (has_vb)
  8057. w = cw;
  8058. else
  8059. w = 300;
  8060. if (st->max_width_kind == 1 && w > st->max_width)
  8061. w = st->max_width;
  8062. if (w > cw && cw > 0 && !(aw > 0))
  8063. w = cw;
  8064. if (w < 1)
  8065. w = 1;
  8066. if (w > 2000)
  8067. w = 2000;
  8068. if (st->height_kind == 1)
  8069. h = st->height;
  8070. else if (ah > 0)
  8071. h = (int)(ah + 0.5);
  8072. else if (has_vb)
  8073. h = (int)(w * vb[3] / vb[2] + 0.5);
  8074. else
  8075. h = 150;
  8076. if (h < 1)
  8077. h = 1;
  8078. if (h > 1400)
  8079. h = 1400;
  8080. *out_w = w;
  8081. *out_h = h;
  8082. }
  8083. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8084. const struct br_style *st, int x, int y, int w, int h)
  8085. {
  8086. struct svg_cache_ent *e;
  8087. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8088. int cx0, cy0, cx1, cy1, px, py;
  8089. double m[6];
  8090. if (ui->nclip > 0)
  8091. clip = ui->clip[ui->nclip - 1];
  8092. cx0 = r.x > clip.x ? r.x : clip.x;
  8093. cy0 = r.y > clip.y ? r.y : clip.y;
  8094. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8095. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8096. if (cx0 >= cx1 || cy0 >= cy1)
  8097. return;
  8098. e = svg_layer(node, w, h, st);
  8099. if (e) {
  8100. for (py = cy0; py < cy1; py++) {
  8101. unsigned int srow = (unsigned int)(py - y) *
  8102. (unsigned int)w;
  8103. unsigned short *dst = ui->px + py * ui->w;
  8104. for (px = cx0; px < cx1; px++) {
  8105. unsigned int si = srow + (unsigned int)(px - x);
  8106. unsigned int a = e->a[si];
  8107. if (!a)
  8108. continue;
  8109. dst[px] = a >= 255 ? e->px[si] :
  8110. blend_rgb565(dst[px], e->px[si], a);
  8111. }
  8112. }
  8113. }
  8114. svg_root_matrix(node, w, h, m);
  8115. ngui_push_clip(ui, r);
  8116. svg_draw_text(ui, node, m, st, x, y, 0);
  8117. ngui_pop_clip(ui);
  8118. }
  8119. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8120. * keep using add_image_run(); this covers the CSS `position:absolute;
  8121. * width:100%` poster pattern used by news sites. */
  8122. static void image_block_size(unsigned int node, const struct br_style *st,
  8123. int cbw, int *out_w, int *out_h)
  8124. {
  8125. struct br_node *nd = &doc.nodes[node];
  8126. int idx = nd->img_index;
  8127. int iw = 0, ih = 0, w, h, aw, ah;
  8128. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8129. iw = (int)images[idx].img.w;
  8130. ih = (int)images[idx].img.h;
  8131. if (iw <= 0 || ih <= 0) {
  8132. iw = (int)images[idx].native_w;
  8133. ih = (int)images[idx].native_h;
  8134. }
  8135. }
  8136. if (st->width_kind)
  8137. w = style_width_px(st, cbw);
  8138. else if (nd->width_attr)
  8139. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8140. (int)nd->width_attr;
  8141. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8142. w = iw * (int)nd->height_attr / ih;
  8143. else if (iw)
  8144. w = iw;
  8145. else
  8146. w = 64;
  8147. /* max-width/min-width against the containing block: Tailwind's
  8148. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8149. * 300x300 thumbnail to its 75 px avatar box. */
  8150. if (st->max_width_kind) {
  8151. int mw = st->max_width_kind == 3 ?
  8152. cbw * st->max_width_calc_pct / 100 +
  8153. st->max_width_calc_px :
  8154. st->max_width_kind == 2 ?
  8155. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8156. if (mw > 0 && w > mw)
  8157. w = mw;
  8158. }
  8159. if (st->min_width_kind) {
  8160. int mn = st->min_width_kind == 3 ?
  8161. cbw * st->min_width_calc_pct / 100 +
  8162. st->min_width_calc_px :
  8163. st->min_width_kind == 2 ?
  8164. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8165. if (mn > w)
  8166. w = mn;
  8167. }
  8168. if (w < 8)
  8169. w = 8;
  8170. if (cbw > 0 && w > cbw)
  8171. w = cbw;
  8172. /* Without a CSS height the attributes (or the bitmap) only give the
  8173. * aspect ratio: a width clamped by max-width scales the height too,
  8174. * instead of letterboxing the image into its attribute height. */
  8175. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8176. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8177. if (st->height_kind)
  8178. h = style_height_px(st, cbw);
  8179. else if (aw > 0 && ah > 0)
  8180. h = w * ah / aw;
  8181. else if (nd->height_attr)
  8182. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8183. (int)nd->height_attr;
  8184. else
  8185. h = 64;
  8186. if (h < 8)
  8187. h = 8;
  8188. *out_w = w;
  8189. *out_h = h;
  8190. }
  8191. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8192. int dw, int dh)
  8193. {
  8194. int idx = doc.nodes[node].img_index;
  8195. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8196. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8197. struct img_blit b;
  8198. if (!src)
  8199. src = &images[idx].img;
  8200. b.dst = l->ui->px;
  8201. b.dst_w = l->ui->w;
  8202. b.dst_h = l->ui->h;
  8203. b.clip_x = page_rect.x;
  8204. b.clip_y = page_rect.y;
  8205. b.clip_w = page_rect.w - 12;
  8206. b.clip_h = page_rect.h;
  8207. b.x = x;
  8208. b.y = y;
  8209. b.scale = ((unsigned int)dw << 16) / src->w;
  8210. b.bg = ui.theme.bg;
  8211. b.bg2 = ui.theme.bg;
  8212. b.dst_a = 0;
  8213. /* OVER_DST is only needed for an alpha source; an opaque one can
  8214. * take img_draw's 1:1 copy path. */
  8215. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8216. img_draw(src, &b);
  8217. } else if (l->draw) {
  8218. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8219. 0xD69A);
  8220. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8221. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8222. }
  8223. }
  8224. static void layout_block(struct lay *l, unsigned int node,
  8225. const struct br_style *st, int depth,
  8226. unsigned short link)
  8227. {
  8228. int old_left = l->left, old_right = l->right, old_align = l->align;
  8229. int parent_cb_h = l->cb_h;
  8230. int saved_parent_top = l->parent_top;
  8231. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8232. int saved_cb_top = l->cb_top;
  8233. int top, l0, r0;
  8234. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8235. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8236. int deco_w, deco_h, content_w, content_h, box_h;
  8237. int img_dh = 0;
  8238. int definite_w = 0;
  8239. int normal_top = 0;
  8240. int rel_dx = 0, rel_dy = 0;
  8241. int clip_pushed = 0;
  8242. struct ngui_rect clip_rect;
  8243. /* A DOM level costs about two depth units (layout_block ->
  8244. * layout_children), so 48 covers a ~24-level page. Real news pages
  8245. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8246. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8247. return;
  8248. flow_y = l->y;
  8249. flow_left = l->left;
  8250. flow_right = l->right;
  8251. positioned = st->pos == 1 || st->pos == 2;
  8252. relative = st->pos == 3;
  8253. sticky = st->pos == 4;
  8254. shifted = relative || sticky || st->transform_set;
  8255. if (positioned) {
  8256. int def_w = st->width_kind == 1 ? st->width : -1;
  8257. if (st->pos == 2) {
  8258. int avail_w = page_rect.w - 12;
  8259. if (st->right_set && def_w >= 0)
  8260. l->left = page_rect.x + avail_w - st->right -
  8261. def_w;
  8262. else if (!st->left_set && !st->right_set)
  8263. l->left = flow_left; /* static position */
  8264. else
  8265. l->left = page_rect.x +
  8266. (st->left_set ? st->left : 0);
  8267. l->right = def_w >= 0 ? l->left + def_w :
  8268. st->width_kind == 2 ?
  8269. l->left + avail_w * (int)st->width / 100 :
  8270. page_rect.x + avail_w;
  8271. /* Placed by `bottom` (a page footer): an auto
  8272. * height is the measured one. */
  8273. if (st->bottom_set && st->height_kind)
  8274. l->y = page_rect.y + page_rect.h -
  8275. st->bottom -
  8276. style_height_px(st, page_rect.w);
  8277. else if (st->bottom_set && !st->top_set &&
  8278. block_h[node])
  8279. l->y = page_rect.y + page_rect.h -
  8280. st->bottom - (int)block_h[node] -
  8281. mp_px(st, 0, avail_w) -
  8282. mp_px(st, 2, avail_w);
  8283. else
  8284. l->y = page_rect.y +
  8285. (st->top_set ? st->top : 0);
  8286. } else {
  8287. int left = flow_left + (st->left_set ? st->left : 0);
  8288. unsigned int parent = doc.nodes[node].parent;
  8289. if (st->right_set && def_w >= 0)
  8290. left = flow_right - st->right - def_w;
  8291. l->left = left;
  8292. l->right = def_w >= 0 ? left + def_w :
  8293. flow_right +
  8294. (st->left_set ? st->left : 0);
  8295. l->y = flow_y + (st->top_set ? st->top : 0);
  8296. if (st->bottom_set && st->height_kind &&
  8297. parent < BR_MAX_NODES && block_h[parent] > 0)
  8298. l->y = flow_y + block_h[parent] - st->bottom -
  8299. style_height_px(st, old_right - old_left);
  8300. else if (st->bottom_set && !st->top_set &&
  8301. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8302. block_h[node] > 0)
  8303. l->y = flow_y + block_h[parent] - st->bottom -
  8304. (int)block_h[node] -
  8305. mp_px(st, 0, old_right - old_left) -
  8306. mp_px(st, 2, old_right - old_left);
  8307. }
  8308. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8309. * content" link) past the containing block's right edge
  8310. * until it is focused. An auto width then has no room: it
  8311. * used to collapse to 8 px and wrap one word per line into a
  8312. * tall column painted over the page. Lay it out at the
  8313. * containing block's width so it stays one line and
  8314. * overflows (off-screen) like in a real browser. */
  8315. if (def_w < 0 && l->right - l->left < 8) {
  8316. int avail = st->pos == 2 ? page_rect.w - 12 :
  8317. flow_right - flow_left;
  8318. l->right = l->left + (avail > 8 ? avail : 8);
  8319. }
  8320. old_left = l->left;
  8321. old_right = l->right;
  8322. } else if (relative) {
  8323. rel_dx = st->left_set ? st->left :
  8324. (st->right_set ? -st->right : 0);
  8325. rel_dy = st->top_set ? st->top :
  8326. (st->bottom_set ? -st->bottom : 0);
  8327. }
  8328. if (st->transform_set) {
  8329. rel_dx += st->tx;
  8330. rel_dy += st->ty;
  8331. }
  8332. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8333. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8334. doc.nodes[node].tag == BR_TAG_SELECT ||
  8335. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8336. !button_has_elements(node)) {
  8337. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8338. s_eq(br_type(&doc, node), "hidden"))
  8339. return;
  8340. /* Reached as a block-level box (a flex item): the control
  8341. * fills the box the caller assigned, and its line is flushed
  8342. * here; flex layout resets the run list for the next item, so
  8343. * a queued run would never be drawn. */
  8344. form_fill_line = 1;
  8345. add_form_run(l, node, st, link);
  8346. form_fill_line = 0;
  8347. flush_line(l);
  8348. return;
  8349. }
  8350. flush_line(l);
  8351. cbw = old_right - old_left;
  8352. if (cbw < 8)
  8353. cbw = 8;
  8354. l->y += mp_px(st, 0, cbw);
  8355. top = l->y;
  8356. ml = mp_px(st, 3, cbw);
  8357. mr = mp_px(st, 1, cbw);
  8358. bl = st->border_w[3];
  8359. br = st->border_w[1];
  8360. pl = mp_px(st, 7, cbw);
  8361. pr = mp_px(st, 5, cbw);
  8362. bt = st->border_w[0];
  8363. bb = st->border_w[2];
  8364. pt = mp_px(st, 4, cbw);
  8365. pb = mp_px(st, 6, cbw);
  8366. deco_w = bl + br + pl + pr;
  8367. deco_h = bt + bb + pt + pb;
  8368. if (st->width_kind) {
  8369. int w;
  8370. if (st->width_kind == 3)
  8371. w = cbw * st->width_calc_pct / 100 +
  8372. st->width_calc_px;
  8373. else
  8374. w = css_size(st->width_kind, st->width, cbw);
  8375. if (w < 0)
  8376. w = 0;
  8377. content_w = st->box_sizing ? w - deco_w : w;
  8378. definite_w = 1;
  8379. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8380. doc.nodes[node].tag == BR_TAG_TD ||
  8381. doc.nodes[node].tag == BR_TAG_TH) &&
  8382. doc.nodes[node].width_attr) {
  8383. /* Legacy table/cell width attributes: percentages resolve
  8384. * against the containing block, bare numbers are pixels. */
  8385. int w = doc.nodes[node].width_pct ?
  8386. cbw * doc.nodes[node].width_attr / 100 :
  8387. doc.nodes[node].width_attr;
  8388. if (w < 0)
  8389. w = 0;
  8390. content_w = st->box_sizing ? w - deco_w : w;
  8391. definite_w = 1;
  8392. } else {
  8393. content_w = cbw - ml - mr - deco_w;
  8394. }
  8395. if (content_w < 0)
  8396. content_w = 0;
  8397. if (st->max_width_kind) {
  8398. int mw = st->max_width_kind == 3 ?
  8399. cbw * st->max_width_calc_pct / 100 +
  8400. st->max_width_calc_px :
  8401. css_size(st->max_width_kind, st->max_width, cbw);
  8402. int max_box = st->box_sizing ? mw : mw + deco_w;
  8403. /* A clamped auto width is used as the width, so auto
  8404. * margins share the rest (Google's 688 px search box). */
  8405. if (content_w + deco_w > max_box) {
  8406. content_w = max_box - deco_w;
  8407. definite_w = 1;
  8408. }
  8409. }
  8410. if (st->min_width_kind) {
  8411. int mw = st->min_width_kind == 3 ?
  8412. cbw * st->min_width_calc_pct / 100 +
  8413. st->min_width_calc_px :
  8414. css_size(st->min_width_kind, st->min_width, cbw);
  8415. int min_box = st->box_sizing ? mw : mw + deco_w;
  8416. if (content_w + deco_w < min_box) {
  8417. content_w = min_box - deco_w;
  8418. definite_w = 1;
  8419. }
  8420. }
  8421. if (content_w < 8)
  8422. content_w = 8;
  8423. if (definite_w) {
  8424. int free_w = cbw - ml - mr - deco_w - content_w;
  8425. if (free_w < 0)
  8426. free_w = 0;
  8427. if (st->ml_auto && st->mr_auto) {
  8428. ml = free_w / 2;
  8429. mr = free_w - ml;
  8430. } else if (st->ml_auto) {
  8431. ml = free_w;
  8432. } else if (st->mr_auto) {
  8433. mr = free_w;
  8434. }
  8435. }
  8436. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8437. int iw, ih;
  8438. image_block_size(node, st, cbw, &iw, &ih);
  8439. content_w = iw;
  8440. img_dh = ih;
  8441. }
  8442. l0 = old_left + ml;
  8443. r0 = l0 + deco_w + content_w;
  8444. if (r0 < l0 + 8)
  8445. r0 = l0 + 8;
  8446. normal_top = top;
  8447. if (sticky) {
  8448. if (st->top_set) {
  8449. int stick = page_rect.y + st->top;
  8450. if (normal_top < stick)
  8451. rel_dy += stick - normal_top;
  8452. } else if (st->bottom_set && block_h[node]) {
  8453. int stick = page_rect.y + page_rect.h - st->bottom -
  8454. block_h[node];
  8455. if (normal_top > stick)
  8456. rel_dy += stick - normal_top;
  8457. }
  8458. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8459. block_h[doc.nodes[node].parent]) {
  8460. unsigned int p = doc.nodes[node].parent;
  8461. int ptop = l->parent_top;
  8462. int pbottom = ptop + block_h[p];
  8463. int eh = block_h[node];
  8464. int moved_top = normal_top + rel_dy;
  8465. int moved_bottom = moved_top + eh;
  8466. if (moved_bottom > pbottom)
  8467. rel_dy -= moved_bottom - pbottom;
  8468. moved_top = normal_top + rel_dy;
  8469. if (moved_top < ptop)
  8470. rel_dy += ptop - moved_top;
  8471. }
  8472. }
  8473. if (shifted && l->draw) {
  8474. top += rel_dy;
  8475. l0 += rel_dx;
  8476. r0 += rel_dx;
  8477. }
  8478. l->parent_top = top;
  8479. if (st->pos != 0) {
  8480. /* Positioned boxes establish the containing block for their
  8481. * absolutely positioned descendants. */
  8482. l->cb_left = l0;
  8483. l->cb_right = r0;
  8484. l->cb_top = top;
  8485. }
  8486. if (l->draw && block_h[node] &&
  8487. top < page_rect.y + page_rect.h &&
  8488. top + block_h[node] > page_rect.y) {
  8489. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8490. int rtl = css_radius(st, 0, box.w, box.h);
  8491. int rtr = css_radius(st, 1, box.w, box.h);
  8492. int rbr = css_radius(st, 2, box.w, box.h);
  8493. int rbl = css_radius(st, 3, box.w, box.h);
  8494. if (st->transform_scale) {
  8495. if (st->has_bg)
  8496. fill_transformed_rect(l->ui, box, st->bg, st);
  8497. } else if (rtl || rtr || rbr || rbl) {
  8498. if (st->has_bg) {
  8499. int bw = st->border_w[0];
  8500. if (bw > 0 && !st->border_t[0] &&
  8501. st->border_c[0] != st->bg &&
  8502. box.w > bw * 2 && box.h > bw * 2) {
  8503. struct ngui_rect inner = {
  8504. box.x + bw, box.y + bw,
  8505. box.w - bw * 2, box.h - bw * 2
  8506. };
  8507. int itl = rtl > bw ? rtl - bw : 0;
  8508. int itr = rtr > bw ? rtr - bw : 0;
  8509. int ibr = rbr > bw ? rbr - bw : 0;
  8510. int ibl = rbl > bw ? rbl - bw : 0;
  8511. ngui_fill_round_rect(l->ui, box, rtl,
  8512. rtr, rbr, rbl,
  8513. st->border_c[0]);
  8514. ngui_fill_round_rect(l->ui, inner,
  8515. itl, itr, ibr,
  8516. ibl, st->bg);
  8517. } else {
  8518. ngui_fill_round_rect(l->ui, box, rtl,
  8519. rtr, rbr, rbl,
  8520. st->bg);
  8521. }
  8522. } else if (st->border_w[0] && !st->border_t[0]) {
  8523. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8524. rbl, st->border_w[0],
  8525. st->border_c[0]);
  8526. }
  8527. /* Rounded boxes paint their background image too
  8528. * (app icons are rounded squares), kept inside the
  8529. * corner arcs. */
  8530. if (st->bg_image)
  8531. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8532. rbr, rbl);
  8533. } else {
  8534. if (st->has_bg)
  8535. ngui_fill_rect(l->ui, box, st->bg);
  8536. if (st->bg_image)
  8537. draw_bg_image(l, box, node, st);
  8538. if (st->border_w[0] || st->border_w[1] ||
  8539. st->border_w[2] || st->border_w[3])
  8540. draw_border_box(l->ui, box, st);
  8541. }
  8542. }
  8543. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8544. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8545. content_w, img_dh);
  8546. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8547. l->ui && l->ui->nclip < 4) {
  8548. clip_rect.x = l0 + bl;
  8549. clip_rect.y = top + bt;
  8550. clip_rect.w = (r0 - l0) - bl - br;
  8551. clip_rect.h = (int)block_h[node] - bt - bb;
  8552. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8553. ngui_push_clip(l->ui, clip_rect);
  8554. clip_pushed = 1;
  8555. }
  8556. }
  8557. l->left = l0 + bl + pl;
  8558. l->right = l->left + content_w;
  8559. if (l->right < l->left + 8)
  8560. l->right = l->left + 8;
  8561. l->align = st->align;
  8562. l->line_left = l->left;
  8563. l->line_right = l->right;
  8564. l->y = top + bt + pt;
  8565. if (doc.nodes[node].tag == BR_TAG_HR) {
  8566. if (l->draw)
  8567. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8568. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8569. l->y += 8;
  8570. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8571. int vw = l->right - l->left;
  8572. int vh;
  8573. if (doc.nodes[node].width_pct)
  8574. vw = vw * doc.nodes[node].width_attr / 100;
  8575. else if (doc.nodes[node].width_attr)
  8576. vw = doc.nodes[node].width_attr;
  8577. if (vw > l->right - l->left)
  8578. vw = l->right - l->left;
  8579. if (vw < 8)
  8580. vw = 8;
  8581. vh = vw * 9 / 16;
  8582. if (vh > 240)
  8583. vh = 240;
  8584. if (vh < 80)
  8585. vh = 80;
  8586. if (l->draw) {
  8587. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8588. vw, vh}, 0xD69A);
  8589. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8590. vw, vh}, 0x8410);
  8591. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8592. 0x4208);
  8593. }
  8594. l->y += vh + 4;
  8595. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8596. int dw, dh, cw = l->right - l->left;
  8597. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8598. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8599. l->y + dh > page_rect.y)
  8600. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8601. l->y += dh;
  8602. } else {
  8603. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8604. !st->no_bullet) {
  8605. char *m = li_marker[node];
  8606. if (!m[0]) {
  8607. unsigned int parent = doc.nodes[node].parent;
  8608. int style = st->list_style;
  8609. int idx = parent ? list_index(parent, node) : 1;
  8610. if (style == BR_LIST_AUTO)
  8611. style = (parent &&
  8612. doc.nodes[parent].tag ==
  8613. BR_TAG_OL) ?
  8614. BR_LIST_DECIMAL : BR_LIST_DISC;
  8615. list_marker_text(m, sizeof(li_marker[node]),
  8616. style, idx);
  8617. }
  8618. if (l->draw && m[0]) {
  8619. int mw = (int)ngui_text_width_ui(l->ui, m);
  8620. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8621. st->color);
  8622. }
  8623. }
  8624. /* This box's definite content height, for its children's
  8625. * percentage heights. */
  8626. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8627. doc.nodes[node].tag == BR_TAG_BODY)
  8628. l->cb_h = layout_view_h;
  8629. else if (st->height_kind == 1)
  8630. l->cb_h = (int)st->height -
  8631. (st->box_sizing ? deco_h : 0);
  8632. else if (st->height_kind == 2 && parent_cb_h > 0)
  8633. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8634. (st->box_sizing ? deco_h : 0);
  8635. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8636. l->cb_h = content_w * (int)st->aspect_h /
  8637. (int)st->aspect_w;
  8638. else if (!st->height_kind && node < BR_MAX_NODES &&
  8639. flex_stretch_h[node] > deco_h)
  8640. l->cb_h = flex_stretch_h[node] - deco_h;
  8641. else
  8642. l->cb_h = 0;
  8643. if (l->cb_h < 0)
  8644. l->cb_h = 0;
  8645. if (doc.nodes[node].tag == BR_TAG_TR)
  8646. layout_table_row(l, node, st, depth + 1, link);
  8647. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8648. table_has_rowspan(node))
  8649. layout_table(l, node, st, depth + 1, link);
  8650. else if (st->grid_auto)
  8651. layout_grid_auto(l, node, st, depth + 1, link);
  8652. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8653. st->grid_gap > 0)
  8654. layout_grid_children(l, node, st, depth + 1, link);
  8655. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8656. flex_wants_row(node, st))
  8657. layout_flex_children(l, node, st, depth + 1, link);
  8658. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8659. layout_flex_column(l, node, st, depth + 1, link);
  8660. else
  8661. layout_children(l, node, st, depth + 1, link);
  8662. l->cb_h = parent_cb_h;
  8663. }
  8664. flush_line(l);
  8665. if (clip_pushed)
  8666. ngui_pop_clip(l->ui);
  8667. if (l->float_active) {
  8668. if (l->y < l->float_bottom)
  8669. l->y = l->float_bottom;
  8670. l->float_active = 0;
  8671. }
  8672. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8673. content_h = img_dh;
  8674. } else if (st->height_kind == 2 &&
  8675. doc.nodes[node].tag != BR_TAG_HTML &&
  8676. doc.nodes[node].tag != BR_TAG_BODY) {
  8677. /* A percentage of the containing block's definite height, or
  8678. * auto when it has none (it used to resolve against the
  8679. * width). The result is a minimum: without scrollable inner
  8680. * boxes, an app shell's height:100%; overflow:hidden column
  8681. * would otherwise clip everything past the first screen. */
  8682. int auto_h = l->y - (top + bt + pt);
  8683. content_h = parent_cb_h > 0 ?
  8684. parent_cb_h * (int)st->height / 100 -
  8685. (st->box_sizing ? deco_h : 0) : 0;
  8686. if (content_h < auto_h)
  8687. content_h = auto_h;
  8688. } else if (st->height_kind &&
  8689. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8690. doc.nodes[node].tag == BR_TAG_BODY) &&
  8691. st->height_kind == 2)) {
  8692. content_h = style_height_px(st, cbw);
  8693. if (st->box_sizing)
  8694. content_h -= deco_h;
  8695. } else {
  8696. /* Percentage heights on html/body resolve against the
  8697. * viewport, but their content still defines the document
  8698. * scroll height. Treating them as auto avoids collapsing
  8699. * the measured page to the containing block width. */
  8700. content_h = l->y - (top + bt + pt);
  8701. /* aspect-ratio: the preferred height of an auto-height box
  8702. * (Tailwind aspect-video image frames); content can still
  8703. * make it taller, as with min-height: auto. */
  8704. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8705. int ah = content_w * (int)st->aspect_h /
  8706. (int)st->aspect_w;
  8707. if (content_h < ah)
  8708. content_h = ah;
  8709. }
  8710. }
  8711. if (content_h < 0)
  8712. content_h = 0;
  8713. if (!st->height_kind && node < BR_MAX_NODES &&
  8714. content_h + deco_h < flex_stretch_h[node])
  8715. content_h = flex_stretch_h[node] - deco_h;
  8716. if (st->max_height_kind) {
  8717. int mh = st->max_height_kind == 3 ?
  8718. cbw * st->max_height_calc_pct / 100 +
  8719. st->max_height_calc_px :
  8720. css_size(st->max_height_kind, st->max_height, cbw);
  8721. int max_box = st->box_sizing ? mh : mh + deco_h;
  8722. if (content_h + deco_h > max_box)
  8723. content_h = max_box - deco_h;
  8724. }
  8725. if (st->min_height_kind &&
  8726. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8727. doc.nodes[node].tag == BR_TAG_BODY) &&
  8728. st->min_height_kind == 2)) {
  8729. int mh = st->min_height_kind == 3 ?
  8730. cbw * st->min_height_calc_pct / 100 +
  8731. st->min_height_calc_px :
  8732. css_size(st->min_height_kind, st->min_height, cbw);
  8733. int min_box = st->box_sizing ? mh : mh + deco_h;
  8734. if (content_h + deco_h < min_box)
  8735. content_h = min_box - deco_h;
  8736. }
  8737. if (content_h < 0)
  8738. content_h = 0;
  8739. box_h = deco_h + content_h;
  8740. if (box_h < 0)
  8741. box_h = 0;
  8742. l->y = (shifted ? normal_top : top) + box_h;
  8743. if (node < BR_MAX_NODES) {
  8744. layout_boxes[node].x = l0;
  8745. layout_boxes[node].y = top;
  8746. layout_boxes[node].w = r0 - l0;
  8747. layout_boxes[node].h = box_h;
  8748. layout_boxes[node].valid = r0 > l0;
  8749. }
  8750. l->left = old_left;
  8751. l->right = old_right;
  8752. l->align = old_align;
  8753. l->y += mp_px(st, 2, cbw);
  8754. if (!l->draw) {
  8755. if (box_h > 65535)
  8756. box_h = 65535;
  8757. block_h[node] = (unsigned short)box_h;
  8758. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8759. top > 65535 ? 65535 : top);
  8760. }
  8761. if (positioned) {
  8762. l->y = flow_y;
  8763. l->left = flow_left;
  8764. l->right = flow_right;
  8765. }
  8766. l->parent_top = saved_parent_top;
  8767. l->cb_left = saved_cb_left;
  8768. l->cb_right = saved_cb_right;
  8769. l->cb_top = saved_cb_top;
  8770. }
  8771. static int text_node_blank(const struct br_node *nd)
  8772. {
  8773. const char *t = doc.text + nd->text_off;
  8774. unsigned int i;
  8775. for (i = 0; i < nd->text_len; i++)
  8776. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8777. t[i] != '\r')
  8778. return 0;
  8779. return 1;
  8780. }
  8781. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8782. * text/image widths in the subtree, plus padding and margins. This keeps
  8783. * Bootstrap's floated nav items on one line instead of giving each the whole
  8784. * row. */
  8785. static int text_space(char c)
  8786. {
  8787. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8788. }
  8789. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8790. const struct br_style *pst, int depth, int base)
  8791. {
  8792. unsigned int c;
  8793. int line_w = 0, max_w = 0;
  8794. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8795. if (depth > 32)
  8796. return 0;
  8797. if (doc.npe_rules) {
  8798. struct br_style ps;
  8799. /* Icon boxes (::before/::after with a size) are inline
  8800. * content of the element. */
  8801. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  8802. pseudo_box_w(node, pst, 2, &ps, base);
  8803. }
  8804. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8805. struct br_node *nd = &doc.nodes[c];
  8806. struct br_style cs;
  8807. if (nd->type == BR_NODE_TEXT) {
  8808. const char *t = doc.text + nd->text_off;
  8809. unsigned int tn = nd->text_len;
  8810. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8811. line_w += (int)face_text_width(ui, pst, t, tn);
  8812. } else {
  8813. unsigned int ti = 0;
  8814. int first = 1;
  8815. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8816. int sp = (int)face_text_width(ui, pst, " ", 1);
  8817. while (ti < tn) {
  8818. unsigned int ts;
  8819. while (ti < tn && text_space(t[ti]))
  8820. ti++;
  8821. ts = ti;
  8822. while (ti < tn && !text_space(t[ti]))
  8823. ti++;
  8824. if (ti == ts)
  8825. break;
  8826. if (!first || lead)
  8827. line_w += sp;
  8828. lead = 0;
  8829. line_w += (int)face_text_width(ui, pst,
  8830. t + ts, ti - ts);
  8831. first = 0;
  8832. }
  8833. }
  8834. continue;
  8835. }
  8836. br_style_for(&doc, c, pst, &cs);
  8837. if (cs.display == BR_DISPLAY_NONE)
  8838. continue;
  8839. if (nd->tag == BR_TAG_BR) {
  8840. if (line_w > max_w)
  8841. max_w = line_w;
  8842. line_w = 0;
  8843. continue;
  8844. }
  8845. if (nd->tag == BR_TAG_IMG) {
  8846. /* Measure the image as layout will draw it: a CSS or
  8847. * attribute height keeps the intrinsic aspect ratio, and
  8848. * a CSS width overrides the native pixel width. Bootstrap
  8849. * sizes the Cloudron logo with height:40px only. */
  8850. int idx = nd->img_index;
  8851. int iw = 0, ih = 0;
  8852. if (idx >= 0 && idx < image_count &&
  8853. images[idx].state == 1) {
  8854. iw = (int)images[idx].native_w;
  8855. ih = (int)images[idx].native_h;
  8856. if (iw <= 0 || ih <= 0) {
  8857. iw = (int)images[idx].img.w;
  8858. ih = (int)images[idx].img.h;
  8859. }
  8860. }
  8861. if (cs.width_kind) {
  8862. int ww = style_width_px(&cs, base);
  8863. line_w += ww > 0 ? ww : 64;
  8864. } else if (nd->width_attr) {
  8865. line_w += nd->width_attr;
  8866. } else if (nd->height_attr && iw && ih) {
  8867. line_w += iw * (int)nd->height_attr / ih;
  8868. } else if (cs.height_kind && iw && ih) {
  8869. /* A percentage height needs the parent's
  8870. * definite height (the logo's 2rem box), as in
  8871. * add_image_run(); otherwise it is auto. */
  8872. int hh = cs.height_kind == 1 ?
  8873. style_height_px(&cs, base) :
  8874. cs.height_kind == 2 &&
  8875. pst->height_kind == 1 ?
  8876. (int)pst->height * (int)cs.height / 100 :
  8877. 0;
  8878. line_w += hh > 0 ? iw * hh / ih : iw;
  8879. } else if (iw) {
  8880. line_w += iw;
  8881. } else {
  8882. line_w += 64;
  8883. }
  8884. continue;
  8885. }
  8886. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8887. nd->tag == BR_TAG_TEXTAREA) &&
  8888. !s_eq(br_type(&doc, c), "hidden")) {
  8889. /* Form controls are replaced: CSS width applies even
  8890. * when they are inline (add_form_run's sizes). */
  8891. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8892. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8893. if (s_eq(br_type(&doc, c), "checkbox") ||
  8894. s_eq(br_type(&doc, c), "radio"))
  8895. fw = 16;
  8896. line_w += (fw > 0 ? fw : 120) +
  8897. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8898. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8899. continue;
  8900. }
  8901. if (nd->tag == BR_TAG_SVG) {
  8902. /* A replaced element: its own size, like add_svg_run()
  8903. * (its path children have no width). */
  8904. int sw, sh, sb = cs.width_kind ?
  8905. style_width_px(&cs, base) : base;
  8906. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8907. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8908. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8909. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8910. line_w += sw;
  8911. } else {
  8912. if (line_w > max_w)
  8913. max_w = line_w;
  8914. line_w = 0;
  8915. if (sw > max_w)
  8916. max_w = sw;
  8917. }
  8918. continue;
  8919. }
  8920. {
  8921. int cw = mp_px(&cs, 7, base) +
  8922. mp_px(&cs, 5, base) +
  8923. mp_px(&cs, 3, base) +
  8924. mp_px(&cs, 1, base) +
  8925. cs.border_w[1] + cs.border_w[3];
  8926. /* width/height do not apply to non-replaced inline
  8927. * boxes. The tagesschau home label is an inline span
  8928. * with width:1px for the mobile icon-only header; using
  8929. * that width made the whole subnav collapse to a
  8930. * one-character column. */
  8931. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8932. cw += cs.width_kind == 1 ? cs.width :
  8933. style_width_px(&cs, base);
  8934. else
  8935. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8936. base);
  8937. if (flex_row || cs.float_left ||
  8938. cs.display == BR_DISPLAY_INLINE ||
  8939. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8940. line_w += cw;
  8941. } else {
  8942. if (line_w > max_w)
  8943. max_w = line_w;
  8944. line_w = 0;
  8945. if (cw > max_w)
  8946. max_w = cw;
  8947. }
  8948. }
  8949. if (line_w > 4096 || max_w > 4096)
  8950. break;
  8951. }
  8952. return line_w > max_w ? line_w : max_w;
  8953. }
  8954. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8955. * the main user: .row > .col-md-* with float:left and a percentage width.
  8956. * Each column is laid out with its own left/right edge and the row advances
  8957. * to the tallest column. Returns the first child not consumed. */
  8958. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8959. const struct br_style *pst, int depth,
  8960. unsigned short link)
  8961. {
  8962. unsigned int n = first;
  8963. int row_left = l->left, row_right = l->right;
  8964. int row_top, row_bottom, xl, xr, any = 0;
  8965. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8966. flush_line(l);
  8967. row_top = l->y;
  8968. row_bottom = l->y;
  8969. fl_bottom = row_top;
  8970. xl = row_left;
  8971. xr = row_right;
  8972. while (n) {
  8973. struct br_node *nd = &doc.nodes[n];
  8974. struct br_style cs;
  8975. unsigned short lk = link;
  8976. int colw, right;
  8977. if (nd->type == BR_NODE_TEXT) {
  8978. if (text_node_blank(nd)) {
  8979. n = nd->next;
  8980. continue;
  8981. }
  8982. break;
  8983. }
  8984. br_style_for(&doc, n, pst, &cs);
  8985. if (cs.display == BR_DISPLAY_NONE) {
  8986. n = nd->next;
  8987. continue;
  8988. }
  8989. /* A float blockifies its box: Bootstrap floats inline
  8990. * anchors too (the navbar brand and its text links), and
  8991. * their padding must be honoured. */
  8992. if (!cs.float_left)
  8993. break;
  8994. if (nd->tag == BR_TAG_A && nd->href_off)
  8995. lk = (unsigned short)n;
  8996. right = cs.float_left == 2;
  8997. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8998. cs.width_kind == 3) {
  8999. /* The column is the margin box: `width` is the
  9000. * content (or, with border-box, the border) box,
  9001. * and layout_block() takes margins, padding and
  9002. * borders back out of the column. A 200px float
  9003. * with margin-right:20px used to get 180px of
  9004. * content. */
  9005. int base = row_right - row_left;
  9006. colw = cs.width_kind == 1 ? (int)cs.width :
  9007. style_width_px(&cs, base);
  9008. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9009. if (!cs.box_sizing)
  9010. colw += mp_px(&cs, 7, base) +
  9011. mp_px(&cs, 5, base) +
  9012. cs.border_w[1] + cs.border_w[3];
  9013. } else {
  9014. int base = row_right - row_left;
  9015. /* Shrink-to-fit outer width: borders too (Google's
  9016. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9017. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9018. mp_px(&cs, 7, base) +
  9019. mp_px(&cs, 5, base) +
  9020. mp_px(&cs, 3, base) +
  9021. mp_px(&cs, 1, base) +
  9022. cs.border_w[1] + cs.border_w[3];
  9023. if (colw < 8)
  9024. colw = 8;
  9025. }
  9026. if (colw < 8)
  9027. colw = 8;
  9028. if (colw > row_right - row_left)
  9029. colw = row_right - row_left;
  9030. /* The float column width is already resolved. */
  9031. cs.width_kind = 0;
  9032. cs.max_width_kind = 0;
  9033. if (right) {
  9034. if (any && xr - colw < xl) {
  9035. row_top = row_bottom;
  9036. row_bottom = row_top;
  9037. xl = row_left;
  9038. xr = row_right;
  9039. }
  9040. if (xr - colw < xl)
  9041. colw = xr - xl;
  9042. if (colw < 8)
  9043. colw = 8;
  9044. l->left = xr - colw;
  9045. if (l->left < row_left)
  9046. l->left = row_left;
  9047. l->right = xr;
  9048. xr = l->left;
  9049. if (xr < fl_right)
  9050. fl_right = xr;
  9051. } else {
  9052. if (any && xl + colw > xr) {
  9053. row_top = row_bottom;
  9054. row_bottom = row_top;
  9055. xl = row_left;
  9056. xr = row_right;
  9057. }
  9058. l->left = xl;
  9059. l->right = xl + colw;
  9060. xl += colw;
  9061. if (xl > fl_left)
  9062. fl_left = xl;
  9063. }
  9064. if (l->right < l->left + 8)
  9065. l->right = l->left + 8;
  9066. l->y = row_top;
  9067. l->line_left = l->line_x = l->left;
  9068. l->run_x = l->left;
  9069. l->line_y = l->y;
  9070. l->line_h = 0;
  9071. l->nruns = 0;
  9072. l->space_pending = 0;
  9073. l->align = cs.align;
  9074. layout_block(l, n, &cs, depth + 1, lk);
  9075. if (l->y > row_bottom)
  9076. row_bottom = l->y;
  9077. if (l->y > fl_bottom)
  9078. fl_bottom = l->y;
  9079. any = 1;
  9080. n = nd->next;
  9081. }
  9082. l->left = row_left;
  9083. l->right = row_right;
  9084. if (n && any) {
  9085. struct br_node *nd = &doc.nodes[n];
  9086. int inline_next = 0;
  9087. if (nd->type == BR_NODE_TEXT) {
  9088. inline_next = 1;
  9089. } else if (nd->type == BR_NODE_ELEM) {
  9090. struct br_style cs;
  9091. br_style_for(&doc, n, pst, &cs);
  9092. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9093. cs.display != BR_DISPLAY_NONE &&
  9094. !br_tag_is_block(nd->tag);
  9095. }
  9096. if (inline_next) {
  9097. if (l->float_active) {
  9098. if (l->float_left > fl_left)
  9099. fl_left = l->float_left;
  9100. if (l->float_right < fl_right)
  9101. fl_right = l->float_right;
  9102. if (l->float_bottom > fl_bottom)
  9103. fl_bottom = l->float_bottom;
  9104. }
  9105. l->float_active = 1;
  9106. l->float_left = fl_left;
  9107. l->float_right = fl_right;
  9108. l->float_bottom = fl_bottom;
  9109. l->y = row_top;
  9110. } else {
  9111. l->float_active = 0;
  9112. l->y = row_bottom;
  9113. }
  9114. } else {
  9115. l->float_active = 0;
  9116. l->y = row_bottom;
  9117. }
  9118. l->line_x = l->left;
  9119. l->run_x = l->left;
  9120. l->line_left = l->left;
  9121. l->line_right = l->right;
  9122. l->line_y = l->y;
  9123. l->line_h = 0;
  9124. l->nruns = 0;
  9125. l->space_pending = 0;
  9126. return n;
  9127. }
  9128. static int flex_item_width(struct lay *l, unsigned int n,
  9129. const struct br_style *cs, int avail)
  9130. {
  9131. struct br_node *nd = &doc.nodes[n];
  9132. (void)l;
  9133. int w;
  9134. if (cs->width_kind == 2 || cs->width_kind == 3)
  9135. w = style_width_px(cs, avail);
  9136. else if (cs->width_kind == 1)
  9137. w = (int)cs->width;
  9138. else if (nd->tag == BR_TAG_IMG) {
  9139. int idx = nd->img_index;
  9140. if (idx >= 0 && idx < image_count &&
  9141. images[idx].state == 1)
  9142. w = (int)images[idx].img.w;
  9143. else if (nd->width_attr)
  9144. w = (int)nd->width_attr;
  9145. else
  9146. w = 64;
  9147. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9148. nd->tag == BR_TAG_TEXTAREA) {
  9149. /* A control has no content to measure: its default size
  9150. * (a search field in a filter bar). */
  9151. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9152. } else {
  9153. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9154. }
  9155. /* Explicit widths are content-box sizes; the flex item's outer width
  9156. * must include padding, borders and margins. */
  9157. w += mp_px(cs, 7, avail);
  9158. w += mp_px(cs, 5, avail);
  9159. w += mp_px(cs, 3, avail);
  9160. w += mp_px(cs, 1, avail);
  9161. w += cs->border_w[1] + cs->border_w[3];
  9162. if (w < 24)
  9163. w = 24;
  9164. if (w > avail)
  9165. w = avail;
  9166. return w;
  9167. }
  9168. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9169. int depth);
  9170. /* An inline child of a text-only inline-block: the same test minus the
  9171. * display check (an inline <span> may have padding/background in CSS, but
  9172. * the inline path paints those for spans anyway). */
  9173. static int inline_block_flows_inline(unsigned int node,
  9174. const struct br_style *cs, int depth)
  9175. {
  9176. unsigned int c;
  9177. if (depth > 3 || cs->pos)
  9178. return 0;
  9179. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9180. const struct br_node *nd = &doc.nodes[c];
  9181. struct br_style ch;
  9182. if (nd->type != BR_NODE_ELEM)
  9183. continue;
  9184. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9185. br_tag_is_block(nd->tag))
  9186. return 0;
  9187. br_style_for(&doc, c, cs, &ch);
  9188. if (ch.display == BR_DISPLAY_NONE)
  9189. continue;
  9190. if (ch.display != BR_DISPLAY_INLINE ||
  9191. !inline_block_flows_inline(c, &ch, depth + 1))
  9192. return 0;
  9193. }
  9194. return 1;
  9195. }
  9196. /* An inline-block that is only text in a line (a <time> in a byline, a
  9197. * label) with no box of its own -- no size, background, border or padding
  9198. * -- lays out exactly like an inline element, so it stays in the text line
  9199. * instead of ending it. Boxes with any of those keep the row path. */
  9200. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9201. int depth)
  9202. {
  9203. unsigned int c;
  9204. int i;
  9205. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9206. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9207. cs->pos || depth > 3)
  9208. return 0;
  9209. for (i = 0; i < 4; i++)
  9210. if (cs->border_w[i])
  9211. return 0;
  9212. for (i = 4; i < 8; i++)
  9213. if (mp_px(cs, i, 0) > 0)
  9214. return 0;
  9215. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9216. const struct br_node *nd = &doc.nodes[c];
  9217. struct br_style ch;
  9218. if (nd->type != BR_NODE_ELEM)
  9219. continue;
  9220. if (nd->tag == BR_TAG_SVG) {
  9221. /* An icon box (Docusaurus' admonition heading:
  9222. * `<span inline-block><svg/></span>Note`): the SVG
  9223. * is an inline replaced run, so the box can stay in
  9224. * the text line. */
  9225. br_style_for(&doc, c, cs, &ch);
  9226. if (ch.display == BR_DISPLAY_NONE ||
  9227. ch.display == BR_DISPLAY_INLINE ||
  9228. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9229. continue;
  9230. return 0;
  9231. }
  9232. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9233. return 0;
  9234. br_style_for(&doc, c, cs, &ch);
  9235. if (ch.display == BR_DISPLAY_NONE)
  9236. continue;
  9237. if (ch.display != BR_DISPLAY_INLINE ||
  9238. !inline_block_flows_inline(c, &ch, depth + 1))
  9239. return 0;
  9240. }
  9241. return 1;
  9242. }
  9243. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9244. * on one line, not one full-width block each. Place intrinsic widths from
  9245. * left to right and wrap when the row is full. */
  9246. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9247. const struct br_style *pst, int depth,
  9248. unsigned short link)
  9249. {
  9250. unsigned int n = first;
  9251. int row_left = l->left, row_right = l->right;
  9252. int avail = row_right - row_left;
  9253. int x = row_left, y = l->y, row_h = 0, any = 0;
  9254. /* Each box sets l->align from its own style; the text after the row
  9255. * must keep the container's (a centred .fa-fw icon centred the menu
  9256. * label that followed it). */
  9257. unsigned char row_align = l->align;
  9258. flush_line(l);
  9259. y = l->y;
  9260. while (n) {
  9261. struct br_node *nd = &doc.nodes[n];
  9262. struct br_style cs;
  9263. unsigned short lk = link;
  9264. int colw, h;
  9265. if (nd->type == BR_NODE_TEXT) {
  9266. if (!text_node_blank(nd))
  9267. break;
  9268. if (any)
  9269. x += 4;
  9270. n = nd->next;
  9271. continue;
  9272. }
  9273. br_style_for(&doc, n, pst, &cs);
  9274. if (cs.display == BR_DISPLAY_NONE) {
  9275. n = nd->next;
  9276. continue;
  9277. }
  9278. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9279. break;
  9280. if (nd->tag == BR_TAG_A && nd->href_off)
  9281. lk = (unsigned short)n;
  9282. colw = flex_item_width(l, n, &cs, avail);
  9283. /* A few pixels of slack keep a single long token (boot.S)
  9284. * from wrapping at the exact content width. */
  9285. colw += 8;
  9286. if (colw > avail)
  9287. colw = avail;
  9288. cs.width_kind = 0;
  9289. cs.max_width_kind = 0;
  9290. if (any && x + colw > row_right) {
  9291. y += row_h + 2;
  9292. x = row_left;
  9293. row_h = 0;
  9294. any = 0;
  9295. }
  9296. if (any && x > row_left)
  9297. x += 4;
  9298. l->left = x;
  9299. l->right = x + colw;
  9300. if (l->right < l->left + 8)
  9301. l->right = l->left + 8;
  9302. l->y = y;
  9303. l->line_left = l->line_x = l->left;
  9304. l->run_x = l->left;
  9305. l->line_y = l->y;
  9306. l->line_h = 0;
  9307. l->nruns = 0;
  9308. l->space_pending = 0;
  9309. l->align = cs.align;
  9310. layout_block(l, n, &cs, depth + 1, lk);
  9311. h = l->y - y;
  9312. if (h > row_h)
  9313. row_h = h;
  9314. x += colw;
  9315. any = 1;
  9316. n = nd->next;
  9317. }
  9318. if (any)
  9319. y += row_h;
  9320. l->left = row_left;
  9321. l->right = row_right;
  9322. l->align = row_align;
  9323. l->y = y;
  9324. l->line_left = l->line_x = l->left;
  9325. l->run_x = l->left;
  9326. l->line_y = l->y;
  9327. l->line_h = 0;
  9328. l->nruns = 0;
  9329. l->space_pending = 0;
  9330. return n;
  9331. }
  9332. struct flex_item {
  9333. unsigned int node;
  9334. unsigned short link;
  9335. int w;
  9336. };
  9337. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9338. * row, or -1 when unset. Percentages and calc() resolve against the
  9339. * container width. */
  9340. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9341. {
  9342. unsigned char kind = which_max ? cs->max_width_kind :
  9343. cs->min_width_kind;
  9344. int w;
  9345. if (kind == 3)
  9346. w = which_max ?
  9347. avail * cs->max_width_calc_pct / 100 +
  9348. cs->max_width_calc_px :
  9349. avail * cs->min_width_calc_pct / 100 +
  9350. cs->min_width_calc_px;
  9351. else
  9352. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9353. avail);
  9354. if (w < 0)
  9355. return -1;
  9356. if (!cs->box_sizing)
  9357. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9358. cs->border_w[1] + cs->border_w[3];
  9359. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9360. }
  9361. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9362. {
  9363. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9364. if (mx >= 0 && w > mx)
  9365. w = mx;
  9366. if (mn >= 0 && w < mn)
  9367. w = mn;
  9368. return w;
  9369. }
  9370. /* Does a flex row stretch this item to the line height? Only items with
  9371. * no height of their own and align-self/align-items stretch; replaced
  9372. * content (images, icons) keeps its aspect ratio. */
  9373. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9374. const struct br_style *pst)
  9375. {
  9376. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9377. unsigned char tag = doc.nodes[node].tag;
  9378. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9379. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9380. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9381. tag != BR_TAG_BUTTON;
  9382. }
  9383. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9384. int line_h, int cbw)
  9385. {
  9386. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9387. if (node >= BR_MAX_NODES || h <= 0)
  9388. return;
  9389. if (h > 65535)
  9390. h = 65535;
  9391. flex_stretch_h[node] = (unsigned short)h;
  9392. if (block_h[node] < h)
  9393. block_h[node] = (unsigned short)h;
  9394. }
  9395. static void layout_flex_children(struct lay *l, unsigned int parent,
  9396. const struct br_style *pst, int depth,
  9397. unsigned short link)
  9398. {
  9399. struct flex_item it[32];
  9400. unsigned int c;
  9401. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9402. int grow_need = 0; /* growing items at their content width */
  9403. int row_left = l->left, row_right = l->right;
  9404. int avail = row_right - row_left;
  9405. int idx, row_top;
  9406. unsigned char row_align = l->align;
  9407. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9408. int bw = 0, aw = 0, first_h = -1;
  9409. int cont_h = l->cb_h; /* the container's definite content height */
  9410. struct br_style bps, aps;
  9411. if (avail < 8 || depth > 48) {
  9412. layout_children(l, parent, pst, depth, link);
  9413. return;
  9414. }
  9415. /* If direct text is not just whitespace, normal block flow handles it
  9416. * better than pretending it is a flex item. */
  9417. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9418. struct br_node *nd = &doc.nodes[c];
  9419. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9420. layout_children(l, parent, pst, depth, link);
  9421. return;
  9422. }
  9423. }
  9424. /* ::before/::after icon boxes are the row's first and last items
  9425. * (Docusaurus' sidebar chevron): reserve their columns. */
  9426. if (doc.npe_rules) {
  9427. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9428. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9429. if (bw + aw > avail - 8) {
  9430. bw = 0;
  9431. aw = 0;
  9432. }
  9433. row_left += bw;
  9434. row_right -= aw;
  9435. avail = row_right - row_left;
  9436. }
  9437. for (c = doc.nodes[parent].first;
  9438. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9439. c = doc.nodes[c].next) {
  9440. struct br_node *nd = &doc.nodes[c];
  9441. struct br_style cs;
  9442. if (nd->type == BR_NODE_TEXT)
  9443. continue;
  9444. br_style_for(&doc, c, pst, &cs);
  9445. if (cs.display == BR_DISPLAY_NONE)
  9446. continue;
  9447. if ((cs.pos == 1 || cs.pos == 2) &&
  9448. layout_out_of_flow(l, c, &cs, depth,
  9449. (nd->tag == BR_TAG_A && nd->href_off) ?
  9450. (unsigned short)c : link))
  9451. continue; /* absolutely positioned: not an item */
  9452. it[nitem].node = c;
  9453. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9454. (unsigned short)c : link;
  9455. it[nitem].w = 0;
  9456. if (cs.flex_grow && !cs.width_kind) {
  9457. grow_count++;
  9458. grow_need += flex_item_width(l, c, &cs, avail);
  9459. } else
  9460. fixed += flex_clamp_w(&cs,
  9461. flex_item_width(l, c, &cs, avail),
  9462. avail);
  9463. nitem++;
  9464. }
  9465. /* A narrow container (an icon row sized to its content, Google's
  9466. * mic + lens buttons) is still a row when its items fit; only a
  9467. * narrow one that would overflow or squeeze growing items falls
  9468. * back to block flow. */
  9469. if (avail < 160 && fixed + grow_need > avail) {
  9470. layout_children(l, parent, pst, depth, link);
  9471. return;
  9472. }
  9473. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9474. /* A growing item capped by max-width (Docusaurus' doc column,
  9475. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9476. * keeps its cap and leaves the rest of the free space to the other
  9477. * growing items. */
  9478. if (grow_count) {
  9479. int pass, capped[32] = { 0 };
  9480. for (pass = 0; pass < nitem; pass++) {
  9481. int changed = 0;
  9482. for (idx = 0; idx < nitem; idx++) {
  9483. struct br_style cs;
  9484. int lim;
  9485. if (capped[idx])
  9486. continue;
  9487. br_style_for(&doc, it[idx].node, pst, &cs);
  9488. if (!cs.flex_grow || cs.width_kind)
  9489. continue;
  9490. lim = flex_clamp_w(&cs, grow_w, avail);
  9491. if (lim == grow_w)
  9492. continue;
  9493. capped[idx] = lim + 1;
  9494. fixed += lim;
  9495. grow_count--;
  9496. changed = 1;
  9497. }
  9498. if (!changed || !grow_count)
  9499. break;
  9500. grow_w = (avail - fixed) / grow_count;
  9501. }
  9502. for (idx = 0; idx < nitem; idx++)
  9503. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9504. }
  9505. if (grow_w < 96 && avail >= 160)
  9506. grow_w = 96;
  9507. for (idx = 0; idx < nitem; idx++) {
  9508. struct br_style cs;
  9509. if (it[idx].w)
  9510. continue; /* capped growing item */
  9511. br_style_for(&doc, it[idx].node, pst, &cs);
  9512. if (cs.flex_grow && !cs.width_kind)
  9513. it[idx].w = grow_w;
  9514. else
  9515. it[idx].w = flex_clamp_w(&cs,
  9516. flex_item_width(l,
  9517. it[idx].node,
  9518. &cs, avail),
  9519. avail);
  9520. if (it[idx].w > avail)
  9521. it[idx].w = avail;
  9522. if (it[idx].w < 8)
  9523. it[idx].w = 8;
  9524. }
  9525. row_top = l->y;
  9526. idx = 0;
  9527. while (idx < nitem) {
  9528. int start = idx, count = 0, row_w = 0;
  9529. int free_w, x, extra = 0, row_h = 0, k;
  9530. while (idx < nitem) {
  9531. int add = it[idx].w + (count ? gap : 0);
  9532. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9533. * starts a new row. */
  9534. if (count && pst->flex_wrap == 1 &&
  9535. row_w + add > avail)
  9536. break;
  9537. row_w += add;
  9538. count++;
  9539. idx++;
  9540. }
  9541. if (!count) {
  9542. count = 1;
  9543. row_w = it[start].w;
  9544. idx = start + 1;
  9545. }
  9546. free_w = avail - row_w;
  9547. if (free_w < 0)
  9548. free_w = 0;
  9549. x = row_left;
  9550. if (pst->justify == 1) {
  9551. x += free_w / 2;
  9552. } else if (pst->justify == 2) {
  9553. x += free_w;
  9554. } else if (pst->justify == 3) {
  9555. extra = count > 1 ? free_w / (count - 1) : 0;
  9556. } else if (pst->justify == 4) {
  9557. extra = count ? free_w / count : 0;
  9558. x += extra / 2;
  9559. } else if (pst->justify == 5) {
  9560. extra = count ? free_w / (count + 1) : 0;
  9561. x += extra;
  9562. }
  9563. for (k = 0; k < count; k++) {
  9564. int node = (int)it[start + k].node;
  9565. int h = block_h[node];
  9566. if (h > row_h)
  9567. row_h = h;
  9568. }
  9569. /* A single line fills a definite container height (an app
  9570. * shell's `height: 100%` sidebar + content row). */
  9571. if (pst->flex_wrap != 1 && cont_h > row_h)
  9572. row_h = cont_h;
  9573. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9574. row_h = pst->height;
  9575. for (k = 0; k < count; k++) {
  9576. struct br_style cs;
  9577. int node = (int)it[start + k].node;
  9578. int yoff = 0;
  9579. br_style_for(&doc, node, pst, &cs);
  9580. cs.width_kind = 0;
  9581. cs.max_width_kind = 0;
  9582. /* align-items: stretch. With a definite line height
  9583. * the item is laid out at it, so its own children see
  9584. * a definite height; otherwise the measure pass
  9585. * stretches it once the line is known (below). */
  9586. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9587. &cs, pst))
  9588. flex_set_stretch(node, &cs, row_h, avail);
  9589. {
  9590. int ai = cs.align_self ? cs.align_self - 1 :
  9591. pst->align_items;
  9592. if (l->draw && ai && row_h > block_h[node]) {
  9593. if (ai == 1)
  9594. yoff = (row_h -
  9595. block_h[node]) / 2;
  9596. else if (ai == 2)
  9597. yoff = row_h - block_h[node];
  9598. }
  9599. }
  9600. l->left = x;
  9601. l->right = x + it[start + k].w;
  9602. if (l->right < l->left + 8)
  9603. l->right = l->left + 8;
  9604. l->y = row_top + yoff;
  9605. /* line_left too: a stale one from the previous item
  9606. * made flush_line() see a non-empty line and push
  9607. * every later item down by an empty line's height. */
  9608. l->line_left = l->line_x = l->run_x = l->left;
  9609. l->line_right = l->right;
  9610. l->line_y = l->y;
  9611. l->line_h = 0;
  9612. l->nruns = 0;
  9613. l->space_pending = 0;
  9614. l->align = cs.align;
  9615. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9616. {
  9617. /* Both passes: a form control item has no
  9618. * block_h of its own, so the draw pass would
  9619. * otherwise end a row of only an <input> at
  9620. * height 0 and pull the content below up. */
  9621. int h = l->y - row_top;
  9622. if (h > row_h)
  9623. row_h = h;
  9624. }
  9625. x += it[start + k].w;
  9626. if (k + 1 < count)
  9627. x += gap + extra;
  9628. }
  9629. if (!l->draw) {
  9630. for (k = 0; k < count; k++) {
  9631. struct br_style cs;
  9632. int node = (int)it[start + k].node;
  9633. br_style_for(&doc, node, pst, &cs);
  9634. if (!flex_item_stretches(node, &cs, pst))
  9635. continue;
  9636. /* To the line's bottom edge from where the
  9637. * item really starts (its top margin, or a
  9638. * line box above it). */
  9639. if (layout_boxes[node].valid)
  9640. flex_set_stretch(node, &cs,
  9641. row_top + row_h -
  9642. layout_boxes[node].y +
  9643. mp_px(&cs, 0, avail), avail);
  9644. else
  9645. flex_set_stretch(node, &cs, row_h, avail);
  9646. }
  9647. }
  9648. if (first_h < 0)
  9649. first_h = row_h;
  9650. row_top += row_h;
  9651. }
  9652. if (bw || aw) {
  9653. int pass;
  9654. for (pass = 0; pass < 2; pass++) {
  9655. const struct br_style *ps = pass ? &aps : &bps;
  9656. int a = pass ? row_right : box_left;
  9657. int b = pass ? box_right : row_left;
  9658. int h = ps->height_kind ?
  9659. style_height_px(ps, box_right - box_left) : 0;
  9660. if (!(pass ? aw : bw))
  9661. continue;
  9662. l->left = l->line_left = l->line_x = l->run_x = a;
  9663. l->right = l->line_right = b;
  9664. l->y = row_top0;
  9665. if (pst->align_items == 1 && first_h > h)
  9666. l->y += (first_h - h) / 2;
  9667. l->line_y = l->y;
  9668. l->line_h = 0;
  9669. l->nruns = 0;
  9670. l->space_pending = 0;
  9671. emit_pseudo_box(l, pst, ps, link);
  9672. flush_line(l);
  9673. /* The box sits inside the first row; it only makes
  9674. * the row taller when it is taller itself. */
  9675. if (row_top0 + h > row_top)
  9676. row_top = row_top0 + h;
  9677. }
  9678. }
  9679. l->left = box_left;
  9680. l->right = box_right;
  9681. l->align = row_align;
  9682. l->y = row_top;
  9683. l->line_left = l->line_x = l->run_x = l->left;
  9684. l->line_right = l->right;
  9685. l->line_y = l->y;
  9686. l->line_h = 0;
  9687. l->nruns = 0;
  9688. l->space_pending = 0;
  9689. }
  9690. /* flex-direction: column. Items stack in order with the gap and never
  9691. * collapse margins. In the draw pass justify-content shares out the free
  9692. * height of the container's measured box (a definite or min-height, or a
  9693. * row stretch), and align-items places each item: stretch (the default)
  9694. * fills the line, start/center/end shrink an item to its content width
  9695. * (a login form's "Log in" button, a centred logo and name). */
  9696. static void layout_flex_column(struct lay *l, unsigned int parent,
  9697. const struct br_style *pst, int depth,
  9698. unsigned short link)
  9699. {
  9700. unsigned int c;
  9701. int box_left = l->left, box_right = l->right;
  9702. int avail = box_right - box_left;
  9703. int gap = pst->grid_gap, y0 = l->y;
  9704. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  9705. unsigned char row_align = l->align;
  9706. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9707. struct br_node *nd = &doc.nodes[c];
  9708. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  9709. break;
  9710. }
  9711. if (c || avail < 8 || depth > 48) {
  9712. /* Loose text: block flow, with centred lines standing in
  9713. * for align-items: center. */
  9714. struct br_style cst = *pst;
  9715. if (pst->align_items == 1) {
  9716. cst.align = BR_ALIGN_CENTER;
  9717. l->align = BR_ALIGN_CENTER;
  9718. }
  9719. layout_children(l, parent, &cst, depth, link);
  9720. return;
  9721. }
  9722. emit_pseudo(l, parent, pst, 1, link);
  9723. flush_line(l);
  9724. y0 = l->y;
  9725. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  9726. int inner = (int)block_h[parent] - pst->border_w[0] -
  9727. pst->border_w[2] - mp_px(pst, 4, avail) -
  9728. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  9729. pst->border_w[0] - mp_px(pst, 4, avail));
  9730. int free_h;
  9731. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9732. struct br_style cs;
  9733. if (doc.nodes[c].type != BR_NODE_ELEM)
  9734. continue;
  9735. br_style_for(&doc, c, pst, &cs);
  9736. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9737. cs.pos == 2)
  9738. continue;
  9739. total += block_h[c] + mp_px(&cs, 0, avail) +
  9740. mp_px(&cs, 2, avail);
  9741. n++;
  9742. }
  9743. if (n > 1)
  9744. total += gap * (n - 1);
  9745. free_h = inner - total;
  9746. if (n && free_h > 0) {
  9747. if (pst->justify == 1) {
  9748. lead = free_h / 2;
  9749. } else if (pst->justify == 2) {
  9750. lead = free_h;
  9751. } else if (pst->justify == 3) {
  9752. extra = n > 1 ? free_h / (n - 1) : 0;
  9753. } else if (pst->justify == 4) {
  9754. extra = free_h / n;
  9755. lead = extra / 2;
  9756. } else if (pst->justify == 5) {
  9757. extra = free_h / (n + 1);
  9758. lead = extra;
  9759. }
  9760. }
  9761. }
  9762. l->y = y0 + lead;
  9763. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9764. struct br_node *nd = &doc.nodes[c];
  9765. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  9766. (unsigned short)c : link;
  9767. struct br_style cs;
  9768. int ai, left = box_left, right = box_right;
  9769. if (nd->type != BR_NODE_ELEM)
  9770. continue;
  9771. br_style_for(&doc, c, pst, &cs);
  9772. if (cs.display == BR_DISPLAY_NONE)
  9773. continue;
  9774. if ((cs.pos == 1 || cs.pos == 2) &&
  9775. layout_out_of_flow(l, c, &cs, depth, lk))
  9776. continue;
  9777. if (k++)
  9778. l->y += gap + extra;
  9779. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  9780. if (ai) {
  9781. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  9782. avail),
  9783. avail);
  9784. if (ai == 1)
  9785. left += (avail - w) / 2;
  9786. else if (ai == 2)
  9787. left += avail - w;
  9788. right = left + w;
  9789. cs.width_kind = 0;
  9790. cs.max_width_kind = 0;
  9791. }
  9792. l->left = l->line_left = l->line_x = l->run_x = left;
  9793. l->right = l->line_right = right;
  9794. l->line_y = l->y;
  9795. l->line_h = 0;
  9796. l->nruns = 0;
  9797. l->space_pending = 0;
  9798. l->align = cs.align;
  9799. layout_block(l, c, &cs, depth + 1, lk);
  9800. }
  9801. l->left = l->line_left = l->line_x = l->run_x = box_left;
  9802. l->right = l->line_right = box_right;
  9803. l->align = row_align;
  9804. l->line_y = l->y;
  9805. l->line_h = 0;
  9806. l->nruns = 0;
  9807. l->space_pending = 0;
  9808. emit_pseudo(l, parent, pst, 2, link);
  9809. }
  9810. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9811. * plus the grid-area hints used by site shells (site notice/footer full
  9812. * width, column-start left, page-content right). Anything more elaborate
  9813. * falls back to normal block flow. */
  9814. static int grid_track_width(unsigned char kind, unsigned short val,
  9815. int avail, int other)
  9816. {
  9817. if (kind == 2)
  9818. return avail * (int)val / 100;
  9819. if (kind == 1)
  9820. return val;
  9821. return other;
  9822. }
  9823. static void layout_grid_children(struct lay *l, unsigned int parent,
  9824. const struct br_style *pst, int depth,
  9825. unsigned short link)
  9826. {
  9827. unsigned int n;
  9828. int row_left = l->left, row_right = l->right;
  9829. int avail = row_right - row_left;
  9830. int gap = pst->grid_gap;
  9831. int track_total = avail - gap;
  9832. int col0, col1, x0, x1;
  9833. int row_y, row_bottom, have_left = 0, have_right = 0;
  9834. unsigned int c;
  9835. if (avail < 32 || depth > 48)
  9836. return;
  9837. if (track_total < 16)
  9838. track_total = 16;
  9839. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9840. pst->width, track_total, 0);
  9841. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9842. pst->max_width, track_total, 0);
  9843. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9844. int w0 = pst->width ? pst->width : 1;
  9845. int w1 = pst->max_width ? pst->max_width : 1;
  9846. col0 = track_total * w0 / (w0 + w1);
  9847. col1 = track_total - col0;
  9848. } else if (pst->width_kind == 3) {
  9849. col0 = track_total - col1;
  9850. if (col0 < 24)
  9851. col0 = 24;
  9852. } else if (pst->max_width_kind == 3) {
  9853. col1 = track_total - col0;
  9854. if (col1 < 24)
  9855. col1 = 24;
  9856. }
  9857. if (col0 < 24)
  9858. col0 = 24;
  9859. if (col1 < 24)
  9860. col1 = 24;
  9861. if (col0 + col1 > track_total) {
  9862. col1 = track_total - col0;
  9863. if (col1 < 24)
  9864. col1 = 24;
  9865. }
  9866. x0 = row_left;
  9867. x1 = row_left + col0 + gap;
  9868. /* Direct text makes a grid ambiguous; use block flow instead. */
  9869. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9870. struct br_node *nd = &doc.nodes[c];
  9871. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9872. layout_children(l, parent, pst, depth, link);
  9873. return;
  9874. }
  9875. }
  9876. row_y = row_bottom = l->y;
  9877. n = doc.nodes[parent].first;
  9878. while (n) {
  9879. struct br_node *nd = &doc.nodes[n];
  9880. struct br_style cs;
  9881. unsigned short lk = link;
  9882. int slot, x, w;
  9883. if (nd->type == BR_NODE_TEXT) {
  9884. n = nd->next;
  9885. continue;
  9886. }
  9887. br_style_for(&doc, n, pst, &cs);
  9888. if (cs.display == BR_DISPLAY_NONE) {
  9889. n = nd->next;
  9890. continue;
  9891. }
  9892. if (nd->tag == BR_TAG_A && nd->href_off)
  9893. lk = (unsigned short)n;
  9894. slot = cs.grid_slot;
  9895. if (!slot) {
  9896. if (!have_left)
  9897. slot = 2;
  9898. else if (!have_right)
  9899. slot = 3;
  9900. else
  9901. slot = 2;
  9902. }
  9903. if (slot == 1) {
  9904. if (have_left || have_right) {
  9905. row_y = row_bottom;
  9906. have_left = have_right = 0;
  9907. }
  9908. x = row_left;
  9909. w = avail;
  9910. } else if (slot == 2) {
  9911. if (have_left) {
  9912. row_y = row_bottom;
  9913. have_left = have_right = 0;
  9914. }
  9915. x = x0;
  9916. w = col0;
  9917. have_left = 1;
  9918. } else {
  9919. if (have_right) {
  9920. row_y = row_bottom;
  9921. have_left = have_right = 0;
  9922. }
  9923. x = x1;
  9924. w = col1;
  9925. have_right = 1;
  9926. }
  9927. cs.width_kind = 0;
  9928. cs.max_width_kind = 0;
  9929. l->left = x;
  9930. l->right = x + w;
  9931. if (l->right < l->left + 8)
  9932. l->right = l->left + 8;
  9933. l->y = row_y;
  9934. l->line_left = l->line_x = l->left;
  9935. l->run_x = l->left;
  9936. l->line_y = l->y;
  9937. l->line_h = 0;
  9938. l->nruns = 0;
  9939. l->space_pending = 0;
  9940. l->align = cs.align;
  9941. layout_block(l, n, &cs, depth + 1, lk);
  9942. if (l->y > row_bottom)
  9943. row_bottom = l->y;
  9944. n = nd->next;
  9945. }
  9946. l->left = row_left;
  9947. l->right = row_right;
  9948. l->y = row_bottom;
  9949. l->line_left = l->line_x = l->left;
  9950. l->run_x = l->left;
  9951. l->line_y = l->y;
  9952. l->line_h = 0;
  9953. l->nruns = 0;
  9954. l->space_pending = 0;
  9955. }
  9956. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9957. * capped at four. Used by the project docs' card grids. A fixed
  9958. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9959. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9960. const struct br_style *pst, int depth,
  9961. unsigned short link)
  9962. {
  9963. unsigned int n, c;
  9964. int row_left = l->left, row_right = l->right;
  9965. int avail = row_right - row_left;
  9966. int gap = pst->grid_gap;
  9967. int minw = pst->width_kind == 1 ? pst->width : 200;
  9968. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9969. if (avail < 32 || depth > 48) {
  9970. layout_children(l, parent, pst, depth, link);
  9971. return;
  9972. }
  9973. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9974. struct br_node *nd = &doc.nodes[c];
  9975. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9976. layout_children(l, parent, pst, depth, link);
  9977. return;
  9978. }
  9979. }
  9980. if (minw < 80)
  9981. minw = 80;
  9982. ncols = (avail + gap) / (minw + gap);
  9983. if (ncols < 1)
  9984. ncols = 1;
  9985. if (ncols > 4)
  9986. ncols = 4;
  9987. if (pst->grid_auto > BR_GRID_FIXED) {
  9988. /* grid-template-columns: repeat(N, 1fr) */
  9989. ncols = pst->grid_auto - BR_GRID_FIXED;
  9990. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9991. ncols--;
  9992. }
  9993. colw = (avail - gap * (ncols - 1)) / ncols;
  9994. if (colw < 24)
  9995. colw = 24;
  9996. x = row_left;
  9997. n = doc.nodes[parent].first;
  9998. while (n) {
  9999. struct br_node *nd = &doc.nodes[n];
  10000. struct br_style cs;
  10001. unsigned short lk = link;
  10002. int h;
  10003. if (nd->type == BR_NODE_TEXT) {
  10004. n = nd->next;
  10005. continue;
  10006. }
  10007. br_style_for(&doc, n, pst, &cs);
  10008. if (cs.display == BR_DISPLAY_NONE) {
  10009. n = nd->next;
  10010. continue;
  10011. }
  10012. if (nd->tag == BR_TAG_A && nd->href_off)
  10013. lk = (unsigned short)n;
  10014. cs.width_kind = 0;
  10015. cs.max_width_kind = 0;
  10016. l->left = x;
  10017. l->right = x + colw;
  10018. if (l->right < l->left + 8)
  10019. l->right = l->left + 8;
  10020. l->y = y;
  10021. l->line_left = l->line_x = l->left;
  10022. l->run_x = l->left;
  10023. l->line_y = l->y;
  10024. l->line_h = 0;
  10025. l->nruns = 0;
  10026. l->space_pending = 0;
  10027. l->align = cs.align;
  10028. layout_block(l, n, &cs, depth + 1, lk);
  10029. h = l->y - y;
  10030. if (h > row_h)
  10031. row_h = h;
  10032. col++;
  10033. n = nd->next;
  10034. if (col == ncols) {
  10035. y += row_h + gap;
  10036. x = row_left;
  10037. row_h = 0;
  10038. col = 0;
  10039. } else {
  10040. x += colw + gap;
  10041. }
  10042. }
  10043. if (col)
  10044. y += row_h;
  10045. else if (y > start_y)
  10046. y -= gap;
  10047. l->left = row_left;
  10048. l->right = row_right;
  10049. l->y = y;
  10050. l->line_left = l->line_x = l->left;
  10051. l->run_x = l->left;
  10052. l->line_y = l->y;
  10053. l->line_h = 0;
  10054. l->nruns = 0;
  10055. l->space_pending = 0;
  10056. }
  10057. /* Column widths are the widest cell in each column across every row, so all
  10058. * rows line up. The table model is still deliberately basic: no colspan,
  10059. * border-collapse or percentage columns. */
  10060. static void table_columns(struct lay *l, unsigned int table,
  10061. const struct br_style *pst, int avail,
  10062. int *raw, int maxcols, int *out_cols,
  10063. int *out_total)
  10064. {
  10065. unsigned int r, c;
  10066. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10067. int fixed[12];
  10068. for (c = 0; c < (unsigned int)maxcols; c++) {
  10069. raw[c] = 0;
  10070. fixed[c] = 0;
  10071. }
  10072. /* Intrinsic widths of single-column cells. */
  10073. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10074. struct br_node *rn = &doc.nodes[r];
  10075. int col = 0;
  10076. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10077. continue;
  10078. for (c = rn->first; c; c = doc.nodes[c].next) {
  10079. struct br_node *cn = &doc.nodes[c];
  10080. struct br_style cs;
  10081. int w, span;
  10082. if (cn->type != BR_NODE_ELEM ||
  10083. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10084. continue;
  10085. span = cn->colspan ? cn->colspan : 1;
  10086. br_style_for(&doc, c, pst, &cs);
  10087. if (cs.display == BR_DISPLAY_NONE)
  10088. continue;
  10089. if (col + span > maxcols)
  10090. span = maxcols - col;
  10091. if (span < 1)
  10092. break;
  10093. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10094. mp_px(&cs, 7, avail) +
  10095. mp_px(&cs, 5, avail) +
  10096. mp_px(&cs, 3, avail) +
  10097. mp_px(&cs, 1, avail) +
  10098. cs.border_w[0] + cs.border_w[1] +
  10099. cs.border_w[2] + cs.border_w[3];
  10100. if (w < 24)
  10101. w = 24;
  10102. if (span == 1) {
  10103. if (w > raw[col])
  10104. raw[col] = w;
  10105. }
  10106. if (col + span > cols)
  10107. cols = col + span;
  10108. col += span;
  10109. }
  10110. }
  10111. /* A colspan cell only has to be as wide as the sum of its columns. */
  10112. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10113. struct br_node *rn = &doc.nodes[r];
  10114. int col = 0;
  10115. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10116. continue;
  10117. for (c = rn->first; c; c = doc.nodes[c].next) {
  10118. struct br_node *cn = &doc.nodes[c];
  10119. struct br_style cs;
  10120. int span, w, sum, i;
  10121. if (cn->type != BR_NODE_ELEM ||
  10122. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10123. continue;
  10124. span = cn->colspan ? cn->colspan : 1;
  10125. if (col + span > maxcols)
  10126. span = maxcols - col;
  10127. if (span < 1)
  10128. break;
  10129. if (span > 1) {
  10130. br_style_for(&doc, c, pst, &cs);
  10131. if (cs.display != BR_DISPLAY_NONE) {
  10132. w = intrinsic_width(l->ui, c, &cs,
  10133. 0, avail) +
  10134. mp_px(&cs, 7, avail) +
  10135. mp_px(&cs, 5, avail) +
  10136. mp_px(&cs, 3, avail) +
  10137. mp_px(&cs, 1, avail) +
  10138. cs.border_w[0] + cs.border_w[1] +
  10139. cs.border_w[2] + cs.border_w[3];
  10140. sum = 0;
  10141. for (i = 0; i < span; i++)
  10142. sum += raw[col + i];
  10143. if (w > sum)
  10144. raw[col + span - 1] += w - sum;
  10145. }
  10146. }
  10147. col += span;
  10148. }
  10149. }
  10150. /* Explicit and percentage widths override intrinsic widths. */
  10151. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10152. struct br_node *rn = &doc.nodes[r];
  10153. int col = 0;
  10154. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10155. continue;
  10156. for (c = rn->first; c; c = doc.nodes[c].next) {
  10157. struct br_node *cn = &doc.nodes[c];
  10158. struct br_style cs;
  10159. int span;
  10160. if (cn->type != BR_NODE_ELEM ||
  10161. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10162. continue;
  10163. span = cn->colspan ? cn->colspan : 1;
  10164. if (col + span > maxcols)
  10165. span = maxcols - col;
  10166. if (span < 1)
  10167. break;
  10168. if (span == 1) {
  10169. br_style_for(&doc, c, pst, &cs);
  10170. if (cs.display != BR_DISPLAY_NONE) {
  10171. if (cs.width_kind == 1) {
  10172. raw[col] = cs.width;
  10173. fixed[col] = 1;
  10174. } else if (cs.width_kind == 2 ||
  10175. cs.width_kind == 3) {
  10176. raw[col] = style_width_px(&cs,
  10177. avail);
  10178. fixed[col] = 1;
  10179. }
  10180. }
  10181. }
  10182. col += span;
  10183. }
  10184. }
  10185. for (c = 0; c < (unsigned int)cols; c++) {
  10186. if (raw[c] < 8)
  10187. raw[c] = 8;
  10188. total += raw[c];
  10189. if (fixed[c])
  10190. fixed_sum += raw[c];
  10191. else {
  10192. free_raw += raw[c];
  10193. free_cols++;
  10194. }
  10195. }
  10196. if (fixed_sum > 0 && fixed_sum < avail) {
  10197. int free_avail = avail - fixed_sum;
  10198. int i;
  10199. if (free_raw > 0) {
  10200. for (i = 0; i < cols; i++)
  10201. if (!fixed[i])
  10202. raw[i] = free_avail * raw[i] /
  10203. free_raw;
  10204. } else if (free_cols > 0) {
  10205. for (i = 0; i < cols; i++)
  10206. if (!fixed[i])
  10207. raw[i] = free_avail / free_cols;
  10208. }
  10209. total = 0;
  10210. for (i = 0; i < cols; i++)
  10211. total += raw[i];
  10212. } else if (total < avail && total > 0) {
  10213. int i;
  10214. for (i = 0; i < cols; i++)
  10215. raw[i] = raw[i] * avail / total;
  10216. total = 0;
  10217. for (i = 0; i < cols; i++)
  10218. total += raw[i];
  10219. }
  10220. *out_cols = cols;
  10221. *out_total = total;
  10222. }
  10223. static void layout_table_row(struct lay *l, unsigned int row,
  10224. const struct br_style *pst, int depth,
  10225. unsigned short link)
  10226. {
  10227. unsigned int n, cell[12];
  10228. int raw[12], colstart[12], colspan[12];
  10229. int prefix[13];
  10230. int ncell = 0, total = 0, cols = 0, col = 0;
  10231. int row_left = l->left, row_right = l->right;
  10232. int avail = row_right - row_left;
  10233. int y = l->y, bottom = l->y;
  10234. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10235. struct br_node *nd = &doc.nodes[n];
  10236. struct br_style cs;
  10237. int span;
  10238. if (nd->type == BR_NODE_TEXT) {
  10239. if (text_node_blank(nd))
  10240. continue;
  10241. layout_children(l, row, pst, depth, link);
  10242. return;
  10243. }
  10244. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10245. layout_children(l, row, pst, depth, link);
  10246. return;
  10247. }
  10248. br_style_for(&doc, n, pst, &cs);
  10249. if (cs.display == BR_DISPLAY_NONE)
  10250. continue;
  10251. if (ncell >= 12) {
  10252. layout_children(l, row, pst, depth, link);
  10253. return;
  10254. }
  10255. span = nd->colspan ? nd->colspan : 1;
  10256. if (span > 12 - col)
  10257. span = 12 - col;
  10258. if (span < 1)
  10259. continue;
  10260. cell[ncell] = n;
  10261. colstart[ncell] = col;
  10262. colspan[ncell] = span;
  10263. col += span;
  10264. ncell++;
  10265. }
  10266. if (ncell < 1 || avail < 32) {
  10267. layout_children(l, row, pst, depth, link);
  10268. return;
  10269. }
  10270. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10271. &total);
  10272. if (cols < 2 || total <= 0) {
  10273. int c;
  10274. total = 0;
  10275. for (c = 0; c < ncell; c++) {
  10276. struct br_style cs;
  10277. br_style_for(&doc, cell[c], pst, &cs);
  10278. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10279. avail) +
  10280. mp_px(&cs, 7, avail) +
  10281. mp_px(&cs, 5, avail) +
  10282. mp_px(&cs, 3, avail) +
  10283. mp_px(&cs, 1, avail);
  10284. if (raw[c] < 24)
  10285. raw[c] = 24;
  10286. total += raw[c];
  10287. }
  10288. /* A one-column table still has to fill its own width; the
  10289. * intrinsic fallback above otherwise leaves the cell at its
  10290. * text width (HN's outer table and nested story table). */
  10291. if (total > 0 && total < avail) {
  10292. int c;
  10293. for (c = 0; c < ncell; c++)
  10294. raw[c] = raw[c] * avail / total;
  10295. total = avail;
  10296. }
  10297. }
  10298. prefix[0] = row_left;
  10299. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10300. prefix[n + 1] = prefix[n] + raw[n];
  10301. for (n = 0; n < (unsigned int)ncell; n++) {
  10302. struct br_style cs;
  10303. int start = colstart[n];
  10304. int end = start + colspan[n];
  10305. int w;
  10306. if (end > cols)
  10307. end = cols;
  10308. if (start >= cols)
  10309. continue;
  10310. w = prefix[end] - prefix[start];
  10311. br_style_for(&doc, cell[n], pst, &cs);
  10312. /* The column width already reflects the cell's width property. */
  10313. cs.width_kind = 0;
  10314. cs.max_width_kind = 0;
  10315. if (w < 24)
  10316. w = 24;
  10317. if (w < 8)
  10318. w = 8;
  10319. l->left = prefix[start];
  10320. l->right = l->left + w;
  10321. l->y = y;
  10322. l->line_left = l->line_x = l->left;
  10323. l->run_x = l->left;
  10324. l->line_y = l->y;
  10325. l->line_h = 0;
  10326. l->nruns = 0;
  10327. l->space_pending = 0;
  10328. l->align = cs.align;
  10329. layout_block(l, cell[n], &cs, depth + 1, link);
  10330. if (l->y > bottom)
  10331. bottom = l->y;
  10332. }
  10333. l->left = row_left;
  10334. l->right = row_right;
  10335. l->y = bottom;
  10336. l->line_left = l->line_x = l->left;
  10337. l->run_x = l->left;
  10338. l->line_y = l->y;
  10339. l->line_h = 0;
  10340. l->nruns = 0;
  10341. l->space_pending = 0;
  10342. }
  10343. #define TBL_MAX_ROWS 32
  10344. #define TBL_MAX_COLS 12
  10345. #define TBL_MAX_CELLS 128
  10346. struct tbl_cell {
  10347. unsigned int node;
  10348. unsigned char row, col, rowspan, colspan;
  10349. int height;
  10350. };
  10351. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10352. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10353. static int table_active;
  10354. static int table_has_rowspan(unsigned int table)
  10355. {
  10356. unsigned int r, c;
  10357. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10358. struct br_node *rn = &doc.nodes[r];
  10359. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10360. continue;
  10361. for (c = rn->first; c; c = doc.nodes[c].next) {
  10362. struct br_node *cn = &doc.nodes[c];
  10363. if (cn->type == BR_NODE_ELEM &&
  10364. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10365. cn->rowspan > 1)
  10366. return 1;
  10367. }
  10368. }
  10369. return 0;
  10370. }
  10371. static void table_cell_style(unsigned int row, unsigned int cell,
  10372. const struct br_style *st, struct br_style *out)
  10373. {
  10374. struct br_style trs;
  10375. br_style_for(&doc, row, st, &trs);
  10376. br_style_for(&doc, cell, &trs, out);
  10377. }
  10378. /* Tables that use rowspan need row heights before anything is painted. This
  10379. * path builds a small occupancy grid, measures the natural cell heights, then
  10380. * lays every cell out at its row/column position. Tables without rowspan
  10381. * keep the lighter per-row path in layout_table_row(). */
  10382. static void layout_table(struct lay *l, unsigned int table,
  10383. const struct br_style *st, int depth,
  10384. unsigned short link)
  10385. {
  10386. unsigned int rows[TBL_MAX_ROWS];
  10387. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10388. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10389. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10390. int free_raw = 0, free_cols = 0;
  10391. int table_left = l->left, table_right = l->right;
  10392. int top = l->y, avail = table_right - table_left;
  10393. unsigned int r, c;
  10394. int i, rr, cc;
  10395. if (depth > 48 || table_active) {
  10396. layout_children(l, table, st, depth, link);
  10397. return;
  10398. }
  10399. table_active = 1;
  10400. for (r = doc.nodes[table].first;
  10401. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10402. struct br_node *rn = &doc.nodes[r];
  10403. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10404. rows[nrows++] = r;
  10405. }
  10406. if (!nrows) {
  10407. table_active = 0;
  10408. layout_children(l, table, st, depth, link);
  10409. return;
  10410. }
  10411. for (rr = 0; rr < nrows; rr++)
  10412. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10413. tbl_at[rr][cc] = 0;
  10414. for (rr = 0; rr < nrows; rr++) {
  10415. int col = 0;
  10416. for (c = doc.nodes[rows[rr]].first; c;
  10417. c = doc.nodes[c].next) {
  10418. struct br_node *cn = &doc.nodes[c];
  10419. struct br_style cs;
  10420. int rs, csn;
  10421. if (cn->type != BR_NODE_ELEM ||
  10422. (cn->tag != BR_TAG_TD &&
  10423. cn->tag != BR_TAG_TH))
  10424. continue;
  10425. table_cell_style(rows[rr], c, st, &cs);
  10426. if (cs.display == BR_DISPLAY_NONE)
  10427. continue;
  10428. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10429. col++;
  10430. if (col >= TBL_MAX_COLS)
  10431. break;
  10432. rs = cn->rowspan ? cn->rowspan : 1;
  10433. csn = cn->colspan ? cn->colspan : 1;
  10434. if (rr + rs > nrows)
  10435. rs = nrows - rr;
  10436. if (col + csn > TBL_MAX_COLS)
  10437. csn = TBL_MAX_COLS - col;
  10438. if (rs < 1 || csn < 1)
  10439. continue;
  10440. if (ncells >= TBL_MAX_CELLS)
  10441. break;
  10442. tbl_cells[ncells].node = c;
  10443. tbl_cells[ncells].row = (unsigned char)rr;
  10444. tbl_cells[ncells].col = (unsigned char)col;
  10445. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10446. tbl_cells[ncells].colspan = (unsigned char)csn;
  10447. tbl_cells[ncells].height = 0;
  10448. for (i = rr; i < rr + rs; i++)
  10449. for (int j = col; j < col + csn; j++)
  10450. tbl_at[i][j] =
  10451. (unsigned short)(ncells + 1);
  10452. ncells++;
  10453. col += csn;
  10454. if (col > cols)
  10455. cols = col;
  10456. }
  10457. }
  10458. if (!ncells || cols < 1) {
  10459. table_active = 0;
  10460. layout_children(l, table, st, depth, link);
  10461. return;
  10462. }
  10463. for (i = 0; i < cols; i++) {
  10464. raw[i] = 0;
  10465. fixed[i] = 0;
  10466. }
  10467. /* Intrinsic widths of single-column cells. */
  10468. for (i = 0; i < ncells; i++) {
  10469. struct br_style cs;
  10470. int w;
  10471. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10472. st, &cs);
  10473. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10474. mp_px(&cs, 7, avail) +
  10475. mp_px(&cs, 5, avail) +
  10476. mp_px(&cs, 3, avail) +
  10477. mp_px(&cs, 1, avail) +
  10478. cs.border_w[0] + cs.border_w[1] +
  10479. cs.border_w[2] + cs.border_w[3];
  10480. if (w < 24)
  10481. w = 24;
  10482. if (tbl_cells[i].colspan == 1) {
  10483. int col = tbl_cells[i].col;
  10484. if (w > raw[col])
  10485. raw[col] = w;
  10486. }
  10487. }
  10488. /* A spanning cell only needs the sum of its columns to be large
  10489. * enough; put the deficit in the last column. */
  10490. for (i = 0; i < ncells; i++) {
  10491. struct br_style cs;
  10492. int w, sum, col, span;
  10493. if (tbl_cells[i].colspan < 2)
  10494. continue;
  10495. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10496. st, &cs);
  10497. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10498. mp_px(&cs, 7, avail) +
  10499. mp_px(&cs, 5, avail) +
  10500. mp_px(&cs, 3, avail) +
  10501. mp_px(&cs, 1, avail) +
  10502. cs.border_w[0] + cs.border_w[1] +
  10503. cs.border_w[2] + cs.border_w[3];
  10504. col = tbl_cells[i].col;
  10505. span = tbl_cells[i].colspan;
  10506. sum = 0;
  10507. for (int j = 0; j < span; j++)
  10508. sum += raw[col + j];
  10509. if (w > sum)
  10510. raw[col + span - 1] += w - sum;
  10511. }
  10512. /* Explicit/percentage widths, as in table_columns(). */
  10513. for (i = 0; i < ncells; i++) {
  10514. struct br_style cs;
  10515. int col;
  10516. if (tbl_cells[i].colspan != 1)
  10517. continue;
  10518. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10519. st, &cs);
  10520. col = tbl_cells[i].col;
  10521. if (cs.width_kind == 1) {
  10522. raw[col] = cs.width;
  10523. fixed[col] = 1;
  10524. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10525. raw[col] = style_width_px(&cs, avail);
  10526. fixed[col] = 1;
  10527. }
  10528. }
  10529. for (i = 0; i < cols; i++) {
  10530. if (raw[i] < 8)
  10531. raw[i] = 8;
  10532. total += raw[i];
  10533. if (fixed[i])
  10534. fixed_sum += raw[i];
  10535. else {
  10536. free_raw += raw[i];
  10537. free_cols++;
  10538. }
  10539. }
  10540. if (fixed_sum > 0 && fixed_sum < avail) {
  10541. int free_avail = avail - fixed_sum;
  10542. if (free_raw > 0) {
  10543. for (i = 0; i < cols; i++)
  10544. if (!fixed[i])
  10545. raw[i] = free_avail * raw[i] /
  10546. free_raw;
  10547. } else if (free_cols > 0) {
  10548. for (i = 0; i < cols; i++)
  10549. if (!fixed[i])
  10550. raw[i] = free_avail / free_cols;
  10551. }
  10552. } else if (total < avail && total > 0) {
  10553. for (i = 0; i < cols; i++)
  10554. raw[i] = raw[i] * avail / total;
  10555. }
  10556. prefix[0] = table_left;
  10557. for (i = 0; i < cols; i++)
  10558. prefix[i + 1] = prefix[i] + raw[i];
  10559. /* Measure natural cell heights with the column widths. */
  10560. for (i = 0; i < ncells; i++) {
  10561. struct br_style cs;
  10562. int col = tbl_cells[i].col;
  10563. int span = tbl_cells[i].colspan;
  10564. int w = prefix[col + span] - prefix[col];
  10565. int sl = l->left, sr = l->right, sy = l->y;
  10566. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10567. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10568. int sal = l->align, sdraw = l->draw;
  10569. struct ngui *sui = l->ui;
  10570. if (w < 8)
  10571. w = 8;
  10572. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10573. st, &cs);
  10574. cs.width_kind = 0;
  10575. cs.max_width_kind = 0;
  10576. l->draw = 0;
  10577. l->ui = 0;
  10578. l->left = prefix[col];
  10579. l->right = l->left + w;
  10580. l->y = 0;
  10581. l->line_left = l->line_x = l->left;
  10582. l->run_x = l->left;
  10583. l->line_y = 0;
  10584. l->line_h = 0;
  10585. l->nruns = 0;
  10586. l->space_pending = 0;
  10587. l->align = cs.align;
  10588. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10589. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10590. l->left = sl;
  10591. l->right = sr;
  10592. l->y = sy;
  10593. l->line_x = slx;
  10594. l->run_x = srx;
  10595. l->line_y = sly;
  10596. l->line_h = slh;
  10597. l->nruns = snr;
  10598. l->space_pending = ssp;
  10599. l->align = sal;
  10600. l->draw = sdraw;
  10601. l->ui = sui;
  10602. }
  10603. for (i = 0; i < nrows; i++)
  10604. rowh[i] = 0;
  10605. for (i = 0; i < ncells; i++) {
  10606. int row = tbl_cells[i].row;
  10607. if (tbl_cells[i].rowspan == 1) {
  10608. if (tbl_cells[i].height > rowh[row])
  10609. rowh[row] = tbl_cells[i].height;
  10610. }
  10611. }
  10612. for (i = 0; i < ncells; i++) {
  10613. int row = tbl_cells[i].row;
  10614. int span = tbl_cells[i].rowspan;
  10615. int sum = 0;
  10616. if (span < 2)
  10617. continue;
  10618. for (int j = 0; j < span; j++)
  10619. sum += rowh[row + j];
  10620. if (sum < tbl_cells[i].height)
  10621. rowh[row + span - 1] +=
  10622. tbl_cells[i].height - sum;
  10623. }
  10624. for (i = 0; i < nrows; i++)
  10625. if (rowh[i] < 8)
  10626. rowh[i] = 8;
  10627. rowy[0] = top;
  10628. for (i = 1; i < nrows; i++)
  10629. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10630. if (!l->draw) {
  10631. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10632. table_active = 0;
  10633. return;
  10634. }
  10635. for (i = 0; i < ncells; i++) {
  10636. struct br_style cs;
  10637. int col = tbl_cells[i].col;
  10638. int span = tbl_cells[i].colspan;
  10639. int row = tbl_cells[i].row;
  10640. int rspan = tbl_cells[i].rowspan;
  10641. int w = prefix[col + span] - prefix[col];
  10642. int h = 0;
  10643. int sl = l->left, sr = l->right, sy = l->y;
  10644. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10645. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10646. int sal = l->align;
  10647. int deco;
  10648. for (int j = 0; j < rspan; j++)
  10649. h += rowh[row + j];
  10650. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10651. cs.width_kind = 0;
  10652. cs.max_width_kind = 0;
  10653. cs.box_sizing = 0;
  10654. deco = mp_px(&cs, 4, avail) +
  10655. mp_px(&cs, 6, avail) +
  10656. cs.border_w[0] + cs.border_w[2];
  10657. cs.height_kind = 1;
  10658. cs.height = h > deco ? h - deco : 0;
  10659. /* The block painter reads block_h[] from the measure pass; make
  10660. * the table cell fill its row/rowspan, not just its content. */
  10661. if (h > 0 && h < 65536)
  10662. block_h[tbl_cells[i].node] = (unsigned short)h;
  10663. l->left = prefix[col];
  10664. l->right = l->left + w;
  10665. l->y = rowy[row];
  10666. l->line_left = l->line_x = l->left;
  10667. l->run_x = l->left;
  10668. l->line_y = l->y;
  10669. l->line_h = 0;
  10670. l->nruns = 0;
  10671. l->space_pending = 0;
  10672. l->align = cs.align;
  10673. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10674. l->left = sl;
  10675. l->right = sr;
  10676. l->y = sy;
  10677. l->line_x = slx;
  10678. l->run_x = srx;
  10679. l->line_y = sly;
  10680. l->line_h = slh;
  10681. l->nruns = snr;
  10682. l->space_pending = ssp;
  10683. l->align = sal;
  10684. }
  10685. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10686. table_active = 0;
  10687. }
  10688. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10689. * flow so they sit above it, like CSS painting order. Their flow origin is
  10690. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10691. struct br_deferred {
  10692. unsigned int node;
  10693. int flow_y, flow_left, flow_right;
  10694. int parent_top; /* the parent box top, for sticky clamping */
  10695. unsigned short link;
  10696. signed short z_index;
  10697. unsigned char z_set;
  10698. unsigned int order;
  10699. };
  10700. /* Positioned boxes painted after the flow. News front pages have one or two
  10701. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10702. * old 16 entries the rest fell back into the flow, so a hero image landed
  10703. * below its padding-top aspect box instead of on top of it. */
  10704. #define BR_MAX_DEFERRED 256
  10705. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10706. static int ndeferred;
  10707. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10708. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10709. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10710. struct br_style *ps, int base)
  10711. {
  10712. char buf[8];
  10713. int w, h;
  10714. if (!doc.npe_rules ||
  10715. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10716. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10717. return 0;
  10718. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10719. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10720. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10721. w = (int)ps->min_width;
  10722. if (w <= 0)
  10723. w = h;
  10724. if (w <= 0 || w > 512)
  10725. return 0;
  10726. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10727. }
  10728. /* An empty ::before/::after with a size and a background: one run the
  10729. * size of the box. Only data: background images are drawn (decoded at
  10730. * the background-size); `margin-left: auto` inside a flex parent pushes
  10731. * the box to the line's right edge like the flex row would. */
  10732. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10733. const struct br_style *ps, unsigned short link)
  10734. {
  10735. struct lay_run *r;
  10736. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10737. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10738. if (lw < 8)
  10739. lw = 8;
  10740. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10741. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10742. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10743. w = (int)ps->min_width;
  10744. if (w <= 0)
  10745. w = h;
  10746. if (h <= 0)
  10747. h = w;
  10748. if (w <= 0 || w > 512 || h > 512)
  10749. return;
  10750. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10751. mr = mp_px(ps, 1, lw);
  10752. if (ml < 0)
  10753. ml = 0;
  10754. if (mr < 0)
  10755. mr = 0;
  10756. if (l->line_x + ml + w > l->line_right &&
  10757. (l->nruns > 0 || l->line_x > l->line_left))
  10758. flush_line(l);
  10759. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  10760. flush_line(l);
  10761. if (l->nruns == 0) {
  10762. l->line_y = l->y;
  10763. l->line_h = 0;
  10764. start_line(l, ps);
  10765. }
  10766. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  10767. l->line_right - w - mr > l->line_x)
  10768. l->line_x = l->line_right - w - mr;
  10769. else
  10770. l->line_x += ml;
  10771. r = &l->runs[l->nruns++];
  10772. memset(r, 0, sizeof(*r));
  10773. r->gap = (unsigned short)(l->line_x > l->run_x ?
  10774. l->line_x - l->run_x : 0);
  10775. r->img = RUN_PBOX;
  10776. r->href = link;
  10777. r->iw = (unsigned short)w;
  10778. r->ih = (unsigned short)h;
  10779. r->w = (unsigned short)w;
  10780. r->font_px = ps->font_px;
  10781. r->pb_has_bg = ps->has_bg;
  10782. r->pb_bg = ps->bg;
  10783. r->pb_img = -1;
  10784. if (ps->transform_set) {
  10785. r->transform_scale = 1;
  10786. r->scale_x = ps->scale_x;
  10787. r->scale_y = ps->scale_y;
  10788. r->rotate_x100 = ps->rotate_x100;
  10789. }
  10790. /* Background size and position, as draw_bg_image() resolves them. */
  10791. tw = w;
  10792. th = h;
  10793. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  10794. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  10795. if (ps->bg_size_kind == 2) {
  10796. bw = bw ? w * bw / 100 : 0;
  10797. bh = bh ? h * bh / 100 : 0;
  10798. }
  10799. tw = bw ? bw : (bh ? bh : w);
  10800. th = bh ? bh : tw;
  10801. }
  10802. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  10803. r->pb_img = (short)data_url_image(url, tw, th);
  10804. r->pb_w = (short)tw;
  10805. r->pb_h = (short)th;
  10806. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  10807. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  10808. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  10809. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  10810. l->line_x += w + mr;
  10811. l->run_x = l->line_x;
  10812. if (l->line_h < h)
  10813. l->line_h = h;
  10814. }
  10815. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10816. * element's line. A block-level pseudo-element gets its own line; its box
  10817. * (margins, padding, background) is not drawn. */
  10818. static void emit_pseudo(struct lay *l, unsigned int node,
  10819. const struct br_style *st, int pe, unsigned short link)
  10820. {
  10821. char buf[160];
  10822. struct br_style ps;
  10823. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10824. unsigned int i = 0;
  10825. int block, space_w;
  10826. if (!n && ps.content == BR_CONTENT_EMPTY &&
  10827. ps.display != BR_DISPLAY_NONE) {
  10828. emit_pseudo_box(l, st, &ps, link);
  10829. return;
  10830. }
  10831. if (!n)
  10832. return;
  10833. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10834. if (block)
  10835. flush_line(l);
  10836. if (ps.uppercase)
  10837. for (i = 0; i < n; i++)
  10838. if (buf[i] >= 'a' && buf[i] <= 'z')
  10839. buf[i] = (char)(buf[i] - 'a' + 'A');
  10840. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10841. if (space_w <= 0)
  10842. space_w = 8;
  10843. i = 0;
  10844. while (i < n) {
  10845. char word[28];
  10846. unsigned int k = 0;
  10847. int w;
  10848. if (buf[i] == ' ') {
  10849. l->space_pending = 1;
  10850. i++;
  10851. continue;
  10852. }
  10853. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10854. word[k++] = buf[i++];
  10855. word[k] = '\0';
  10856. if (l->space_pending &&
  10857. (l->nruns > 0 || l->line_x > l->line_left) &&
  10858. l->line_x + space_w <= l->line_right)
  10859. l->line_x += space_w;
  10860. l->space_pending = 0;
  10861. w = (int)face_text_width(l->ui, &ps, word, k);
  10862. if (l->line_x + w > l->line_right &&
  10863. (l->nruns > 0 || l->line_x > l->line_left))
  10864. flush_line(l);
  10865. add_run(l, 0, 0, &ps, link, word);
  10866. }
  10867. if (block)
  10868. flush_line(l);
  10869. }
  10870. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  10871. * z-index): measured in place, painted from the deferred stacked pass
  10872. * against its containing block. Shared by block and flex layout, so an
  10873. * absolute icon inside a flex row (a password field's reveal button) is
  10874. * not laid out as one of the row's items. Returns 1 when it handled n. */
  10875. static int layout_out_of_flow(struct lay *l, unsigned int n,
  10876. const struct br_style *cs, int depth,
  10877. unsigned short lk)
  10878. {
  10879. if (!(cs->pos == 1 || cs->pos == 2 ||
  10880. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  10881. return 0;
  10882. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  10883. ndeferred < BR_MAX_DEFERRED) {
  10884. /* Relative or sticky z-index (a sticky site
  10885. * header): measure and advance the flow without
  10886. * painting, then paint it in the deferred
  10887. * (stacked) pass, above the content after it. */
  10888. int fy = l->y, fl = l->left, fr = l->right;
  10889. int save_draw = l->draw;
  10890. l->draw = 0;
  10891. layout_block(l, n, cs, depth + 1, lk);
  10892. l->draw = save_draw;
  10893. deferred[ndeferred].node = n;
  10894. deferred[ndeferred].parent_top = l->parent_top;
  10895. deferred[ndeferred].flow_y = fy;
  10896. deferred[ndeferred].flow_left = fl;
  10897. deferred[ndeferred].flow_right = fr;
  10898. deferred[ndeferred].link = lk;
  10899. deferred[ndeferred].z_index = cs->z_index;
  10900. deferred[ndeferred].z_set = cs->z_set;
  10901. deferred[ndeferred].order = (unsigned int)ndeferred;
  10902. ndeferred++;
  10903. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10904. deferred[ndeferred].node = n;
  10905. deferred[ndeferred].parent_top = l->parent_top;
  10906. deferred[ndeferred].flow_y =
  10907. cs->pos == 1 ? l->cb_top : l->y;
  10908. deferred[ndeferred].flow_left =
  10909. cs->pos == 1 ? l->cb_left : l->left;
  10910. deferred[ndeferred].flow_right =
  10911. cs->pos == 1 ? l->cb_right : l->right;
  10912. deferred[ndeferred].link = lk;
  10913. deferred[ndeferred].z_index = cs->z_index;
  10914. deferred[ndeferred].z_set = cs->z_set;
  10915. deferred[ndeferred].order = (unsigned int)ndeferred;
  10916. ndeferred++;
  10917. } else if (l->draw && cs->pos == 1) {
  10918. /* Deferred list full: paint in place, but still
  10919. * against the containing block, not the flow. */
  10920. int fy = l->y, fl = l->left, fr = l->right;
  10921. l->y = l->cb_top;
  10922. l->left = l->cb_left;
  10923. l->right = l->cb_right;
  10924. layout_block(l, n, cs, depth + 1, lk);
  10925. l->y = fy;
  10926. l->left = fl;
  10927. l->right = fr;
  10928. } else {
  10929. layout_block(l, n, cs, depth + 1, lk);
  10930. }
  10931. if (cs->pos == 1 && block_h[n] &&
  10932. doc.nodes[n].class_off) {
  10933. const char *cl = doc.attrs +
  10934. doc.nodes[n].class_off;
  10935. if ((contains_ci(cl, "poster-wrapper") ||
  10936. contains_ci(cl, "ts-picture")) &&
  10937. !has_skeleton_sibling(n))
  10938. l->y += block_h[n];
  10939. }
  10940. return 1;
  10941. }
  10942. static void layout_children(struct lay *l, unsigned int parent,
  10943. const struct br_style *pst, int depth,
  10944. unsigned short link)
  10945. {
  10946. unsigned int n;
  10947. if (depth > 48)
  10948. return;
  10949. emit_pseudo(l, parent, pst, 1, link);
  10950. n = doc.nodes[parent].first;
  10951. while (n) {
  10952. struct br_node *nd = &doc.nodes[n];
  10953. struct br_style cs;
  10954. unsigned short lk = link;
  10955. if (nd->type == BR_NODE_TEXT) {
  10956. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10957. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10958. n = nd->next;
  10959. continue;
  10960. }
  10961. br_style_for(&doc, n, pst, &cs);
  10962. if (cs.display == BR_DISPLAY_NONE) {
  10963. n = nd->next;
  10964. continue;
  10965. }
  10966. if (cs.clear && l->float_active) {
  10967. flush_line(l);
  10968. if (l->y < l->float_bottom)
  10969. l->y = l->float_bottom;
  10970. l->float_active = 0;
  10971. l->line_x = l->left;
  10972. l->run_x = l->left;
  10973. l->line_left = l->left;
  10974. l->line_right = l->right;
  10975. l->line_y = l->y;
  10976. l->line_h = 0;
  10977. l->nruns = 0;
  10978. l->space_pending = 0;
  10979. }
  10980. if (nd->tag == BR_TAG_A && nd->href_off)
  10981. lk = (unsigned short)n;
  10982. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  10983. n = nd->next;
  10984. continue;
  10985. }
  10986. if (nd->tag == BR_TAG_BR) {
  10987. flush_line(l);
  10988. n = nd->next;
  10989. continue;
  10990. }
  10991. if (nd->tag == BR_TAG_HR) {
  10992. flush_line(l);
  10993. if (l->draw)
  10994. ngui_fill_rect(l->ui,
  10995. (struct ngui_rect){l->left, l->y + 2,
  10996. l->right - l->left, 1}, BR_GRAY);
  10997. l->y += 8;
  10998. n = nd->next;
  10999. continue;
  11000. }
  11001. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11002. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11003. !button_has_elements(n)) {
  11004. if (!(nd->tag == BR_TAG_INPUT &&
  11005. s_eq(br_type(&doc, n), "hidden"))) {
  11006. form_fill_line = pst->display ==
  11007. BR_DISPLAY_FLEX &&
  11008. pst->flex_col;
  11009. add_form_run(l, n, &cs, lk);
  11010. form_fill_line = 0;
  11011. }
  11012. n = nd->next;
  11013. continue;
  11014. }
  11015. if (nd->tag == BR_TAG_IMG) {
  11016. add_image_run(l, n, &cs, lk);
  11017. n = nd->next;
  11018. continue;
  11019. }
  11020. if (nd->tag == BR_TAG_SVG &&
  11021. (cs.display == BR_DISPLAY_INLINE ||
  11022. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11023. !cs.float_left) {
  11024. add_svg_run(l, n, &cs, lk);
  11025. n = nd->next;
  11026. continue;
  11027. }
  11028. if (nd->tag == BR_TAG_VIDEO) {
  11029. layout_block(l, n, &cs, depth + 1, lk);
  11030. n = nd->next;
  11031. continue;
  11032. }
  11033. if (cs.float_left) {
  11034. n = layout_float_group(l, n, pst, depth, lk);
  11035. continue;
  11036. }
  11037. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11038. inline_block_flows(n, &cs, 0)) {
  11039. layout_children(l, n, &cs, depth + 1, lk);
  11040. n = nd->next;
  11041. continue;
  11042. }
  11043. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11044. n = layout_inline_blocks(l, n, pst, depth, link);
  11045. continue;
  11046. }
  11047. /* A flex container is block-level like any block box even when
  11048. * the element is an inline tag such as <a> (a link card with
  11049. * display:flex is common on news sites). Without the block box
  11050. * its children were laid out in the parent flow with a 0x0 box
  11051. * of their own. */
  11052. /* inline-flex around inline content only ("| mehr" link
  11053. * tails, icon+label pills) stays in the text line. */
  11054. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11055. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11056. !flex_wants_row(n, &cs)) {
  11057. layout_children(l, n, &cs, depth + 1, lk);
  11058. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11059. cs.display == BR_DISPLAY_FLEX ||
  11060. br_tag_is_block(nd->tag))
  11061. layout_block(l, n, &cs, depth + 1, lk);
  11062. else {
  11063. layout_children(l, n, &cs, depth + 1, lk);
  11064. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11065. l->space_pending = 1;
  11066. }
  11067. n = nd->next;
  11068. }
  11069. emit_pseudo(l, parent, pst, 2, link);
  11070. }
  11071. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11072. * runs and a recursive page can otherwise overflow the stack. */
  11073. static struct lay layout_state;
  11074. static int measure_page(int left, int right)
  11075. {
  11076. struct lay *l = &layout_state;
  11077. struct br_style base = base_style();
  11078. unsigned int i;
  11079. for (i = 0; i < BR_MAX_NODES; i++) {
  11080. block_h[i] = 0;
  11081. flex_stretch_h[i] = 0;
  11082. img_top[i] = 0;
  11083. block_top[i] = 0;
  11084. img_h[i] = 0;
  11085. layout_boxes[i].valid = 0;
  11086. }
  11087. memset(li_marker, 0, sizeof(li_marker));
  11088. l->draw = 0;
  11089. l->ui = &ui;
  11090. l->left = left;
  11091. l->right = right;
  11092. l->y = 0;
  11093. l->line_x = left;
  11094. l->run_x = left;
  11095. l->line_left = left;
  11096. l->line_right = right;
  11097. l->line_y = 0;
  11098. l->line_h = 0;
  11099. l->align = BR_ALIGN_LEFT;
  11100. l->cb_h = layout_view_h;
  11101. l->float_active = 0;
  11102. l->parent_top = 0;
  11103. l->cb_left = left;
  11104. l->cb_right = right;
  11105. l->cb_top = 0;
  11106. l->depth = 0;
  11107. l->nruns = 0;
  11108. l->space_pending = 0;
  11109. base = root_style();
  11110. layout_children(l, doc.root, &base, 0, 0);
  11111. return l->y + 8;
  11112. }
  11113. static int deferred_cmp(const struct br_deferred *a,
  11114. const struct br_deferred *b)
  11115. {
  11116. int az = a->z_set ? a->z_index : 0;
  11117. int bz = b->z_set ? b->z_index : 0;
  11118. if (az != bz)
  11119. return az < bz ? -1 : 1;
  11120. if (a->order != b->order)
  11121. return a->order < b->order ? -1 : 1;
  11122. return 0;
  11123. }
  11124. static void sort_deferred(void)
  11125. {
  11126. int i;
  11127. for (i = 1; i < ndeferred; i++) {
  11128. struct br_deferred key = deferred[i];
  11129. int j = i;
  11130. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11131. deferred[j] = deferred[j - 1];
  11132. j--;
  11133. }
  11134. deferred[j] = key;
  11135. }
  11136. }
  11137. static void render_page(int left, int right, int y0)
  11138. {
  11139. struct lay *l = &layout_state;
  11140. struct br_style base = base_style();
  11141. l->draw = 1;
  11142. l->ui = &ui;
  11143. l->left = left;
  11144. l->right = right;
  11145. l->y = y0;
  11146. l->line_x = left;
  11147. l->run_x = left;
  11148. l->line_left = left;
  11149. l->line_right = right;
  11150. l->line_y = y0;
  11151. l->line_h = 0;
  11152. l->align = BR_ALIGN_LEFT;
  11153. l->cb_h = layout_view_h;
  11154. l->float_active = 0;
  11155. l->parent_top = 0;
  11156. l->cb_left = left;
  11157. l->cb_right = right;
  11158. l->cb_top = y0;
  11159. l->depth = 0;
  11160. l->nruns = 0;
  11161. l->space_pending = 0;
  11162. nhits = 0;
  11163. ndeferred = 0;
  11164. base = root_style();
  11165. layout_children(l, doc.root, &base, 0, 0);
  11166. sort_deferred();
  11167. {
  11168. int i;
  11169. for (i = 0; i < ndeferred; i++) {
  11170. struct br_style st;
  11171. br_style_for(&doc, deferred[i].node, &base, &st);
  11172. if (st.display == BR_DISPLAY_NONE)
  11173. continue;
  11174. l->draw = 1;
  11175. l->left = deferred[i].flow_left;
  11176. l->right = deferred[i].flow_right;
  11177. l->y = deferred[i].flow_y;
  11178. l->parent_top = deferred[i].parent_top;
  11179. l->line_left = l->line_x = l->left;
  11180. l->run_x = l->left;
  11181. l->line_y = l->y;
  11182. l->line_h = 0;
  11183. l->nruns = 0;
  11184. l->space_pending = 0;
  11185. l->align = st.align;
  11186. if (st.pos == 2 && block_h[deferred[i].node]) {
  11187. struct ngui_rect clip;
  11188. int ch = block_h[deferred[i].node] + 24;
  11189. int pr = page_rect.x + page_rect.w - 12;
  11190. int x0 = page_rect.x, x1 = pr;
  11191. int y0 = page_rect.y;
  11192. /* A box placed by `bottom` (a page footer) is
  11193. * clipped and filled where layout_block puts
  11194. * it, against the bottom edge. */
  11195. if (st.bottom_set && !st.top_set) {
  11196. ch = block_h[deferred[i].node] +
  11197. mp_px(&st, 0, pr - page_rect.x) +
  11198. mp_px(&st, 2, pr - page_rect.x);
  11199. y0 = page_rect.y + page_rect.h -
  11200. st.bottom - ch;
  11201. }
  11202. /* The background pre-fill spans the box's own
  11203. * columns, not the whole page: Docusaurus parks
  11204. * a white "Skip to main content" link at
  11205. * `left: 100%` with a z-index above the navbar,
  11206. * and a full-width fill painted over the bar. */
  11207. if (st.left_set)
  11208. x0 = page_rect.x + st.left;
  11209. else if (!st.right_set)
  11210. x0 = deferred[i].flow_left;
  11211. if (st.width_kind == 1) {
  11212. if (st.right_set && !st.left_set)
  11213. x0 = pr - st.right - st.width;
  11214. x1 = x0 + st.width;
  11215. } else if (st.right_set) {
  11216. x1 = pr - st.right;
  11217. }
  11218. if (x0 >= pr || x1 <= page_rect.x)
  11219. continue; /* entirely off-screen */
  11220. if (x0 < page_rect.x)
  11221. x0 = page_rect.x;
  11222. if (x1 > pr)
  11223. x1 = pr;
  11224. if (y0 < page_rect.y) {
  11225. ch -= page_rect.y - y0;
  11226. y0 = page_rect.y;
  11227. }
  11228. clip.x = x0;
  11229. clip.y = y0;
  11230. clip.w = x1 - x0;
  11231. if (ch > page_rect.h)
  11232. ch = page_rect.h;
  11233. if (ch <= 0)
  11234. continue;
  11235. clip.h = ch;
  11236. ngui_push_clip(&ui, clip);
  11237. if (st.has_bg)
  11238. ngui_fill_rect(&ui, clip, st.bg);
  11239. layout_block(l, deferred[i].node, &st, 0,
  11240. deferred[i].link);
  11241. ngui_pop_clip(&ui);
  11242. } else {
  11243. layout_block(l, deferred[i].node, &st, 0,
  11244. deferred[i].link);
  11245. }
  11246. }
  11247. }
  11248. }
  11249. /* ---- UI ---- */
  11250. static int find_hit(int x, int y)
  11251. {
  11252. int i;
  11253. for (i = nhits - 1; i >= 0; i--) {
  11254. struct hit *h = &hits[i];
  11255. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11256. y < h->y + h->h)
  11257. return (int)h->node;
  11258. }
  11259. return 0;
  11260. }
  11261. /* ---- URL-bar autocomplete ----
  11262. *
  11263. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11264. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11265. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11266. * without the scheme and "www.") above substring matches of the URL, then
  11267. * of the title, and adds visit count and recency. Typing at the end of the
  11268. * text also completes inline to the next '/' of the best prefix match
  11269. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11270. * keystroke replaces it; Enter on that text opens the history URL it came
  11271. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11272. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11273. * bar), and a click on a row opens it. */
  11274. #define SUG_MAX 6
  11275. #define SUG_ROW_H 36
  11276. static int sug_idx[SUG_MAX];
  11277. static int sug_n, sug_sel = -1, sug_open;
  11278. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11279. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11280. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11281. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11282. static struct ngui_rect url_rect, sug_rect;
  11283. static int url_had_focus;
  11284. static char lc(char c)
  11285. {
  11286. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11287. }
  11288. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11289. {
  11290. for (; *p; s++, p++)
  11291. if (lc(*s) != *p)
  11292. return 0;
  11293. return 1;
  11294. }
  11295. static unsigned int url_scheme_len(const char *url)
  11296. {
  11297. if (starts_with(url, "https://"))
  11298. return 8;
  11299. if (starts_with(url, "http://"))
  11300. return 7;
  11301. return 0;
  11302. }
  11303. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11304. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11305. static int hist_prefix_at(const char *url, const char *t)
  11306. {
  11307. unsigned int s = url_scheme_len(url);
  11308. if (prefix_ci(url, t))
  11309. return 0;
  11310. if (s && prefix_ci(url + s, t))
  11311. return (int)s;
  11312. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11313. return (int)s + 4;
  11314. return -1;
  11315. }
  11316. static int hist_score(const struct hist_ent *e, const char *t,
  11317. unsigned int next)
  11318. {
  11319. unsigned int age = next - e->stamp;
  11320. int sc, at;
  11321. if (!t[0]) {
  11322. sc = 0;
  11323. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11324. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11325. int rest = (int)s_len(e->url + at);
  11326. sc = 4000 - (rest > 400 ? 400 : rest);
  11327. } else if (contains_ci(e->url, t)) {
  11328. sc = 1000;
  11329. } else if (contains_ci(e->title, t)) {
  11330. sc = 600;
  11331. } else {
  11332. return -1;
  11333. }
  11334. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11335. sc += age >= 500 ? 0 : (int)(500 - age);
  11336. return sc;
  11337. }
  11338. static void sug_lower(char *t, unsigned int cap)
  11339. {
  11340. unsigned int k;
  11341. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11342. t[k] = lc(sug_typed[k]);
  11343. t[k] = '\0';
  11344. }
  11345. static void sug_refresh(void)
  11346. {
  11347. char t[NGUI_INPUT_MAX];
  11348. int sc[SUG_MAX], i, j;
  11349. unsigned int next = hist_next_stamp();
  11350. sug_lower(t, sizeof(t));
  11351. sug_n = 0;
  11352. for (i = 0; i < hist_n; i++) {
  11353. int s = hist_score(&hist_tab[i], t, next);
  11354. if (s < 0)
  11355. continue;
  11356. j = sug_n;
  11357. if (j == SUG_MAX) {
  11358. if (sc[SUG_MAX - 1] >= s)
  11359. continue;
  11360. j = SUG_MAX - 1;
  11361. }
  11362. while (j > 0 && sc[j - 1] < s) {
  11363. sc[j] = sc[j - 1];
  11364. sug_idx[j] = sug_idx[j - 1];
  11365. j--;
  11366. }
  11367. sc[j] = s;
  11368. sug_idx[j] = i;
  11369. if (sug_n < SUG_MAX)
  11370. sug_n++;
  11371. }
  11372. if (sug_sel >= sug_n)
  11373. sug_sel = -1;
  11374. }
  11375. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11376. static void sug_inline(void)
  11377. {
  11378. char t[NGUI_INPUT_MAX];
  11379. const char *url, *rest;
  11380. unsigned int L, start, end, hs, tn, n = 0;
  11381. unsigned int next = hist_next_stamp();
  11382. int i, best = -1, best_sc = -1, at = 0;
  11383. sug_lower(t, sizeof(t));
  11384. L = s_len(t);
  11385. if (!L)
  11386. return;
  11387. for (i = 0; i < hist_n; i++) {
  11388. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11389. if (a < 0)
  11390. continue;
  11391. s = hist_score(&hist_tab[i], t, next);
  11392. if (s > best_sc) {
  11393. best_sc = s;
  11394. best = i;
  11395. at = a;
  11396. }
  11397. }
  11398. if (best < 0)
  11399. return;
  11400. url = hist_tab[best].url;
  11401. rest = url + at;
  11402. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11403. hs = at == 0 ? url_scheme_len(url) : 0;
  11404. start = L > hs ? L : hs;
  11405. end = start;
  11406. while (rest[end] && rest[end] != '/')
  11407. end++;
  11408. if (rest[end] == '/')
  11409. end++;
  11410. tn = s_len(sug_typed);
  11411. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11412. return;
  11413. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11414. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11415. ac_text[n++] = rest[L];
  11416. ac_text[n] = '\0';
  11417. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11418. ngui_input_set(&url_in, ac_text);
  11419. url_in.anchor = tn; /* select the completed part */
  11420. }
  11421. static void sug_close(void)
  11422. {
  11423. sug_open = 0;
  11424. sug_sel = -1;
  11425. ac_text[0] = '\0';
  11426. }
  11427. static int sug_visible(void)
  11428. {
  11429. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11430. }
  11431. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11432. * start page) lists the top sites until something is typed. */
  11433. static int sug_focus_check(void)
  11434. {
  11435. int focused = ngui_focus(&ui) == ID_URL;
  11436. if (focused && !url_had_focus) {
  11437. sug_typed[0] = '\0';
  11438. sug_close();
  11439. sug_open = 1;
  11440. sug_refresh();
  11441. }
  11442. url_had_focus = focused;
  11443. return focused;
  11444. }
  11445. static void url_submit(unsigned int *action)
  11446. {
  11447. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11448. s_copy(click_url, ac_url, sizeof(click_url));
  11449. *action |= ACT_NAV;
  11450. sug_close();
  11451. }
  11452. /* The bar text changed through typing or editing. */
  11453. static void sug_changed(void)
  11454. {
  11455. unsigned int pl = s_len(sug_typed);
  11456. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11457. !memcmp(url_in.text, sug_typed, pl);
  11458. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11459. ac_text[0] = '\0';
  11460. sug_sel = -1;
  11461. sug_open = 1;
  11462. sug_refresh();
  11463. if (grew)
  11464. sug_inline();
  11465. }
  11466. /* Keys for the list, taken off the queue before the text field sees them.
  11467. * Only a leading run is handled; the rest goes to the field. */
  11468. static void sug_keys(void)
  11469. {
  11470. int k;
  11471. while ((k = ngui_key_peek(&ui)) != 0) {
  11472. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11473. ngui_key(&ui);
  11474. if (!sug_open) {
  11475. sug_open = 1;
  11476. continue;
  11477. }
  11478. if (sug_sel < 0)
  11479. s_copy(sug_restore, url_in.text,
  11480. sizeof(sug_restore));
  11481. if (k == NGUI_KEY_DOWN)
  11482. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11483. else
  11484. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11485. ngui_input_set(&url_in, sug_sel >= 0 ?
  11486. hist_tab[sug_idx[sug_sel]].url :
  11487. sug_restore);
  11488. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11489. ngui_key(&ui);
  11490. if (sug_sel >= 0)
  11491. ngui_input_set(&url_in, sug_restore);
  11492. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11493. ngui_input_set(&url_in, sug_typed);
  11494. sug_close();
  11495. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11496. sug_sel >= 0) {
  11497. ngui_key(&ui);
  11498. hist_forget(sug_idx[sug_sel]);
  11499. ngui_input_set(&url_in, sug_restore);
  11500. sug_sel = -1;
  11501. sug_refresh();
  11502. } else {
  11503. break;
  11504. }
  11505. }
  11506. }
  11507. /* A press on a row of last frame's list opens it; any press on the list is
  11508. * swallowed so the page underneath does not see it. */
  11509. static void sug_click(unsigned int *action)
  11510. {
  11511. int row;
  11512. if (!(ui.pressed & 1) || !sug_rect.w ||
  11513. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11514. return;
  11515. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11516. if (row >= 0 && row < sug_n) {
  11517. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11518. sizeof(click_url));
  11519. *action |= ACT_NAV;
  11520. sug_close();
  11521. }
  11522. ui.pressed = 0;
  11523. }
  11524. static void draw_suggest(struct ngui_rect page)
  11525. {
  11526. struct ngui_rect r;
  11527. int i, rows = sug_n, hover = -1;
  11528. r.x = url_rect.x;
  11529. r.y = url_rect.y + url_rect.h + 1;
  11530. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11531. if (r.x + r.w > ui.w - 2)
  11532. r.w = ui.w - 2 - r.x;
  11533. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11534. rows--;
  11535. if (rows <= 0 || r.w < 60) {
  11536. sug_rect.w = 0;
  11537. return;
  11538. }
  11539. r.h = rows * SUG_ROW_H + 2;
  11540. sug_rect = r;
  11541. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11542. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11543. ngui_set_cursor(&ui, CURSOR_POINTER);
  11544. }
  11545. ngui_fill_rect(&ui, r, ui.theme.border);
  11546. for (i = 0; i < rows; i++) {
  11547. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11548. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11549. r.w - 2, SUG_ROW_H};
  11550. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11551. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11552. i == hover ? ui.theme.panel_alt :
  11553. ui.theme.panel;
  11554. ngui_fill_rect(&ui, rr, bg);
  11555. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11556. e->title[0] ? e->title : e->url,
  11557. ui.theme.text);
  11558. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11559. i == sug_sel ? ui.theme.text :
  11560. ui.theme.text_dim);
  11561. }
  11562. }
  11563. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11564. {
  11565. int x = r.x + 4, y = r.y + 4, h = 22;
  11566. int compact = r.w < 560;
  11567. int go_w = r.w < 420 ? 32 : 42;
  11568. int in_x, in_w, res;
  11569. ngui_fill_rect(&ui, r, ui.theme.panel);
  11570. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11571. ui.theme.border);
  11572. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11573. NGUI_ICON_CHEVRON_LEFT))
  11574. *action |= ACT_BACK;
  11575. x += 32;
  11576. if (!compact) {
  11577. if (ngui_icon_button(&ui, ID_FORWARD,
  11578. (struct ngui_rect){x, y, 28, h},
  11579. NGUI_ICON_CHEVRON_RIGHT))
  11580. *action |= ACT_FORWARD;
  11581. x += 32;
  11582. }
  11583. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11584. NGUI_ICON_REFRESH))
  11585. *action |= ACT_RELOAD;
  11586. x += 32;
  11587. if (!compact) {
  11588. if (ngui_icon_button(&ui, ID_HOME,
  11589. (struct ngui_rect){x, y, 28, h},
  11590. NGUI_ICON_HOME))
  11591. *action |= ACT_HOME;
  11592. x += 32;
  11593. }
  11594. in_x = x + 2;
  11595. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11596. if (in_w < 60)
  11597. in_w = 60;
  11598. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11599. if (sug_focus_check())
  11600. sug_keys();
  11601. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11602. sug_focus_check(); /* a click into the bar focuses it here */
  11603. if (res & NGUI_INPUT_CHANGED)
  11604. sug_changed();
  11605. if (res & NGUI_INPUT_SUBMIT)
  11606. url_submit(action);
  11607. if (res & NGUI_INPUT_CANCEL)
  11608. ngui_set_focus(&ui, 0);
  11609. if (ngui_button(&ui, ID_GO,
  11610. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11611. "Go"))
  11612. url_submit(action);
  11613. if (!sug_focus_check())
  11614. sug_close();
  11615. }
  11616. static int page_hover_node(void)
  11617. {
  11618. if (!ui.inside)
  11619. return 0;
  11620. if (ui.mouse_x < page_rect.x ||
  11621. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11622. ui.mouse_y < page_rect.y ||
  11623. ui.mouse_y >= page_rect.y + page_rect.h)
  11624. return 0;
  11625. return find_hit(ui.mouse_x, ui.mouse_y);
  11626. }
  11627. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11628. {
  11629. int x, y, w = page.w, h = page.h;
  11630. if (!src || w <= 0 || h <= 0)
  11631. return;
  11632. for (y = 0; y < h; y++) {
  11633. unsigned short *s = src + (page.y + y) * sw + page.x;
  11634. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11635. for (x = 0; x + 1 < w; x += 2) {
  11636. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11637. }
  11638. if (x < w)
  11639. d[x] = s[x];
  11640. }
  11641. }
  11642. static void draw_page(struct ngui_rect page)
  11643. {
  11644. int left, right, ch;
  11645. int old_panel, old_dim;
  11646. unsigned short *saved_px;
  11647. unsigned short page_bg = ui.theme.bg;
  11648. int saved_w, saved_h, use_buf;
  11649. unsigned int t0 = u_ticks_ms();
  11650. page_rect = page;
  11651. {
  11652. unsigned int root = doc.nnode > 1 ?
  11653. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11654. unsigned int body = doc.nnode > 1 ?
  11655. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11656. struct br_style bs;
  11657. int bg_found = 0;
  11658. if (root) {
  11659. style_for_node(root - 1, &bs);
  11660. if (bs.has_bg) {
  11661. page_bg = bs.bg;
  11662. bg_found = 1;
  11663. }
  11664. }
  11665. if (body) {
  11666. style_for_node(body - 1, &bs);
  11667. if (bs.has_bg) {
  11668. page_bg = bs.bg;
  11669. bg_found = 1;
  11670. }
  11671. }
  11672. /* No canvas colour, but the author made the text dark
  11673. * (Infima's light theme: `--ifm-background-color:
  11674. * transparent` on html, #1c1e21 text): the page expects the
  11675. * white canvas of a normal browser, and dark text on the
  11676. * dark default canvas is unreadable. */
  11677. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11678. unsigned int c = bs.color;
  11679. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11680. ((c >> 5) & 63) * 4 * 587 +
  11681. (c & 31) * 8 * 114;
  11682. if (lum < 100 * 1000)
  11683. page_bg = 0xFFFF;
  11684. }
  11685. }
  11686. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11687. page_cache_valid && layout_valid &&
  11688. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11689. !(ui.scroll_y &&
  11690. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11691. page_scroll.offset == page_cache_scroll &&
  11692. page_cache_nnode == doc.nnode &&
  11693. page_cache_x == page.x && page_cache_y == page.y &&
  11694. page_cache_w == page.w && page_cache_h == page.h) {
  11695. blit_page(page, page_backbuf, pagebuf_w);
  11696. if (img_stat_n)
  11697. img_stat_paint += u_ticks_ms() - t0;
  11698. return;
  11699. }
  11700. ngui_fill_rect(&ui, page, page_bg);
  11701. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11702. const char *s = page_loading ? "Loading..." : "No page";
  11703. int w = (int)ngui_text_width_ui(&ui, s);
  11704. ngui_text(&ui, page.x + (page.w - w) / 2,
  11705. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11706. page_scroll.content_h = 0;
  11707. page_scroll.view_h = page.h;
  11708. page_cache_valid = 0;
  11709. return;
  11710. }
  11711. if (page.w < 40 || page.h < 40) {
  11712. page_cache_valid = 0;
  11713. return;
  11714. }
  11715. saved_px = ui.px;
  11716. saved_w = ui.w;
  11717. saved_h = ui.h;
  11718. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11719. if (use_buf) {
  11720. ui.px = page_backbuf;
  11721. ui.w = pagebuf_w;
  11722. ui.h = pagebuf_h;
  11723. ngui_fill_rect(&ui, page, page_bg);
  11724. }
  11725. /* No gutter of our own: the body's UA margin provides it. The
  11726. * right 12 px stay clear for the scrollbar, like every viewport
  11727. * width below (page_rect.w - 12). */
  11728. left = page.x;
  11729. right = page.x + page.w - 12;
  11730. if (!layout_valid || left != layout_left || right != layout_right ||
  11731. layout_nnode != doc.nnode) {
  11732. unsigned int tm = u_ticks_ms();
  11733. layout_view_h = page.h;
  11734. layout_content_h = measure_page(left, right);
  11735. if (img_stat_n)
  11736. img_stat_reflow += u_ticks_ms() - tm;
  11737. layout_valid = 1;
  11738. layout_left = left;
  11739. layout_right = right;
  11740. layout_nnode = doc.nnode;
  11741. /* Scripts that measured before any layout (offsetWidth on
  11742. * mount) get a resize event once real boxes exist, and again
  11743. * whenever the page width changes. */
  11744. if (js_browser_active() && right - left != resize_sent_w)
  11745. resize_pending = 1;
  11746. }
  11747. ch = layout_content_h;
  11748. page_scroll.content_h = ch;
  11749. page_scroll.view_h = page.h;
  11750. t0 = u_ticks_ms();
  11751. ngui_scroll_begin(&ui, page, &page_scroll);
  11752. ngui_scroll_wheel(&ui, page, &page_scroll);
  11753. render_page(left, right, page.y - page_scroll.offset);
  11754. old_panel = ui.theme.panel_alt;
  11755. old_dim = ui.theme.text_dim;
  11756. ui.theme.panel_alt = 0xC618;
  11757. ui.theme.text_dim = 0x8410;
  11758. ngui_scroll_end(&ui, page, &page_scroll);
  11759. ui.theme.panel_alt = old_panel;
  11760. ui.theme.text_dim = old_dim;
  11761. if (use_buf) {
  11762. ui.px = saved_px;
  11763. ui.w = saved_w;
  11764. ui.h = saved_h;
  11765. blit_page(page, page_backbuf, pagebuf_w);
  11766. page_cache_valid = 1;
  11767. page_cache_scroll = page_scroll.offset;
  11768. page_cache_nnode = doc.nnode;
  11769. page_cache_x = page.x;
  11770. page_cache_y = page.y;
  11771. page_cache_w = page.w;
  11772. page_cache_h = page.h;
  11773. } else {
  11774. page_cache_valid = 0;
  11775. }
  11776. if (img_stat_n)
  11777. img_stat_paint += u_ticks_ms() - t0;
  11778. }
  11779. static void draw_status(struct ngui_rect r)
  11780. {
  11781. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11782. unsigned int n = 0;
  11783. int hover = page_hover_node();
  11784. unsigned short color;
  11785. const char *kind;
  11786. ngui_fill_rect(&ui, r, ui.theme.panel);
  11787. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11788. ui.theme.border);
  11789. /* Only a real link target is shown: a form control, or an element
  11790. * that is merely clickable through a script listener (google.com's
  11791. * jsaction wrapper around its search field), is not a link. */
  11792. if (hover && !br_href(&doc, (unsigned int)hover))
  11793. hover = 0;
  11794. if (hover) {
  11795. const char *href = br_href(&doc, (unsigned int)hover);
  11796. char url[BR_URL_MAX];
  11797. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11798. s_append(msg, &n, "Link: ", sizeof(msg));
  11799. s_append(msg, &n, url, sizeof(msg));
  11800. } else {
  11801. s_copy(msg, "Link", sizeof(msg));
  11802. }
  11803. color = ui.theme.accent;
  11804. } else if (status_text[0]) {
  11805. s_copy(msg, status_text, sizeof(msg));
  11806. color = status_error ? ui.theme.error : ui.theme.text;
  11807. } else if (page_title[0]) {
  11808. s_copy(msg, page_title, sizeof(msg));
  11809. color = ui.theme.text;
  11810. } else {
  11811. s_copy(msg, "Ready", sizeof(msg));
  11812. color = ui.theme.text_dim;
  11813. }
  11814. kind = s_eq(page_url, "about:home") ? "HOME" :
  11815. page_is_local ? "FILE" :
  11816. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11817. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11818. {
  11819. int kw = (int)ngui_text_width_ui(&ui, kind);
  11820. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11821. ui.theme.text_dim);
  11822. }
  11823. }
  11824. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11825. * for `auto`, a hand over links, the I-beam over text fields, and the
  11826. * progress arrow anywhere on the page while it is still loading. The
  11827. * toolbar's URL field sets its own I-beam through ngui. */
  11828. static void page_cursor(void)
  11829. {
  11830. int hover = page_hover_node();
  11831. struct br_style st;
  11832. if (!hover) {
  11833. if (page_loading && ui.inside &&
  11834. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11835. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11836. return;
  11837. }
  11838. style_for_node((unsigned int)hover, &st);
  11839. if (st.cursor != BR_CURSOR_AUTO) {
  11840. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11841. return;
  11842. }
  11843. if (br_href(&doc, (unsigned int)hover)) {
  11844. ngui_set_cursor(&ui, CURSOR_POINTER);
  11845. return;
  11846. }
  11847. if (form_is_control((unsigned int)hover)) {
  11848. int k = form_kind_of((unsigned int)hover);
  11849. if (form_disabled((unsigned int)hover))
  11850. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11851. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11852. k == FORM_TEXTAREA)
  11853. ngui_set_cursor(&ui, CURSOR_TEXT);
  11854. return;
  11855. }
  11856. if (page_loading)
  11857. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11858. }
  11859. static void draw(unsigned int *action)
  11860. {
  11861. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11862. struct ngui_rect toolbar, status, page;
  11863. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11864. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11865. page = r;
  11866. if (sug_visible())
  11867. sug_click(action);
  11868. draw_toolbar(toolbar, action);
  11869. draw_page(page);
  11870. draw_status(status);
  11871. page_cursor();
  11872. if (sug_visible())
  11873. draw_suggest(page);
  11874. else
  11875. sug_rect.w = 0;
  11876. }
  11877. static void redraw_now(void)
  11878. {
  11879. unsigned int action = 0;
  11880. ngui_begin(&ui);
  11881. draw(&action);
  11882. ngui_end(&ui);
  11883. }
  11884. static void handle_keys(unsigned int *action)
  11885. {
  11886. int k, scrolled = 0;
  11887. if (form_focus >= doc.nnode)
  11888. form_focus = 0;
  11889. if (form_focus && !ngui_focus(&ui)) {
  11890. while ((k = ngui_key(&ui)) != 0)
  11891. form_key(k);
  11892. return;
  11893. }
  11894. /* Batch queued page keys: a slow full-page render must not make a
  11895. * held Page Down advance only once every few frames. */
  11896. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11897. scrolled++;
  11898. if (scrolled)
  11899. ngui_invalidate(&ui);
  11900. if (ngui_focus(&ui))
  11901. return;
  11902. while ((k = ngui_key(&ui)) != 0) {
  11903. switch (k) {
  11904. case NGUI_KEY_ESC:
  11905. *action |= ACT_CLOSE;
  11906. break;
  11907. case NGUI_KEY_TAB:
  11908. case 0x0C: /* Ctrl+L */
  11909. ngui_set_focus(&ui, ID_URL);
  11910. break;
  11911. case 0x12: /* Ctrl+R */
  11912. *action |= ACT_RELOAD;
  11913. break;
  11914. case NGUI_KEY_BACKSPACE:
  11915. *action |= ACT_BACK;
  11916. break;
  11917. case NGUI_KEY_UP:
  11918. ngui_scroll_to(&page_scroll,
  11919. page_scroll.offset - 24);
  11920. ngui_invalidate(&ui);
  11921. break;
  11922. case NGUI_KEY_DOWN:
  11923. ngui_scroll_to(&page_scroll,
  11924. page_scroll.offset + 24);
  11925. ngui_invalidate(&ui);
  11926. break;
  11927. case NGUI_KEY_HOME:
  11928. ngui_scroll_to(&page_scroll, 0);
  11929. ngui_invalidate(&ui);
  11930. break;
  11931. case NGUI_KEY_END:
  11932. ngui_scroll_to(&page_scroll,
  11933. page_scroll.content_h -
  11934. page_scroll.view_h);
  11935. ngui_invalidate(&ui);
  11936. break;
  11937. default:
  11938. break;
  11939. }
  11940. }
  11941. }
  11942. static unsigned int form_ancestor(unsigned int node)
  11943. {
  11944. unsigned int p = node;
  11945. while (p && p < doc.nnode) {
  11946. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11947. doc.nodes[p].type == BR_NODE_ELEM)
  11948. return p;
  11949. p = doc.nodes[p].parent;
  11950. }
  11951. return 0;
  11952. }
  11953. static int form_descendant(unsigned int node, unsigned int form)
  11954. {
  11955. unsigned int p = node;
  11956. while (p && p < doc.nnode) {
  11957. if (p == form)
  11958. return 1;
  11959. p = doc.nodes[p].parent;
  11960. }
  11961. return 0;
  11962. }
  11963. static void form_reset_form(unsigned int form)
  11964. {
  11965. unsigned int i;
  11966. for (i = 0; i < FORM_MAX; i++)
  11967. if (form_states[i].used &&
  11968. form_descendant(form_states[i].node, form))
  11969. form_states[i].used = 0;
  11970. form_focus = 0;
  11971. }
  11972. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11973. const char *s)
  11974. {
  11975. static const char hex[] = "0123456789ABCDEF";
  11976. while (s && *s && *n + 1 < cap) {
  11977. unsigned char c = (unsigned char)*s++;
  11978. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11979. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11980. c == '.' || c == '~') {
  11981. dst[(*n)++] = (char)c;
  11982. } else if (c == ' ') {
  11983. dst[(*n)++] = '+';
  11984. } else if (*n + 3 < cap) {
  11985. dst[(*n)++] = '%';
  11986. dst[(*n)++] = hex[c >> 4];
  11987. dst[(*n)++] = hex[c & 15];
  11988. }
  11989. }
  11990. dst[*n] = '\0';
  11991. }
  11992. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11993. const char *name, const char *value, int *first)
  11994. {
  11995. if (!name || !name[0])
  11996. return;
  11997. if (!*first && *n + 1 < cap)
  11998. dst[(*n)++] = '&';
  11999. *first = 0;
  12000. form_url_append(dst, n, cap, name);
  12001. if (*n + 1 < cap)
  12002. dst[(*n)++] = '=';
  12003. form_url_append(dst, n, cap, value ? value : "");
  12004. dst[*n] = '\0';
  12005. }
  12006. static int form_submit_form(unsigned int node, int fire_event)
  12007. {
  12008. unsigned int form = form_ancestor(node);
  12009. char action[BR_URL_MAX], query[2048];
  12010. unsigned int qn = 0, i;
  12011. int first = 1, is_post = 0;
  12012. const char *a, *method;
  12013. if (!form)
  12014. return 0;
  12015. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12016. return 0;
  12017. method = br_find_attr(&doc, form, "method");
  12018. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12019. is_post = 1;
  12020. a = br_find_attr(&doc, form, "action");
  12021. if (a && a[0]) {
  12022. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12023. return 0;
  12024. } else {
  12025. s_copy(action, page_url, sizeof(action));
  12026. }
  12027. query[0] = '\0';
  12028. for (i = 0; i < doc.nnode; i++) {
  12029. struct br_node *nd = &doc.nodes[i];
  12030. struct form_state *fs;
  12031. const char *name;
  12032. const char *value = "";
  12033. if (nd->type != BR_NODE_ELEM || i == form ||
  12034. !form_descendant(i, form))
  12035. continue;
  12036. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12037. nd->tag != BR_TAG_SELECT)
  12038. continue;
  12039. if (form_disabled(i))
  12040. continue;
  12041. name = br_find_attr(&doc, i, "name");
  12042. if (!name || !name[0])
  12043. continue;
  12044. fs = form_get(i, 1);
  12045. if (!fs)
  12046. continue;
  12047. if (nd->tag == BR_TAG_SELECT) {
  12048. char opt[64];
  12049. if (!form_option_text(i, fs->selected, opt,
  12050. sizeof(opt)))
  12051. s_copy(opt, "", sizeof(opt));
  12052. value = opt;
  12053. {
  12054. unsigned int c, oi = 0;
  12055. for (c = nd->first; c;
  12056. c = doc.nodes[c].next) {
  12057. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12058. doc.nodes[c].tag != BR_TAG_OPTION)
  12059. continue;
  12060. if (oi == fs->selected) {
  12061. const char *v =
  12062. br_value(&doc, c);
  12063. if (v && v[0])
  12064. value = v;
  12065. break;
  12066. }
  12067. oi++;
  12068. }
  12069. }
  12070. } else if (nd->tag == BR_TAG_INPUT) {
  12071. int kind = form_kind_of(i);
  12072. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12073. if (!fs->checked)
  12074. continue;
  12075. value = br_value(&doc, i);
  12076. if (!value || !value[0])
  12077. value = "on";
  12078. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12079. kind == FORM_BUTTON) {
  12080. if (i != node)
  12081. continue;
  12082. value = fs->value;
  12083. } else {
  12084. value = fs->value;
  12085. }
  12086. } else {
  12087. value = fs->value;
  12088. }
  12089. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12090. }
  12091. if (is_post) {
  12092. if (action[0] == '/') {
  12093. set_status("POST forms need an HTTP action URL", 1, 4000);
  12094. ngui_invalidate(&ui);
  12095. return 0;
  12096. }
  12097. if (qn >= sizeof(pending_post))
  12098. qn = sizeof(pending_post) - 1;
  12099. if (qn)
  12100. memcpy(pending_post, query, qn);
  12101. pending_post[qn] = '\0';
  12102. pending_post_len = qn;
  12103. pending_post_is = 1;
  12104. } else {
  12105. pending_post_len = 0;
  12106. pending_post_is = 0;
  12107. if (qn) {
  12108. unsigned int an = s_len(action);
  12109. if (an + qn + 2 < sizeof(action)) {
  12110. action[an++] = strchr(action, '?') ? '&' : '?';
  12111. action[an] = '\0';
  12112. s_copy(action + an, query,
  12113. sizeof(action) - an);
  12114. }
  12115. }
  12116. }
  12117. s_copy(pending_url, action, sizeof(pending_url));
  12118. pending_action |= ACT_NAV;
  12119. cancel_fetch = 1;
  12120. ngui_invalidate(&ui);
  12121. return 1;
  12122. }
  12123. static void form_reset_event(unsigned int form)
  12124. {
  12125. if (form && !js_browser_event(form, "reset", 1, 1))
  12126. return;
  12127. if (form)
  12128. form_reset_form(form);
  12129. else
  12130. form_reset_state();
  12131. form_dirty = 0;
  12132. layout_valid = 0;
  12133. ngui_invalidate(&ui);
  12134. }
  12135. static void form_blur(void)
  12136. {
  12137. unsigned int node = form_focus;
  12138. form_focus = 0;
  12139. if (node && form_dirty) {
  12140. form_dirty = 0;
  12141. js_browser_event(node, "change", 1, 0);
  12142. }
  12143. }
  12144. static void form_click(unsigned int node)
  12145. {
  12146. struct form_state *fs;
  12147. int kind, changed = 0;
  12148. if (!form_is_control(node) || form_disabled(node))
  12149. return;
  12150. if (form_focus != node)
  12151. form_blur();
  12152. fs = form_get(node, 1);
  12153. if (!fs)
  12154. return;
  12155. kind = form_kind_of(node);
  12156. /* Focus moves on the press, before `click` is dispatched: a page
  12157. * that cancels the click (a framework's root listener) suppresses
  12158. * the activation behaviour below, never the focus (as in other
  12159. * browsers, where focus follows mousedown). */
  12160. form_focus = node;
  12161. form_dirty = 0;
  12162. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12163. kind == FORM_TEXTAREA)
  12164. fs->caret = fs->len;
  12165. layout_valid = 0;
  12166. ngui_invalidate(&ui);
  12167. if (!js_browser_event(node, "click", 1, 1))
  12168. return;
  12169. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12170. if (!fs)
  12171. return;
  12172. if (kind == FORM_CHECKBOX) {
  12173. fs->checked = !fs->checked;
  12174. changed = 1;
  12175. } else if (kind == FORM_RADIO) {
  12176. const char *name = br_find_attr(&doc, node, "name");
  12177. unsigned int i;
  12178. fs->checked = 1;
  12179. changed = 1;
  12180. if (name) {
  12181. for (i = 0; i < FORM_MAX; i++) {
  12182. struct form_state *o = &form_states[i];
  12183. if (!o->used || o->node == node)
  12184. continue;
  12185. if (form_kind_of(o->node) == FORM_RADIO) {
  12186. const char *on = br_find_attr(&doc,
  12187. o->node,
  12188. "name");
  12189. if (on && s_eq(on, name))
  12190. o->checked = 0;
  12191. }
  12192. }
  12193. }
  12194. } else if (kind == FORM_SELECT) {
  12195. unsigned int n = form_option_count(node);
  12196. if (n) {
  12197. fs->selected = (unsigned char)
  12198. ((fs->selected + 1) % n);
  12199. changed = 1;
  12200. }
  12201. } else if (kind == FORM_SUBMIT) {
  12202. form_submit_form(node, 1);
  12203. return;
  12204. } else if (kind == FORM_RESET) {
  12205. form_reset_event(form_ancestor(node));
  12206. return;
  12207. }
  12208. if (changed) {
  12209. js_browser_event(node, "input", 1, 0);
  12210. js_browser_event(node, "change", 1, 0);
  12211. }
  12212. layout_valid = 0;
  12213. ngui_invalidate(&ui);
  12214. }
  12215. static void form_focus_next(void)
  12216. {
  12217. unsigned int start = form_focus ? form_focus + 1 : 0;
  12218. unsigned int i;
  12219. form_blur();
  12220. for (i = start; i < doc.nnode; i++) {
  12221. if (form_is_control(i) && !form_disabled(i) &&
  12222. !s_eq(br_type(&doc, i), "hidden")) {
  12223. form_focus = i;
  12224. layout_valid = 0;
  12225. ngui_invalidate(&ui);
  12226. return;
  12227. }
  12228. }
  12229. form_focus = 0;
  12230. layout_valid = 0;
  12231. ngui_invalidate(&ui);
  12232. }
  12233. static void form_key(int k)
  12234. {
  12235. struct form_state *fs;
  12236. int kind;
  12237. if (!form_focus || form_focus >= doc.nnode) {
  12238. form_focus = 0;
  12239. return;
  12240. }
  12241. fs = form_get(form_focus, 1);
  12242. if (!fs || form_disabled(form_focus))
  12243. return;
  12244. kind = form_kind_of(form_focus);
  12245. if (kind == FORM_SELECT) {
  12246. unsigned int n = form_option_count(form_focus);
  12247. int changed = 0;
  12248. if (k == NGUI_KEY_UP && n) {
  12249. fs->selected = (unsigned char)
  12250. ((fs->selected + n - 1) % n);
  12251. changed = 1;
  12252. } else if (k == NGUI_KEY_DOWN && n) {
  12253. fs->selected = (unsigned char)
  12254. ((fs->selected + 1) % n);
  12255. changed = 1;
  12256. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12257. form_blur();
  12258. layout_valid = 0;
  12259. ngui_invalidate(&ui);
  12260. return;
  12261. } else {
  12262. return;
  12263. }
  12264. if (changed) {
  12265. js_browser_event(form_focus, "input", 1, 0);
  12266. js_browser_event(form_focus, "change", 1, 0);
  12267. }
  12268. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12269. if (k == ' ') {
  12270. form_click(form_focus);
  12271. return;
  12272. }
  12273. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12274. form_blur();
  12275. layout_valid = 0;
  12276. ngui_invalidate(&ui);
  12277. }
  12278. return;
  12279. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12280. kind == FORM_RESET) {
  12281. if (k == NGUI_KEY_ESC) {
  12282. form_blur();
  12283. layout_valid = 0;
  12284. ngui_invalidate(&ui);
  12285. } else if (k == '\r' || k == '\n' || k == ' ') {
  12286. form_click(form_focus);
  12287. }
  12288. return;
  12289. } else if (k == NGUI_KEY_TAB) {
  12290. form_focus_next();
  12291. return;
  12292. } else if (k == NGUI_KEY_ESC) {
  12293. form_blur();
  12294. layout_valid = 0;
  12295. ngui_invalidate(&ui);
  12296. return;
  12297. } else if (k == '\r' || k == '\n') {
  12298. unsigned int node = form_focus;
  12299. form_blur();
  12300. if (form_ancestor(node))
  12301. form_submit_form(node, 1);
  12302. layout_valid = 0;
  12303. ngui_invalidate(&ui);
  12304. return;
  12305. } else if (k == NGUI_KEY_BACKSPACE) {
  12306. if (fs->caret) {
  12307. unsigned int i = --fs->caret;
  12308. for (; i < fs->len; i++)
  12309. fs->value[i] = fs->value[i + 1];
  12310. if (fs->len)
  12311. fs->len--;
  12312. form_dirty = 1;
  12313. js_browser_event(form_focus, "input", 1, 0);
  12314. }
  12315. } else if (k == NGUI_KEY_DELETE) {
  12316. if (fs->caret < fs->len) {
  12317. unsigned int i;
  12318. for (i = fs->caret; i < fs->len; i++)
  12319. fs->value[i] = fs->value[i + 1];
  12320. fs->len--;
  12321. form_dirty = 1;
  12322. js_browser_event(form_focus, "input", 1, 0);
  12323. }
  12324. } else if (k == NGUI_KEY_LEFT) {
  12325. if (fs->caret)
  12326. fs->caret--;
  12327. } else if (k == NGUI_KEY_RIGHT) {
  12328. if (fs->caret < fs->len)
  12329. fs->caret++;
  12330. } else if (k == NGUI_KEY_HOME) {
  12331. fs->caret = 0;
  12332. } else if (k == NGUI_KEY_END) {
  12333. fs->caret = fs->len;
  12334. } else if (k >= 32 && k < 127) {
  12335. if (fs->len < FORM_VALUE_MAX) {
  12336. unsigned int i;
  12337. for (i = fs->len; i > fs->caret; i--)
  12338. fs->value[i] = fs->value[i - 1];
  12339. fs->value[fs->caret++] = (char)k;
  12340. fs->len++;
  12341. form_dirty = 1;
  12342. js_browser_event(form_focus, "input", 1, 0);
  12343. }
  12344. } else {
  12345. return;
  12346. }
  12347. fs->value[fs->len] = '\0';
  12348. layout_valid = 0;
  12349. ngui_invalidate(&ui);
  12350. }
  12351. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12352. * a same-document navigation: update the URL and fire hashchange. Returns
  12353. * 1 when handled. */
  12354. static int link_fragment_nav(unsigned int node)
  12355. {
  12356. const char *href = br_href(&doc, node);
  12357. char url[BR_URL_MAX];
  12358. unsigned int n = 0;
  12359. if (!href || !href[0] || !js_browser_active())
  12360. return 0;
  12361. if (href[0] == '#') {
  12362. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12363. url[n] = page_url[n];
  12364. n++;
  12365. }
  12366. url[n] = '\0';
  12367. s_append(url, &n, href, sizeof(url));
  12368. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12369. return 0;
  12370. }
  12371. if (!same_doc_fragment(url))
  12372. return href[0] == '#';
  12373. page_set_fragment(url, 1);
  12374. js_browser_hashchange();
  12375. return 1;
  12376. }
  12377. /* The innermost laid-out box under a screen point: the smallest valid box
  12378. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12379. * Used to deliver clicks to elements that are neither links nor controls
  12380. * (a Vue <div role="button">, a card with a click listener). */
  12381. static unsigned int find_box_hit(int x, int y)
  12382. {
  12383. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12384. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12385. const struct br_layout_box *b = &layout_boxes[i];
  12386. unsigned int area;
  12387. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12388. x < b->x || y < b->y || x >= b->x + b->w ||
  12389. y >= b->y + b->h)
  12390. continue;
  12391. area = (unsigned int)b->w * (unsigned int)b->h;
  12392. if (area <= best_area) {
  12393. best = i;
  12394. best_area = area;
  12395. }
  12396. }
  12397. return best;
  12398. }
  12399. static void handle_page_click(unsigned int *action)
  12400. {
  12401. int node;
  12402. char url[BR_URL_MAX];
  12403. if (!ui.pressed)
  12404. return;
  12405. if (ui.press_x < page_rect.x ||
  12406. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12407. ui.press_y < page_rect.y ||
  12408. ui.press_y >= page_rect.y + page_rect.h)
  12409. return;
  12410. node = find_hit(ui.press_x, ui.press_y);
  12411. if (!node) {
  12412. unsigned int box;
  12413. if (!js_browser_active())
  12414. return;
  12415. box = find_box_hit(ui.press_x, ui.press_y);
  12416. if (box) {
  12417. form_blur();
  12418. js_browser_event(box, "click", 1, 1);
  12419. }
  12420. return;
  12421. }
  12422. if (form_is_control((unsigned int)node)) {
  12423. form_click((unsigned int)node);
  12424. return;
  12425. }
  12426. form_blur();
  12427. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12428. return;
  12429. if (link_fragment_nav((unsigned int)node))
  12430. return;
  12431. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12432. sizeof(url)) != 0)
  12433. return;
  12434. s_copy(click_url, url, sizeof(click_url));
  12435. *action |= ACT_NAV;
  12436. }
  12437. void _start(const char *arg)
  12438. {
  12439. struct win_info wi;
  12440. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12441. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12442. u_win_create(780, 540, "Browser", &wi) != 0) {
  12443. u_puts("browser: no graphics window\n");
  12444. u_exit(1);
  12445. }
  12446. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12447. url_in.placeholder = "http://...";
  12448. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12449. ui.theme.accent);
  12450. br_set_viewport(wi.width);
  12451. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12452. s_copy(cwd, "/", sizeof(cwd));
  12453. heap_clear();
  12454. origin_cache_load();
  12455. css_cache_init();
  12456. script_cache_init();
  12457. persist_restore();
  12458. hist_load();
  12459. page_scroll.offset = 0;
  12460. page_scroll.content_h = 0;
  12461. if (arg && arg[0]) {
  12462. navigate(arg, 1);
  12463. } else {
  12464. load_home(1);
  12465. /* Start ready to type: keep the home page, but leave the address
  12466. * bar empty instead of showing "about:home". */
  12467. ngui_input_set(&url_in, "");
  12468. ngui_set_focus(&ui, ID_URL);
  12469. }
  12470. for (;;) {
  12471. unsigned int action = 0;
  12472. unsigned int now;
  12473. click_url[0] = '\0';
  12474. if (pending_action) {
  12475. action |= pending_action & ACT_WAIT_NAV;
  12476. if (pending_url[0])
  12477. s_copy(click_url, pending_url, sizeof(click_url));
  12478. pending_action = 0;
  12479. pending_url[0] = '\0';
  12480. cancel_fetch = 0;
  12481. } else if (preload_active) {
  12482. if (preload_wait)
  12483. preload_wait = 0;
  12484. else
  12485. preload_step();
  12486. } else if ((preload_pending &&
  12487. page_scroll.offset != preload_scroll) ||
  12488. (preload_rescan && layout_valid)) {
  12489. preload_scroll = page_scroll.offset;
  12490. preload_rescan = 0;
  12491. preload_pending = 0;
  12492. preload_node = 0;
  12493. preload_active = 1;
  12494. }
  12495. js_browser_tick();
  12496. if (resize_pending && !pending_action) {
  12497. resize_pending = 0;
  12498. resize_sent_w = layout_right - layout_left;
  12499. js_browser_window_event("resize");
  12500. }
  12501. persist_tick();
  12502. if (pending_action)
  12503. continue;
  12504. now = u_ticks_ms();
  12505. if (status_until && (int)(now - status_until) >= 0) {
  12506. status_text[0] = '\0';
  12507. status_until = 0;
  12508. status_error = 0;
  12509. ngui_invalidate(&ui);
  12510. }
  12511. if (!ngui_begin(&ui)) {
  12512. /* A queued navigation (e.g. Enter in the URL bar during
  12513. * a slow fetch) must be handled even when this frame
  12514. * needs no redraw. */
  12515. if (!action) {
  12516. fetch_workers_stop_if_unfocused();
  12517. u_sleep_ms(10);
  12518. continue;
  12519. }
  12520. } else {
  12521. draw(&action);
  12522. handle_keys(&action);
  12523. handle_page_click(&action);
  12524. ngui_end(&ui);
  12525. }
  12526. if (action & ACT_NAV) {
  12527. if (click_url[0]) {
  12528. navigate(click_url, 1);
  12529. click_url[0] = '\0';
  12530. } else {
  12531. navigate(url_in.text, 1);
  12532. }
  12533. }
  12534. if (action & ACT_BACK) {
  12535. if (hist_pos > 0) {
  12536. hist_pos--;
  12537. if (same_doc_fragment(history[hist_pos])) {
  12538. page_set_fragment(history[hist_pos], 0);
  12539. js_browser_hashchange();
  12540. } else {
  12541. navigate(history[hist_pos], 0);
  12542. }
  12543. }
  12544. }
  12545. if (action & ACT_FORWARD) {
  12546. if (hist_pos + 1 < hist_len) {
  12547. hist_pos++;
  12548. if (same_doc_fragment(history[hist_pos])) {
  12549. page_set_fragment(history[hist_pos], 0);
  12550. js_browser_hashchange();
  12551. } else {
  12552. navigate(history[hist_pos], 0);
  12553. }
  12554. }
  12555. }
  12556. if (action & ACT_RELOAD) {
  12557. if (s_eq(page_url, "about:home"))
  12558. load_home(0);
  12559. else
  12560. navigate(page_url, 0);
  12561. }
  12562. if (action & ACT_HOME)
  12563. load_home(1);
  12564. if (action & ACT_CLOSE)
  12565. quit = 1;
  12566. if (quit)
  12567. break;
  12568. if (pending_action)
  12569. continue;
  12570. fetch_workers_stop_if_unfocused();
  12571. u_sleep_ms(10);
  12572. }
  12573. fetch_workers_stop_all();
  12574. u_win_close();
  12575. u_exit(0);
  12576. }