browser.c 371 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887138881388913890138911389213893138941389513896138971389813899139001390113902139031390413905139061390713908139091391013911
  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. /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
  71. #define FONT_CACHE_MAX 8
  72. #define FONT_CACHE_PREFIX "bfont-"
  73. /* The ufont arena (built-in faces, @font-face files and glyph masks); the
  74. * 512 KB default holds the built-in set but not a page's web fonts. */
  75. #define BR_FONT_ARENA (3u * 1024u * 1024u)
  76. #define BR_MAX_SHEETS 6
  77. #define BR_HISTORY 16
  78. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  79. #define BR_STATUS_MAX 200
  80. #define BR_IMG_RGB565(r, g, b) \
  81. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  82. #define BR_GRAY 0x8410
  83. enum {
  84. ID_URL = 1,
  85. ID_GO,
  86. ID_BACK,
  87. ID_FORWARD,
  88. ID_RELOAD,
  89. ID_HOME
  90. };
  91. #define ACT_NAV (1u << 0)
  92. #define ACT_BACK (1u << 1)
  93. #define ACT_FORWARD (1u << 2)
  94. #define ACT_RELOAD (1u << 3)
  95. #define ACT_HOME (1u << 4)
  96. #define ACT_CLOSE (1u << 5)
  97. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  98. ACT_HOME | ACT_CLOSE)
  99. struct br_image {
  100. int state; /* 0 empty, 1 ready */
  101. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  102. int native_w, native_h;
  103. unsigned int url_hash; /* <img> source, 0 = not shareable */
  104. char err[32];
  105. /* Display-size cache: the box an image is actually painted in. The
  106. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  107. * window resize can re-scale it; the cached copy is exactly dw x dh,
  108. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  109. struct img_image disp;
  110. unsigned int disp_pixels;
  111. unsigned int disp_last;
  112. };
  113. static struct ngui ui;
  114. static struct ngui_input url_in;
  115. static struct ngui_scroll page_scroll;
  116. static struct br_doc doc;
  117. static struct br_image images[BR_MAX_IMAGES];
  118. static int image_count;
  119. static unsigned int image_pixels;
  120. static unsigned int image_disp_pixels;
  121. static unsigned int image_disp_clock;
  122. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  123. * numbers are what decides whether the next work is network, decode or
  124. * display; keep them cheap (one tick read per phase). */
  125. static unsigned int img_stat_start;
  126. static unsigned int img_stat_wall;
  127. static unsigned int img_stat_net;
  128. static unsigned int img_stat_open;
  129. static unsigned int img_stat_first;
  130. static unsigned int img_stat_io;
  131. static unsigned int img_stat_dec;
  132. static unsigned int img_stat_scale;
  133. static unsigned int img_stat_paint;
  134. static unsigned int img_stat_reflow;
  135. static unsigned int img_stat_bytes;
  136. static int img_stat_n;
  137. static unsigned int img_last_dec_ms;
  138. static unsigned int img_last_scale_ms;
  139. static char img_stat_log[BR_IMG_STAT_LOG];
  140. static unsigned int img_stat_log_len;
  141. static unsigned int img_repaint_ms;
  142. static int img_repaint_pending;
  143. /* Painted border boxes, in page/screen coordinates (layout starts at
  144. * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
  145. struct br_layout_box {
  146. int x, y;
  147. int w, h;
  148. unsigned char valid;
  149. };
  150. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  151. /* Inline boxes are built from their line runs in flush_line(): a box is
  152. * replaced when a new layout pass (or a re-layout at the same or an
  153. * earlier line) reaches it, and grown when its runs continue on the same
  154. * or a later line of the same pass. inline_box_parent[] is the enclosing
  155. * inline box (node + 1), so nested spans grow their ancestors too. */
  156. static unsigned int inline_box_pass_id;
  157. static unsigned int inline_box_flush_id;
  158. static unsigned int inline_box_pass[BR_MAX_NODES];
  159. static unsigned int inline_box_flush[BR_MAX_NODES];
  160. static int inline_box_y[BR_MAX_NODES];
  161. static unsigned short inline_box_parent[BR_MAX_NODES];
  162. /* Images are loaded one per main-loop iteration so the parsed page stays
  163. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  164. static int preload_active;
  165. static int preload_max_jobs;
  166. static int preload_pending;
  167. static int preload_wait;
  168. static unsigned int preload_node;
  169. static int preload_loaded;
  170. static int preload_scroll;
  171. static int preload_rescan;
  172. static char post_status_text[BR_STATUS_MAX];
  173. static int post_status_error;
  174. static unsigned int post_status_ttl;
  175. /* Content-relative position/height of each <img>, recorded by the measure
  176. * pass so image loading can be deferred until it is near the viewport. */
  177. static unsigned short img_top[BR_MAX_NODES];
  178. static unsigned short img_h[BR_MAX_NODES];
  179. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  180. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  181. * body. Decode arenas are allocated per image instead of living here. */
  182. static unsigned char *image_io_buf;
  183. static struct ufont_face *font_faces[BR_MAX_FACES];
  184. /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
  185. static unsigned char font_pick[BR_MAX_FACES][4];
  186. #define image_file_buf (image_io_buf)
  187. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  188. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  189. static struct inflate image_inflate_ws;
  190. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  191. #error "CSS scratch must fit in image_io_buf"
  192. #endif
  193. static char page_url[BR_URL_MAX];
  194. static char page_title[BR_TITLE_MAX];
  195. static char cwd[64];
  196. static int page_is_local;
  197. static int page_loading;
  198. static char status_text[BR_STATUS_MAX];
  199. static unsigned int status_until;
  200. static int status_error;
  201. static char history[BR_HISTORY][BR_URL_MAX];
  202. static int hist_len, hist_pos;
  203. static char click_url[BR_URL_MAX];
  204. static char pending_url[BR_URL_MAX];
  205. #define BR_POST_MAX 4096
  206. static char pending_post[BR_POST_MAX];
  207. static unsigned int pending_post_len;
  208. /* The pending navigation is a POST even when its body is empty (a form
  209. * without fields, e.g. the OIDC consent auto-submit). */
  210. static int pending_post_is;
  211. /* window "resize" bookkeeping: the page width the last event was for. */
  212. static int resize_sent_w = -1;
  213. static int resize_pending;
  214. static unsigned int pending_action;
  215. static int cancel_fetch;
  216. static int quit;
  217. static struct ngui_rect page_rect;
  218. static unsigned short *page_backbuf;
  219. static int pagebuf_w, pagebuf_h;
  220. static int page_cache_valid;
  221. static int page_cache_scroll;
  222. static unsigned int page_cache_nnode;
  223. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  224. static int layout_valid, layout_left, layout_right;
  225. /* Height of the page viewport: what html/body height:100% resolves to. */
  226. static int layout_view_h;
  227. static unsigned int layout_nnode;
  228. static int layout_content_h;
  229. /* layout output */
  230. struct lay_run {
  231. unsigned int off;
  232. unsigned short len;
  233. unsigned short gap;
  234. unsigned short color;
  235. unsigned short href;
  236. char lit[28];
  237. short img;
  238. signed short dy; /* inline image vertical offset */
  239. unsigned short iw, ih;
  240. unsigned short w;
  241. unsigned char font_px, bold, italic, mono, underline, strike;
  242. unsigned char overline, font_face;
  243. unsigned char transform_scale;
  244. unsigned char origin_x_kind, origin_y_kind;
  245. signed short scale_x, scale_y, rotate_x100;
  246. signed short origin_x, origin_y;
  247. unsigned char has_lit;
  248. unsigned int form; /* node + 1, 0 = not a control */
  249. unsigned char form_kind;
  250. unsigned char form_disabled;
  251. /* RUN_PBOX: background colour, background image and its placement
  252. * inside the iw x ih box (relative offsets, drawn size). */
  253. unsigned char pb_has_bg;
  254. unsigned short pb_bg;
  255. short pb_img;
  256. short pb_x, pb_y, pb_w, pb_h;
  257. /* Innermost inline element (node + 1) whose box this run belongs
  258. * to, 0 = none; flush_line() unions the placed runs into
  259. * layout_boxes[] so getBoundingClientRect() sees inline boxes. */
  260. unsigned short box;
  261. };
  262. struct lay {
  263. int draw;
  264. struct ngui *ui;
  265. int left, right;
  266. int y;
  267. int line_x, line_y, line_h;
  268. int line_left, line_right;
  269. int parent_top;
  270. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  271. int cb_h; /* definite content height of the containing block for
  272. * percentage heights; 0 = indefinite (auto) */
  273. int run_x;
  274. int align;
  275. int depth;
  276. int space_pending;
  277. unsigned char float_active;
  278. int float_left, float_right, float_bottom;
  279. struct lay_run runs[96];
  280. int nruns;
  281. unsigned short box_owner; /* node + 1 of the open inline box */
  282. };
  283. struct hit {
  284. int x, y, w, h;
  285. unsigned short node;
  286. };
  287. /* Live form state; the DOM attributes stay the initial/default value. */
  288. #define FORM_MAX 64
  289. #define FORM_VALUE_MAX 63
  290. enum {
  291. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  292. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  293. };
  294. struct form_state {
  295. unsigned int node;
  296. char value[FORM_VALUE_MAX + 1];
  297. unsigned char len, caret, checked, selected, used;
  298. };
  299. static struct form_state form_states[FORM_MAX];
  300. static unsigned int form_focus;
  301. static unsigned int form_dirty;
  302. static int form_descendant(unsigned int node, unsigned int form);
  303. static int form_submit_form(unsigned int node, int fire_event);
  304. static int link_fragment_nav(unsigned int node);
  305. static void history_push(const char *url);
  306. static void form_reset_event(unsigned int form);
  307. static unsigned int s_len(const char *s);
  308. static int s_eq(const char *a, const char *b);
  309. static void form_key(int k);
  310. static void form_click(unsigned int node);
  311. static void style_for_node(unsigned int node, struct br_style *out);
  312. static int form_author_styled(const struct br_style *st);
  313. static int css_radius(const struct br_style *st, int corner, int w, int h);
  314. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  315. const struct br_style *st, int focused);
  316. static int form_disabled(unsigned int node)
  317. {
  318. struct br_node *n = &doc.nodes[node];
  319. if (n->attr_flags & BR_ATTR_DISABLED)
  320. return 1;
  321. return br_find_attr(&doc, node, "disabled") != 0;
  322. }
  323. static int form_kind_of(unsigned int node)
  324. {
  325. const char *type = br_type(&doc, node);
  326. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  327. return FORM_TEXTAREA;
  328. if (doc.nodes[node].tag == BR_TAG_SELECT)
  329. return FORM_SELECT;
  330. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  331. if (s_eq(type, "reset"))
  332. return FORM_RESET;
  333. if (s_eq(type, "button"))
  334. return FORM_BUTTON;
  335. return FORM_SUBMIT;
  336. }
  337. if (s_eq(type, "password"))
  338. return FORM_PASSWORD;
  339. if (s_eq(type, "checkbox"))
  340. return FORM_CHECKBOX;
  341. if (s_eq(type, "radio"))
  342. return FORM_RADIO;
  343. if (s_eq(type, "submit"))
  344. return FORM_SUBMIT;
  345. if (s_eq(type, "reset"))
  346. return FORM_RESET;
  347. if (s_eq(type, "button"))
  348. return FORM_BUTTON;
  349. return FORM_TEXT;
  350. }
  351. static unsigned int form_option_count(unsigned int node)
  352. {
  353. unsigned int c, n = 0;
  354. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  355. if (doc.nodes[c].type == BR_NODE_ELEM &&
  356. doc.nodes[c].tag == BR_TAG_OPTION)
  357. n++;
  358. return n;
  359. }
  360. static unsigned int form_option_selected(unsigned int node)
  361. {
  362. unsigned int c, i = 0;
  363. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  364. if (doc.nodes[c].type != BR_NODE_ELEM ||
  365. doc.nodes[c].tag != BR_TAG_OPTION)
  366. continue;
  367. if (br_find_attr(&doc, c, "selected"))
  368. return i;
  369. i++;
  370. }
  371. return 0;
  372. }
  373. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  374. char *out, unsigned int cap)
  375. {
  376. unsigned int c, i = 0;
  377. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  378. if (doc.nodes[c].type != BR_NODE_ELEM ||
  379. doc.nodes[c].tag != BR_TAG_OPTION)
  380. continue;
  381. if (i == idx)
  382. return br_text_content(&doc, c, out, cap);
  383. i++;
  384. }
  385. return 0;
  386. }
  387. static int form_is_control(unsigned int node);
  388. static struct form_state *form_get(unsigned int node, int create)
  389. {
  390. struct form_state *slot = 0;
  391. unsigned int i;
  392. for (i = 0; i < FORM_MAX; i++) {
  393. if (form_states[i].used) {
  394. if (form_states[i].node == node)
  395. return &form_states[i];
  396. } else if (!slot) {
  397. slot = &form_states[i];
  398. }
  399. }
  400. if (create && !slot) {
  401. /* Full: a client-side router (Docusaurus' React Router)
  402. * replaces page content without a navigation, so slots of
  403. * controls that left the document pile up until no new
  404. * control can be drawn or focused.
  405. * Reuse those first, then slots of nodes that are no longer
  406. * controls. */
  407. for (i = 0; i < FORM_MAX && !slot; i++)
  408. if (form_states[i].node != form_focus &&
  409. br_node_detached(&doc, form_states[i].node))
  410. slot = &form_states[i];
  411. for (i = 0; i < FORM_MAX && !slot; i++)
  412. if (form_states[i].node != form_focus &&
  413. !form_is_control(form_states[i].node))
  414. slot = &form_states[i];
  415. }
  416. if (!create || !slot)
  417. return 0;
  418. slot->node = node;
  419. slot->len = 0;
  420. slot->caret = 0;
  421. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  422. slot->selected = form_option_selected(node);
  423. slot->used = 1;
  424. {
  425. unsigned int n = 0;
  426. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  427. n = br_text_content(&doc, node, slot->value,
  428. FORM_VALUE_MAX + 1);
  429. } else {
  430. const char *v = br_value(&doc, node);
  431. if (v) {
  432. n = s_len(v);
  433. if (n > FORM_VALUE_MAX)
  434. n = FORM_VALUE_MAX;
  435. for (unsigned int j = 0; j < n; j++)
  436. slot->value[j] = v[j];
  437. }
  438. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  439. n = br_text_content(&doc, node, slot->value,
  440. FORM_VALUE_MAX + 1);
  441. }
  442. if (n > FORM_VALUE_MAX)
  443. n = FORM_VALUE_MAX;
  444. slot->value[n] = '\0';
  445. slot->len = (unsigned char)n;
  446. slot->caret = (unsigned char)n;
  447. }
  448. return slot;
  449. }
  450. static void form_reset_state(void)
  451. {
  452. unsigned int i;
  453. for (i = 0; i < FORM_MAX; i++)
  454. form_states[i].used = 0;
  455. form_focus = 0;
  456. }
  457. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  458. * is laid out like a normal element so that content shows; only a text or
  459. * empty button is drawn as a native control. Clicks still reach it
  460. * through the box hit test. */
  461. static int button_has_elements(unsigned int node)
  462. {
  463. unsigned int c;
  464. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  465. return 0;
  466. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  467. if (doc.nodes[c].type == BR_NODE_ELEM)
  468. return 1;
  469. /* An empty button whose icon is a ::before/::after box (Docusaurus'
  470. * sidebar caret) is laid out as an element so the box is drawn. */
  471. if (!doc.nodes[node].first && doc.npe_rules) {
  472. struct br_style st, ps;
  473. char buf[8];
  474. int pe;
  475. style_for_node(node, &st);
  476. for (pe = 1; pe <= 2; pe++)
  477. if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
  478. sizeof(buf)) &&
  479. ps.content == BR_CONTENT_EMPTY &&
  480. ps.display != BR_DISPLAY_NONE)
  481. return 1;
  482. }
  483. return 0;
  484. }
  485. static int form_is_control(unsigned int node)
  486. {
  487. unsigned int tag;
  488. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  489. return 0;
  490. tag = doc.nodes[node].tag;
  491. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  492. tag == BR_TAG_SELECT ||
  493. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  494. }
  495. #define HIT_MAX 96
  496. static struct hit hits[HIT_MAX];
  497. static int nhits;
  498. static unsigned short block_h[BR_MAX_NODES];
  499. /* Border-box height a flex container stretches an item to (align-items:
  500. * stretch in a row with a taller line or a definite height), 0 = none.
  501. * Written by the measure pass, read by both. */
  502. static unsigned short flex_stretch_h[BR_MAX_NODES];
  503. /* Measure-pass top of each block, in the same document coordinates as
  504. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  505. * paint, so it cannot drive the lazy background loader). */
  506. static unsigned short block_top[BR_MAX_NODES];
  507. static char li_marker[BR_MAX_NODES][12];
  508. /* one connection object; the browser fetches one resource at a time */
  509. /* ---- tiny strings ---- */
  510. static unsigned int s_len(const char *s)
  511. {
  512. unsigned int n = 0;
  513. while (s && s[n])
  514. n++;
  515. return n;
  516. }
  517. static void s_copy(char *d, const char *s, unsigned int cap)
  518. {
  519. unsigned int i = 0;
  520. if (!cap)
  521. return;
  522. while (s && s[i] && i + 1 < cap) {
  523. d[i] = s[i];
  524. i++;
  525. }
  526. d[i] = '\0';
  527. }
  528. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  529. {
  530. while (s && *s && *n + 1 < cap)
  531. d[(*n)++] = *s++;
  532. d[*n] = '\0';
  533. }
  534. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  535. unsigned int cap)
  536. {
  537. char tmp[12];
  538. unsigned int i = 0, j;
  539. do {
  540. tmp[i++] = (char)('0' + v % 10);
  541. v /= 10;
  542. } while (v && i < sizeof(tmp));
  543. for (j = 0; j < i && *n + 1 < cap; j++)
  544. d[(*n)++] = tmp[i - 1 - j];
  545. d[*n] = '\0';
  546. }
  547. static int s_eq(const char *a, const char *b)
  548. {
  549. while (*a && *b) {
  550. if (*a != *b)
  551. return 0;
  552. a++;
  553. b++;
  554. }
  555. return *a == *b;
  556. }
  557. static int starts_with(const char *s, const char *p)
  558. {
  559. unsigned int i = 0;
  560. while (p[i]) {
  561. if (s[i] != p[i])
  562. return 0;
  563. i++;
  564. }
  565. return 1;
  566. }
  567. static int contains_ci(const char *s, const char *p)
  568. {
  569. unsigned int i, j;
  570. for (i = 0; s[i]; i++) {
  571. for (j = 0; p[j]; j++) {
  572. char a = s[i + j];
  573. if (a >= 'A' && a <= 'Z')
  574. a = (char)(a - 'A' + 'a');
  575. if (a != p[j])
  576. break;
  577. }
  578. if (!p[j])
  579. return 1;
  580. }
  581. return 0;
  582. }
  583. static char *trim(char *s)
  584. {
  585. unsigned int n;
  586. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  587. s++;
  588. n = s_len(s);
  589. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  590. s[n - 1] == '\r' || s[n - 1] == '\n'))
  591. s[--n] = '\0';
  592. return s;
  593. }
  594. /* ---- per-process heap ---- */
  595. static int heap_start(void)
  596. {
  597. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  598. if (!image_io_buf)
  599. return -1;
  600. page_backbuf = (unsigned short *)malloc(
  601. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  602. pagebuf_w = page_backbuf ? ui.w : 0;
  603. pagebuf_h = page_backbuf ? ui.h : 0;
  604. page_cache_valid = 0;
  605. return 0;
  606. }
  607. static void heap_clear(void)
  608. {
  609. memset(font_faces, 0, sizeof(font_faces));
  610. memset(font_pick, 0, sizeof(font_pick));
  611. ngui_font_detach(&ui);
  612. svg_cache_clear();
  613. decode_arena = 0; /* lives in the page heap too */
  614. decode_arena_size = 0;
  615. heap_reset();
  616. /* The document arenas live in that heap; drop the stale pointers so
  617. * the next br_parse_plain() allocates fresh ones. */
  618. doc.nodes = 0;
  619. doc.text = 0;
  620. doc.attrs = 0;
  621. image_io_buf = 0;
  622. page_backbuf = 0;
  623. pagebuf_w = pagebuf_h = 0;
  624. page_cache_valid = 0;
  625. }
  626. static void browser_rules_alloc(void)
  627. {
  628. struct br_rule *rules;
  629. rules = (struct br_rule *)malloc(
  630. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  631. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  632. }
  633. /* ---- status ---- */
  634. static void set_status(const char *s, int err, unsigned int ttl_ms)
  635. {
  636. s_copy(status_text, s, sizeof(status_text));
  637. status_error = err;
  638. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  639. ngui_invalidate(&ui);
  640. }
  641. /* Update the status text without forcing a frame; the throttled image
  642. * repaint picks it up. Starting one helper per image used to invalidate the
  643. * whole page before every decode. */
  644. static void set_status_quiet(const char *s)
  645. {
  646. s_copy(status_text, s, sizeof(status_text));
  647. status_error = 0;
  648. status_until = 0;
  649. }
  650. /* ---- JavaScript ---- */
  651. static int resolve_link(const char *base, const char *href, char *out,
  652. unsigned int cap);
  653. static char js_last_status[BR_STATUS_MAX];
  654. static int js_last_error;
  655. static void js_host_status(const char *msg, int error)
  656. {
  657. s_copy(js_last_status, msg, sizeof(js_last_status));
  658. js_last_error = error;
  659. set_status(msg, error, 6000);
  660. }
  661. static void js_host_report(const char *msg)
  662. {
  663. u_puts("[js] ");
  664. u_puts(msg);
  665. u_putc('\n');
  666. s_copy(js_last_status, msg, sizeof(js_last_status));
  667. js_last_error = 1;
  668. set_status(msg, 1, 8000);
  669. }
  670. static void js_host_navigate(const char *url)
  671. {
  672. char resolved[BR_URL_MAX];
  673. if (!url || !url[0])
  674. return;
  675. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  676. return;
  677. s_copy(pending_url, resolved, sizeof(pending_url));
  678. pending_action |= ACT_NAV;
  679. cancel_fetch = 1;
  680. }
  681. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  682. * back/forward between fragments): the page URL, address bar and history
  683. * follow, nothing is reloaded. `push` adds a history entry. */
  684. static int page_set_fragment(const char *url, int push)
  685. {
  686. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  687. return -1;
  688. s_copy(page_url, url, sizeof(page_url));
  689. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  690. url_in.len = s_len(url_in.text);
  691. url_in.cursor = url_in.len;
  692. url_in.scroll = 0;
  693. if (push)
  694. history_push(page_url);
  695. ngui_invalidate(&ui);
  696. return 0;
  697. }
  698. static int js_host_set_hash(const char *url)
  699. {
  700. return page_set_fragment(url, 1);
  701. }
  702. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  703. * the page, so a hash router can react). */
  704. static int same_doc_fragment(const char *url)
  705. {
  706. unsigned int a = 0, b = 0;
  707. if (!js_browser_active() || !url)
  708. return 0;
  709. while (url[a] && url[a] != '#')
  710. a++;
  711. while (page_url[b] && page_url[b] != '#')
  712. b++;
  713. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  714. !s_eq(url, page_url);
  715. }
  716. static void js_host_changed(void)
  717. {
  718. /* Class/style/attribute mutations change computed styles, not just the
  719. * text: drop the per-node style cache before the next layout. */
  720. br_reset_styles(&doc);
  721. layout_valid = 0;
  722. /* Script-built content (Angular's ng-repeat cards) brings new images
  723. * and inline background styles: rescan once the main loop is idle. */
  724. preload_rescan = 1;
  725. ngui_invalidate(&ui);
  726. }
  727. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  728. {
  729. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  730. return 0;
  731. *x = layout_boxes[node].x - page_rect.x;
  732. *y = layout_boxes[node].y - page_rect.y;
  733. *w = layout_boxes[node].w;
  734. *h = layout_boxes[node].h;
  735. return 1;
  736. }
  737. static void form_copy_out(const char *s, char *buf, int cap)
  738. {
  739. int i = 0;
  740. if (!buf || cap <= 0)
  741. return;
  742. while (s && s[i] && i + 1 < cap) {
  743. buf[i] = s[i];
  744. i++;
  745. }
  746. buf[i] = '\0';
  747. }
  748. static int js_host_form_value(unsigned int node, char *buf, int cap)
  749. {
  750. struct form_state *fs;
  751. int kind;
  752. if (!form_is_control(node))
  753. return 0;
  754. kind = form_kind_of(node);
  755. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  756. return 0;
  757. if (kind == FORM_SELECT) {
  758. char opt[64] = "";
  759. unsigned int c, i = 0;
  760. fs = form_get(node, 1);
  761. if (!fs)
  762. return 0;
  763. form_option_text(node, fs->selected, opt, sizeof(opt));
  764. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  765. if (doc.nodes[c].type != BR_NODE_ELEM ||
  766. doc.nodes[c].tag != BR_TAG_OPTION)
  767. continue;
  768. if (i == fs->selected) {
  769. const char *v = br_value(&doc, c);
  770. if (v && v[0])
  771. form_copy_out(v, buf, cap);
  772. else
  773. form_copy_out(opt, buf, cap);
  774. return 1;
  775. }
  776. i++;
  777. }
  778. form_copy_out(opt, buf, cap);
  779. return 1;
  780. }
  781. fs = form_get(node, 1);
  782. if (!fs)
  783. return 0;
  784. form_copy_out(fs->value, buf, cap);
  785. return 1;
  786. }
  787. static int js_host_form_checked(unsigned int node)
  788. {
  789. struct form_state *fs;
  790. int kind;
  791. if (!form_is_control(node))
  792. return -1;
  793. kind = form_kind_of(node);
  794. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  795. return -1;
  796. fs = form_get(node, 1);
  797. return fs ? fs->checked : 0;
  798. }
  799. static int js_host_form_selected(unsigned int node)
  800. {
  801. struct form_state *fs;
  802. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  803. return -1;
  804. fs = form_get(node, 1);
  805. return fs ? fs->selected : 0;
  806. }
  807. static int js_host_form_set_value(unsigned int node, const char *value)
  808. {
  809. struct form_state *fs;
  810. unsigned int n;
  811. if (!form_is_control(node))
  812. return 0;
  813. fs = form_get(node, 1);
  814. if (!fs)
  815. return 0;
  816. n = s_len(value ? value : "");
  817. if (n > FORM_VALUE_MAX)
  818. n = FORM_VALUE_MAX;
  819. for (unsigned int i = 0; i < n; i++)
  820. fs->value[i] = value[i];
  821. fs->value[n] = '\0';
  822. fs->len = (unsigned char)n;
  823. fs->caret = (unsigned char)n;
  824. layout_valid = 0;
  825. ngui_invalidate(&ui);
  826. return 1;
  827. }
  828. static int js_host_form_set_checked(unsigned int node, int checked)
  829. {
  830. struct form_state *fs;
  831. int kind;
  832. if (!form_is_control(node))
  833. return 0;
  834. kind = form_kind_of(node);
  835. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  836. return 0;
  837. fs = form_get(node, 1);
  838. if (!fs)
  839. return 0;
  840. fs->checked = (unsigned char)(checked != 0);
  841. layout_valid = 0;
  842. ngui_invalidate(&ui);
  843. return 1;
  844. }
  845. static int js_host_form_set_selected(unsigned int node, int index)
  846. {
  847. struct form_state *fs;
  848. unsigned int n;
  849. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  850. return 0;
  851. fs = form_get(node, 1);
  852. if (!fs)
  853. return 0;
  854. n = form_option_count(node);
  855. if (index < 0)
  856. index = 0;
  857. if (n && (unsigned int)index >= n)
  858. index = (int)n - 1;
  859. fs->selected = (unsigned char)index;
  860. layout_valid = 0;
  861. ngui_invalidate(&ui);
  862. return 1;
  863. }
  864. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  865. {
  866. unsigned int i;
  867. int n = 0;
  868. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  869. doc.nodes[form].tag != BR_TAG_FORM)
  870. return 0;
  871. for (i = 0; i < doc.nnode && n < cap; i++) {
  872. struct br_node *nd = &doc.nodes[i];
  873. if (i == form || nd->type != BR_NODE_ELEM)
  874. continue;
  875. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  876. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  877. continue;
  878. if (!form_descendant(i, form))
  879. continue;
  880. out[n++] = i;
  881. }
  882. return n;
  883. }
  884. static int js_host_form_submit(unsigned int form)
  885. {
  886. form_submit_form(form, 0);
  887. return 1;
  888. }
  889. static int js_host_form_reset(unsigned int form)
  890. {
  891. form_reset_event(form);
  892. return 1;
  893. }
  894. static void css_computed_name(const char *p, char *out, int cap)
  895. {
  896. int n = 0;
  897. for (; p && *p && n + 2 < cap; p++) {
  898. char c = *p;
  899. if (c >= 'A' && c <= 'Z') {
  900. out[n++] = '-';
  901. c = (char)(c - 'A' + 'a');
  902. } else if (c == '_') {
  903. c = '-';
  904. } else if (c >= 'a' && c <= 'z') {
  905. /* keep */
  906. }
  907. out[n++] = c;
  908. }
  909. out[n] = '\0';
  910. if (!strcmp(out, "css-float"))
  911. strcpy(out, "float");
  912. }
  913. static void css_rgb(unsigned short c, char *buf, int cap)
  914. {
  915. int r = ((c >> 11) & 31) * 255 / 31;
  916. int g = ((c >> 5) & 63) * 255 / 63;
  917. int b = (c & 31) * 255 / 31;
  918. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  919. }
  920. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  921. int font_px)
  922. {
  923. if (unit == 4) {
  924. snprintf(buf, cap, "auto");
  925. } else if (unit == 0) {
  926. snprintf(buf, cap, "%dpx", raw);
  927. } else if (unit == 1) {
  928. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  929. } else if (unit == 2) {
  930. /* Chrome's getComputedStyle() reports used pixel values. */
  931. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  932. } else if (unit == 3) {
  933. snprintf(buf, cap, "%dpx",
  934. (int)br_root_font_px() * raw / 100);
  935. } else {
  936. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  937. raw / 100, raw % 100, px);
  938. }
  939. }
  940. static int js_host_computed(unsigned int node, const char *property,
  941. char *buf, int cap)
  942. {
  943. struct br_style st;
  944. char name[40];
  945. /* Node 0 is a real element when the page starts with <html>. */
  946. if (!buf || cap <= 0 || node >= doc.nnode ||
  947. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  948. return 0;
  949. buf[0] = '\0';
  950. css_computed_name(property, name, sizeof(name));
  951. style_for_node(node, &st);
  952. if (!strcmp(name, "display")) {
  953. const char *v = "inline";
  954. if (st.display == BR_DISPLAY_BLOCK)
  955. v = "block";
  956. else if (st.display == BR_DISPLAY_NONE)
  957. v = "none";
  958. else if (st.display == BR_DISPLAY_FLEX)
  959. v = "flex";
  960. else if (st.display == BR_DISPLAY_GRID)
  961. v = "grid";
  962. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  963. v = "inline-block";
  964. snprintf(buf, cap, "%s", v);
  965. } else if (!strcmp(name, "position")) {
  966. static const char *pos[] = {
  967. "static", "absolute", "fixed", "relative", "sticky"
  968. };
  969. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  970. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  971. int is_w = name[0] == 'w';
  972. int kind = is_w ? st.width_kind : st.height_kind;
  973. int val = is_w ? st.width : st.height;
  974. if (kind == 3) {
  975. if (is_w)
  976. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  977. st.width_calc_pct / 100,
  978. st.width_calc_pct % 100,
  979. st.width_calc_px);
  980. else
  981. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  982. st.height_calc_pct / 100,
  983. st.height_calc_pct % 100,
  984. st.height_calc_px);
  985. } else if (kind == 1) {
  986. snprintf(buf, cap, "%dpx", val);
  987. } else if (kind == 2) {
  988. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  989. } else {
  990. snprintf(buf, cap, "auto");
  991. }
  992. } else if (!strcmp(name, "color") ||
  993. !strcmp(name, "background-color")) {
  994. if (!strcmp(name, "background-color") && !st.has_bg)
  995. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  996. else
  997. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  998. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  999. int is_fill = name[0] == 'f';
  1000. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  1001. if (mode == BR_PAINT_COLOR)
  1002. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  1003. else if (mode == BR_PAINT_CURRENT)
  1004. css_rgb(st.color, buf, cap);
  1005. else if (mode == BR_PAINT_UNSET && is_fill)
  1006. snprintf(buf, cap, "rgb(0, 0, 0)");
  1007. else if (mode == BR_PAINT_URL)
  1008. snprintf(buf, cap, "url()");
  1009. else
  1010. snprintf(buf, cap, "none");
  1011. } else if (!strcmp(name, "font-size")) {
  1012. snprintf(buf, cap, "%dpx", st.font_px);
  1013. } else if (!strcmp(name, "font-weight")) {
  1014. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  1015. } else if (!strcmp(name, "font-style")) {
  1016. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  1017. } else if (!strcmp(name, "font-family")) {
  1018. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  1019. br_font_face_family(st.font_face)[0])
  1020. snprintf(buf, cap, "%s",
  1021. br_font_face_family(st.font_face));
  1022. else
  1023. snprintf(buf, cap, "%s",
  1024. st.mono ? "monospace" : "sans-serif");
  1025. } else if (!strcmp(name, "text-align")) {
  1026. static const char *al[] = { "left", "center", "right", "justify" };
  1027. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  1028. } else if (!strcmp(name, "float")) {
  1029. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  1030. st.float_left == 2 ? "right" : "none");
  1031. } else if (!strcmp(name, "clear")) {
  1032. static const char *cl[] = { "none", "left", "right", "both" };
  1033. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  1034. } else if (!strcmp(name, "opacity")) {
  1035. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  1036. } else if (!strcmp(name, "visibility")) {
  1037. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  1038. } else if (!strcmp(name, "overflow")) {
  1039. snprintf(buf, cap, "%s",
  1040. st.overflow_hidden ? "hidden" : "visible");
  1041. } else if (!strcmp(name, "white-space")) {
  1042. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  1043. } else if (!strcmp(name, "text-transform")) {
  1044. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  1045. } else if (!strcmp(name, "box-sizing")) {
  1046. snprintf(buf, cap, "%s",
  1047. st.box_sizing ? "border-box" : "content-box");
  1048. } else if (!strcmp(name, "line-height")) {
  1049. if (st.line_h_px)
  1050. snprintf(buf, cap, "%dpx", st.line_h_px);
  1051. else if (st.line_h_pct)
  1052. snprintf(buf, cap, "%d%%", st.line_h_pct);
  1053. else
  1054. snprintf(buf, cap, "normal");
  1055. } else if (!strcmp(name, "z-index")) {
  1056. if (st.z_set)
  1057. snprintf(buf, cap, "%d", st.z_index);
  1058. else
  1059. snprintf(buf, cap, "auto");
  1060. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  1061. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  1062. int set = name[0] == 't' ? st.top_set :
  1063. name[0] == 'l' ? st.left_set :
  1064. name[0] == 'r' ? st.right_set : st.bottom_set;
  1065. int v = name[0] == 't' ? st.top :
  1066. name[0] == 'l' ? st.left :
  1067. name[0] == 'r' ? st.right : st.bottom;
  1068. if (set)
  1069. snprintf(buf, cap, "%dpx", v);
  1070. else
  1071. snprintf(buf, cap, "auto");
  1072. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1073. !strcmp(name, "margin-bottom") ||
  1074. !strcmp(name, "margin-left") ||
  1075. !strcmp(name, "padding-top") ||
  1076. !strcmp(name, "padding-right") ||
  1077. !strcmp(name, "padding-bottom") ||
  1078. !strcmp(name, "padding-left")) {
  1079. int is_pad = name[0] == 'p';
  1080. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1081. name[strlen(name) - 1] == 't' ? 1 :
  1082. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1083. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1084. if (!strcmp(name, "margin-right") ||
  1085. !strcmp(name, "padding-right"))
  1086. side = 1;
  1087. else if (!strcmp(name, "margin-bottom") ||
  1088. !strcmp(name, "padding-bottom"))
  1089. side = 2;
  1090. else if (!strcmp(name, "margin-left") ||
  1091. !strcmp(name, "padding-left"))
  1092. side = 3;
  1093. else
  1094. side = 0;
  1095. side += is_pad ? 4 : 0;
  1096. css_mp_value(buf, cap,
  1097. side == 0 ? st.mt : side == 1 ? st.mr :
  1098. side == 2 ? st.mb : side == 3 ? st.ml :
  1099. side == 4 ? st.pt : side == 5 ? st.pr :
  1100. side == 6 ? st.pb : st.pl,
  1101. st.mp_unit[side], st.mp_calc_px[side],
  1102. st.font_px);
  1103. } else if (!strcmp(name, "border-top-width") ||
  1104. !strcmp(name, "border-right-width") ||
  1105. !strcmp(name, "border-bottom-width") ||
  1106. !strcmp(name, "border-left-width")) {
  1107. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1108. name[7] == 'b' ? 2 : 3;
  1109. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1110. } else if (!strcmp(name, "border-top-color") ||
  1111. !strcmp(name, "border-right-color") ||
  1112. !strcmp(name, "border-bottom-color") ||
  1113. !strcmp(name, "border-left-color")) {
  1114. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1115. name[7] == 'b' ? 2 : 3;
  1116. if (st.border_w[side] && !st.border_t[side])
  1117. css_rgb(st.border_c[side], buf, cap);
  1118. else
  1119. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1120. } else if (!strcmp(name, "background-image")) {
  1121. if (st.bg_image)
  1122. snprintf(buf, cap, "url(\"%s\")",
  1123. br_bg_image_url(st.bg_image - 1));
  1124. else
  1125. snprintf(buf, cap, "none");
  1126. } else if (!strcmp(name, "background-repeat")) {
  1127. static const char *rp[] = {
  1128. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1129. };
  1130. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1131. st.bg_repeat : 0]);
  1132. } else if (!strcmp(name, "background-position")) {
  1133. if (st.bg_pos_x_kind == 1)
  1134. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1135. st.bg_pos_y);
  1136. else
  1137. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1138. st.bg_pos_y);
  1139. } else if (!strcmp(name, "background-size")) {
  1140. if (st.bg_size_kind == 3)
  1141. snprintf(buf, cap, "cover");
  1142. else if (st.bg_size_kind == 4)
  1143. snprintf(buf, cap, "contain");
  1144. else if (st.bg_size_kind == 1)
  1145. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1146. st.bg_size_h);
  1147. else if (st.bg_size_kind == 2)
  1148. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1149. st.bg_size_h);
  1150. else
  1151. snprintf(buf, cap, "auto");
  1152. } else if (!strcmp(name, "transform")) {
  1153. char tmp[128];
  1154. unsigned int n = 0;
  1155. if (!st.transform_set) {
  1156. snprintf(buf, cap, "none");
  1157. } else {
  1158. tmp[0] = '\0';
  1159. if (st.tx || st.ty) {
  1160. snprintf(tmp + n, sizeof(tmp) - n,
  1161. "translate(%dpx, %dpx)", st.tx, st.ty);
  1162. n = (unsigned int)strlen(tmp);
  1163. }
  1164. if (st.transform_scale) {
  1165. snprintf(tmp + n, sizeof(tmp) - n,
  1166. "%sscale(%d.%02d, %d.%02d)",
  1167. n ? " " : "", st.scale_x / 100,
  1168. st.scale_x % 100, st.scale_y / 100,
  1169. st.scale_y % 100);
  1170. n = (unsigned int)strlen(tmp);
  1171. if (st.rotate_x100) {
  1172. snprintf(tmp + n, sizeof(tmp) - n,
  1173. " rotate(%d.%02ddeg)",
  1174. st.rotate_x100 / 100,
  1175. st.rotate_x100 % 100);
  1176. }
  1177. } else if (st.rotate_x100) {
  1178. snprintf(tmp + n, sizeof(tmp) - n,
  1179. "%srotate(%d.%02ddeg)",
  1180. n ? " " : "", st.rotate_x100 / 100,
  1181. st.rotate_x100 % 100);
  1182. }
  1183. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1184. }
  1185. } else {
  1186. return 0;
  1187. }
  1188. return buf[0] != '\0';
  1189. }
  1190. static int js_host_click(unsigned int node)
  1191. {
  1192. char url[BR_URL_MAX];
  1193. const char *href;
  1194. if (node >= doc.nnode)
  1195. return 0;
  1196. if (form_is_control(node)) {
  1197. form_click(node); /* dispatches its own click event */
  1198. return 1;
  1199. }
  1200. /* element.click() fires a bubbling, cancelable click before the
  1201. * default action, like a real click (delegated list handlers). */
  1202. if (!js_browser_event(node, "click", 1, 1))
  1203. return 1;
  1204. if (link_fragment_nav(node))
  1205. return 1;
  1206. href = br_href(&doc, node);
  1207. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1208. return 0;
  1209. s_copy(pending_url, url, sizeof(pending_url));
  1210. pending_action |= ACT_NAV;
  1211. cancel_fetch = 1;
  1212. ngui_invalidate(&ui);
  1213. return 1;
  1214. }
  1215. static int fetch_script_text(const char *url, unsigned char **out,
  1216. unsigned int *outlen, char *err,
  1217. unsigned int errcap);
  1218. struct fetch_worker;
  1219. static struct fetch_worker *fetch_worker_alloc(void);
  1220. static void fetch_worker_release(struct fetch_worker *w);
  1221. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1222. unsigned int cap, const char *post,
  1223. unsigned int post_len, unsigned int node,
  1224. int bg, char *err, unsigned int errcap);
  1225. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1226. unsigned int errcap);
  1227. static int fetch_worker_read_body(struct fetch_worker *w,
  1228. unsigned char *plain,
  1229. unsigned int plaincap,
  1230. unsigned char *comp,
  1231. unsigned int compcap,
  1232. int *truncated, char *err,
  1233. unsigned int errcap);
  1234. static void fetch_workers_stop_all(void);
  1235. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1236. unsigned int cap, const char *method,
  1237. const char *ctype, const char *post,
  1238. unsigned int post_len, unsigned int node,
  1239. int bg, unsigned int dec_w,
  1240. unsigned int dec_h, char *err,
  1241. unsigned int errcap);
  1242. static int script_cache_has(const char *url);
  1243. static void script_cache_put(const char *url, const unsigned char *data,
  1244. unsigned int len);
  1245. static unsigned int script_cache_hash(const char *s);
  1246. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1247. unsigned int errcap);
  1248. static void fetch_workers_cancel_busy(void);
  1249. static void worker_wait_ui(void);
  1250. static int fetch_worker_status(const struct fetch_worker *w);
  1251. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1252. * module load: the wait must not pump input, or a click would dispatch DOM
  1253. * events into the middle of the running script. */
  1254. static int fetch_wait_passive;
  1255. static void script_error(const char *what, const char *url, const char *why)
  1256. {
  1257. char msg[192];
  1258. unsigned int n = 0;
  1259. s_append(msg, &n, what, sizeof(msg));
  1260. if (url && url[0]) {
  1261. s_append(msg, &n, " ", sizeof(msg));
  1262. s_append(msg, &n, url, sizeof(msg));
  1263. }
  1264. if (why && why[0]) {
  1265. s_append(msg, &n, ": ", sizeof(msg));
  1266. s_append(msg, &n, why, sizeof(msg));
  1267. }
  1268. js_host_report(msg);
  1269. }
  1270. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1271. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1272. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1273. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1274. #define JS_HTTP_POST_MAX (16u * 1024u)
  1275. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1276. static int js_worker_http(const char *method, const char *url,
  1277. const char *ctype, const char *body,
  1278. unsigned int body_len, struct js_http_resp *r,
  1279. char *err, int errcap);
  1280. static int js_host_http(const char *method, const char *url,
  1281. const char *ctype, const char *body,
  1282. unsigned int body_len, struct js_http_resp *r,
  1283. char *err, int errcap)
  1284. {
  1285. if (pending_action) {
  1286. s_copy(err, "page is navigating", (unsigned int)errcap);
  1287. return -1;
  1288. }
  1289. if (url[0] == '/') {
  1290. /* Local file: GET only. */
  1291. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1292. int rv;
  1293. if (!buf) {
  1294. s_copy(err, "out of memory", (unsigned int)errcap);
  1295. return -1;
  1296. }
  1297. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1298. (int)JS_HTTP_MAX);
  1299. r->status = rv < 0 ? 404 : 200;
  1300. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1301. buf[r->len] = '\0';
  1302. r->body = (char *)buf;
  1303. s_copy(r->url, url, sizeof(r->url));
  1304. if (contains_ci(url, ".json"))
  1305. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1306. return 0;
  1307. }
  1308. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1309. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1310. return -1;
  1311. }
  1312. if (body_len > JS_HTTP_POST_MAX) {
  1313. s_copy(err, "request body too large", (unsigned int)errcap);
  1314. return -1;
  1315. }
  1316. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1317. errcap);
  1318. }
  1319. /* Module source for the engine's loader: the boot script cache first, then
  1320. * one blocking fetch with input pumping disabled (the loader runs inside
  1321. * JavaScript). */
  1322. static char *js_host_load_script(const char *url, unsigned int *len)
  1323. {
  1324. unsigned char *data = 0;
  1325. char err[64];
  1326. int rv;
  1327. fetch_wait_passive++;
  1328. set_status("Loading module...", 0, 0);
  1329. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1330. fetch_wait_passive--;
  1331. if (rv != 0) {
  1332. script_error("Cannot load module", url,
  1333. rv == FETCH_ABORT ? "navigation" : err);
  1334. return 0;
  1335. }
  1336. return (char *)data;
  1337. }
  1338. /* Web Storage lives in /share, outside the page heap that every navigation
  1339. * resets: localStorage per origin for the boot, sessionStorage per origin
  1340. * and browser window. */
  1341. #define JS_ORIGIN_MAX 160
  1342. /* scheme://host[:port] of the page (a local page's whole path). */
  1343. static void js_page_origin(char *origin, unsigned int cap)
  1344. {
  1345. unsigned int i = 0, slashes = 0;
  1346. while (page_url[i] && i + 1 < cap) {
  1347. if (page_url[i] == '/' && ++slashes == 3)
  1348. break;
  1349. origin[i] = page_url[i];
  1350. i++;
  1351. }
  1352. origin[i] = '\0';
  1353. }
  1354. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1355. {
  1356. unsigned int n = 0;
  1357. s_append(out, &n, "/share/bls", cap);
  1358. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1359. }
  1360. static void js_storage_path(int kind, char *out, unsigned int cap)
  1361. {
  1362. char origin[JS_ORIGIN_MAX];
  1363. unsigned int n = 0;
  1364. js_page_origin(origin, sizeof(origin));
  1365. if (!kind) {
  1366. js_origin_path(origin, out, cap);
  1367. return;
  1368. }
  1369. s_append(out, &n, "/share/bss", cap);
  1370. if (kind) {
  1371. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1372. s_append(out, &n, "-", cap);
  1373. }
  1374. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1375. }
  1376. static void persist_mark_origin(const char *origin);
  1377. static int persist_store_lookup(const char *origin, char *out, int cap);
  1378. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1379. {
  1380. char path[48], origin[JS_ORIGIN_MAX];
  1381. int rv;
  1382. js_storage_path(kind, path, sizeof(path));
  1383. if (set) {
  1384. if (kind) {
  1385. if (!set[0] || !strcmp(set, "{}")) {
  1386. u_syscall1(SYS_UNLINK, (int)path);
  1387. return 0;
  1388. }
  1389. } else {
  1390. /* localStorage keeps an explicit "{}" rather than no
  1391. * file: a missing /share file means "not loaded from
  1392. * /data yet", and a cleared store must not come back
  1393. * from the disk copy before it is flushed. */
  1394. if (!set[0])
  1395. set = "{}";
  1396. js_page_origin(origin, sizeof(origin));
  1397. persist_mark_origin(origin);
  1398. }
  1399. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1400. (int)strlen(set)) < 0 ? -1 : 0;
  1401. }
  1402. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1403. if (rv < 0 && !kind) {
  1404. /* First use this boot: the persistent copy on /data. */
  1405. js_page_origin(origin, sizeof(origin));
  1406. rv = persist_store_lookup(origin, out, cap);
  1407. if (rv >= 0)
  1408. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1409. }
  1410. if (rv < 0)
  1411. return -1;
  1412. out[rv] = '\0';
  1413. return rv;
  1414. }
  1415. /* ---- persistence on /data ----
  1416. *
  1417. * /share is the working copy (RAM, shared by every helper and window); the
  1418. * installed disk's /data volume keeps the cookie jar and localStorage
  1419. * across reboots when it is mounted. The browser owns the disk copies: at
  1420. * start it restores the jar into /share, and its main loop writes back
  1421. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1422. * setItem updates costs one FAT write. The helpers only touch /share (they
  1423. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1424. * /data mount every disk access simply fails. Both files are plaintext
  1425. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1426. #define PERSIST_MS 3000u
  1427. #define SHARE_COOKIES "/share/bcookies"
  1428. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1429. #define DATA_STORE "/data/BSTORE.DAT"
  1430. #define DATA_STORE_MAGIC "NBLS1\n"
  1431. #define DATA_STORE_MAX (192u * 1024u)
  1432. #define PERSIST_DIRTY_MAX 8
  1433. static unsigned int persist_due;
  1434. static unsigned int cookie_sum_saved;
  1435. static int cookie_sum_valid;
  1436. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1437. static int persist_ndirty;
  1438. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1439. {
  1440. unsigned int h = 2166136261u, i;
  1441. for (i = 0; i < n; i++)
  1442. h = (h ^ p[i]) * 16777619u;
  1443. return h;
  1444. }
  1445. /* Called once at startup, before any helper runs. */
  1446. static void persist_restore(void)
  1447. {
  1448. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1449. int n;
  1450. if (!jar)
  1451. return;
  1452. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1453. (int)sizeof(struct uhttp_jar));
  1454. if (n != (int)sizeof(struct uhttp_jar)) {
  1455. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1456. (int)sizeof(struct uhttp_jar));
  1457. if (n == (int)sizeof(struct uhttp_jar)) {
  1458. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1459. (int)jar, n);
  1460. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1461. cookie_sum_valid = 1;
  1462. }
  1463. }
  1464. free(jar);
  1465. persist_due = u_ticks_ms() + PERSIST_MS;
  1466. }
  1467. static void persist_mark_origin(const char *origin)
  1468. {
  1469. int i;
  1470. for (i = 0; i < persist_ndirty; i++)
  1471. if (s_eq(persist_dirty[i], origin))
  1472. return;
  1473. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1474. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1475. }
  1476. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1477. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1478. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1479. unsigned int *o_off, unsigned int *o_len,
  1480. unsigned int *d_off, unsigned int *d_len,
  1481. unsigned int *rec_end)
  1482. {
  1483. unsigned int p = *pos, v = 0;
  1484. if (p >= len)
  1485. return 0;
  1486. *o_off = p;
  1487. while (p < len && buf[p] != '\n')
  1488. p++;
  1489. if (p >= len)
  1490. return 0;
  1491. *o_len = p - *o_off;
  1492. p++;
  1493. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1494. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1495. if (p >= len || buf[p] != '\n')
  1496. return 0;
  1497. p++;
  1498. if (v > len - p)
  1499. return 0;
  1500. *d_off = p;
  1501. *d_len = v;
  1502. p += v;
  1503. if (p < len && buf[p] == '\n')
  1504. p++;
  1505. *rec_end = p;
  1506. *pos = p;
  1507. return 1;
  1508. }
  1509. static int store_load(char **out)
  1510. {
  1511. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1512. int n;
  1513. *out = buf;
  1514. if (!buf)
  1515. return -1;
  1516. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1517. (int)DATA_STORE_MAX);
  1518. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1519. !starts_with(buf, DATA_STORE_MAGIC))
  1520. return 0;
  1521. return n;
  1522. }
  1523. static int persist_store_lookup(const char *origin, char *out, int cap)
  1524. {
  1525. char *buf;
  1526. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1527. unsigned int olen = s_len(origin);
  1528. int n = store_load(&buf), rv = -1;
  1529. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1530. &dl, &e)) {
  1531. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1532. if ((int)dl < cap) {
  1533. memcpy(out, buf + d, dl);
  1534. out[dl] = '\0';
  1535. rv = (int)dl;
  1536. }
  1537. break;
  1538. }
  1539. }
  1540. free(buf);
  1541. return rv;
  1542. }
  1543. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1544. static void persist_store_flush(void)
  1545. {
  1546. char *old, *nb, path[48];
  1547. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1548. int n = store_load(&old), i, w;
  1549. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1550. if (n < 0 || !nb) {
  1551. free(old);
  1552. free(nb);
  1553. return;
  1554. }
  1555. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1556. /* Untouched origins first, in their old order. */
  1557. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1558. &dl, &e)) {
  1559. int dirty = 0;
  1560. for (i = 0; i < persist_ndirty; i++)
  1561. if (s_len(persist_dirty[i]) == ol &&
  1562. !memcmp(persist_dirty[i], old + oo, ol))
  1563. dirty = 1;
  1564. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1565. continue;
  1566. memcpy(nb + nn, old + oo, e - oo);
  1567. nn += e - oo;
  1568. }
  1569. /* Then the changed ones (an emptied store is dropped). */
  1570. for (i = 0; i < persist_ndirty; i++) {
  1571. char num[12];
  1572. unsigned int k = 0;
  1573. js_origin_path(persist_dirty[i], path, sizeof(path));
  1574. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1575. (int)DATA_STORE_MAX);
  1576. if (w <= 2) /* missing or "{}" */
  1577. continue;
  1578. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1579. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1580. DATA_STORE_MAX) {
  1581. set_status("Saved site data is full; a site's "
  1582. "localStorage was not saved", 1, 6000);
  1583. continue;
  1584. }
  1585. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1586. nb[nn++] = '\n';
  1587. s_append(nb, &nn, num, DATA_STORE_MAX);
  1588. nb[nn++] = '\n';
  1589. memcpy(nb + nn, old, (unsigned int)w);
  1590. nn += (unsigned int)w;
  1591. nb[nn++] = '\n';
  1592. }
  1593. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1594. persist_ndirty = 0;
  1595. free(old);
  1596. free(nb);
  1597. }
  1598. static void persist_cookies_flush(void)
  1599. {
  1600. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1601. unsigned int sum;
  1602. int n;
  1603. if (!jar)
  1604. return;
  1605. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1606. (int)sizeof(struct uhttp_jar));
  1607. if (n == (int)sizeof(struct uhttp_jar)) {
  1608. sum = persist_sum(jar, (unsigned int)n);
  1609. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1610. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1611. (int)jar, n) >= 0) {
  1612. cookie_sum_saved = sum;
  1613. cookie_sum_valid = 1;
  1614. }
  1615. }
  1616. }
  1617. free(jar);
  1618. }
  1619. /* ---- visit history (URL-bar autocomplete) ----
  1620. *
  1621. * Every page that finishes loading is recorded with its title, a visit
  1622. * count and a stamp: a counter that only grows and travels with the file,
  1623. * so it orders visits across windows and boots without a wall clock. The
  1624. * table lives in BSS, because the page heap is reset on every navigation.
  1625. * The boot's browser windows share it through /share/bhist (rewritten on
  1626. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1627. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1628. * /share/bhist and merges it first, so two windows add to one history
  1629. * instead of overwriting each other. File format: "NBHIST1\n", then
  1630. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1631. * other browser state on /data. */
  1632. #define HIST_MAX 128
  1633. #define HIST_URL_MAX 512
  1634. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1635. #define HIST_MAGIC "NBHIST1\n"
  1636. #define SHARE_HIST "/share/bhist"
  1637. #define DATA_HIST "/data/BHIST.DAT"
  1638. #define HIST_FORGET_MAX 16
  1639. struct hist_ent {
  1640. unsigned int visits;
  1641. unsigned int stamp;
  1642. char url[HIST_URL_MAX];
  1643. char title[BR_TITLE_MAX];
  1644. };
  1645. static struct hist_ent hist_tab[HIST_MAX];
  1646. static int hist_n;
  1647. static int hist_share_dirty, hist_data_dirty;
  1648. /* URLs removed in this process: a merge must not bring them back. */
  1649. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1650. static int hist_nforgot;
  1651. static unsigned int hist_hash(const char *s)
  1652. {
  1653. return persist_sum((const unsigned char *)s, s_len(s));
  1654. }
  1655. static int hist_is_forgotten(const char *url)
  1656. {
  1657. unsigned int h = hist_hash(url);
  1658. int i;
  1659. for (i = 0; i < hist_nforgot; i++)
  1660. if (hist_forgot[i] == h)
  1661. return 1;
  1662. return 0;
  1663. }
  1664. static int hist_find(const char *url)
  1665. {
  1666. int i;
  1667. for (i = 0; i < hist_n; i++)
  1668. if (s_eq(hist_tab[i].url, url))
  1669. return i;
  1670. return -1;
  1671. }
  1672. static unsigned int hist_next_stamp(void)
  1673. {
  1674. unsigned int m = 0;
  1675. int i;
  1676. for (i = 0; i < hist_n; i++)
  1677. if (hist_tab[i].stamp > m)
  1678. m = hist_tab[i].stamp;
  1679. return m + 1;
  1680. }
  1681. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1682. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1683. {
  1684. unsigned int i;
  1685. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1686. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1687. d[i] = '\0';
  1688. }
  1689. /* Insert or update an entry; the newer stamp wins the title, the larger
  1690. * visit count is kept. A full table evicts the least recent entry, unless
  1691. * the new one is older still. Returns NULL when nothing was stored. */
  1692. static struct hist_ent *hist_put(const char *url, const char *title,
  1693. unsigned int visits, unsigned int stamp)
  1694. {
  1695. struct hist_ent *e;
  1696. int i = hist_find(url);
  1697. if (i < 0) {
  1698. if (hist_n < HIST_MAX) {
  1699. i = hist_n++;
  1700. } else {
  1701. int j;
  1702. i = 0;
  1703. for (j = 1; j < hist_n; j++)
  1704. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1705. i = j;
  1706. if (hist_tab[i].stamp >= stamp)
  1707. return 0;
  1708. }
  1709. e = &hist_tab[i];
  1710. e->visits = 0;
  1711. e->stamp = 0;
  1712. e->title[0] = '\0';
  1713. s_copy(e->url, url, sizeof(e->url));
  1714. }
  1715. e = &hist_tab[i];
  1716. if (visits > e->visits)
  1717. e->visits = visits;
  1718. if (stamp >= e->stamp) {
  1719. e->stamp = stamp;
  1720. if (title && title[0])
  1721. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1722. } else if (!e->title[0] && title) {
  1723. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1724. }
  1725. return e;
  1726. }
  1727. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1728. {
  1729. unsigned int v = 0;
  1730. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1731. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1732. return v;
  1733. }
  1734. static void hist_merge_buf(const char *b, int n)
  1735. {
  1736. int pos = (int)s_len(HIST_MAGIC);
  1737. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1738. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1739. return;
  1740. while (pos < n) {
  1741. unsigned int visits, stamp, ul = 0;
  1742. int t0, t1;
  1743. visits = hist_parse_dec(b, n, &pos);
  1744. if (pos < n && b[pos] == ' ')
  1745. pos++;
  1746. stamp = hist_parse_dec(b, n, &pos);
  1747. if (pos < n && b[pos] == ' ')
  1748. pos++;
  1749. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1750. if (ul + 1 < sizeof(url))
  1751. url[ul++] = b[pos];
  1752. pos++;
  1753. }
  1754. url[ul] = '\0';
  1755. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1756. while (t1 < n && b[t1] != '\n')
  1757. t1++;
  1758. pos = t1 + 1;
  1759. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1760. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1761. hist_put(url, title, visits, stamp);
  1762. }
  1763. }
  1764. static int hist_serialize(char *b, unsigned int cap)
  1765. {
  1766. unsigned int n = 0;
  1767. int i;
  1768. s_append(b, &n, HIST_MAGIC, cap);
  1769. for (i = 0; i < hist_n; i++) {
  1770. struct hist_ent *e = &hist_tab[i];
  1771. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1772. break;
  1773. s_append_dec(b, &n, e->visits, cap);
  1774. b[n++] = ' ';
  1775. s_append_dec(b, &n, e->stamp, cap);
  1776. b[n++] = ' ';
  1777. s_append(b, &n, e->url, cap);
  1778. b[n++] = '\t';
  1779. s_append(b, &n, e->title, cap);
  1780. b[n++] = '\n';
  1781. }
  1782. return (int)n;
  1783. }
  1784. /* Merge /share/bhist, then write it back (and /data when asked). */
  1785. static void hist_sync(int to_data)
  1786. {
  1787. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1788. int n;
  1789. if (!b)
  1790. return;
  1791. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1792. (int)HIST_FILE_MAX);
  1793. if (n > 0)
  1794. hist_merge_buf(b, n);
  1795. n = hist_serialize(b, HIST_FILE_MAX);
  1796. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1797. hist_share_dirty = 0;
  1798. if (to_data) {
  1799. /* No /data mount: the write fails, and there is nothing to
  1800. * retry until the next visit. */
  1801. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1802. hist_data_dirty = 0;
  1803. }
  1804. free(b);
  1805. }
  1806. /* Startup: the boot's shared copy, else the saved one from /data. */
  1807. static void hist_load(void)
  1808. {
  1809. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1810. int n;
  1811. if (!b)
  1812. return;
  1813. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1814. (int)HIST_FILE_MAX);
  1815. if (n <= 0) {
  1816. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1817. (int)HIST_FILE_MAX);
  1818. if (n > 0)
  1819. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1820. }
  1821. if (n > 0)
  1822. hist_merge_buf(b, n);
  1823. free(b);
  1824. }
  1825. static void hist_visit(const char *url, const char *title)
  1826. {
  1827. struct hist_ent *e;
  1828. unsigned int i;
  1829. if (!url[0] || starts_with(url, "about:") ||
  1830. s_len(url) >= HIST_URL_MAX)
  1831. return;
  1832. for (i = 0; url[i]; i++)
  1833. if ((unsigned char)url[i] < 0x20)
  1834. return;
  1835. e = hist_put(url, title, 0, hist_next_stamp());
  1836. if (!e)
  1837. return;
  1838. e->visits++;
  1839. hist_data_dirty = 1;
  1840. hist_sync(0);
  1841. }
  1842. static void hist_forget(int i)
  1843. {
  1844. if (i < 0 || i >= hist_n)
  1845. return;
  1846. if (hist_nforgot < HIST_FORGET_MAX)
  1847. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1848. hist_n--;
  1849. for (; i < hist_n; i++)
  1850. hist_tab[i] = hist_tab[i + 1];
  1851. hist_data_dirty = 1;
  1852. hist_sync(0);
  1853. }
  1854. static void hist_tick(void)
  1855. {
  1856. if (hist_share_dirty || hist_data_dirty)
  1857. hist_sync(hist_data_dirty);
  1858. }
  1859. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1860. static void persist_tick(void)
  1861. {
  1862. unsigned int now = u_ticks_ms();
  1863. if ((int)(now - persist_due) < 0)
  1864. return;
  1865. persist_due = now + PERSIST_MS;
  1866. persist_cookies_flush();
  1867. if (persist_ndirty)
  1868. persist_store_flush();
  1869. hist_tick();
  1870. }
  1871. /* <link rel="modulepreload">: download the page's module graph on all
  1872. * helpers at once into the boot script cache, before any script runs. The
  1873. * engine's module loader is sequential (one blocking fetch per import), so
  1874. * without this a Vite app with a dozen chunks pays every round trip in a
  1875. * row. Failures are ignored; the loader fetches what is missing. */
  1876. #define MODULE_PRELOAD_MAX 24
  1877. static void prefetch_module_preloads(void)
  1878. {
  1879. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1880. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1881. unsigned int count = 0, next = 0, done = 0, i;
  1882. char err[64];
  1883. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1884. struct br_node *nd = &doc.nodes[i];
  1885. const char *rel, *href;
  1886. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1887. continue;
  1888. rel = br_rel(&doc, i);
  1889. href = br_href(&doc, i);
  1890. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1891. continue;
  1892. if (resolve_link(page_url, href, urls[count],
  1893. sizeof(urls[count])) != 0 ||
  1894. urls[count][0] == '/' || script_cache_has(urls[count]))
  1895. continue;
  1896. slot[count++] = 0;
  1897. }
  1898. if (!count)
  1899. return;
  1900. set_status("Loading modules...", 0, 0);
  1901. while (done < count) {
  1902. struct fetch_worker *w;
  1903. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1904. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1905. 0, 0, 0, err,
  1906. sizeof(err)) != 0) {
  1907. fetch_worker_release(w);
  1908. done++;
  1909. } else {
  1910. slot[next] = w;
  1911. }
  1912. next++;
  1913. }
  1914. worker_wait_ui();
  1915. if (cancel_fetch || pending_action) {
  1916. fetch_workers_cancel_busy();
  1917. return;
  1918. }
  1919. for (i = 0; i < next; i++) {
  1920. unsigned char *body;
  1921. int rv, tr = 0;
  1922. if (!slot[i])
  1923. continue;
  1924. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1925. if (rv == 0)
  1926. continue;
  1927. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1928. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1929. if (body) {
  1930. rv = fetch_worker_read_body(slot[i], body,
  1931. BR_SCRIPT_MAX, image_io_buf,
  1932. BR_PAGE_COMP_MAX, &tr, err,
  1933. sizeof(err));
  1934. if (rv > 0 && !tr)
  1935. script_cache_put(urls[i], body,
  1936. (unsigned int)rv);
  1937. free(body);
  1938. }
  1939. fetch_worker_release(slot[i]);
  1940. slot[i] = 0;
  1941. done++;
  1942. }
  1943. u_sleep_ms(10);
  1944. }
  1945. }
  1946. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1947. * submitted to helper workers ahead of time, but scripts still execute in
  1948. * document order. */
  1949. #define SCRIPT_INLINE 0
  1950. #define SCRIPT_LOCAL 1
  1951. #define SCRIPT_REMOTE 2
  1952. #define SCRIPT_ERROR 3
  1953. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1954. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1955. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1956. static void script_submit_window(unsigned int *next, char *err,
  1957. unsigned int errcap)
  1958. {
  1959. while (*next < doc.nscripts) {
  1960. struct fetch_worker *w;
  1961. if (script_kind[*next] != SCRIPT_REMOTE) {
  1962. (*next)++;
  1963. continue;
  1964. }
  1965. w = fetch_worker_alloc();
  1966. if (!w)
  1967. return;
  1968. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1969. 0, 0, 0, 0, err, errcap) != 0) {
  1970. fetch_worker_release(w);
  1971. script_kind[*next] = SCRIPT_ERROR;
  1972. (*next)++;
  1973. continue;
  1974. }
  1975. script_slot[*next] = w;
  1976. (*next)++;
  1977. }
  1978. }
  1979. /* Run the page's scripts in document order. External bodies are prefetched
  1980. * in parallel so downloading script N+1 overlaps executing script N; inline
  1981. * bodies are copied because the engine needs NUL-terminated text. */
  1982. static void run_page_scripts(void)
  1983. {
  1984. struct js_browser_host host;
  1985. unsigned int i, next = 0;
  1986. char err[64], ferr[64];
  1987. if (!doc.nscripts)
  1988. return;
  1989. host.status = js_host_status;
  1990. host.report = js_host_report;
  1991. host.navigate = js_host_navigate;
  1992. host.changed = js_host_changed;
  1993. host.rect = js_host_rect;
  1994. host.form_value = js_host_form_value;
  1995. host.form_checked = js_host_form_checked;
  1996. host.form_selected = js_host_form_selected;
  1997. host.form_set_value = js_host_form_set_value;
  1998. host.form_set_checked = js_host_form_set_checked;
  1999. host.form_set_selected = js_host_form_set_selected;
  2000. host.form_elements = js_host_form_elements;
  2001. host.form_submit = js_host_form_submit;
  2002. host.form_reset = js_host_form_reset;
  2003. host.click = js_host_click;
  2004. host.computed = js_host_computed;
  2005. host.http = js_host_http;
  2006. host.load_script = js_host_load_script;
  2007. host.storage = js_host_storage;
  2008. host.set_hash = js_host_set_hash;
  2009. host.page_url = page_url;
  2010. host.width = ui.w;
  2011. host.height = ui.h;
  2012. if (js_browser_start(&doc, &host) != 0) {
  2013. js_host_status("JavaScript: out of memory", 1);
  2014. return;
  2015. }
  2016. resize_sent_w = -1;
  2017. resize_pending = 0;
  2018. prefetch_module_preloads();
  2019. for (i = 0; i < doc.nscripts; i++) {
  2020. struct br_script *script = &doc.scripts[i];
  2021. const char *src_attr = script->src_off ?
  2022. doc.attrs + script->src_off : "";
  2023. script_slot[i] = 0;
  2024. if (!script->src_off) {
  2025. script_kind[i] = SCRIPT_INLINE;
  2026. continue;
  2027. }
  2028. if (!src_attr[0] ||
  2029. resolve_link(page_url, src_attr, script_urls[i],
  2030. sizeof(script_urls[i])) != 0) {
  2031. script_urls[i][0] = '\0';
  2032. script_kind[i] = SCRIPT_ERROR;
  2033. continue;
  2034. }
  2035. if (script_urls[i][0] == '/' ||
  2036. script_cache_has(script_urls[i]))
  2037. script_kind[i] = SCRIPT_LOCAL;
  2038. else
  2039. script_kind[i] = SCRIPT_REMOTE;
  2040. }
  2041. script_submit_window(&next, ferr, sizeof(ferr));
  2042. for (i = 0; i < doc.nscripts; i++) {
  2043. struct br_script *script = &doc.scripts[i];
  2044. /* document.currentScript for classic scripts (null for modules) */
  2045. js_browser_set_current_script(script->module ? 0 : script->node);
  2046. if (script_kind[i] == SCRIPT_INLINE) {
  2047. unsigned int off = script->off;
  2048. unsigned int len = script->len;
  2049. unsigned int k;
  2050. char *src = (char *)malloc(len + 1);
  2051. if (!src) {
  2052. js_host_status("JavaScript: out of memory", 1);
  2053. break;
  2054. }
  2055. for (k = 0; k < len; k++)
  2056. src[k] = doc.script_src[off + k];
  2057. src[len] = '\0';
  2058. if (script->module) {
  2059. /* A distinct module name per inline module
  2060. * (QuickJS registers modules by name); the
  2061. * fragment keeps relative imports resolving
  2062. * against the page. */
  2063. char mname[BR_URL_MAX + 16];
  2064. unsigned int mn = 0;
  2065. s_append(mname, &mn, page_url, sizeof(mname));
  2066. s_append(mname, &mn, "#module", sizeof(mname));
  2067. s_append_dec(mname, &mn, i, sizeof(mname));
  2068. js_browser_run_module(src, mname);
  2069. } else {
  2070. js_browser_run(src, page_url);
  2071. }
  2072. free(src);
  2073. } else if (script->src_off) {
  2074. const char *src_attr = doc.attrs + script->src_off;
  2075. if (script_kind[i] == SCRIPT_ERROR) {
  2076. script_error("Cannot load script", src_attr,
  2077. script_urls[i][0] ?
  2078. "network busy" :
  2079. "unsupported URL");
  2080. continue;
  2081. }
  2082. if (script_kind[i] == SCRIPT_LOCAL) {
  2083. unsigned char *data = 0;
  2084. unsigned int len = 0;
  2085. int rv;
  2086. set_status("Loading script...", 0, 0);
  2087. rv = fetch_script_text(script_urls[i], &data,
  2088. &len, err, sizeof(err));
  2089. if (rv == FETCH_ABORT)
  2090. break;
  2091. if (rv != 0) {
  2092. script_error("Cannot load script",
  2093. script_urls[i], err);
  2094. continue;
  2095. }
  2096. if (script->module)
  2097. js_browser_run_module(
  2098. (const char *)data,
  2099. script_urls[i]);
  2100. else
  2101. js_browser_run((const char *)data,
  2102. script_urls[i]);
  2103. free(data);
  2104. } else {
  2105. struct fetch_worker *w = script_slot[i];
  2106. unsigned char *body = 0;
  2107. int tr = 0, rv;
  2108. if (!w) {
  2109. w = fetch_worker_alloc();
  2110. if (!w)
  2111. continue;
  2112. if (fetch_worker_submit(w,
  2113. script_urls[i],
  2114. BR_SCRIPT_MAX,
  2115. 0, 0, 0, 0, err,
  2116. sizeof(err)) != 0) {
  2117. fetch_worker_release(w);
  2118. script_kind[i] = SCRIPT_ERROR;
  2119. if (i == next)
  2120. next++;
  2121. continue;
  2122. }
  2123. script_slot[i] = w;
  2124. if (i == next)
  2125. next++;
  2126. }
  2127. set_status("Loading script...", 0, 0);
  2128. rv = fetch_worker_wait(w, err, sizeof(err));
  2129. if (rv == FETCH_ABORT) {
  2130. fetch_workers_stop_all();
  2131. break;
  2132. }
  2133. /* The body gets its own buffer (scripts are up
  2134. * to 2 MB); image_io_buf takes the gzip
  2135. * stream. */
  2136. body = rv == 0 ? (unsigned char *)malloc(
  2137. BR_SCRIPT_MAX + 1) : 0;
  2138. if (body)
  2139. rv = fetch_worker_read_body(w, body,
  2140. BR_SCRIPT_MAX, image_io_buf,
  2141. BR_PAGE_COMP_MAX, &tr, err,
  2142. sizeof(err));
  2143. else {
  2144. if (rv == 0)
  2145. s_copy(err, "out of memory",
  2146. sizeof(err));
  2147. rv = -1;
  2148. }
  2149. fetch_worker_release(w);
  2150. script_slot[i] = 0;
  2151. script_submit_window(&next, ferr, sizeof(ferr));
  2152. if (rv <= 0)
  2153. script_error("Cannot load script",
  2154. script_urls[i], err);
  2155. else if (tr || (unsigned int)rv >=
  2156. BR_SCRIPT_MAX)
  2157. script_error("Cannot load script",
  2158. script_urls[i],
  2159. "script is too large");
  2160. else {
  2161. body[rv] = '\0';
  2162. script_cache_put(script_urls[i], body,
  2163. (unsigned int)rv);
  2164. if (script->module)
  2165. js_browser_run_module(
  2166. (const char *)body,
  2167. script_urls[i]);
  2168. else
  2169. js_browser_run(
  2170. (const char *)body,
  2171. script_urls[i]);
  2172. }
  2173. free(body);
  2174. }
  2175. }
  2176. if (pending_action)
  2177. break;
  2178. }
  2179. js_browser_set_current_script(0);
  2180. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2181. * load_home() stop it before the next navigation. */
  2182. if (doc.scripts_truncated && !js_last_error)
  2183. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2184. 1);
  2185. }
  2186. /* ---- images ---- */
  2187. /* data: images that failed to decode (key = data_img_key()), so a layout
  2188. * pass does not retry them on every frame. */
  2189. #define DATA_IMG_FAIL_MAX 32
  2190. static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
  2191. static int data_img_nfail;
  2192. static void image_reset(void)
  2193. {
  2194. int i;
  2195. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2196. images[i].state = 0;
  2197. images[i].native_w = images[i].native_h = 0;
  2198. images[i].err[0] = '\0';
  2199. /* heap_clear() ran before us, so these pointers are stale: drop
  2200. * them without calling free(). */
  2201. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2202. images[i].disp_pixels = 0;
  2203. images[i].disp_last = 0;
  2204. }
  2205. image_count = 0;
  2206. data_img_nfail = 0;
  2207. image_pixels = 0;
  2208. image_disp_pixels = 0;
  2209. image_disp_clock = 0;
  2210. memset(img_stat_log, 0, sizeof(img_stat_log));
  2211. img_stat_log_len = 0;
  2212. img_stat_start = 0;
  2213. img_stat_wall = 0;
  2214. img_stat_net = img_stat_open = img_stat_first = 0;
  2215. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2216. img_stat_paint = img_stat_reflow = 0;
  2217. img_stat_bytes = 0;
  2218. img_stat_n = 0;
  2219. img_last_dec_ms = img_last_scale_ms = 0;
  2220. img_repaint_ms = 0;
  2221. img_repaint_pending = 0;
  2222. preload_active = 0;
  2223. preload_pending = 0;
  2224. preload_wait = 0;
  2225. preload_node = 0;
  2226. preload_loaded = 0;
  2227. }
  2228. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2229. * are arriving. The main loop draws once per dirty frame; without this a
  2230. * page of N images did N full layout+paint passes. */
  2231. static void image_repaint(void)
  2232. {
  2233. unsigned int now = u_ticks_ms();
  2234. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2235. img_repaint_ms = now;
  2236. img_repaint_pending = 0;
  2237. ngui_invalidate(&ui);
  2238. } else {
  2239. img_repaint_pending = 1;
  2240. }
  2241. }
  2242. static void image_disp_drop(struct br_image *bi)
  2243. {
  2244. if (bi->disp.px)
  2245. free(bi->disp.px);
  2246. if (bi->disp.alpha)
  2247. free(bi->disp.alpha);
  2248. memset(&bi->disp, 0, sizeof(bi->disp));
  2249. if (bi->disp_pixels) {
  2250. if (image_disp_pixels >= bi->disp_pixels)
  2251. image_disp_pixels -= bi->disp_pixels;
  2252. bi->disp_pixels = 0;
  2253. }
  2254. }
  2255. /* Free the least recently used display caches until need pixels fit. The
  2256. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2257. static int image_disp_room(unsigned int need)
  2258. {
  2259. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2260. unsigned int oldest = ~0u;
  2261. int i, victim = -1;
  2262. for (i = 0; i < image_count; i++) {
  2263. if (!images[i].disp.px)
  2264. continue;
  2265. if (images[i].disp_last < oldest) {
  2266. oldest = images[i].disp_last;
  2267. victim = i;
  2268. }
  2269. }
  2270. if (victim < 0)
  2271. return -1;
  2272. image_disp_drop(&images[victim]);
  2273. }
  2274. return 0;
  2275. }
  2276. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2277. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2278. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2279. {
  2280. struct img_blit b;
  2281. unsigned int px;
  2282. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2283. return 0;
  2284. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2285. return &bi->img;
  2286. if (dw > 4096 || dh > 4096)
  2287. return &bi->img;
  2288. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2289. bi->disp.h == (unsigned int)dh) {
  2290. bi->disp_last = ++image_disp_clock;
  2291. return &bi->disp;
  2292. }
  2293. px = (unsigned int)dw * (unsigned int)dh;
  2294. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2295. return &bi->img;
  2296. image_disp_drop(bi);
  2297. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2298. if (!bi->disp.px)
  2299. return &bi->img;
  2300. if (bi->img.alpha) {
  2301. bi->disp.alpha = (unsigned char *)malloc(px);
  2302. if (!bi->disp.alpha) {
  2303. free(bi->disp.px);
  2304. bi->disp.px = 0;
  2305. return &bi->img;
  2306. }
  2307. }
  2308. bi->disp.w = (unsigned int)dw;
  2309. bi->disp.h = (unsigned int)dh;
  2310. bi->disp.format = bi->img.format;
  2311. bi->disp.flags = 0;
  2312. memset(&b, 0, sizeof(b));
  2313. b.dst = bi->disp.px;
  2314. b.dst_w = dw;
  2315. b.dst_h = dh;
  2316. b.clip_w = dw;
  2317. b.clip_h = dh;
  2318. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2319. b.dst_a = bi->disp.alpha;
  2320. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2321. img_draw(&bi->img, &b);
  2322. bi->disp_pixels = px;
  2323. image_disp_pixels += px;
  2324. bi->disp_last = ++image_disp_clock;
  2325. return &bi->disp;
  2326. }
  2327. /* Decode into the shared arena, then copy/scale the result into a display
  2328. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2329. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2330. * pixels. Transparent edges are composited over white. */
  2331. /* One decode scratch arena per page, reused across images. Allocating and
  2332. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2333. * each small display bitmap landed in the hole the previous arena left, so
  2334. * the next arena no longer fit and the heap ratcheted up until an app
  2335. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2336. * still released right after their one image. */
  2337. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2338. static unsigned char *decode_arena_get(unsigned int bytes)
  2339. {
  2340. if (decode_arena && decode_arena_size >= bytes)
  2341. return decode_arena;
  2342. free(decode_arena);
  2343. decode_arena = (unsigned char *)malloc(bytes);
  2344. decode_arena_size = decode_arena ? bytes : 0;
  2345. return decode_arena;
  2346. }
  2347. static void decode_arena_put(void)
  2348. {
  2349. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2350. free(decode_arena);
  2351. decode_arena = 0;
  2352. decode_arena_size = 0;
  2353. }
  2354. }
  2355. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2356. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2357. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2358. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2359. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2360. struct br_image *bi, int box_w, int box_h);
  2361. static int decode_image_data(const unsigned char *data, unsigned int len,
  2362. struct br_image *bi, int box_w, int box_h,
  2363. int fit_w, int fit_h)
  2364. {
  2365. struct img_info info;
  2366. struct img_options opt;
  2367. struct img_mem mem;
  2368. struct img_image decoded;
  2369. unsigned char *arena;
  2370. unsigned int est, bytes, i;
  2371. unsigned int t0;
  2372. unsigned short *px;
  2373. unsigned char *alpha = 0;
  2374. int dw, dh, r;
  2375. bi->url_hash = 0;
  2376. img_last_dec_ms = 0;
  2377. img_last_scale_ms = 0;
  2378. if (img_sniff(data, len, &info) != 0) {
  2379. if (svg_text_sniff(data, len))
  2380. return svg_decode_image(data, len, bi,
  2381. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2382. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2383. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2384. return -1;
  2385. }
  2386. est = img_estimate(&info);
  2387. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2388. s_copy(bi->err, "image too large", sizeof(bi->err));
  2389. return -1;
  2390. }
  2391. arena = decode_arena_get(est);
  2392. if (!arena) {
  2393. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2394. return -1;
  2395. }
  2396. img_mem_init(&mem, arena, est);
  2397. opt.max_pixels = BR_IMG_PIX_MAX;
  2398. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2399. (box_w > 0 ? (unsigned int)box_w : 0);
  2400. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2401. (box_h > 0 ? (unsigned int)box_h : 0);
  2402. t0 = u_ticks_ms();
  2403. r = img_decode(data, len, &opt, &mem, &decoded);
  2404. img_last_dec_ms = u_ticks_ms() - t0;
  2405. if (r != 0) {
  2406. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2407. goto fail;
  2408. }
  2409. if (decoded.w == 0 || decoded.h == 0) {
  2410. s_copy(bi->err, "empty image", sizeof(bi->err));
  2411. goto fail;
  2412. }
  2413. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2414. * needs the intrinsic dimensions from the header. */
  2415. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2416. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2417. dw = (int)decoded.w;
  2418. dh = (int)decoded.h;
  2419. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2420. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2421. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2422. * axes with one scale so the aspect ratio is preserved. */
  2423. if (fit_w > 0 || fit_h > 0) {
  2424. unsigned int scw = fit_w > 0 ?
  2425. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2426. unsigned int sch = fit_h > 0 ?
  2427. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2428. unsigned int sc = scw < sch ? scw : sch;
  2429. if (sc < 0x10000u) {
  2430. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2431. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2432. if (dw < 1)
  2433. dw = 1;
  2434. if (dh < 1)
  2435. dh = 1;
  2436. }
  2437. }
  2438. if (box_w > 0 && box_h > 0) {
  2439. /* cover: scale so both box sides are filled, never up */
  2440. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2441. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2442. unsigned int sc = sw > sh ? sw : sh;
  2443. if (sc < 0x10000u) {
  2444. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2445. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2446. }
  2447. }
  2448. if (dw > BR_IMG_LAYOUT_W) {
  2449. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2450. dw = BR_IMG_LAYOUT_W;
  2451. }
  2452. if (dh < 1)
  2453. dh = 1;
  2454. if (dw < 1)
  2455. dw = 1;
  2456. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2457. BR_IMG_PIXEL_BUDGET) {
  2458. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2459. goto fail;
  2460. }
  2461. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2462. px = (unsigned short *)malloc(bytes);
  2463. if (!px) {
  2464. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2465. goto fail;
  2466. }
  2467. /* Keep the alpha plane for the scaled image so transparent logos and
  2468. * icons composite over the page instead of the browser's dark theme
  2469. * background. Very large alpha images stay flattened to bound the
  2470. * heap use. */
  2471. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2472. alpha = (unsigned char *)malloc((unsigned int)dw *
  2473. (unsigned int)dh);
  2474. if (alpha) {
  2475. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2476. alpha[i] = 255;
  2477. }
  2478. }
  2479. /* With an alpha plane the colour under transparent pixels only shows
  2480. * through partially covered edge pixels of the downscale: use white,
  2481. * as documented above, not the dark browser theme (which left a dark
  2482. * fringe around scaled app icons). */
  2483. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2484. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2485. {
  2486. struct img_blit b;
  2487. b.dst = px;
  2488. b.dst_w = dw;
  2489. b.dst_h = dh;
  2490. b.clip_x = 0;
  2491. b.clip_y = 0;
  2492. b.clip_w = dw;
  2493. b.clip_h = dh;
  2494. b.x = 0;
  2495. b.y = 0;
  2496. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2497. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2498. b.bg2 = b.bg;
  2499. b.dst_a = alpha;
  2500. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2501. t0 = u_ticks_ms();
  2502. img_draw(&decoded, &b);
  2503. img_last_scale_ms = u_ticks_ms() - t0;
  2504. }
  2505. bi->img.format = decoded.format;
  2506. bi->img.w = (unsigned int)dw;
  2507. bi->img.h = (unsigned int)dh;
  2508. bi->img.px = px;
  2509. bi->img.alpha = alpha;
  2510. bi->img.flags = 0;
  2511. bi->state = 1;
  2512. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2513. decode_arena_put();
  2514. return 0;
  2515. fail:
  2516. decode_arena_put();
  2517. return -1;
  2518. }
  2519. /* ---- URL / local path handling ---- */
  2520. static int is_http(const char *s)
  2521. {
  2522. return starts_with(s, "http://") || starts_with(s, "https://");
  2523. }
  2524. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2525. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2526. {
  2527. char seg[64];
  2528. unsigned int i = 0, o = 1;
  2529. int depth = 0;
  2530. int trailing;
  2531. if (!in || in[0] != '/' || cap < 2)
  2532. return -1;
  2533. trailing = 0;
  2534. {
  2535. unsigned int n = s_len(in);
  2536. if (n > 1 && in[n - 1] == '/')
  2537. trailing = 1;
  2538. }
  2539. out[0] = '/';
  2540. while (in[i]) {
  2541. unsigned int n = 0;
  2542. while (in[i] == '/')
  2543. i++;
  2544. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2545. if (n + 1 < sizeof(seg))
  2546. seg[n++] = in[i];
  2547. i++;
  2548. }
  2549. seg[n] = '\0';
  2550. if (n == 0)
  2551. break;
  2552. if (s_eq(seg, "."))
  2553. continue;
  2554. if (s_eq(seg, "..")) {
  2555. if (depth > 0) {
  2556. while (o > 1 && out[o - 1] != '/')
  2557. o--;
  2558. if (o > 1)
  2559. o--;
  2560. depth--;
  2561. }
  2562. continue;
  2563. }
  2564. if (o > 1) {
  2565. if (o + 1 >= cap)
  2566. return -1;
  2567. out[o++] = '/';
  2568. }
  2569. if (o + n + 1 >= cap)
  2570. return -1;
  2571. {
  2572. unsigned int j;
  2573. for (j = 0; j < n; j++)
  2574. out[o++] = seg[j];
  2575. }
  2576. depth++;
  2577. }
  2578. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2579. if (o + 1 >= cap)
  2580. return -1;
  2581. out[o++] = '/';
  2582. }
  2583. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2584. if (in[i] == '?' || in[i] == '#') {
  2585. while (in[i]) {
  2586. if (o + 1 >= cap)
  2587. return -1;
  2588. out[o++] = in[i++];
  2589. }
  2590. }
  2591. out[o] = '\0';
  2592. return 0;
  2593. }
  2594. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2595. {
  2596. char joined[BR_URL_MAX];
  2597. if (!in || !in[0]) {
  2598. s_copy(out, cwd[0] ? cwd : "/", cap);
  2599. return;
  2600. }
  2601. if (in[0] == '/') {
  2602. if (normalize_abs(in, out, cap) != 0)
  2603. s_copy(out, in, cap);
  2604. return;
  2605. }
  2606. {
  2607. unsigned int n = 0;
  2608. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2609. s_append(joined, &n, "/", sizeof(joined));
  2610. s_append(joined, &n, in, sizeof(joined));
  2611. }
  2612. if (normalize_abs(joined, out, cap) != 0)
  2613. s_copy(out, joined, cap);
  2614. }
  2615. /* ---- canonical origin cache ---- *
  2616. *
  2617. * Sites commonly redirect http://host to https://host and then to
  2618. * https://www.host. Remember the final scheme/host of the last navigation so
  2619. * a bare domain typed again goes straight there instead of paying for two
  2620. * more connections and TLS handshakes. Only default-port requests are
  2621. * rewritten; explicit ports are left alone. */
  2622. #define ORIGIN_CACHE_MAX 8
  2623. #define ORIGIN_FILE "/share/borigins"
  2624. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2625. UHTTP_HOST_MAX + 2))
  2626. struct origin_cache_entry {
  2627. char host[UHTTP_HOST_MAX];
  2628. char origin[UHTTP_HOST_MAX + 16];
  2629. };
  2630. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2631. static int origin_count;
  2632. static char origin_buf[ORIGIN_BUF_SIZE];
  2633. static int default_port(const struct uhttp_url *u)
  2634. {
  2635. return u->secure ? u->port == 443 : u->port == 80;
  2636. }
  2637. static void url_origin(const struct uhttp_url *u, char *out,
  2638. unsigned int cap)
  2639. {
  2640. unsigned int n = 0;
  2641. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2642. s_append(out, &n, u->host, cap);
  2643. if (!default_port(u)) {
  2644. s_append(out, &n, ":", cap);
  2645. s_append_dec(out, &n, u->port, cap);
  2646. }
  2647. }
  2648. static void origin_cache_apply(char *url, unsigned int cap)
  2649. {
  2650. struct uhttp_url u;
  2651. char out[BR_URL_MAX];
  2652. unsigned int n = 0;
  2653. int i;
  2654. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2655. return;
  2656. for (i = 0; i < origin_count; i++) {
  2657. if (!s_eq(u.host, origins[i].host))
  2658. continue;
  2659. s_append(out, &n, origins[i].origin, sizeof(out));
  2660. s_append(out, &n, u.path, sizeof(out));
  2661. s_copy(url, out, cap);
  2662. return;
  2663. }
  2664. }
  2665. static void origin_cache_save(void)
  2666. {
  2667. unsigned int n = 0;
  2668. int i;
  2669. for (i = 0; i < origin_count; i++) {
  2670. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2671. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2672. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2673. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2674. }
  2675. if (n)
  2676. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2677. (int)origin_buf, (int)n);
  2678. }
  2679. static void origin_cache_load(void)
  2680. {
  2681. char *p;
  2682. int rn;
  2683. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2684. (int)(sizeof(origin_buf) - 1));
  2685. if (rn <= 0)
  2686. return;
  2687. origin_buf[rn] = '\0';
  2688. p = origin_buf;
  2689. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2690. char *line = p, *origin;
  2691. while (*p && *p != '\n')
  2692. p++;
  2693. if (*p)
  2694. *p++ = '\0';
  2695. if (!line[0])
  2696. continue;
  2697. origin = line;
  2698. while (*origin && *origin != ' ')
  2699. origin++;
  2700. if (!*origin)
  2701. continue;
  2702. *origin++ = '\0';
  2703. if (!line[0] || !is_http(origin))
  2704. continue;
  2705. {
  2706. struct uhttp_url uo;
  2707. if (uhttp_parse_url(origin, &uo) != 0 ||
  2708. !s_eq(uo.path, "/"))
  2709. continue;
  2710. }
  2711. s_copy(origins[origin_count].host, line,
  2712. sizeof(origins[origin_count].host));
  2713. s_copy(origins[origin_count].origin, origin,
  2714. sizeof(origins[origin_count].origin));
  2715. origin_count++;
  2716. }
  2717. }
  2718. static int host_is_www_of(const char *host, const char *base)
  2719. {
  2720. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2721. host[3] == '.' && s_eq(host + 4, base);
  2722. }
  2723. static void origin_cache_learn(const char *requested, const char *final)
  2724. {
  2725. struct uhttp_url from, to;
  2726. char origin[UHTTP_HOST_MAX + 16];
  2727. int i;
  2728. if (!is_http(requested) || !is_http(final))
  2729. return;
  2730. if (uhttp_parse_url(requested, &from) != 0 ||
  2731. uhttp_parse_url(final, &to) != 0)
  2732. return;
  2733. if (!default_port(&from))
  2734. return;
  2735. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2736. from.port == to.port)
  2737. return;
  2738. /* Only remember origin-level canonicalisation: the same path, and
  2739. * either the same host or its www./apex sibling. A path- or
  2740. * host-specific redirect (a shortener, a login page) must not poison
  2741. * every request to the typed host. */
  2742. if (!s_eq(from.path, to.path))
  2743. return;
  2744. if (!s_eq(from.host, to.host) &&
  2745. !host_is_www_of(to.host, from.host) &&
  2746. !host_is_www_of(from.host, to.host))
  2747. return;
  2748. url_origin(&to, origin, sizeof(origin));
  2749. for (i = 0; i < origin_count; i++) {
  2750. if (s_eq(origins[i].host, from.host)) {
  2751. if (!s_eq(origins[i].origin, origin)) {
  2752. s_copy(origins[i].origin, origin,
  2753. sizeof(origins[i].origin));
  2754. origin_cache_save();
  2755. }
  2756. return;
  2757. }
  2758. }
  2759. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2760. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2761. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2762. origin_cache_save();
  2763. }
  2764. static int path_dir(const char *path, char *out, unsigned int cap)
  2765. {
  2766. unsigned int i, last = 0;
  2767. for (i = 0; path[i]; i++)
  2768. if (path[i] == '/')
  2769. last = i;
  2770. if (last == 0) {
  2771. if (cap < 2)
  2772. return -1;
  2773. out[0] = '/';
  2774. out[1] = '\0';
  2775. return 0;
  2776. }
  2777. if (last + 1 >= cap)
  2778. return -1;
  2779. {
  2780. unsigned int j;
  2781. for (j = 0; j < last; j++)
  2782. out[j] = path[j];
  2783. out[last] = '\0';
  2784. }
  2785. return 0;
  2786. }
  2787. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2788. static int resolve_link(const char *base, const char *href, char *out,
  2789. unsigned int cap)
  2790. {
  2791. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2792. if (!href || !href[0] || href[0] == '#')
  2793. return -1;
  2794. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2795. starts_with(href, "data:") || starts_with(href, "tel:"))
  2796. return -1;
  2797. if (starts_with(href, "about:")) {
  2798. s_copy(out, href, cap);
  2799. return 0;
  2800. }
  2801. if (is_http(href)) {
  2802. s_copy(out, href, cap);
  2803. return 0;
  2804. }
  2805. if (starts_with(href, "//")) {
  2806. if (is_http(base)) {
  2807. unsigned int n = 0;
  2808. s_append(out, &n, starts_with(base, "https:") ?
  2809. "https:" : "http:", cap);
  2810. s_append(out, &n, href, cap);
  2811. return 0;
  2812. }
  2813. return -1;
  2814. }
  2815. if (is_http(base)) {
  2816. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2817. }
  2818. /* local page */
  2819. if (href[0] == '/') {
  2820. if (normalize_abs(href, out, cap) != 0)
  2821. return -1;
  2822. return 0;
  2823. }
  2824. {
  2825. static char dir[BR_URL_MAX];
  2826. unsigned int n = 0;
  2827. if (s_eq(base, "about:home"))
  2828. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2829. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2830. s_copy(dir, "/", sizeof(dir));
  2831. s_append(joined, &n, dir, sizeof(joined));
  2832. if (n == 0 || joined[n - 1] != '/')
  2833. s_append(joined, &n, "/", sizeof(joined));
  2834. s_append(joined, &n, href, sizeof(joined));
  2835. }
  2836. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2837. }
  2838. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2839. * rest instead of failing when a page or stylesheet is larger than the
  2840. * buffer. The stream is still walked to the end, so a normal page is
  2841. * verified; a truncated compressed input still returns whatever was decoded
  2842. * so far. */
  2843. struct trunc_buf {
  2844. unsigned char *dst;
  2845. unsigned int cap, pos;
  2846. int full;
  2847. };
  2848. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2849. {
  2850. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2851. if (len > m->cap - m->pos) {
  2852. unsigned int room = m->cap - m->pos;
  2853. if (room) {
  2854. unsigned int i;
  2855. for (i = 0; i < room; i++)
  2856. m->dst[m->pos + i] = data[i];
  2857. m->pos += room;
  2858. }
  2859. m->full = 1;
  2860. return 0;
  2861. }
  2862. {
  2863. unsigned int i;
  2864. for (i = 0; i < len; i++)
  2865. m->dst[m->pos + i] = data[i];
  2866. }
  2867. m->pos += len;
  2868. return 0;
  2869. }
  2870. static void worker_wait_ui(void);
  2871. static void inflate_ui_pump(void *ctx)
  2872. {
  2873. static unsigned int last;
  2874. unsigned int now = u_ticks_ms();
  2875. (void)ctx;
  2876. if ((int)(now - last) >= 50) {
  2877. last = now;
  2878. worker_wait_ui();
  2879. }
  2880. }
  2881. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2882. unsigned char *dst, unsigned int cap,
  2883. unsigned int *outlen, int gzip, int *truncated)
  2884. {
  2885. struct inflate_src in;
  2886. struct inflate_sink sink;
  2887. struct trunc_buf m;
  2888. unsigned int got = 0;
  2889. int r;
  2890. in.p = src;
  2891. in.len = len;
  2892. in.more = 0;
  2893. in.ctx = 0;
  2894. m.dst = dst;
  2895. m.cap = cap;
  2896. m.pos = 0;
  2897. m.full = 0;
  2898. sink.write = trunc_write;
  2899. sink.ctx = &m;
  2900. inflate_init(&image_inflate_ws, &in, &sink);
  2901. image_inflate_ws.progress = inflate_ui_pump;
  2902. image_inflate_ws.progress_ctx = 0;
  2903. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2904. inflate_zlib(&image_inflate_ws, &got);
  2905. *outlen = m.pos;
  2906. *truncated = m.full || r != 0;
  2907. if (r != 0 && m.pos == 0)
  2908. return -1;
  2909. return 0;
  2910. }
  2911. /* ---- headless fetch workers ------------------------------------------ *
  2912. *
  2913. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2914. * writes the raw response, a small metadata file and a done marker under
  2915. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2916. * or a multi-megabyte body never freezes the UI and images download in
  2917. * parallel.
  2918. */
  2919. struct fetch_meta {
  2920. int status;
  2921. int error;
  2922. int trunc;
  2923. unsigned int len;
  2924. unsigned int open_ms;
  2925. unsigned int first_ms;
  2926. unsigned int total_ms;
  2927. /* Optional decoded bitmap produced by the helper (image jobs). */
  2928. unsigned int dw, dh, nw, nh;
  2929. unsigned int alpha;
  2930. unsigned int px_len;
  2931. unsigned int dec_ms;
  2932. int dec_err;
  2933. char encoding[16];
  2934. char ctype[64];
  2935. char final[BR_URL_MAX];
  2936. };
  2937. static void draw(unsigned int *action);
  2938. static void handle_keys(unsigned int *action);
  2939. static void handle_page_click(unsigned int *action);
  2940. #define FETCH_WORKERS 4
  2941. #define FETCH_PATH_MAX 32
  2942. /* One long-lived curl __serve helper per worker. Each worker has its own
  2943. * request/body/meta/done files under /share so several downloads can be in
  2944. * flight at once; the keep-alive connection stays in the helper process, so
  2945. * tls.c's per-process state remains valid. */
  2946. struct fetch_worker {
  2947. int pid;
  2948. int slot;
  2949. int busy;
  2950. int ready;
  2951. int image_job;
  2952. unsigned int seq;
  2953. unsigned int deadline;
  2954. int retried;
  2955. unsigned int dec_w, dec_h;
  2956. int dec_retried;
  2957. char req[FETCH_PATH_MAX];
  2958. char body[FETCH_PATH_MAX];
  2959. char meta[FETCH_PATH_MAX];
  2960. char done[FETCH_PATH_MAX];
  2961. char post[FETCH_PATH_MAX];
  2962. char px[FETCH_PATH_MAX];
  2963. /* Optional preload job attached to this worker. */
  2964. unsigned int node;
  2965. int bg;
  2966. char url[BR_URL_MAX];
  2967. struct fetch_meta m;
  2968. };
  2969. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2970. static int fetch_tty = -2;
  2971. static void fetch_tty_drain(void);
  2972. static unsigned int fetch_session;
  2973. static unsigned int fetch_seq;
  2974. static struct fetch_meta fetch_meta;
  2975. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2976. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2977. static int fetch_last_error;
  2978. static unsigned int meta_uint(char **pp)
  2979. {
  2980. char *p = *pp;
  2981. unsigned int v = 0;
  2982. while (*p >= '0' && *p <= '9') {
  2983. v = v * 10 + (unsigned int)(*p - '0');
  2984. p++;
  2985. }
  2986. while (*p && *p != '\n')
  2987. p++;
  2988. if (*p == '\n')
  2989. p++;
  2990. *pp = p;
  2991. return v;
  2992. }
  2993. static void meta_str(char **pp, char *out, unsigned int cap)
  2994. {
  2995. char *p = *pp;
  2996. unsigned int n = 0;
  2997. while (*p && *p != '\n' && n + 1 < cap)
  2998. out[n++] = *p++;
  2999. out[n] = '\0';
  3000. while (*p && *p != '\n')
  3001. p++;
  3002. if (*p == '\n')
  3003. p++;
  3004. *pp = p;
  3005. }
  3006. static void worker_wait_ui(void)
  3007. {
  3008. unsigned int action = 0;
  3009. if (!ngui_begin(&ui))
  3010. return;
  3011. draw(&action);
  3012. handle_keys(&action);
  3013. handle_page_click(&action);
  3014. if (action & ACT_WAIT_NAV) {
  3015. pending_action |= action & ACT_WAIT_NAV;
  3016. if ((action & ACT_NAV) && click_url[0])
  3017. s_copy(pending_url, click_url, sizeof(pending_url));
  3018. click_url[0] = '\0';
  3019. cancel_fetch = 1;
  3020. }
  3021. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  3022. ngui_invalidate(&ui);
  3023. ngui_end(&ui);
  3024. }
  3025. static void fetch_path(char *out, unsigned int cap, const char *kind,
  3026. unsigned int session, int slot)
  3027. {
  3028. unsigned int n = 0;
  3029. s_append(out, &n, "/share/bf", cap);
  3030. s_append_dec(out, &n, session, cap);
  3031. s_append(out, &n, "_", cap);
  3032. s_append_dec(out, &n, (unsigned int)slot, cap);
  3033. s_append(out, &n, kind, cap);
  3034. }
  3035. static void fetch_pool_init(void)
  3036. {
  3037. static int ready;
  3038. int i;
  3039. if (ready)
  3040. return;
  3041. ready = 1;
  3042. fetch_session = ((unsigned int)u_getpid() << 16) ^
  3043. (u_ticks_ms() & 0xFFFFu);
  3044. if (!fetch_session)
  3045. fetch_session = 1;
  3046. for (i = 0; i < FETCH_WORKERS; i++) {
  3047. struct fetch_worker *w = &fetch_workers[i];
  3048. w->pid = -1;
  3049. w->slot = i;
  3050. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  3051. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  3052. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  3053. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  3054. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  3055. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  3056. }
  3057. }
  3058. static void fetch_worker_stop(struct fetch_worker *w)
  3059. {
  3060. int i;
  3061. /* An abandoned image job leaves its node loadable again. */
  3062. if (w->busy && w->image_job && w->node < doc.nnode) {
  3063. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  3064. doc.nodes[w->node].bg_img_index = -1;
  3065. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  3066. doc.nodes[w->node].img_index = -1;
  3067. }
  3068. if (w->pid > 0) {
  3069. u_kill((unsigned int)w->pid);
  3070. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  3071. u_sleep_ms(5);
  3072. /* Let the reaper close the socket before we reuse the slot. */
  3073. u_sleep_ms(10);
  3074. }
  3075. w->pid = -1;
  3076. w->busy = 0;
  3077. w->ready = 0;
  3078. w->image_job = 0;
  3079. if (w->req[0]) {
  3080. u_syscall1(SYS_UNLINK, (int)w->done);
  3081. u_syscall1(SYS_UNLINK, (int)w->meta);
  3082. u_syscall1(SYS_UNLINK, (int)w->body);
  3083. u_syscall1(SYS_UNLINK, (int)w->post);
  3084. u_syscall1(SYS_UNLINK, (int)w->req);
  3085. }
  3086. }
  3087. static void fetch_workers_stop_all(void)
  3088. {
  3089. int i;
  3090. for (i = 0; i < FETCH_WORKERS; i++)
  3091. fetch_worker_stop(&fetch_workers[i]);
  3092. }
  3093. /* Abandon the transfers of the current page but keep idle helpers and their
  3094. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3095. * because its response would otherwise land in a reused /share slot. */
  3096. static void fetch_workers_cancel_busy(void)
  3097. {
  3098. int i;
  3099. for (i = 0; i < FETCH_WORKERS; i++)
  3100. if (fetch_workers[i].busy)
  3101. fetch_worker_stop(&fetch_workers[i]);
  3102. }
  3103. static void fetch_workers_prepare_nav(const char *url)
  3104. {
  3105. int i;
  3106. (void)url;
  3107. for (i = 0; i < FETCH_WORKERS; i++) {
  3108. struct fetch_worker *w = &fetch_workers[i];
  3109. if (w->pid <= 0)
  3110. continue;
  3111. /* Only an in-flight transfer must be aborted. Idle helpers
  3112. * stay warm across origins: there are just FETCH_WORKERS of
  3113. * them, and uhttp_open drops the old connection when the
  3114. * next job is for another host. Killing and respawning all
  3115. * four on every navigation churned processes and sockets
  3116. * while images were still loading. */
  3117. if (w->busy)
  3118. fetch_worker_stop(w);
  3119. }
  3120. }
  3121. /* The browser is no longer the active window and no fetch is running: give
  3122. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3123. static void fetch_workers_stop_if_unfocused(void)
  3124. {
  3125. int i;
  3126. fetch_tty_drain();
  3127. if (ui.focused || page_loading || preload_active)
  3128. return;
  3129. for (i = 0; i < FETCH_WORKERS; i++)
  3130. if (fetch_workers[i].pid > 0) {
  3131. fetch_workers_stop_all();
  3132. return;
  3133. }
  3134. }
  3135. /* The helpers (and this process, since u_tty_create() rebinds our own
  3136. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3137. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3138. * a dozen TLS connections every helper hung in its next log line, so the
  3139. * following cross-origin navigation sat at "Loading..." until it timed out.
  3140. * Drain and discard it from every wait/poll loop. */
  3141. static void fetch_tty_drain(void)
  3142. {
  3143. char sink[512];
  3144. int i;
  3145. if (fetch_tty <= 0)
  3146. return;
  3147. for (i = 0; i < 16; i++)
  3148. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3149. break;
  3150. }
  3151. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3152. unsigned int errcap)
  3153. {
  3154. char arg[40];
  3155. unsigned int n = 0;
  3156. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3157. return 0;
  3158. w->pid = -1;
  3159. fetch_pool_init();
  3160. if (fetch_tty == -2) {
  3161. int t = u_tty_create();
  3162. fetch_tty = t > 0 ? t : 0;
  3163. }
  3164. s_append(arg, &n, "__serve ", sizeof(arg));
  3165. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3166. s_append(arg, &n, " ", sizeof(arg));
  3167. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3168. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3169. if (w->pid <= 0) {
  3170. w->pid = -1;
  3171. s_copy(err, "cannot start network helper", errcap);
  3172. return -1;
  3173. }
  3174. return 0;
  3175. }
  3176. static struct fetch_worker *fetch_worker_alloc(void)
  3177. {
  3178. int i;
  3179. fetch_pool_init();
  3180. for (i = 0; i < FETCH_WORKERS; i++)
  3181. if (!fetch_workers[i].busy)
  3182. return &fetch_workers[i];
  3183. return 0;
  3184. }
  3185. /* A worker for a synchronous foreground fetch (the page, a module, a
  3186. * script's fetch()/XHR). When image prefetches hold every helper, the
  3187. * newest image job (least progress) is abandoned: fetch_worker_stop()
  3188. * re-arms its node, so a later scan loads it again. Failing instead made
  3189. * cloudron.io's catalogue XHR return status 0 while its icons loaded. */
  3190. static struct fetch_worker *fetch_worker_alloc_fg(void)
  3191. {
  3192. struct fetch_worker *w = fetch_worker_alloc(), *victim = 0;
  3193. int i;
  3194. if (w)
  3195. return w;
  3196. for (i = 0; i < FETCH_WORKERS; i++) {
  3197. struct fetch_worker *c = &fetch_workers[i];
  3198. if (c->busy && c->image_job &&
  3199. (!victim || (int)(c->seq - victim->seq) > 0))
  3200. victim = c;
  3201. }
  3202. if (victim)
  3203. fetch_worker_stop(victim);
  3204. return victim;
  3205. }
  3206. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3207. unsigned int cap, const char *method,
  3208. const char *ctype, const char *post,
  3209. unsigned int post_len, unsigned int node,
  3210. int bg, unsigned int dec_w,
  3211. unsigned int dec_h, char *err,
  3212. unsigned int errcap);
  3213. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3214. unsigned int cap, const char *post,
  3215. unsigned int post_len, unsigned int node,
  3216. int bg, char *err, unsigned int errcap)
  3217. {
  3218. /* A body pointer with no bytes is still a POST: the classic request
  3219. * line would turn it into a GET. */
  3220. if (post && !post_len)
  3221. return fetch_worker_submit_req(w, url, cap, "POST",
  3222. "application/x-www-form-urlencoded", post, 0, node,
  3223. bg, 0, 0, err, errcap);
  3224. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3225. node, bg, 0, 0, err, errcap);
  3226. }
  3227. /* Image job: ask the helper to decode at these display bounds as well. */
  3228. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3229. unsigned int cap, unsigned int node,
  3230. int bg, unsigned int dec_w,
  3231. unsigned int dec_h, char *err,
  3232. unsigned int errcap)
  3233. {
  3234. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3235. dec_w, dec_h, err, errcap);
  3236. }
  3237. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3238. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3239. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3240. unsigned int cap, const char *method,
  3241. const char *ctype, const char *post,
  3242. unsigned int post_len, unsigned int node,
  3243. int bg, unsigned int dec_w,
  3244. unsigned int dec_h, char *err,
  3245. unsigned int errcap)
  3246. {
  3247. static char req[BR_URL_MAX + 256];
  3248. unsigned int n = 0;
  3249. fetch_seq++;
  3250. if (!fetch_seq)
  3251. fetch_seq = 1;
  3252. w->seq = fetch_seq;
  3253. w->ready = 0;
  3254. w->image_job = 0;
  3255. w->retried = 0;
  3256. w->m.error = 0;
  3257. w->node = node;
  3258. w->bg = bg;
  3259. w->dec_w = dec_w;
  3260. w->dec_h = dec_h;
  3261. w->dec_retried = 0;
  3262. s_copy(w->url, url, sizeof(w->url));
  3263. s_append_dec(req, &n, w->seq, sizeof(req));
  3264. s_append(req, &n, " ", sizeof(req));
  3265. s_append_dec(req, &n, cap, sizeof(req));
  3266. s_append(req, &n, " ", sizeof(req));
  3267. if (dec_w || dec_h) {
  3268. s_append(req, &n, "D ", sizeof(req));
  3269. s_append_dec(req, &n, dec_w, sizeof(req));
  3270. s_append(req, &n, " ", sizeof(req));
  3271. s_append_dec(req, &n, dec_h, sizeof(req));
  3272. s_append(req, &n, " ", sizeof(req));
  3273. } else if (method) {
  3274. unsigned int k;
  3275. s_append(req, &n, "X ", sizeof(req));
  3276. s_append(req, &n, method, sizeof(req));
  3277. s_append(req, &n, " ", sizeof(req));
  3278. s_append_dec(req, &n, post_len, sizeof(req));
  3279. s_append(req, &n, " ", sizeof(req));
  3280. if (!ctype || !ctype[0])
  3281. s_append(req, &n, "-", sizeof(req));
  3282. /* One token on the request line: drop the spaces
  3283. * ("application/json; charset=utf-8" stays valid). */
  3284. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3285. if (ctype[k] != ' ')
  3286. req[n++] = ctype[k];
  3287. req[n] = '\0';
  3288. s_append(req, &n, " ", sizeof(req));
  3289. } else if (post_len) {
  3290. s_append(req, &n, "POST ", sizeof(req));
  3291. s_append_dec(req, &n, post_len, sizeof(req));
  3292. s_append(req, &n, " ", sizeof(req));
  3293. }
  3294. s_append(req, &n, url, sizeof(req));
  3295. s_append(req, &n, "\n", sizeof(req));
  3296. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3297. (int)post, (int)post_len) < 0) {
  3298. s_copy(err, "cannot queue form body", errcap);
  3299. return -1;
  3300. }
  3301. u_syscall1(SYS_UNLINK, (int)w->done);
  3302. u_syscall1(SYS_UNLINK, (int)w->meta);
  3303. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3304. s_copy(err, "cannot queue network request", errcap);
  3305. return -1;
  3306. }
  3307. if (fetch_worker_start(w, err, errcap) != 0)
  3308. return -1;
  3309. w->busy = 1;
  3310. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3311. return 0;
  3312. }
  3313. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3314. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3315. unsigned int errcap)
  3316. {
  3317. static char meta[BR_URL_MAX + 1024];
  3318. char *p;
  3319. int rn, mseq;
  3320. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3321. (int)(sizeof(meta) - 1));
  3322. if (rn <= 0) {
  3323. s_copy(err, "network helper failed", errcap);
  3324. return -1;
  3325. }
  3326. meta[rn] = '\0';
  3327. p = meta;
  3328. mseq = (int)meta_uint(&p);
  3329. if (mseq != (int)w->seq) {
  3330. s_copy(err, "stale network response", errcap);
  3331. return -1;
  3332. }
  3333. w->m.status = (int)meta_uint(&p);
  3334. w->m.error = (int)meta_uint(&p);
  3335. w->m.trunc = (int)meta_uint(&p);
  3336. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3337. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3338. meta_str(&p, w->m.final, sizeof(w->m.final));
  3339. w->m.len = meta_uint(&p);
  3340. w->m.open_ms = 0;
  3341. w->m.first_ms = 0;
  3342. w->m.total_ms = 0;
  3343. if (*p) {
  3344. w->m.open_ms = meta_uint(&p);
  3345. w->m.first_ms = meta_uint(&p);
  3346. w->m.total_ms = meta_uint(&p);
  3347. }
  3348. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3349. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3350. w->m.dec_err = 0;
  3351. if (*p) {
  3352. w->m.dw = meta_uint(&p);
  3353. w->m.dh = meta_uint(&p);
  3354. w->m.nw = meta_uint(&p);
  3355. w->m.nh = meta_uint(&p);
  3356. w->m.alpha = meta_uint(&p);
  3357. w->m.px_len = meta_uint(&p);
  3358. w->m.dec_err = (int)meta_uint(&p);
  3359. w->m.dec_ms = meta_uint(&p);
  3360. }
  3361. if (w->m.error) {
  3362. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3363. return -1;
  3364. }
  3365. w->ready = 1;
  3366. return 0;
  3367. }
  3368. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3369. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3370. unsigned int errcap)
  3371. {
  3372. static char done[24];
  3373. char *p;
  3374. int rn, mseq;
  3375. fetch_tty_drain();
  3376. if (!w->busy)
  3377. return -1;
  3378. if (w->ready)
  3379. return 1;
  3380. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3381. (int)(sizeof(done) - 1));
  3382. if (rn > 0) {
  3383. done[rn] = '\0';
  3384. p = done;
  3385. mseq = (int)meta_uint(&p);
  3386. if (mseq == (int)w->seq) {
  3387. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3388. fetch_worker_stop(w);
  3389. return -1;
  3390. }
  3391. return 1;
  3392. }
  3393. }
  3394. if (!u_alive((unsigned int)w->pid)) {
  3395. w->pid = -1;
  3396. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3397. w->retried = 1;
  3398. return 0;
  3399. }
  3400. s_copy(err, "network helper stopped", errcap);
  3401. fetch_worker_stop(w);
  3402. return -1;
  3403. }
  3404. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3405. s_copy(err, "network request timed out", errcap);
  3406. fetch_worker_stop(w);
  3407. return -1;
  3408. }
  3409. return 0;
  3410. }
  3411. /* Copy the completed body, inflating it if the server ignored our identity
  3412. * request. Mirrors the old fetch_remote body path. */
  3413. static int fetch_worker_read_body(struct fetch_worker *w,
  3414. unsigned char *plain,
  3415. unsigned int plaincap,
  3416. unsigned char *comp,
  3417. unsigned int compcap,
  3418. int *truncated, char *err,
  3419. unsigned int errcap)
  3420. {
  3421. int rv, zr, was_trunc;
  3422. if (contains_ci(w->m.encoding, "gzip") ||
  3423. contains_ci(w->m.encoding, "deflate")) {
  3424. unsigned int comp_len = 0, plen = 0;
  3425. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3426. (int)compcap);
  3427. if (rv < 0) {
  3428. s_copy(err, "empty response", errcap);
  3429. return -1;
  3430. }
  3431. comp_len = (unsigned int)rv;
  3432. if (comp_len < w->m.len) {
  3433. s_copy(err, "compressed response is too large", errcap);
  3434. return -1;
  3435. }
  3436. if (contains_ci(w->m.encoding, "deflate"))
  3437. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3438. &plen, 0, &was_trunc);
  3439. else
  3440. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3441. &plen, 1, &was_trunc);
  3442. if (zr != 0) {
  3443. s_copy(err, "compressed response is corrupt", errcap);
  3444. return -1;
  3445. }
  3446. *truncated = w->m.trunc || was_trunc;
  3447. return (int)plen;
  3448. }
  3449. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3450. if (rv < 0) {
  3451. s_copy(err, "empty response", errcap);
  3452. return -1;
  3453. }
  3454. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3455. return rv;
  3456. }
  3457. static void fetch_worker_release(struct fetch_worker *w)
  3458. {
  3459. u_syscall1(SYS_UNLINK, (int)w->done);
  3460. u_syscall1(SYS_UNLINK, (int)w->meta);
  3461. u_syscall1(SYS_UNLINK, (int)w->body);
  3462. u_syscall1(SYS_UNLINK, (int)w->post);
  3463. u_syscall1(SYS_UNLINK, (int)w->px);
  3464. u_syscall1(SYS_UNLINK, (int)w->req);
  3465. w->busy = 0;
  3466. w->ready = 0;
  3467. w->image_job = 0;
  3468. w->dec_w = 0;
  3469. w->dec_h = 0;
  3470. w->dec_retried = 0;
  3471. }
  3472. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3473. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3474. unsigned int errcap)
  3475. {
  3476. for (;;) {
  3477. int rv;
  3478. if (!fetch_wait_passive)
  3479. worker_wait_ui();
  3480. if (cancel_fetch || pending_action) {
  3481. fetch_workers_cancel_busy();
  3482. return FETCH_ABORT;
  3483. }
  3484. rv = fetch_worker_poll(w, err, errcap);
  3485. if (rv != 0)
  3486. return rv == 1 ? 0 : -1;
  3487. u_sleep_ms(10);
  3488. }
  3489. }
  3490. static int fetch_remote(const char *url, unsigned int cap,
  3491. const char *post, unsigned int post_len,
  3492. unsigned char *plain, unsigned int plaincap,
  3493. unsigned char *comp, unsigned int compcap,
  3494. struct fetch_meta *m, int *truncated,
  3495. char *err, unsigned int errcap)
  3496. {
  3497. struct fetch_worker *w = fetch_worker_alloc_fg();
  3498. int rv;
  3499. fetch_last_error = 0;
  3500. if (!w) {
  3501. s_copy(err, "network busy", errcap);
  3502. return -1;
  3503. }
  3504. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3505. err, errcap) != 0) {
  3506. fetch_worker_release(w);
  3507. return -1;
  3508. }
  3509. rv = fetch_worker_wait(w, err, errcap);
  3510. if (rv == FETCH_ABORT) {
  3511. fetch_worker_release(w);
  3512. return FETCH_ABORT;
  3513. }
  3514. if (rv != 0) {
  3515. fetch_last_error = w->m.error;
  3516. fetch_worker_release(w);
  3517. return -1;
  3518. }
  3519. *m = w->m;
  3520. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3521. truncated, err, errcap);
  3522. fetch_worker_release(w);
  3523. if (rv >= 0 && (cancel_fetch || pending_action))
  3524. return FETCH_ABORT;
  3525. return rv;
  3526. }
  3527. static int fetch_worker_status(const struct fetch_worker *w)
  3528. {
  3529. return w->m.status;
  3530. }
  3531. /* fetch()/XHR through a helper: one request, the status and body come back
  3532. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3533. static int js_worker_http(const char *method, const char *url,
  3534. const char *ctype, const char *body,
  3535. unsigned int body_len, struct js_http_resp *r,
  3536. char *err, int errcap)
  3537. {
  3538. struct fetch_worker *w = fetch_worker_alloc_fg();
  3539. unsigned char *plain;
  3540. int rv, tr = 0;
  3541. if (!w) {
  3542. s_copy(err, "network busy", (unsigned int)errcap);
  3543. return -1;
  3544. }
  3545. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3546. body_len, 0, 0, 0, 0, err,
  3547. (unsigned int)errcap) != 0) {
  3548. fetch_worker_release(w);
  3549. return -1;
  3550. }
  3551. fetch_wait_passive++;
  3552. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3553. fetch_wait_passive--;
  3554. if (rv != 0) {
  3555. if (rv == FETCH_ABORT)
  3556. s_copy(err, "page is navigating", (unsigned int)errcap);
  3557. fetch_worker_release(w);
  3558. return -1;
  3559. }
  3560. r->status = w->m.status;
  3561. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3562. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3563. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3564. if (!plain) {
  3565. fetch_worker_release(w);
  3566. s_copy(err, "out of memory", (unsigned int)errcap);
  3567. return -1;
  3568. }
  3569. if (w->m.len == 0) {
  3570. rv = 0; /* 204, an empty 200: no body file */
  3571. } else {
  3572. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3573. image_io_buf, BR_PAGE_COMP_MAX,
  3574. &tr, err, (unsigned int)errcap);
  3575. }
  3576. fetch_worker_release(w);
  3577. if (rv < 0) {
  3578. free(plain);
  3579. return -1;
  3580. }
  3581. plain[rv] = '\0';
  3582. r->body = (char *)plain;
  3583. r->len = (unsigned int)rv;
  3584. return 0;
  3585. }
  3586. /* ---- HTTP / file fetch ---- */
  3587. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3588. unsigned int *outlen, int *is_local, char *ctype,
  3589. unsigned int ctcap, char *final, unsigned int finalcap,
  3590. char *err, unsigned int errcap, int *truncated,
  3591. const char *post, unsigned int post_len)
  3592. {
  3593. unsigned char *buf;
  3594. unsigned int len;
  3595. int tr = 0;
  3596. int rv;
  3597. *out = 0;
  3598. *outlen = 0;
  3599. *truncated = 0;
  3600. if (final && finalcap)
  3601. final[0] = '\0';
  3602. if (ctype && ctcap)
  3603. ctype[0] = '\0';
  3604. if (url[0] == '/') {
  3605. char pathbuf[BR_URL_MAX];
  3606. const char *open_url = url;
  3607. unsigned int i = 0;
  3608. /* A local form GET keeps ?query in the address bar but the
  3609. * file lookup uses the path alone, like a real browser. */
  3610. while (url[i] && url[i] != '?' && url[i] != '#')
  3611. i++;
  3612. if (url[i]) {
  3613. s_copy(pathbuf, url, i + 1);
  3614. open_url = pathbuf;
  3615. }
  3616. buf = (unsigned char *)malloc(cap);
  3617. if (!buf) {
  3618. s_copy(err, "out of memory", errcap);
  3619. return -1;
  3620. }
  3621. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3622. if (rv < 0) {
  3623. free(buf);
  3624. s_copy(err, "file not found", errcap);
  3625. return -1;
  3626. }
  3627. *out = buf;
  3628. *outlen = (unsigned int)rv;
  3629. *is_local = 1;
  3630. if (ctype)
  3631. s_copy(ctype, "text/html", ctcap);
  3632. if (final)
  3633. s_copy(final, url, finalcap);
  3634. if ((unsigned int)rv == cap)
  3635. *truncated = 1;
  3636. return 0;
  3637. }
  3638. buf = (unsigned char *)malloc(cap);
  3639. if (!buf) {
  3640. s_copy(err, "out of memory", errcap);
  3641. return -1;
  3642. }
  3643. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3644. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3645. if (rv == FETCH_ABORT) {
  3646. free(buf);
  3647. return FETCH_ABORT;
  3648. }
  3649. if (rv < 0) {
  3650. free(buf);
  3651. return -1;
  3652. }
  3653. len = (unsigned int)rv;
  3654. if (len == 0) {
  3655. free(buf);
  3656. s_copy(err, "empty response", errcap);
  3657. return -1;
  3658. }
  3659. if (ctype)
  3660. s_copy(ctype, fetch_meta.ctype, ctcap);
  3661. if (final && fetch_meta.final[0])
  3662. s_copy(final, fetch_meta.final, finalcap);
  3663. *is_local = 0;
  3664. *out = buf;
  3665. *outlen = len;
  3666. *truncated = tr;
  3667. return 0;
  3668. }
  3669. static unsigned int css_cache_hash(const char *s);
  3670. /* Remote fonts are cached under /share for the current boot like the
  3671. * stylesheets, as the raw response (a WOFF stays compressed). */
  3672. static int font_cache_count;
  3673. static void font_cache_path(const char *url, char *out, unsigned int cap)
  3674. {
  3675. unsigned int n = 0;
  3676. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  3677. s_append_dec(out, &n, css_cache_hash(url), cap);
  3678. }
  3679. static void font_cache_init(void)
  3680. {
  3681. struct sys_dirent d;
  3682. int i;
  3683. font_cache_count = 0;
  3684. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3685. (int)&d) == 1; i++)
  3686. if (starts_with(d.name, FONT_CACHE_PREFIX))
  3687. font_cache_count++;
  3688. }
  3689. /* Read one font file (local path, boot cache or network) into a fresh
  3690. * malloc'ed buffer. Returns its length, or -1. */
  3691. static int font_fetch(const char *abs, unsigned char **out)
  3692. {
  3693. unsigned char *buf;
  3694. char path[96];
  3695. int rv;
  3696. *out = 0;
  3697. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  3698. if (!buf)
  3699. return -1;
  3700. if (abs[0] == '/') {
  3701. struct sys_stat st;
  3702. /* FAT reads may write past the length: the 512 bytes of
  3703. * slack above cover the final partial sector. */
  3704. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  3705. st.size > UFONT_MAX_FILE) {
  3706. free(buf);
  3707. return -1;
  3708. }
  3709. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  3710. (int)st.size);
  3711. if (rv != (int)st.size) {
  3712. free(buf);
  3713. return -1;
  3714. }
  3715. *out = buf;
  3716. return rv;
  3717. }
  3718. if (!is_http(abs)) {
  3719. free(buf);
  3720. return -1;
  3721. }
  3722. font_cache_path(abs, path, sizeof(path));
  3723. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  3724. (int)UFONT_MAX_FILE);
  3725. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  3726. *out = buf;
  3727. return rv;
  3728. }
  3729. {
  3730. char err[64];
  3731. int tr = 0;
  3732. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3733. UFONT_MAX_FILE, image_io_buf,
  3734. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  3735. sizeof(err));
  3736. /* An error page is not a font: never parse or cache it. */
  3737. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  3738. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  3739. rv = 0;
  3740. }
  3741. if (rv <= 0 || tr) {
  3742. u_puts("[font] failed: ");
  3743. u_puts(abs);
  3744. u_puts(rv <= 0 ? " " : " truncated ");
  3745. u_puts(rv <= 0 ? err : "");
  3746. u_putc('\n');
  3747. free(buf);
  3748. return -1;
  3749. }
  3750. }
  3751. if (font_cache_count < FONT_CACHE_MAX &&
  3752. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  3753. font_cache_count++;
  3754. *out = buf;
  3755. return rv;
  3756. }
  3757. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  3758. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  3759. static struct ufont_face *font_open_entry(int id)
  3760. {
  3761. const char *url = br_font_face_url(id);
  3762. const char *base = br_font_face_base(id);
  3763. char abs[BR_URL_MAX];
  3764. unsigned char *buf, *sfnt;
  3765. unsigned int slen = 0;
  3766. struct ufont_face *f = 0;
  3767. const char *why = 0;
  3768. int n;
  3769. if (!url || !url[0] ||
  3770. resolve_link(base && base[0] ? base : page_url, url, abs,
  3771. sizeof(abs)) != 0)
  3772. return 0;
  3773. n = font_fetch(abs, &buf);
  3774. if (n <= 0)
  3775. return 0;
  3776. sfnt = buf;
  3777. slen = (unsigned int)n;
  3778. if (ufont_is_woff2(buf, slen)) {
  3779. why = "WOFF2 not supported";
  3780. } else if (ufont_is_woff(buf, slen)) {
  3781. sfnt = ufont_woff_decode(buf, slen, &slen);
  3782. if (!sfnt)
  3783. why = "bad WOFF";
  3784. }
  3785. if (!why) {
  3786. f = ufont_face_open_mem(sfnt, slen);
  3787. if (!f)
  3788. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  3789. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  3790. "CFF outlines not supported" :
  3791. "not a TrueType font or arena full";
  3792. }
  3793. if (sfnt && sfnt != buf)
  3794. free(sfnt);
  3795. free(buf);
  3796. u_puts(f ? "[font] loaded " : "[font] skipped ");
  3797. u_puts(br_font_face_family(id));
  3798. u_puts(": ");
  3799. u_puts(abs);
  3800. if (why) {
  3801. u_puts(" (");
  3802. u_puts(why);
  3803. u_putc(')');
  3804. }
  3805. u_putc('\n');
  3806. return f;
  3807. }
  3808. /* Distance of a face from the requested weight: 0 inside its range. A
  3809. * bold request prefers heavier faces and a normal one lighter faces, as
  3810. * the CSS font-matching steps do. */
  3811. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  3812. unsigned int want)
  3813. {
  3814. if (want >= fi->wmin && want <= fi->wmax)
  3815. return 0;
  3816. if (want > fi->wmax)
  3817. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  3818. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  3819. }
  3820. /* Load the @font-face entries a font-family declaration named: per family
  3821. * the regular face first, then bold, italic and the rest, so a full arena
  3822. * drops the least common variants. Then precompute, for every family and
  3823. * (bold, italic) combination, the loaded face CSS font matching picks;
  3824. * layout reads only that table. A family with no loaded face keeps
  3825. * font_pick 0, and its text uses the built-in set. */
  3826. static void load_font_faces(void)
  3827. {
  3828. int n = br_font_face_count(), pass, id;
  3829. memset(font_faces, 0, sizeof(font_faces));
  3830. memset(font_pick, 0, sizeof(font_pick));
  3831. if (n > BR_MAX_FACES)
  3832. n = BR_MAX_FACES;
  3833. for (pass = 0; pass < 4; pass++) {
  3834. for (id = 1; id <= n; id++) {
  3835. struct br_font_face_info fi;
  3836. int cls;
  3837. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  3838. continue;
  3839. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  3840. cls = 0;
  3841. else if (!fi.italic && fi.wmin <= 700 &&
  3842. fi.wmax >= 700)
  3843. cls = 1;
  3844. else if (fi.italic && fi.wmin <= 400 &&
  3845. fi.wmax >= 400)
  3846. cls = 2;
  3847. else
  3848. cls = 3;
  3849. if (cls == pass)
  3850. font_faces[id - 1] = font_open_entry(id);
  3851. }
  3852. }
  3853. for (id = 1; id <= n; id++) {
  3854. struct br_font_face_info fam;
  3855. int combo;
  3856. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  3857. continue;
  3858. for (combo = 0; combo < 4; combo++) {
  3859. unsigned int want = (combo & 2) ? 700u : 400u;
  3860. int italic = combo & 1, k, best = 0;
  3861. unsigned int best_score = 0;
  3862. for (k = 1; k <= n; k++) {
  3863. struct br_font_face_info fi;
  3864. unsigned int score;
  3865. if (!font_faces[k - 1] ||
  3866. br_font_face_info(k, &fi) != 0 ||
  3867. fi.family_id != id)
  3868. continue;
  3869. score = font_weight_dist(&fi, want) +
  3870. ((fi.italic != 0) != (italic != 0) ?
  3871. 100000u : 0u);
  3872. if (!best || score < best_score) {
  3873. best = k;
  3874. best_score = score;
  3875. }
  3876. }
  3877. font_pick[id - 1][combo] = (unsigned char)best;
  3878. }
  3879. }
  3880. }
  3881. /* Remote scripts are cached under /share for the current boot, like the
  3882. * stylesheet cache, so reloads and later visits skip the network. */
  3883. static int script_cache_count;
  3884. static unsigned int script_cache_hash(const char *s)
  3885. {
  3886. unsigned int h = 2166136261u;
  3887. while (*s) {
  3888. h ^= (unsigned char)*s++;
  3889. h *= 16777619u;
  3890. }
  3891. return h;
  3892. }
  3893. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3894. {
  3895. unsigned int n = 0;
  3896. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3897. s_append_dec(out, &n, script_cache_hash(url), cap);
  3898. }
  3899. static void script_cache_clear(void)
  3900. {
  3901. struct sys_dirent d;
  3902. char path[96];
  3903. for (;;) {
  3904. int i, found = 0;
  3905. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3906. (int)&d) == 1; i++) {
  3907. unsigned int n = 0;
  3908. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3909. continue;
  3910. s_append(path, &n, "/share/", sizeof(path));
  3911. s_append(path, &n, d.name, sizeof(path));
  3912. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3913. return;
  3914. found = 1;
  3915. break;
  3916. }
  3917. if (!found)
  3918. break;
  3919. }
  3920. script_cache_count = 0;
  3921. }
  3922. static void script_cache_init(void)
  3923. {
  3924. struct sys_dirent d;
  3925. int i, count = 0;
  3926. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3927. (int)&d) == 1; i++)
  3928. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3929. count++;
  3930. if (count >= SCRIPT_CACHE_MAX) {
  3931. script_cache_clear();
  3932. return;
  3933. }
  3934. script_cache_count = count;
  3935. }
  3936. static int script_cache_get(const char *url, unsigned char **out,
  3937. unsigned int *outlen)
  3938. {
  3939. char path[96];
  3940. struct sys_stat st;
  3941. unsigned char *buf;
  3942. int rn;
  3943. script_cache_path(url, path, sizeof(path));
  3944. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3945. st.size >= SCRIPT_CACHE_FILE_MAX)
  3946. return 0;
  3947. buf = (unsigned char *)malloc(st.size + 1);
  3948. if (!buf)
  3949. return 0;
  3950. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3951. if (rn != (int)st.size) {
  3952. free(buf);
  3953. return 0;
  3954. }
  3955. buf[st.size] = '\0';
  3956. *out = buf;
  3957. *outlen = st.size;
  3958. return 1;
  3959. }
  3960. static void script_cache_put(const char *url, const unsigned char *data,
  3961. unsigned int len)
  3962. {
  3963. char path[96];
  3964. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3965. len >= SCRIPT_CACHE_FILE_MAX)
  3966. return;
  3967. script_cache_path(url, path, sizeof(path));
  3968. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3969. (int)len) >= 0)
  3970. script_cache_count++;
  3971. }
  3972. static int script_cache_has(const char *url)
  3973. {
  3974. char path[96];
  3975. struct sys_stat st;
  3976. script_cache_path(url, path, sizeof(path));
  3977. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3978. st.size < SCRIPT_CACHE_FILE_MAX;
  3979. }
  3980. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3981. static int fetch_script_text(const char *url, unsigned char **out,
  3982. unsigned int *outlen, char *err,
  3983. unsigned int errcap)
  3984. {
  3985. unsigned char *buf;
  3986. unsigned int len;
  3987. int local, truncated = 0;
  3988. char ctype[64], final[BR_URL_MAX];
  3989. int rv;
  3990. *out = 0;
  3991. *outlen = 0;
  3992. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3993. return 0;
  3994. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3995. sizeof(ctype), final, sizeof(final), err, errcap,
  3996. &truncated, 0, 0);
  3997. if (rv != 0)
  3998. return rv;
  3999. if (truncated || len >= BR_SCRIPT_MAX) {
  4000. free(buf);
  4001. s_copy(err, "script is too large", errcap);
  4002. return -1;
  4003. }
  4004. buf[len] = '\0';
  4005. if (!local)
  4006. script_cache_put(url, buf, len);
  4007. *out = buf;
  4008. *outlen = len;
  4009. return 0;
  4010. }
  4011. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  4012. * the heap, so images must not allocate their file body from it as well. */
  4013. static int fetch_image(const char *url, unsigned int cap,
  4014. unsigned char **out, unsigned int *outlen,
  4015. char *err, unsigned int errcap)
  4016. {
  4017. unsigned int len;
  4018. int tr = 0;
  4019. int rv;
  4020. *out = 0;
  4021. *outlen = 0;
  4022. if (cap > BR_IMG_FILE_MAX)
  4023. cap = BR_IMG_FILE_MAX;
  4024. if (url[0] == '/') {
  4025. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  4026. (int)cap);
  4027. if (rv < 0) {
  4028. s_copy(err, "file not found", errcap);
  4029. return -1;
  4030. }
  4031. *out = image_file_buf;
  4032. *outlen = (unsigned int)rv;
  4033. return 0;
  4034. }
  4035. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  4036. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4037. if (rv == FETCH_ABORT)
  4038. return FETCH_ABORT;
  4039. if (rv < 0)
  4040. return -1;
  4041. len = (unsigned int)rv;
  4042. if (len == 0) {
  4043. s_copy(err, "empty image", errcap);
  4044. return -1;
  4045. }
  4046. *out = image_file_buf;
  4047. *outlen = len;
  4048. return 0;
  4049. }
  4050. /* Remote stylesheets are immutable enough for the current boot: keep
  4051. * successful responses under /share so a reload, a second visit or a fresh
  4052. * browser launch does not fetch the same five sheets over the network again.
  4053. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4054. static int css_cache_count;
  4055. static unsigned int css_cache_hash(const char *s)
  4056. {
  4057. unsigned int h = 2166136261u;
  4058. while (*s) {
  4059. h ^= (unsigned char)*s++;
  4060. h *= 16777619u;
  4061. }
  4062. return h;
  4063. }
  4064. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4065. {
  4066. unsigned int n = 0;
  4067. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4068. s_append_dec(out, &n, css_cache_hash(url), cap);
  4069. }
  4070. static void css_cache_clear(void)
  4071. {
  4072. struct sys_dirent d;
  4073. char path[96];
  4074. for (;;) {
  4075. int i, found = 0;
  4076. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4077. (int)&d) == 1; i++) {
  4078. unsigned int n = 0;
  4079. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4080. continue;
  4081. s_append(path, &n, "/share/", sizeof(path));
  4082. s_append(path, &n, d.name, sizeof(path));
  4083. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4084. return;
  4085. found = 1;
  4086. break;
  4087. }
  4088. if (!found)
  4089. break;
  4090. }
  4091. css_cache_count = 0;
  4092. }
  4093. static void css_cache_init(void)
  4094. {
  4095. struct sys_dirent d;
  4096. int i, count = 0;
  4097. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4098. (int)&d) == 1; i++)
  4099. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4100. count++;
  4101. if (count >= CSS_CACHE_MAX) {
  4102. css_cache_clear();
  4103. return;
  4104. }
  4105. css_cache_count = count;
  4106. }
  4107. static int css_cache_get(const char *url, unsigned char **out,
  4108. unsigned int *outlen)
  4109. {
  4110. char path[96];
  4111. int rn;
  4112. css_cache_path(url, path, sizeof(path));
  4113. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4114. (int)CSS_CACHE_FILE_MAX);
  4115. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4116. return 0;
  4117. *out = image_io_buf;
  4118. *outlen = (unsigned int)rn;
  4119. return 1;
  4120. }
  4121. static void css_cache_put(const char *url, const unsigned char *data,
  4122. unsigned int len)
  4123. {
  4124. char path[96];
  4125. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4126. len >= CSS_CACHE_FILE_MAX)
  4127. return;
  4128. css_cache_path(url, path, sizeof(path));
  4129. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4130. (int)len) >= 0)
  4131. css_cache_count++;
  4132. }
  4133. static int css_cache_has(const char *url)
  4134. {
  4135. char path[96];
  4136. struct sys_stat st;
  4137. css_cache_path(url, path, sizeof(path));
  4138. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4139. st.size < CSS_CACHE_FILE_MAX;
  4140. }
  4141. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4142. * immediately, so it does not need the page heap; this leaves the heap for
  4143. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4144. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4145. char *err, unsigned int errcap)
  4146. {
  4147. unsigned int len;
  4148. int tr = 0;
  4149. int rv;
  4150. *out = 0;
  4151. *outlen = 0;
  4152. if (url[0] == '/') {
  4153. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4154. (int)BR_CSS_MAX);
  4155. if (rv < 0) {
  4156. s_copy(err, "stylesheet not found", errcap);
  4157. return -1;
  4158. }
  4159. *out = image_io_buf;
  4160. *outlen = (unsigned int)rv;
  4161. return 0;
  4162. }
  4163. if (css_cache_get(url, out, outlen))
  4164. return 0;
  4165. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4166. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4167. &fetch_meta, &tr, err, errcap);
  4168. if (rv == FETCH_ABORT)
  4169. return FETCH_ABORT;
  4170. if (rv < 0)
  4171. return -1;
  4172. len = (unsigned int)rv;
  4173. if (len == 0) {
  4174. s_copy(err, "empty stylesheet", errcap);
  4175. return -1;
  4176. }
  4177. *out = image_io_buf;
  4178. *outlen = len;
  4179. css_cache_put(url, image_io_buf, len);
  4180. return 0;
  4181. }
  4182. static void redraw_now(void);
  4183. static char error_page[1024];
  4184. static void show_error(const char *title, const char *detail)
  4185. {
  4186. char *page = error_page;
  4187. unsigned int n = 0;
  4188. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4189. s_append(page, &n, title, sizeof(error_page));
  4190. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4191. {
  4192. const char *p = detail;
  4193. while (*p && n + 1 < sizeof(error_page)) {
  4194. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4195. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4196. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4197. else page[n++] = *p;
  4198. p++;
  4199. }
  4200. }
  4201. page[n] = '\0';
  4202. s_append(page, &n, "</p><p>", sizeof(error_page));
  4203. s_append(page, &n, page_url, sizeof(error_page));
  4204. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4205. sizeof(error_page));
  4206. br_parse(&doc, page, n);
  4207. layout_valid = 0;
  4208. preload_active = 0;
  4209. preload_pending = 0;
  4210. preload_wait = 0;
  4211. fetch_workers_cancel_busy();
  4212. s_copy(page_title, title, sizeof(page_title));
  4213. page_loading = 0;
  4214. set_status(title, 1, 0);
  4215. ngui_invalidate(&ui);
  4216. }
  4217. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4218. unsigned int node)
  4219. {
  4220. if (image_count >= BR_MAX_IMAGES)
  4221. return -1;
  4222. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4223. return -1;
  4224. doc.nodes[node].img_index = 0;
  4225. image_count = 1;
  4226. return 0;
  4227. }
  4228. static int ancestor_is(unsigned int node, unsigned int tag)
  4229. {
  4230. unsigned int p = doc.nodes[node].parent;
  4231. while (p) {
  4232. if (doc.nodes[p].tag == tag)
  4233. return 1;
  4234. p = doc.nodes[p].parent;
  4235. }
  4236. return 0;
  4237. }
  4238. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4239. * parallel but parsed in document order, so the cascade is unchanged. */
  4240. static int load_stylesheets(void)
  4241. {
  4242. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4243. static unsigned char remote[BR_MAX_SHEETS];
  4244. struct fetch_worker *slot[BR_MAX_SHEETS];
  4245. unsigned int i, n = 0, next = 0, k;
  4246. char err[64];
  4247. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4248. struct br_node *nd = &doc.nodes[i];
  4249. const char *rel, *href;
  4250. char url[BR_URL_MAX];
  4251. int dup = 0;
  4252. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4253. continue;
  4254. rel = br_rel(&doc, i);
  4255. if (!contains_ci(rel, "stylesheet"))
  4256. continue;
  4257. href = br_href(&doc, i);
  4258. if (!href[0])
  4259. continue;
  4260. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4261. continue;
  4262. for (k = 0; k < n; k++)
  4263. if (s_eq(urls[k], url)) {
  4264. dup = 1;
  4265. break;
  4266. }
  4267. if (dup)
  4268. continue;
  4269. s_copy(urls[n], url, BR_URL_MAX);
  4270. remote[n] = url[0] != '/' && !css_cache_has(url);
  4271. n++;
  4272. }
  4273. for (i = 0; i < BR_MAX_SHEETS; i++)
  4274. slot[i] = 0;
  4275. /* Start as many remote sheets as there are free workers. */
  4276. for (; next < n; next++) {
  4277. struct fetch_worker *w;
  4278. if (!remote[next])
  4279. continue;
  4280. w = fetch_worker_alloc();
  4281. if (!w)
  4282. break;
  4283. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4284. err, sizeof(err)) != 0) {
  4285. fetch_worker_release(w);
  4286. remote[next] = 0;
  4287. continue;
  4288. }
  4289. slot[next] = w;
  4290. }
  4291. for (i = 0; i < n; i++) {
  4292. unsigned char *data = 0;
  4293. unsigned int len = 0;
  4294. int rv;
  4295. if (!remote[i]) {
  4296. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4297. if (rv == FETCH_ABORT) {
  4298. fetch_workers_stop_all();
  4299. return FETCH_ABORT;
  4300. }
  4301. if (rv != 0 || !len)
  4302. continue;
  4303. } else {
  4304. struct fetch_worker *w = slot[i];
  4305. int tr = 0;
  4306. if (!w) {
  4307. w = fetch_worker_alloc();
  4308. if (!w) {
  4309. rv = -1;
  4310. goto css_failed;
  4311. }
  4312. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4313. 0, 0, 0, 0, err,
  4314. sizeof(err)) != 0) {
  4315. fetch_worker_release(w);
  4316. remote[i] = 0;
  4317. if (i == next)
  4318. next++;
  4319. continue;
  4320. }
  4321. slot[i] = w;
  4322. if (i == next)
  4323. next++;
  4324. }
  4325. rv = fetch_worker_wait(w, err, sizeof(err));
  4326. if (rv == FETCH_ABORT) {
  4327. fetch_workers_stop_all();
  4328. return FETCH_ABORT;
  4329. }
  4330. if (rv == 0)
  4331. rv = fetch_worker_read_body(w, image_io_buf,
  4332. BR_CSS_MAX,
  4333. image_io_buf + BR_CSS_MAX,
  4334. BR_CSS_COMP_MAX, &tr,
  4335. err, sizeof(err));
  4336. else
  4337. rv = -1;
  4338. fetch_worker_release(w);
  4339. slot[i] = 0;
  4340. /* Refill the worker window before parsing this sheet. */
  4341. for (; next < n; next++) {
  4342. struct fetch_worker *nw;
  4343. if (!remote[next])
  4344. continue;
  4345. nw = fetch_worker_alloc();
  4346. if (!nw)
  4347. break;
  4348. if (fetch_worker_submit(nw, urls[next],
  4349. BR_CSS_MAX, 0, 0, 0, 0,
  4350. err, sizeof(err)) != 0) {
  4351. fetch_worker_release(nw);
  4352. remote[next] = 0;
  4353. continue;
  4354. }
  4355. slot[next] = nw;
  4356. }
  4357. css_failed:
  4358. if (rv <= 0) {
  4359. /* One synchronous retry: a dropped sheet leaves the
  4360. * whole page unstyled (seen intermittently on
  4361. * arstechnica's CDN). */
  4362. u_puts("[css] retry ");
  4363. u_puts(urls[i]);
  4364. u_puts(": ");
  4365. u_puts(err[0] ? err : "no worker/empty body");
  4366. u_putc('\n');
  4367. err[0] = '\0';
  4368. rv = fetch_css(urls[i], &data, &len, err,
  4369. sizeof(err));
  4370. if (rv == FETCH_ABORT) {
  4371. fetch_workers_stop_all();
  4372. return FETCH_ABORT;
  4373. }
  4374. if (rv != 0 || !len) {
  4375. u_puts("[css] failed: ");
  4376. u_puts(err);
  4377. u_putc('\n');
  4378. continue;
  4379. }
  4380. } else {
  4381. len = (unsigned int)rv;
  4382. data = image_io_buf;
  4383. css_cache_put(urls[i], data, len);
  4384. }
  4385. }
  4386. if (len) {
  4387. br_set_font_base(urls[i]);
  4388. br_parse_css_text(&doc, (const char *)data, len);
  4389. }
  4390. }
  4391. br_set_font_base(page_url);
  4392. br_parse_inline_css(&doc);
  4393. load_font_faces();
  4394. br_reset_styles(&doc);
  4395. layout_valid = 0;
  4396. return 0;
  4397. }
  4398. static void preload_begin(void)
  4399. {
  4400. preload_active = 1;
  4401. preload_pending = 0;
  4402. preload_wait = 1;
  4403. preload_max_jobs = FETCH_WORKERS;
  4404. preload_node = 0;
  4405. preload_loaded = 0;
  4406. preload_scroll = 0;
  4407. img_stat_start = u_ticks_ms();
  4408. img_stat_wall = 0;
  4409. img_stat_net = img_stat_open = img_stat_first = 0;
  4410. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4411. img_stat_paint = img_stat_reflow = 0;
  4412. img_stat_bytes = 0;
  4413. img_stat_n = 0;
  4414. img_stat_log_len = 0;
  4415. if (img_stat_log[0])
  4416. img_stat_log[0] = '\0';
  4417. img_repaint_ms = 0;
  4418. img_repaint_pending = 0;
  4419. }
  4420. /* Styles are computed top-down during layout, but images inside a hidden
  4421. * menu/carousel are never visited and keep img_top == 0. Without this check
  4422. * the preloader walks the DOM in node order and spends the whole image
  4423. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4424. static struct br_style base_style(void);
  4425. static int node_hidden(unsigned int node)
  4426. {
  4427. unsigned int path[32], n = 0, p = node, i;
  4428. struct br_style st, parent;
  4429. while (p && n < sizeof(path) / sizeof(path[0])) {
  4430. path[n++] = p;
  4431. p = doc.nodes[p].parent;
  4432. }
  4433. /* Node 0 is the <html> element when the page starts with one: it
  4434. * is an ancestor too. Styles are cached per node, so the chain
  4435. * must start from the same base as style_for_node(); seeding it
  4436. * with a zeroed style left <body> cached with black text and no
  4437. * line-height once an image job ran (docs.cloudron.io). */
  4438. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4439. doc.nodes[0].type == BR_NODE_ELEM &&
  4440. doc.nodes[0].tag == BR_TAG_HTML &&
  4441. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4442. path[n++] = 0;
  4443. parent = base_style();
  4444. for (i = n; i > 0; i--) {
  4445. br_style_for(&doc, path[i - 1], &parent, &st);
  4446. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4447. st.opacity_hidden)
  4448. return 1;
  4449. parent = st;
  4450. }
  4451. return 0;
  4452. }
  4453. static struct br_style base_style(void);
  4454. static int style_width_px(const struct br_style *st, int base);
  4455. static int style_height_px(const struct br_style *st, int base);
  4456. static void style_for_node(unsigned int node, struct br_style *out)
  4457. {
  4458. unsigned int p = doc.nodes[node].parent;
  4459. struct br_style parent;
  4460. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4461. * starts with one (see root_style()), but also the parent field of a
  4462. * detached subtree root. */
  4463. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4464. doc.nodes[0].tag == BR_TAG_HTML &&
  4465. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4466. style_for_node(p, &parent);
  4467. br_style_for(&doc, node, &parent, out);
  4468. } else {
  4469. parent = base_style();
  4470. br_style_for(&doc, node, &parent, out);
  4471. }
  4472. }
  4473. /* ---- parallel image preloading ---- *
  4474. *
  4475. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4476. * preload_step() only starts jobs and harvests completed ones; the browser
  4477. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4478. */
  4479. static int preload_active_jobs(void)
  4480. {
  4481. int i, n = 0;
  4482. for (i = 0; i < FETCH_WORKERS; i++)
  4483. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4484. n++;
  4485. return n;
  4486. }
  4487. static void preload_job_error(struct fetch_worker *w)
  4488. {
  4489. if (w->node < doc.nnode) {
  4490. if (w->bg)
  4491. doc.nodes[w->node].bg_img_index = -2;
  4492. else
  4493. doc.nodes[w->node].img_index = -2;
  4494. image_repaint();
  4495. }
  4496. }
  4497. /* Is the image's box anywhere near the visible page? A decode below the
  4498. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4499. * so it does not need a repaint. top/h come from the last layout; treat an
  4500. * unknown box as visible to stay safe. */
  4501. static int image_preload_visible(unsigned int node, int bg)
  4502. {
  4503. int top, h, scroll;
  4504. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4505. return 1;
  4506. if (bg) {
  4507. top = (int)block_top[node];
  4508. h = (int)block_h[node];
  4509. } else {
  4510. top = (int)img_top[node];
  4511. h = (int)img_h[node];
  4512. }
  4513. if (!top && !h)
  4514. return 1;
  4515. scroll = (int)page_scroll.offset;
  4516. if (top > scroll + page_rect.h + 160)
  4517. return 0;
  4518. if (top + h + 160 < scroll)
  4519. return 0;
  4520. return 1;
  4521. }
  4522. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4523. * decode_image_data applies one scale to both axes so the aspect ratio is
  4524. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4525. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4526. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4527. {
  4528. struct br_style st;
  4529. struct br_node *nd;
  4530. unsigned int p;
  4531. int cw, w = 0, h = 0;
  4532. *out_w = *out_h = 0;
  4533. if (node >= doc.nnode)
  4534. return;
  4535. nd = &doc.nodes[node];
  4536. style_for_node(node, &st);
  4537. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4538. p = doc.nodes[node].parent;
  4539. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4540. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4541. cw = layout_boxes[p].w;
  4542. if (st.width_kind)
  4543. w = style_width_px(&st, cw);
  4544. else if (nd->width_attr)
  4545. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4546. (int)nd->width_attr;
  4547. if (st.height_kind)
  4548. h = style_height_px(&st, cw);
  4549. else if (nd->height_attr)
  4550. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4551. (int)nd->height_attr;
  4552. if (st.max_width_kind) {
  4553. int mw = st.max_width_kind == 3 ?
  4554. cw * st.max_width_calc_pct / 100 +
  4555. st.max_width_calc_px :
  4556. st.max_width_kind == 2 ?
  4557. cw * (int)st.max_width / 100 :
  4558. (int)st.max_width;
  4559. if (mw > 0 && (w == 0 || w > mw))
  4560. w = mw;
  4561. }
  4562. if (st.max_height_kind) {
  4563. int mh = st.max_height_kind == 3 ?
  4564. cw * st.max_height_calc_pct / 100 +
  4565. st.max_height_calc_px :
  4566. st.max_height_kind == 2 ?
  4567. cw * (int)st.max_height / 100 :
  4568. (int)st.max_height;
  4569. if (mh > 0 && (h == 0 || h > mh))
  4570. h = mh;
  4571. }
  4572. if (w > BR_IMG_LAYOUT_W)
  4573. w = BR_IMG_LAYOUT_W;
  4574. if (h > 4096)
  4575. h = 4096;
  4576. if (w < 0)
  4577. w = 0;
  4578. if (h < 0)
  4579. h = 0;
  4580. *out_w = w;
  4581. *out_h = h;
  4582. }
  4583. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4584. {
  4585. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4586. * same source reuses it (heise repeats one comment icon 85 times).
  4587. * Backgrounds are scaled to their box and are not shared. */
  4588. images[image_count].url_hash =
  4589. !bg && url ? script_cache_hash(url) | 1u : 0;
  4590. if (bg)
  4591. doc.nodes[node].bg_img_index = (short)image_count;
  4592. else
  4593. doc.nodes[node].img_index = (short)image_count;
  4594. image_count++;
  4595. preload_loaded++;
  4596. /* A background bitmap never changes its box, so keep the (expensive)
  4597. * measured layout and only repaint the pixels. */
  4598. if (bg)
  4599. page_cache_valid = 0;
  4600. else
  4601. layout_valid = 0;
  4602. if (image_preload_visible(node, bg))
  4603. image_repaint();
  4604. }
  4605. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4606. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4607. * on the UI thread instead of a decode. */
  4608. static int preload_store_helper(unsigned int node, int bg,
  4609. unsigned char *px, unsigned int pxlen,
  4610. unsigned int dw, unsigned int dh,
  4611. int alpha, unsigned int nw, unsigned int nh,
  4612. const char *url)
  4613. {
  4614. struct br_image *bi;
  4615. unsigned int npx;
  4616. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4617. dw > 4096 || dh > 4096) {
  4618. free(px);
  4619. return -1;
  4620. }
  4621. npx = dw * dh;
  4622. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4623. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4624. free(px);
  4625. return -1;
  4626. }
  4627. bi = &images[image_count];
  4628. bi->img.format = 0;
  4629. bi->img.w = dw;
  4630. bi->img.h = dh;
  4631. bi->img.px = (unsigned short *)px;
  4632. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4633. bi->img.flags = 0;
  4634. bi->native_w = nw ? (int)nw : (int)dw;
  4635. bi->native_h = nh ? (int)nh : (int)dh;
  4636. bi->state = 1;
  4637. image_pixels += npx;
  4638. preload_accept_image(node, bg, url);
  4639. return 0;
  4640. }
  4641. static void preload_decode(unsigned int node, int bg,
  4642. const unsigned char *data, unsigned int len,
  4643. const char *url)
  4644. {
  4645. int fit_w = 0, fit_h = 0;
  4646. if (image_count >= BR_MAX_IMAGES) {
  4647. if (bg)
  4648. doc.nodes[node].bg_img_index = -2;
  4649. else
  4650. doc.nodes[node].img_index = -2;
  4651. return;
  4652. }
  4653. if (!bg)
  4654. image_fit_size(node, &fit_w, &fit_h);
  4655. if (decode_image_data(data, len, &images[image_count],
  4656. bg && node < BR_MAX_NODES &&
  4657. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4658. bg && node < BR_MAX_NODES &&
  4659. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4660. fit_w, fit_h) == 0) {
  4661. preload_accept_image(node, bg, url);
  4662. } else {
  4663. if (bg)
  4664. doc.nodes[node].bg_img_index = -2;
  4665. else
  4666. doc.nodes[node].img_index = -2;
  4667. layout_valid = 0;
  4668. }
  4669. if (image_preload_visible(node, bg))
  4670. image_repaint();
  4671. }
  4672. /* ---- data: URLs ----
  4673. *
  4674. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4675. * (the caller frees them). The payload is percent-decoded, then base64-
  4676. * decoded when the header says so. Infima's menu chevron and many icon
  4677. * fonts' fallbacks are inline SVGs written this way. */
  4678. static int b64_val(int c)
  4679. {
  4680. if (c >= 'A' && c <= 'Z') return c - 'A';
  4681. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4682. if (c >= '0' && c <= '9') return c - '0' + 52;
  4683. if (c == '+' || c == '-') return 62;
  4684. if (c == '/' || c == '_') return 63;
  4685. return -1;
  4686. }
  4687. static int hex_val(int c)
  4688. {
  4689. if (c >= '0' && c <= '9') return c - '0';
  4690. c |= 32;
  4691. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4692. return -1;
  4693. }
  4694. static int data_url_decode(const char *url, unsigned char **out,
  4695. unsigned int *out_len)
  4696. {
  4697. const char *comma, *p;
  4698. unsigned int n = 0, len, i;
  4699. unsigned char *buf;
  4700. int base64 = 0;
  4701. *out = 0;
  4702. *out_len = 0;
  4703. if (!starts_with(url, "data:"))
  4704. return -1;
  4705. comma = url + 5;
  4706. while (*comma && *comma != ',')
  4707. comma++;
  4708. if (!*comma)
  4709. return -1;
  4710. for (p = url + 5; p + 7 <= comma; p++)
  4711. if (!strncmp(p, ";base64", 7))
  4712. base64 = 1;
  4713. len = s_len(comma + 1);
  4714. buf = (unsigned char *)malloc(len + 1);
  4715. if (!buf)
  4716. return -1;
  4717. for (i = 0, p = comma + 1; i < len; i++) {
  4718. int c = (unsigned char)p[i];
  4719. if (c == '%' && i + 2 < len &&
  4720. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4721. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4722. i += 2;
  4723. }
  4724. buf[n++] = (unsigned char)c;
  4725. }
  4726. if (base64) {
  4727. unsigned int acc = 0, o = 0;
  4728. int bits = 0;
  4729. for (i = 0; i < n; i++) {
  4730. int v = b64_val(buf[i]);
  4731. if (v < 0)
  4732. continue; /* padding, whitespace */
  4733. acc = (acc << 6) | (unsigned int)v;
  4734. bits += 6;
  4735. if (bits >= 8) {
  4736. bits -= 8;
  4737. buf[o++] = (unsigned char)(acc >> bits);
  4738. }
  4739. }
  4740. n = o;
  4741. }
  4742. buf[n] = 0;
  4743. *out = buf;
  4744. *out_len = n;
  4745. return 0;
  4746. }
  4747. static unsigned int data_img_key(const char *url, int w, int h)
  4748. {
  4749. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4750. ((unsigned int)h * 40503u)) | 1u;
  4751. }
  4752. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4753. * rasterized at that size), decoding it on first use; -1 on failure.
  4754. * Decoded bitmaps are found again through url_hash, which is distinct
  4755. * from the <img> sharing hash because it mixes in the size. */
  4756. static int data_url_image(const char *url, int w, int h)
  4757. {
  4758. unsigned int key, len;
  4759. unsigned char *data;
  4760. int i;
  4761. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4762. return -1;
  4763. key = data_img_key(url, w, h);
  4764. for (i = 0; i < image_count; i++)
  4765. if (images[i].state == 1 && images[i].url_hash == key)
  4766. return i;
  4767. for (i = 0; i < data_img_nfail; i++)
  4768. if (data_img_fail[i] == key)
  4769. return -1;
  4770. if (image_count < BR_MAX_IMAGES &&
  4771. data_url_decode(url, &data, &len) == 0) {
  4772. int r = decode_image_data(data, len, &images[image_count],
  4773. w, h, w, h);
  4774. free(data);
  4775. if (r == 0) {
  4776. images[image_count].url_hash = key;
  4777. return image_count++;
  4778. }
  4779. }
  4780. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4781. data_img_fail[data_img_nfail++] = key;
  4782. return -1;
  4783. }
  4784. /* A local file image bypasses the helpers: count its decode so a page opened
  4785. * from /share or /data still produces the same timing breakdown. */
  4786. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4787. {
  4788. img_stat_n++;
  4789. img_stat_bytes += bytes;
  4790. img_stat_io += io_ms;
  4791. if (image_count > before) {
  4792. struct br_image *bi = &images[image_count - 1];
  4793. img_stat_dec += img_last_dec_ms;
  4794. img_stat_scale += img_last_scale_ms;
  4795. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4796. unsigned int n = img_stat_log_len;
  4797. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4798. s_append_dec(img_stat_log, &n, bytes,
  4799. sizeof(img_stat_log));
  4800. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4801. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4802. sizeof(img_stat_log));
  4803. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4804. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4805. sizeof(img_stat_log));
  4806. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4807. s_append_dec(img_stat_log, &n,
  4808. (unsigned int)bi->native_w,
  4809. sizeof(img_stat_log));
  4810. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4811. s_append_dec(img_stat_log, &n,
  4812. (unsigned int)bi->native_h,
  4813. sizeof(img_stat_log));
  4814. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4815. s_append_dec(img_stat_log, &n, bi->img.w,
  4816. sizeof(img_stat_log));
  4817. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4818. s_append_dec(img_stat_log, &n, bi->img.h,
  4819. sizeof(img_stat_log));
  4820. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4821. s_append_dec(img_stat_log, &n,
  4822. bi->img.alpha ? 1u : 0u,
  4823. sizeof(img_stat_log));
  4824. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4825. img_stat_log_len = n;
  4826. }
  4827. }
  4828. }
  4829. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4830. static int preload_finish_worker(struct fetch_worker *w)
  4831. {
  4832. char err[64];
  4833. int rv, tr = 0;
  4834. unsigned int t0, io_ms;
  4835. int before;
  4836. int used_px = 0;
  4837. rv = fetch_worker_poll(w, err, sizeof(err));
  4838. if (rv < 0) {
  4839. /* A helper from an older pack does not understand the image
  4840. * decode request; retry once without it and decode in-process. */
  4841. if (w->image_job && w->dec_w && !w->dec_retried &&
  4842. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4843. 0, 0, 0, 0, w->node, w->bg,
  4844. 0, 0, err, sizeof(err)) == 0) {
  4845. w->image_job = 1;
  4846. w->dec_retried = 1;
  4847. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4848. return 0;
  4849. }
  4850. preload_job_error(w);
  4851. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4852. unsigned int n = img_stat_log_len;
  4853. char u[48];
  4854. s_copy(u, w->url, sizeof(u));
  4855. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4856. s_append(img_stat_log, &n, " error\n",
  4857. sizeof(img_stat_log));
  4858. img_stat_log_len = n;
  4859. }
  4860. img_stat_n++;
  4861. fetch_worker_release(w);
  4862. return 1;
  4863. }
  4864. if (rv == 0)
  4865. return 0;
  4866. t0 = u_ticks_ms();
  4867. rv = -1;
  4868. before = image_count;
  4869. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4870. w->m.px_len <= 8u * 1024u * 1024u) {
  4871. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4872. int pr = -1;
  4873. if (px)
  4874. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4875. (int)w->m.px_len);
  4876. if (pr == (int)w->m.px_len) {
  4877. if (preload_store_helper(w->node, w->bg, px,
  4878. w->m.px_len, w->m.dw,
  4879. w->m.dh, (int)w->m.alpha,
  4880. w->m.nw, w->m.nh,
  4881. w->url) == 0) {
  4882. rv = (int)w->m.len;
  4883. img_last_dec_ms = w->m.dec_ms;
  4884. img_last_scale_ms = 0;
  4885. used_px = 1;
  4886. } else {
  4887. px = 0; /* the helper freed it */
  4888. }
  4889. }
  4890. if (px && !(pr == (int)w->m.px_len))
  4891. free(px);
  4892. }
  4893. io_ms = u_ticks_ms() - t0;
  4894. if (rv < 0) {
  4895. t0 = u_ticks_ms();
  4896. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4897. image_comp_buf, BR_IMG_FILE_MAX,
  4898. &tr, err, sizeof(err));
  4899. io_ms += u_ticks_ms() - t0;
  4900. before = image_count;
  4901. if (rv >= 0)
  4902. preload_decode(w->node, w->bg, image_file_buf,
  4903. (unsigned int)rv, w->url);
  4904. else
  4905. preload_job_error(w);
  4906. }
  4907. img_stat_n++;
  4908. img_stat_net += w->m.total_ms;
  4909. img_stat_open += w->m.open_ms;
  4910. img_stat_first += w->m.first_ms;
  4911. img_stat_io += io_ms;
  4912. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4913. img_stat_dec += w->m.dec_ms;
  4914. if (rv >= 0 && !used_px) {
  4915. img_stat_dec += img_last_dec_ms;
  4916. img_stat_scale += img_last_scale_ms;
  4917. }
  4918. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4919. unsigned int n = img_stat_log_len;
  4920. char u[48];
  4921. s_copy(u, w->url, sizeof(u));
  4922. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4923. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4924. s_append_dec(img_stat_log, &n,
  4925. rv > 0 ? (unsigned int)rv : 0,
  4926. sizeof(img_stat_log));
  4927. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4928. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4929. sizeof(img_stat_log));
  4930. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4931. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4932. sizeof(img_stat_log));
  4933. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4934. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4935. sizeof(img_stat_log));
  4936. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4937. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4938. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4939. s_append_dec(img_stat_log, &n,
  4940. rv >= 0 ? img_last_dec_ms : 0,
  4941. sizeof(img_stat_log));
  4942. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4943. s_append_dec(img_stat_log, &n,
  4944. rv >= 0 ? img_last_scale_ms : 0,
  4945. sizeof(img_stat_log));
  4946. if (image_count > before) {
  4947. struct br_image *bi = &images[image_count - 1];
  4948. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4949. s_append_dec(img_stat_log, &n,
  4950. (unsigned int)bi->native_w,
  4951. sizeof(img_stat_log));
  4952. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4953. s_append_dec(img_stat_log, &n,
  4954. (unsigned int)bi->native_h,
  4955. sizeof(img_stat_log));
  4956. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4957. s_append_dec(img_stat_log, &n, bi->img.w,
  4958. sizeof(img_stat_log));
  4959. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4960. s_append_dec(img_stat_log, &n, bi->img.h,
  4961. sizeof(img_stat_log));
  4962. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4963. s_append_dec(img_stat_log, &n,
  4964. bi->img.alpha ? 1u : 0u,
  4965. sizeof(img_stat_log));
  4966. }
  4967. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4968. img_stat_log_len = n;
  4969. }
  4970. fetch_worker_release(w);
  4971. return 1;
  4972. }
  4973. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4974. * the number of jobs started. */
  4975. static int preload_fill_jobs(void)
  4976. {
  4977. int started = 0;
  4978. char err[64];
  4979. while (preload_active && preload_node < doc.nnode) {
  4980. unsigned int i = preload_node;
  4981. struct br_node *nd = &doc.nodes[i];
  4982. const char *src;
  4983. char url[BR_URL_MAX];
  4984. struct fetch_worker *w;
  4985. if (preload_active_jobs() >= preload_max_jobs)
  4986. break;
  4987. if (nd->type != BR_NODE_ELEM) {
  4988. preload_node++;
  4989. continue;
  4990. }
  4991. if (nd->tag != BR_TAG_IMG) {
  4992. if (nd->bg_img_index == -1) {
  4993. struct br_style bs;
  4994. style_for_node(i, &bs);
  4995. if (bs.display != BR_DISPLAY_NONE &&
  4996. !bs.vis_hidden && bs.bg_image) {
  4997. const char *bsrc =
  4998. br_bg_image_url(bs.bg_image - 1);
  4999. /* Lazy like <img>: a background box
  5000. * below the viewport (or not laid
  5001. * out yet) waits for the next scan. */
  5002. if (bsrc[0] &&
  5003. (!layout_boxes[i].valid ||
  5004. block_top[i] >
  5005. (unsigned int)(page_scroll.offset +
  5006. page_rect.h + 160))) {
  5007. preload_pending = 1;
  5008. preload_node++;
  5009. continue;
  5010. }
  5011. if (starts_with(bsrc, "data:")) {
  5012. /* Inline image: decode now,
  5013. * no fetch helper. */
  5014. unsigned char *data;
  5015. unsigned int len;
  5016. preload_node = i + 1;
  5017. if (data_url_decode(bsrc, &data,
  5018. &len) == 0) {
  5019. preload_decode(i, 1, data,
  5020. len, 0);
  5021. free(data);
  5022. } else {
  5023. nd->bg_img_index = -2;
  5024. }
  5025. continue;
  5026. }
  5027. if (bsrc[0] &&
  5028. resolve_link(page_url, bsrc, url,
  5029. sizeof(url)) == 0) {
  5030. if (image_count +
  5031. preload_active_jobs() >=
  5032. BR_MAX_IMAGES) {
  5033. preload_node = doc.nnode;
  5034. break;
  5035. }
  5036. if (url[0] == '/') {
  5037. unsigned char *data = 0;
  5038. unsigned int len = 0;
  5039. unsigned int t0;
  5040. int before;
  5041. preload_node = i + 1;
  5042. before = image_count;
  5043. t0 = u_ticks_ms();
  5044. if (fetch_image(url,
  5045. BR_IMG_FILE_MAX,
  5046. &data, &len,
  5047. err,
  5048. sizeof(err)) == 0) {
  5049. preload_decode(i, 1, data, len, 0);
  5050. img_stat_local(before, len,
  5051. u_ticks_ms() - t0);
  5052. } else {
  5053. nd->bg_img_index = -2;
  5054. }
  5055. continue;
  5056. }
  5057. w = fetch_worker_alloc();
  5058. if (!w)
  5059. return started;
  5060. preload_node = i + 1;
  5061. if (fetch_worker_submit(w, url,
  5062. BR_IMG_FILE_MAX,
  5063. 0, 0, i, 1,
  5064. err,
  5065. sizeof(err)) != 0) {
  5066. nd->bg_img_index = -2;
  5067. fetch_worker_release(w);
  5068. continue;
  5069. }
  5070. w->image_job = 1;
  5071. w->deadline = u_ticks_ms() +
  5072. BR_IMG_JOB_TIMEOUT_MS;
  5073. /* in flight: rescans skip it */
  5074. nd->bg_img_index = -3;
  5075. started++;
  5076. continue;
  5077. }
  5078. }
  5079. nd->bg_img_index = -2;
  5080. }
  5081. preload_node++;
  5082. continue;
  5083. }
  5084. if (nd->img_index != -1) {
  5085. preload_node++;
  5086. continue;
  5087. }
  5088. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5089. preload_node++;
  5090. continue;
  5091. }
  5092. src = br_src(&doc, i);
  5093. if (starts_with(src, "data:")) {
  5094. unsigned char *data;
  5095. unsigned int len;
  5096. preload_node = i + 1;
  5097. if (data_url_decode(src, &data, &len) == 0) {
  5098. preload_decode(i, 0, data, len, 0);
  5099. free(data);
  5100. } else {
  5101. doc.nodes[i].img_index = -2;
  5102. }
  5103. continue;
  5104. }
  5105. if (!src[0]) {
  5106. preload_node++;
  5107. continue;
  5108. }
  5109. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5110. preload_node++;
  5111. continue;
  5112. }
  5113. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5114. preload_node = doc.nnode;
  5115. break;
  5116. }
  5117. /* Do not stop at the first below-fold image: DOM order is
  5118. * not visual order, and a footer/ad image early in the DOM
  5119. * used to hide every later article image from the loader. */
  5120. if (img_top[i] >
  5121. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5122. preload_pending = 1;
  5123. preload_node++;
  5124. continue;
  5125. }
  5126. {
  5127. unsigned int uh = script_cache_hash(url) | 1u;
  5128. int k;
  5129. for (k = 0; k < image_count; k++)
  5130. if (images[k].state == 1 &&
  5131. images[k].url_hash == uh)
  5132. break;
  5133. if (k < image_count) {
  5134. nd->img_index = (short)k;
  5135. layout_valid = 0;
  5136. preload_node = i + 1;
  5137. image_repaint();
  5138. continue;
  5139. }
  5140. }
  5141. if (url[0] == '/') {
  5142. unsigned char *data = 0;
  5143. unsigned int len = 0;
  5144. unsigned int t0;
  5145. int before;
  5146. preload_node = i + 1;
  5147. before = image_count;
  5148. t0 = u_ticks_ms();
  5149. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5150. err, sizeof(err)) == 0) {
  5151. preload_decode(i, 0, data, len, url);
  5152. img_stat_local(before, len, u_ticks_ms() - t0);
  5153. } else {
  5154. nd->img_index = -2;
  5155. }
  5156. continue;
  5157. }
  5158. w = fetch_worker_alloc();
  5159. if (!w)
  5160. return started;
  5161. preload_node = i + 1;
  5162. {
  5163. char msg[64];
  5164. unsigned int n = 0;
  5165. s_append(msg, &n, "Loading images ", sizeof(msg));
  5166. s_append_dec(msg, &n,
  5167. (unsigned int)preload_loaded + 1,
  5168. sizeof(msg));
  5169. s_append(msg, &n, "...", sizeof(msg));
  5170. set_status_quiet(msg);
  5171. image_repaint();
  5172. }
  5173. {
  5174. int fit_w = 0, fit_h = 0;
  5175. image_fit_size(i, &fit_w, &fit_h);
  5176. if (!fit_w)
  5177. fit_w = BR_IMG_LAYOUT_W;
  5178. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5179. i, 0,
  5180. (unsigned int)fit_w,
  5181. (unsigned int)fit_h,
  5182. err, sizeof(err)) != 0) {
  5183. nd->img_index = -2;
  5184. fetch_worker_release(w);
  5185. continue;
  5186. }
  5187. }
  5188. w->image_job = 1;
  5189. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5190. nd->img_index = -3; /* in flight: rescans skip it */
  5191. started++;
  5192. }
  5193. return started;
  5194. }
  5195. /* Report where the image batch spent its time: status bar for the headline,
  5196. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5197. static void img_stats_report(void)
  5198. {
  5199. char msg[80];
  5200. static char out[BR_IMG_STAT_LOG + 512];
  5201. unsigned int n = 0, o = 0;
  5202. if (!img_stat_n)
  5203. return;
  5204. img_stat_wall = img_stat_start ?
  5205. u_ticks_ms() - img_stat_start : 1;
  5206. if (!img_stat_wall)
  5207. img_stat_wall = 1;
  5208. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5209. s_append(msg, &n, "img ", sizeof(msg));
  5210. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5211. s_append(msg, &n, " ", sizeof(msg));
  5212. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5213. s_append(msg, &n, "ms net ", sizeof(msg));
  5214. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5215. s_append(msg, &n, " dec ", sizeof(msg));
  5216. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5217. s_append(msg, &n, " sc ", sizeof(msg));
  5218. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5219. s_append(msg, &n, " paint ", sizeof(msg));
  5220. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5221. /* Keep the page's phase breakdown and append the image summary when
  5222. * it fits; never hide a JS error or a truncation notice. */
  5223. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5224. unsigned int plen = s_len(post_status_text);
  5225. if (!plen) {
  5226. s_copy(post_status_text, msg, sizeof(post_status_text));
  5227. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5228. unsigned int pn = plen;
  5229. s_append(post_status_text, &pn, " | ",
  5230. sizeof(post_status_text));
  5231. s_append(post_status_text, &pn, msg,
  5232. sizeof(post_status_text));
  5233. } else {
  5234. s_copy(post_status_text, msg, sizeof(post_status_text));
  5235. }
  5236. post_status_ttl = 12000;
  5237. }
  5238. s_append(out, &o, "browser image stats\n", sizeof(out));
  5239. s_append(out, &o, "n=", sizeof(out));
  5240. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5241. s_append(out, &o, " wall=", sizeof(out));
  5242. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5243. s_append(out, &o, " net=", sizeof(out));
  5244. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5245. s_append(out, &o, " open=", sizeof(out));
  5246. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5247. s_append(out, &o, " first=", sizeof(out));
  5248. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5249. s_append(out, &o, " io=", sizeof(out));
  5250. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5251. s_append(out, &o, " dec=", sizeof(out));
  5252. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5253. s_append(out, &o, " scale=", sizeof(out));
  5254. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5255. s_append(out, &o, " paint=", sizeof(out));
  5256. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5257. s_append(out, &o, " reflow=", sizeof(out));
  5258. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5259. s_append(out, &o, " bytes=", sizeof(out));
  5260. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5261. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5262. sizeof(out));
  5263. s_append(out, &o, img_stat_log, sizeof(out));
  5264. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5265. (int)s_len(out));
  5266. }
  5267. static void preload_step(void)
  5268. {
  5269. int i;
  5270. unsigned int t0;
  5271. if (!preload_active)
  5272. return;
  5273. if (cancel_fetch || pending_action) {
  5274. preload_active = 0;
  5275. preload_pending = 0;
  5276. fetch_workers_cancel_busy();
  5277. return;
  5278. }
  5279. preload_fill_jobs();
  5280. /* Decode completed images in a short batch instead of one per pass.
  5281. * A pass used to decode one image and then sleep 10 ms, so a page of
  5282. * small icons trickled in at the decode rate. The budget keeps a
  5283. * single huge JPEG from monopolising the UI while small images
  5284. * finish together. */
  5285. t0 = u_ticks_ms();
  5286. for (i = 0; i < FETCH_WORKERS; i++) {
  5287. if (!fetch_workers[i].busy)
  5288. continue;
  5289. if (preload_finish_worker(&fetch_workers[i]) &&
  5290. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5291. break;
  5292. }
  5293. if (preload_active && preload_node >= doc.nnode &&
  5294. preload_active_jobs() == 0) {
  5295. preload_active = 0;
  5296. if (preload_pending)
  5297. preload_scroll = page_scroll.offset;
  5298. else
  5299. preload_pending = 0;
  5300. /* Keep the now idle helpers and their connections; a later
  5301. * navigation reuses them. They exit after ten idle seconds,
  5302. * and losing window focus stops them at once. */
  5303. if (img_repaint_pending) {
  5304. img_repaint_pending = 0;
  5305. ngui_invalidate(&ui);
  5306. }
  5307. img_stats_report();
  5308. set_status(post_status_text, post_status_error, post_status_ttl);
  5309. ngui_invalidate(&ui);
  5310. }
  5311. }
  5312. /* Set by navigate() when it turned a typed bare host into https://; the next
  5313. * load_page() consumes it and may retry over http. */
  5314. static int nav_https_upgraded;
  5315. /* Errors that mean "https is not served here" rather than "the site is
  5316. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5317. static int https_fallback_error(int e)
  5318. {
  5319. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5320. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5321. e == UHTTP_ERR_RESET;
  5322. }
  5323. static void history_push(const char *url)
  5324. {
  5325. if (!url || !url[0])
  5326. return;
  5327. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5328. s_eq(history[hist_pos], url))
  5329. return;
  5330. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5331. hist_len = hist_pos + 1;
  5332. if (hist_len < BR_HISTORY) {
  5333. s_copy(history[hist_len], url, BR_URL_MAX);
  5334. hist_pos = hist_len;
  5335. hist_len++;
  5336. } else {
  5337. int i;
  5338. for (i = 1; i < BR_HISTORY; i++)
  5339. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5340. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5341. hist_pos = BR_HISTORY - 1;
  5342. }
  5343. }
  5344. static void load_page(const char *url, int local, int push)
  5345. {
  5346. unsigned char *body = 0;
  5347. unsigned int len = 0;
  5348. int truncated = 0;
  5349. struct img_info image_info;
  5350. char ctype[64];
  5351. char final[BR_URL_MAX];
  5352. char err[80];
  5353. const char *detail = 0;
  5354. const char *post = pending_post_is ? pending_post : 0;
  5355. unsigned int post_len = pending_post_len;
  5356. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5357. /* Phase timings for the status line: where a slow load spends it. */
  5358. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5359. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5360. int upgraded = nav_https_upgraded;
  5361. int retried = 0;
  5362. int rv;
  5363. nav_https_upgraded = 0;
  5364. final[0] = '\0';
  5365. pending_post_len = 0;
  5366. pending_post_is = 0;
  5367. cancel_fetch = 0;
  5368. preload_active = 0;
  5369. preload_pending = 0;
  5370. fetch_workers_prepare_nav(url);
  5371. js_browser_stop();
  5372. js_last_status[0] = '\0';
  5373. js_last_error = 0;
  5374. heap_clear();
  5375. image_reset();
  5376. form_reset_state();
  5377. layout_valid = 0;
  5378. page_scroll.offset = 0;
  5379. page_scroll.dragging = 0;
  5380. page_title[0] = '\0';
  5381. page_loading = 1;
  5382. page_is_local = local;
  5383. s_copy(page_url, url, sizeof(page_url));
  5384. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5385. url_in.len = s_len(url_in.text);
  5386. url_in.cursor = url_in.len;
  5387. url_in.scroll = 0;
  5388. ngui_set_focus(&ui, 0);
  5389. if (final[0])
  5390. final[0] = '\0';
  5391. if (push)
  5392. history_push(url);
  5393. set_status("Loading...", 0, 0);
  5394. ngui_invalidate(&ui);
  5395. /* heap_clear() detaches the fonts, so attach them again before the
  5396. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5397. if (heap_start() != 0) {
  5398. show_error("Out of memory", "Cannot allocate the page buffer");
  5399. return;
  5400. }
  5401. br_parse_plain(&doc, "", 0); /* blank while loading */
  5402. ngui_font_attach(&ui);
  5403. redraw_now();
  5404. browser_rules_alloc();
  5405. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5406. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5407. &truncated, post, post_len);
  5408. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5409. fetch_last_error == UHTTP_ERR_DNS) {
  5410. /* A busy previous page can leave the receiver ring full just
  5411. * long enough to lose a DNS reply. Tear the old helpers down
  5412. * and try once more before giving up. */
  5413. retried = 1;
  5414. fetch_workers_stop_all();
  5415. u_sleep_ms(500);
  5416. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5417. sizeof(ctype), final, sizeof(final), err,
  5418. sizeof(err), &truncated, post, post_len);
  5419. }
  5420. if (rv == FETCH_ABORT)
  5421. return;
  5422. t_fetch = u_ticks_ms() - t_start;
  5423. /* Capture the page timing before CSS/script/image fetches overwrite the
  5424. * shared fetch_meta block. */
  5425. if (rv == 0 && !local) {
  5426. page_open_ms = fetch_meta.open_ms;
  5427. page_first_ms = fetch_meta.first_ms;
  5428. page_total_ms = fetch_meta.total_ms;
  5429. }
  5430. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5431. https_fallback_error(fetch_last_error)) {
  5432. char http_url[BR_URL_MAX];
  5433. unsigned int n = 0;
  5434. s_append(http_url, &n, "http://", sizeof(http_url));
  5435. s_append(http_url, &n, url + 8, sizeof(http_url));
  5436. /* Replace the https entry instead of adding a second one. */
  5437. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5438. s_eq(history[hist_pos], url))
  5439. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5440. load_page(http_url, 0, 0);
  5441. return;
  5442. }
  5443. if (rv != 0) {
  5444. detail = err;
  5445. show_error("Cannot load this page", detail);
  5446. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5447. url_in.len = s_len(url_in.text);
  5448. url_in.cursor = url_in.len;
  5449. url_in.scroll = 0;
  5450. return;
  5451. }
  5452. if (!local)
  5453. origin_cache_learn(url, final[0] ? final : url);
  5454. page_is_local = local;
  5455. if (final[0]) {
  5456. s_copy(page_url, final, sizeof(page_url));
  5457. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5458. url_in.len = s_len(url_in.text);
  5459. url_in.cursor = url_in.len;
  5460. url_in.scroll = 0;
  5461. }
  5462. if (contains_ci(ctype, "text/plain")) {
  5463. br_parse_plain(&doc, (const char *)body, len);
  5464. } else if (contains_ci(ctype, "image/") ||
  5465. (!contains_ci(ctype, "text/html") &&
  5466. img_sniff(body, len, &image_info) == 0)) {
  5467. unsigned int node = br_parse_image_doc(&doc, page_url);
  5468. if (node)
  5469. decode_direct_image(body, len, node);
  5470. s_copy(page_title, "Image", sizeof(page_title));
  5471. } else {
  5472. br_set_viewport(ui.w);
  5473. t_mark = u_ticks_ms();
  5474. br_parse(&doc, (const char *)body, len);
  5475. t_parse = u_ticks_ms() - t_mark;
  5476. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5477. sizeof(page_title));
  5478. t_mark = u_ticks_ms();
  5479. if (load_stylesheets() == FETCH_ABORT)
  5480. return;
  5481. t_css = u_ticks_ms() - t_mark;
  5482. if (pending_action)
  5483. return;
  5484. }
  5485. preload_begin();
  5486. page_loading = 0;
  5487. hist_visit(page_url, page_title);
  5488. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5489. url_in.len = s_len(url_in.text);
  5490. url_in.cursor = url_in.len;
  5491. url_in.scroll = 0;
  5492. ngui_set_focus(&ui, 0);
  5493. /* Paint the parsed page before fetching/running scripts. A slow
  5494. * remote <script src> then does not hide the page behind the loading
  5495. * screen; the fetch helper pumps this UI while it waits. */
  5496. set_status("Loading scripts...", 0, 0);
  5497. t_mark = u_ticks_ms();
  5498. redraw_now();
  5499. t_paint = u_ticks_ms() - t_mark;
  5500. /* Start one image download before the scripts. The other workers
  5501. * fetch the external script bodies in parallel, and the remaining
  5502. * images start as soon as the script phase ends. */
  5503. preload_max_jobs = 1;
  5504. preload_fill_jobs();
  5505. preload_wait = 0;
  5506. t_mark = u_ticks_ms();
  5507. run_page_scripts();
  5508. t_js = u_ticks_ms() - t_mark;
  5509. preload_max_jobs = FETCH_WORKERS;
  5510. if (pending_action)
  5511. return;
  5512. post_status_text[0] = '\0';
  5513. post_status_error = 0;
  5514. post_status_ttl = 0;
  5515. if (js_last_status[0]) {
  5516. s_copy(post_status_text, js_last_status,
  5517. sizeof(post_status_text));
  5518. post_status_error = js_last_error;
  5519. post_status_ttl = 8000;
  5520. } else if (truncated) {
  5521. s_copy(post_status_text, "Page truncated at the buffer limit",
  5522. sizeof(post_status_text));
  5523. post_status_ttl = 6000;
  5524. } else if (doc.truncated) {
  5525. s_copy(post_status_text, "Page truncated by the parser",
  5526. sizeof(post_status_text));
  5527. post_status_ttl = 6000;
  5528. } else if (page_total_ms) {
  5529. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5530. * paint 220, js 1750" -- the phases of this load. */
  5531. unsigned int n = 0;
  5532. static const char *const names[] = {
  5533. ", parse ", ", css ", ", paint ", ", js "
  5534. };
  5535. unsigned int vals[4];
  5536. int k;
  5537. vals[0] = t_parse;
  5538. vals[1] = t_css;
  5539. vals[2] = t_paint;
  5540. vals[3] = t_js;
  5541. (void)page_first_ms;
  5542. if (starts_with(page_url, "https://"))
  5543. s_append(post_status_text, &n,
  5544. "HTTPS (not verified), ",
  5545. sizeof(post_status_text));
  5546. s_append(post_status_text, &n, "Loaded in ",
  5547. sizeof(post_status_text));
  5548. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5549. sizeof(post_status_text));
  5550. s_append(post_status_text, &n, " ms: page ",
  5551. sizeof(post_status_text));
  5552. s_append_dec(post_status_text, &n, t_fetch,
  5553. sizeof(post_status_text));
  5554. s_append(post_status_text, &n, " (headers ",
  5555. sizeof(post_status_text));
  5556. s_append_dec(post_status_text, &n, page_open_ms,
  5557. sizeof(post_status_text));
  5558. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5559. for (k = 0; k < 4; k++) {
  5560. s_append(post_status_text, &n, names[k],
  5561. sizeof(post_status_text));
  5562. s_append_dec(post_status_text, &n, vals[k],
  5563. sizeof(post_status_text));
  5564. }
  5565. post_status_ttl = 12000;
  5566. } else if (starts_with(page_url, "https://")) {
  5567. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5568. sizeof(post_status_text));
  5569. post_status_ttl = 6000;
  5570. }
  5571. set_status(post_status_text, post_status_error, post_status_ttl);
  5572. ngui_invalidate(&ui);
  5573. }
  5574. static void load_home(int push)
  5575. {
  5576. pending_post_len = 0;
  5577. pending_post_is = 0;
  5578. cancel_fetch = 0;
  5579. preload_active = 0;
  5580. preload_pending = 0;
  5581. js_browser_stop();
  5582. js_last_status[0] = '\0';
  5583. js_last_error = 0;
  5584. heap_clear();
  5585. image_reset();
  5586. form_reset_state();
  5587. layout_valid = 0;
  5588. page_scroll.offset = 0;
  5589. page_scroll.dragging = 0;
  5590. page_loading = 1;
  5591. page_is_local = 0;
  5592. s_copy(page_url, "about:home", sizeof(page_url));
  5593. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5594. url_in.len = s_len(url_in.text);
  5595. url_in.cursor = url_in.len;
  5596. url_in.scroll = 0;
  5597. ngui_set_focus(&ui, 0);
  5598. if (push)
  5599. history_push(page_url);
  5600. ngui_invalidate(&ui);
  5601. /* See load_page(): reattach the fonts before the first redraw. */
  5602. if (heap_start() != 0) {
  5603. show_error("Out of memory", "Cannot allocate the browser heap");
  5604. return;
  5605. }
  5606. br_parse_plain(&doc, "", 0);
  5607. ngui_font_attach(&ui);
  5608. redraw_now();
  5609. browser_rules_alloc();
  5610. {
  5611. static const char home[] =
  5612. "<html><head><title>NebOS Browser</title><style>"
  5613. "body { margin: 10px; color: #e4e6f0; }"
  5614. "h1 { color: #7fb0ff; }"
  5615. ".box { background-color: #262b3a; margin: 12px; "
  5616. "padding: 10px; }"
  5617. "a { color: #7fb0ff; }"
  5618. "pre { background-color: #32384a; }"
  5619. "</style></head><body>"
  5620. "<h1>NebOS Browser</h1>"
  5621. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5622. "shared HTTP client and the image library.</p>"
  5623. "<div class=\"box\"><b>Try:</b>"
  5624. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5625. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5626. "<li><a href=\"/floppy1/JS.HTM\">/"
  5627. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5628. "<li><a href=\"http://10.0.2.2:8000/\">"
  5629. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5630. "<li><a href=\"https://example.com/\">"
  5631. "https://example.com/</a> (TLS, not verified)</li>"
  5632. "</ul></div>"
  5633. "<p>Type a URL in the bar above. Esc closes the "
  5634. "window, Ctrl+L focuses the address bar.</p>"
  5635. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5636. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5637. "</body></html>";
  5638. br_set_viewport(ui.w);
  5639. br_parse(&doc, home, sizeof(home) - 1);
  5640. br_parse_inline_css(&doc);
  5641. br_reset_styles(&doc);
  5642. s_copy(page_title, doc.title, sizeof(page_title));
  5643. }
  5644. post_status_text[0] = '\0';
  5645. post_status_error = 0;
  5646. post_status_ttl = 0;
  5647. page_loading = 0;
  5648. set_status("", 0, 0);
  5649. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5650. url_in.len = s_len(url_in.text);
  5651. url_in.cursor = url_in.len;
  5652. url_in.scroll = 0;
  5653. ngui_set_focus(&ui, 0);
  5654. ngui_invalidate(&ui);
  5655. }
  5656. /* Extensions the browser opens from the local filesystem. A dotted input
  5657. * with one of these still resolves relative to the cwd. */
  5658. static int local_file_ext(const char *s)
  5659. {
  5660. static const char *const exts[] = {
  5661. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5662. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5663. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5664. "cfg", "conf", 0
  5665. };
  5666. unsigned int i = 0, start = 0, len = 0, e;
  5667. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5668. s[i] != '#') {
  5669. if (s[i] == '.') {
  5670. start = i + 1;
  5671. len = 0;
  5672. } else if (start) {
  5673. len++;
  5674. }
  5675. i++;
  5676. }
  5677. if (!len)
  5678. return 0;
  5679. for (e = 0; exts[e]; e++) {
  5680. const char *x = exts[e];
  5681. unsigned int xn = s_len(x), k;
  5682. if (xn != len)
  5683. continue;
  5684. for (k = 0; k < len; k++) {
  5685. char a = s[start + k];
  5686. if (a >= 'A' && a <= 'Z')
  5687. a = (char)(a - 'A' + 'a');
  5688. if (a != x[k])
  5689. break;
  5690. }
  5691. if (k == len)
  5692. return 1;
  5693. }
  5694. return 0;
  5695. }
  5696. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5697. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5698. * Enter to the first network request. */
  5699. static int looks_like_host(const char *s)
  5700. {
  5701. unsigned int i = 0;
  5702. int dot = 0;
  5703. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5704. s[i] != ':') {
  5705. char c = s[i];
  5706. if (c == '.') {
  5707. dot = 1;
  5708. } else if (!((c >= 'a' && c <= 'z') ||
  5709. (c >= 'A' && c <= 'Z') ||
  5710. (c >= '0' && c <= '9') ||
  5711. c == '-' || c == '_')) {
  5712. return 0;
  5713. }
  5714. i++;
  5715. }
  5716. return dot && i > 0 && !local_file_ext(s);
  5717. }
  5718. static void load_remote(const char *url, int push)
  5719. {
  5720. char canon[BR_URL_MAX];
  5721. s_copy(canon, url, sizeof(canon));
  5722. origin_cache_apply(canon, sizeof(canon));
  5723. load_page(canon, 0, push);
  5724. }
  5725. static void navigate(const char *input, int push)
  5726. {
  5727. char target[BR_URL_MAX];
  5728. char *t;
  5729. if (!input)
  5730. return;
  5731. s_copy(target, input, sizeof(target));
  5732. t = trim(target);
  5733. if (!t[0])
  5734. return;
  5735. if (s_eq(t, "about:home")) {
  5736. load_home(push);
  5737. return;
  5738. }
  5739. if (starts_with(t, "file://")) {
  5740. make_abs_local(t + 7, target, sizeof(target));
  5741. load_page(target, 1, push);
  5742. return;
  5743. }
  5744. if (is_http(t)) {
  5745. load_remote(t, push);
  5746. return;
  5747. }
  5748. if (t[0] == '/') {
  5749. make_abs_local(t, target, sizeof(target));
  5750. load_page(target, 1, push);
  5751. return;
  5752. }
  5753. if (!looks_like_host(t)) {
  5754. struct sys_stat st;
  5755. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5756. make_abs_local(t, target, sizeof(target));
  5757. load_page(target, 1, push);
  5758. return;
  5759. }
  5760. }
  5761. {
  5762. /* A typed bare host tries https first: nearly every site
  5763. * redirects http -> https anyway, and that hop costs a whole
  5764. * extra connection. load_page() falls back to http when the
  5765. * https connection itself fails. */
  5766. char with_scheme[BR_URL_MAX];
  5767. unsigned int n = 0;
  5768. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5769. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5770. nav_https_upgraded = 1;
  5771. load_remote(with_scheme, push);
  5772. }
  5773. }
  5774. /* ---- layout ---- */
  5775. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  5776. {
  5777. unsigned int id;
  5778. if (!family || family > BR_MAX_FACES)
  5779. return 0;
  5780. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  5781. return id ? font_faces[id - 1] : 0;
  5782. }
  5783. static struct ufont_face *style_face(const struct br_style *st)
  5784. {
  5785. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  5786. }
  5787. static struct ufont_face *run_face(const struct lay_run *r)
  5788. {
  5789. return face_for(r->font_face, r->bold, r->italic);
  5790. }
  5791. static unsigned int face_text_width(struct ngui *gui,
  5792. const struct br_style *st,
  5793. const char *s, unsigned int n)
  5794. {
  5795. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5796. st->bold, st->italic, st->mono);
  5797. }
  5798. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5799. {
  5800. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5801. st->mono);
  5802. }
  5803. static unsigned int run_text_width(struct ngui *gui,
  5804. const struct lay_run *r,
  5805. const char *s, unsigned int n)
  5806. {
  5807. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5808. r->bold, r->italic, r->mono);
  5809. }
  5810. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5811. {
  5812. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5813. r->mono);
  5814. }
  5815. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5816. {
  5817. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5818. }
  5819. static struct br_style base_style(void)
  5820. {
  5821. struct br_style s = { 0 };
  5822. s.color = ui.theme.text;
  5823. s.bg = ui.theme.bg;
  5824. s.has_bg = 0;
  5825. for (int i = 0; i < 4; i++) {
  5826. s.border_c[i] = 0;
  5827. s.border_w[i] = 0;
  5828. s.border_s[i] = BR_BORDER_SOLID;
  5829. }
  5830. s.font_px = 16;
  5831. s.bold = 0;
  5832. s.italic = 0;
  5833. s.mono = 0;
  5834. s.underline = 0;
  5835. s.strike = 0;
  5836. s.overline = 0;
  5837. s.align = BR_ALIGN_LEFT;
  5838. s.display = BR_DISPLAY_BLOCK;
  5839. s.no_bullet = 0;
  5840. s.list_style = BR_LIST_AUTO;
  5841. s.uppercase = 0;
  5842. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5843. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5844. s.width = s.max_width = s.min_width = 0;
  5845. s.height = s.min_height = s.max_height = 0;
  5846. s.box_sizing = 0;
  5847. s.ml_auto = s.mr_auto = 0;
  5848. s.line_h_pct = 0;
  5849. s.line_h_px = 0;
  5850. s.mt = s.mb = s.ml = s.mr = 0;
  5851. s.pt = s.pb = s.pl = s.pr = 0;
  5852. return s;
  5853. }
  5854. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5855. * a minified page that starts `<!doctype html><html ...>` makes it the
  5856. * <html> element itself, and the layout walks only its children, so its
  5857. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5858. * colour and font there) used to be skipped and the theme defaults showed
  5859. * through. Only inherited properties are taken: the root's box (margins,
  5860. * display, background) is not a container style for its children here. */
  5861. static struct br_style root_style(void)
  5862. {
  5863. struct br_style base = base_style(), st;
  5864. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5865. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5866. return base;
  5867. br_style_for(&doc, doc.root, &base, &st);
  5868. base.color = st.color;
  5869. base.font_px = st.font_px;
  5870. base.bold = st.bold;
  5871. base.italic = st.italic;
  5872. base.mono = st.mono;
  5873. base.font_face = st.font_face;
  5874. base.align = st.align;
  5875. base.line_h_pct = st.line_h_pct;
  5876. base.line_h_px = st.line_h_px;
  5877. base.nowrap = st.nowrap;
  5878. base.uppercase = st.uppercase;
  5879. base.cursor = st.cursor;
  5880. base.vis_hidden = st.vis_hidden;
  5881. base.fill_mode = st.fill_mode;
  5882. base.fill = st.fill;
  5883. base.stroke_mode = st.stroke_mode;
  5884. base.stroke = st.stroke;
  5885. base.stroke_w = st.stroke_w;
  5886. base.fill_evenodd = st.fill_evenodd;
  5887. return base;
  5888. }
  5889. /* Resolve a margin/padding raw value. Percentages use the containing
  5890. * block width for all four sides, as CSS specifies. */
  5891. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5892. {
  5893. if (unit == 1)
  5894. return base * v / 10000;
  5895. if (unit == 2)
  5896. return st->font_px * v / 100;
  5897. if (unit == 3)
  5898. return (int)br_root_font_px() * v / 100;
  5899. if (unit == 4)
  5900. return 0;
  5901. return v;
  5902. }
  5903. static int mp_px(const struct br_style *st, int side, int base)
  5904. {
  5905. int raw;
  5906. switch (side) {
  5907. case 0: raw = st->mt; break;
  5908. case 1: raw = st->mr; break;
  5909. case 2: raw = st->mb; break;
  5910. case 3: raw = st->ml; break;
  5911. case 4: raw = st->pt; break;
  5912. case 5: raw = st->pr; break;
  5913. case 6: raw = st->pb; break;
  5914. default: raw = st->pl; break;
  5915. }
  5916. if (st->mp_unit[side] == 5)
  5917. return base * raw / 100 + st->mp_calc_px[side];
  5918. return css_mp_px(st, raw, st->mp_unit[side], base);
  5919. }
  5920. static int style_width_px(const struct br_style *st, int base)
  5921. {
  5922. if (st->width_kind == 1)
  5923. return st->width;
  5924. if (st->width_kind == 2)
  5925. return base * (int)st->width / 100;
  5926. if (st->width_kind == 3)
  5927. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5928. return 0;
  5929. }
  5930. static int style_height_px(const struct br_style *st, int base)
  5931. {
  5932. if (st->height_kind == 1)
  5933. return st->height;
  5934. if (st->height_kind == 2)
  5935. return base * (int)st->height / 100;
  5936. if (st->height_kind == 3)
  5937. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5938. return 0;
  5939. }
  5940. static int css_size(unsigned char kind, int val, int base)
  5941. {
  5942. if (kind == 1)
  5943. return val;
  5944. if (kind == 2)
  5945. return base * val / 100;
  5946. return -1;
  5947. }
  5948. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5949. int thick, int horizontal, unsigned short color,
  5950. unsigned char style)
  5951. {
  5952. int pos;
  5953. if (len <= 0 || thick <= 0)
  5954. return;
  5955. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5956. if (horizontal)
  5957. ngui_fill_rect(ui, (struct ngui_rect){
  5958. x, y, len, thick}, color);
  5959. else
  5960. ngui_fill_rect(ui, (struct ngui_rect){
  5961. x, y, thick, len}, color);
  5962. return;
  5963. }
  5964. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5965. int seg = len - pos;
  5966. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5967. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5968. if (horizontal)
  5969. ngui_fill_rect(ui, (struct ngui_rect){
  5970. x + pos, y, seg, thick}, color);
  5971. else
  5972. ngui_fill_rect(ui, (struct ngui_rect){
  5973. x, y + pos, thick, seg}, color);
  5974. }
  5975. }
  5976. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5977. const struct br_style *st)
  5978. {
  5979. int top = st->border_w[0], right = st->border_w[1];
  5980. int bottom = st->border_w[2], left = st->border_w[3];
  5981. if (r.w <= 0 || r.h <= 0)
  5982. return;
  5983. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5984. int i;
  5985. for (i = 0; i < 4; i++)
  5986. if (st->border_w[i] && !st->border_t[i]) {
  5987. ngui_fill_rect(ui, r, st->border_c[i]);
  5988. break;
  5989. }
  5990. return;
  5991. }
  5992. if (top && !st->border_t[0])
  5993. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5994. st->border_c[0], st->border_s[0]);
  5995. if (bottom && !st->border_t[2])
  5996. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5997. st->border_c[2], st->border_s[2]);
  5998. if (left && !st->border_t[3])
  5999. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  6000. left, 0, st->border_c[3], st->border_s[3]);
  6001. if (right && !st->border_t[1])
  6002. draw_border_side(ui, r.x + r.w - right, r.y + top,
  6003. r.h - top - bottom, right, 0,
  6004. st->border_c[1], st->border_s[1]);
  6005. }
  6006. static void transform_origin(const struct br_style *st, int w, int h,
  6007. int *ox, int *oy)
  6008. {
  6009. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  6010. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  6011. }
  6012. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  6013. unsigned int a)
  6014. {
  6015. unsigned int dr, dg, db, sr, sg, sb;
  6016. if (a >= 255)
  6017. return s;
  6018. dr = (d >> 11) & 31;
  6019. dg = (d >> 5) & 63;
  6020. db = d & 31;
  6021. sr = (s >> 11) & 31;
  6022. sg = (s >> 5) & 63;
  6023. sb = s & 31;
  6024. dr = (dr * (255 - a) + sr * a) / 255;
  6025. dg = (dg * (255 - a) + sg * a) / 255;
  6026. db = (db * (255 - a) + sb * a) / 255;
  6027. return (unsigned short)((dr << 11) | (dg << 5) | db);
  6028. }
  6029. /* Paint a solid box through scale()/rotate() around transform-origin. This
  6030. * transforms the element's own background box; text and descendants keep
  6031. * their layout (documented approximation). */
  6032. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  6033. unsigned short color,
  6034. const struct br_style *st)
  6035. {
  6036. double sx = st->scale_x / 100.0;
  6037. double sy = st->scale_y / 100.0;
  6038. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6039. double c = cos(th), sn = sin(th);
  6040. int ox, oy, minx, miny, maxx, maxy, x, y;
  6041. double ax, ay;
  6042. double px[4], py[4];
  6043. int cx1, cy1, cx2, cy2, i;
  6044. if (sx == 0)
  6045. sx = 0.01;
  6046. if (sy == 0)
  6047. sy = 0.01;
  6048. transform_origin(st, box.w, box.h, &ox, &oy);
  6049. ax = box.x + ox;
  6050. ay = box.y + oy;
  6051. px[0] = -ox; py[0] = -oy;
  6052. px[1] = box.w - ox; py[1] = -oy;
  6053. px[2] = box.w - ox; py[2] = box.h - oy;
  6054. px[3] = -ox; py[3] = box.h - oy;
  6055. minx = miny = 1000000;
  6056. maxx = maxy = -1000000;
  6057. for (i = 0; i < 4; i++) {
  6058. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6059. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6060. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6061. if (dx < minx) minx = dx;
  6062. if (dx > maxx) maxx = dx;
  6063. if (dy < miny) miny = dy;
  6064. if (dy > maxy) maxy = dy;
  6065. }
  6066. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6067. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6068. cx2 = page_rect.x + page_rect.w - 12;
  6069. cy2 = page_rect.y + page_rect.h;
  6070. if (cx2 > gui->w) cx2 = gui->w;
  6071. if (cy2 > gui->h) cy2 = gui->h;
  6072. if (minx < cx1) minx = cx1;
  6073. if (miny < cy1) miny = cy1;
  6074. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6075. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6076. for (y = miny; y <= maxy; y++) {
  6077. for (x = minx; x <= maxx; x++) {
  6078. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6079. double rx = dx * c + dy * sn;
  6080. double ry = -dx * sn + dy * c;
  6081. double bx = rx / sx + ox;
  6082. double by = ry / sy + oy;
  6083. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6084. gui->px[y * gui->w + x] = color;
  6085. }
  6086. }
  6087. }
  6088. static void draw_image_transformed(struct ngui *gui,
  6089. const struct img_image *im,
  6090. int x, int y, int w, int h,
  6091. int sx100, int sy100, int rot100,
  6092. int origin_x, int origin_y,
  6093. int origin_x_kind, int origin_y_kind)
  6094. {
  6095. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6096. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6097. double c = cos(th), sn = sin(th);
  6098. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6099. double ax, ay;
  6100. double bx[4], by[4];
  6101. int cx1, cy1, cx2, cy2;
  6102. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6103. return;
  6104. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6105. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6106. ax = x + ox;
  6107. ay = y + oy;
  6108. bx[0] = -ox; by[0] = -oy;
  6109. bx[1] = w - ox; by[1] = -oy;
  6110. bx[2] = w - ox; by[2] = h - oy;
  6111. bx[3] = -ox; by[3] = h - oy;
  6112. minx = miny = 1000000;
  6113. maxx = maxy = -1000000;
  6114. for (i = 0; i < 4; i++) {
  6115. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6116. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6117. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6118. if (dx < minx) minx = dx;
  6119. if (dx > maxx) maxx = dx;
  6120. if (dy < miny) miny = dy;
  6121. if (dy > maxy) maxy = dy;
  6122. }
  6123. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6124. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6125. cx2 = page_rect.x + page_rect.w - 12;
  6126. cy2 = page_rect.y + page_rect.h;
  6127. if (cx2 > gui->w) cx2 = gui->w;
  6128. if (cy2 > gui->h) cy2 = gui->h;
  6129. if (minx < cx1) minx = cx1;
  6130. if (miny < cy1) miny = cy1;
  6131. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6132. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6133. for (py = miny; py <= maxy; py++) {
  6134. for (px = minx; px <= maxx; px++) {
  6135. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6136. double rx = dx * c + dy * sn;
  6137. double ry = -dx * sn + dy * c;
  6138. double fx = rx / sx + ox;
  6139. double fy = ry / sy + oy;
  6140. int ix, iy;
  6141. unsigned int si, a;
  6142. unsigned short src;
  6143. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6144. continue;
  6145. ix = (int)(fx * (double)im->w / w);
  6146. iy = (int)(fy * (double)im->h / h);
  6147. if (ix < 0 || ix >= (int)im->w ||
  6148. iy < 0 || iy >= (int)im->h)
  6149. continue;
  6150. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6151. src = im->px[si];
  6152. a = im->alpha ? im->alpha[si] : 255;
  6153. gui->px[py * gui->w + px] =
  6154. a >= 255 ? src :
  6155. blend_rgb565(gui->px[py * gui->w + px],
  6156. src, a);
  6157. }
  6158. }
  6159. }
  6160. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6161. unsigned int node, const struct br_style *st);
  6162. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6163. * first and every pixel outside a corner's arc is restored afterwards. */
  6164. #define BG_ROUND_MAX 64
  6165. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6166. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6167. unsigned int node, const struct br_style *st,
  6168. int rtl, int rtr, int rbr, int rbl)
  6169. {
  6170. struct ngui *ui = l->ui;
  6171. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6172. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6173. if (ui->nclip > 0)
  6174. clip = ui->clip[ui->nclip - 1];
  6175. for (c = 0; c < 4; c++) {
  6176. if (r[c] > BG_ROUND_MAX)
  6177. r[c] = BG_ROUND_MAX;
  6178. if (r[c] > box.w / 2)
  6179. r[c] = box.w / 2;
  6180. if (r[c] > box.h / 2)
  6181. r[c] = box.h / 2;
  6182. }
  6183. for (c = 0; c < 4; c++) {
  6184. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6185. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6186. for (dy = 0; dy < r[c]; dy++)
  6187. for (dx = 0; dx < r[c]; dx++) {
  6188. int px = ox + dx, py = oy + dy;
  6189. if (px >= clip.x && py >= clip.y &&
  6190. px < clip.x + clip.w && py < clip.y + clip.h)
  6191. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6192. ui->px[py * ui->w + px];
  6193. }
  6194. }
  6195. draw_bg_image(l, box, node, st);
  6196. for (c = 0; c < 4; c++) {
  6197. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6198. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6199. /* arc centre, in corner-square coordinates */
  6200. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6201. int cy = (c >= 2) ? 0 : r[c];
  6202. for (dy = 0; dy < r[c]; dy++)
  6203. for (dx = 0; dx < r[c]; dx++) {
  6204. int px = ox + dx, py = oy + dy;
  6205. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6206. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6207. continue;
  6208. if (px >= clip.x && py >= clip.y &&
  6209. px < clip.x + clip.w && py < clip.y + clip.h)
  6210. ui->px[py * ui->w + px] =
  6211. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6212. }
  6213. }
  6214. }
  6215. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6216. unsigned int node, const struct br_style *st)
  6217. {
  6218. struct br_image *bi;
  6219. struct img_blit b;
  6220. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6221. unsigned int scale = 65536;
  6222. int legacy, tiles = 0, rows = 0;
  6223. int cx1, cy1, cx2, cy2;
  6224. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6225. return;
  6226. if (doc.nodes[node].bg_img_index < 0 ||
  6227. doc.nodes[node].bg_img_index >= image_count)
  6228. return;
  6229. bi = &images[doc.nodes[node].bg_img_index];
  6230. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6231. return;
  6232. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6233. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6234. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6235. if (legacy) {
  6236. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6237. tw = box.w;
  6238. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6239. x = box.x;
  6240. y = box.y;
  6241. rep_x = rep_y = 0;
  6242. } else {
  6243. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6244. unsigned int sx = ((unsigned int)box.w << 16) /
  6245. bi->img.w;
  6246. unsigned int sy = ((unsigned int)box.h << 16) /
  6247. bi->img.h;
  6248. scale = st->bg_size_kind == 3 ?
  6249. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6250. } else if (st->bg_size_kind == 1 ||
  6251. st->bg_size_kind == 2) {
  6252. int w = st->bg_size_w;
  6253. int h = st->bg_size_h;
  6254. if (st->bg_size_kind == 2) {
  6255. if (w)
  6256. w = box.w * w / 100;
  6257. if (h)
  6258. h = box.h * h / 100;
  6259. }
  6260. if (w)
  6261. scale = ((unsigned int)w << 16) / bi->img.w;
  6262. else if (h)
  6263. scale = ((unsigned int)h << 16) / bi->img.h;
  6264. }
  6265. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6266. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6267. if (tw < 1)
  6268. tw = 1;
  6269. if (th < 1)
  6270. th = 1;
  6271. posx = st->bg_pos_x_kind == 1 ?
  6272. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6273. posy = st->bg_pos_y_kind == 1 ?
  6274. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6275. x = box.x + posx;
  6276. y = box.y + posy;
  6277. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6278. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6279. if (rep_x) {
  6280. int m = (x - box.x) % tw;
  6281. if (m > 0)
  6282. m -= tw;
  6283. x = box.x + m;
  6284. }
  6285. if (rep_y) {
  6286. int m = (y - box.y) % th;
  6287. if (m > 0)
  6288. m -= th;
  6289. y = box.y + m;
  6290. }
  6291. }
  6292. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6293. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6294. cx2 = box.x + box.w;
  6295. cy2 = box.y + box.h;
  6296. if (cx2 > page_rect.x + page_rect.w - 12)
  6297. cx2 = page_rect.x + page_rect.w - 12;
  6298. if (cy2 > page_rect.y + page_rect.h)
  6299. cy2 = page_rect.y + page_rect.h;
  6300. if (cx1 >= cx2 || cy1 >= cy2)
  6301. return;
  6302. b.dst = l->ui->px;
  6303. b.dst_w = l->ui->w;
  6304. b.dst_h = l->ui->h;
  6305. b.clip_x = cx1;
  6306. b.clip_y = cy1;
  6307. b.clip_w = cx2 - cx1;
  6308. b.clip_h = cy2 - cy1;
  6309. b.bg = ui.theme.bg;
  6310. b.bg2 = ui.theme.bg;
  6311. b.dst_a = 0;
  6312. {
  6313. struct img_image *src = image_display_get(bi, tw, th);
  6314. int row_x;
  6315. if (!src)
  6316. src = &bi->img;
  6317. b.scale = ((unsigned int)tw << 16) / src->w;
  6318. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6319. row_x = x;
  6320. for (;;) {
  6321. for (;;) {
  6322. b.x = x;
  6323. b.y = y;
  6324. img_draw(src, &b);
  6325. if (!rep_x || ++tiles > 512)
  6326. break;
  6327. x += tw;
  6328. if (x >= box.x + box.w)
  6329. break;
  6330. }
  6331. if (!rep_y || ++rows > 64)
  6332. break;
  6333. y += th;
  6334. if (y >= box.y + box.h)
  6335. break;
  6336. x = row_x;
  6337. }
  6338. }
  6339. }
  6340. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6341. int *out_w, int *out_h);
  6342. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6343. const struct br_style *st, int x, int y, int w,
  6344. int h);
  6345. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6346. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6347. * ::before/::after box with a background (Infima's menu chevrons). */
  6348. #define RUN_SVG (-3)
  6349. #define RUN_PBOX (-4)
  6350. static int run_width(const struct lay_run *r)
  6351. {
  6352. if (r->img >= 0)
  6353. return r->iw;
  6354. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6355. return r->iw;
  6356. return (int)r->w;
  6357. }
  6358. static void start_line(struct lay *l, const struct br_style *st)
  6359. {
  6360. (void)st;
  6361. if (l->nruns == 0) {
  6362. l->line_y = l->y;
  6363. l->line_h = 0;
  6364. }
  6365. l->line_left = l->left;
  6366. l->line_right = l->right;
  6367. if (l->float_active && l->line_y < l->float_bottom) {
  6368. if (l->float_left > l->line_left)
  6369. l->line_left = l->float_left;
  6370. if (l->float_right < l->line_right)
  6371. l->line_right = l->float_right;
  6372. }
  6373. if (l->line_right < l->line_left + 8)
  6374. l->line_right = l->line_left + 8;
  6375. l->line_x = l->line_left;
  6376. l->run_x = l->line_left;
  6377. }
  6378. static void inline_box_add(const struct lay *l, unsigned int owner, int x,
  6379. int w)
  6380. {
  6381. int y = l->line_y;
  6382. int h = l->line_h ? l->line_h : 16;
  6383. int depth = 0;
  6384. while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
  6385. unsigned int node = owner - 1;
  6386. struct br_layout_box *b = &layout_boxes[node];
  6387. if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
  6388. (inline_box_flush[node] == inline_box_flush_id ||
  6389. inline_box_y[node] < y)) {
  6390. int x1 = b->x + b->w, y1 = b->y + b->h;
  6391. if (x < b->x)
  6392. b->x = x;
  6393. if (y < b->y)
  6394. b->y = y;
  6395. if (x + w > x1)
  6396. x1 = x + w;
  6397. if (y + h > y1)
  6398. y1 = y + h;
  6399. b->w = x1 - b->x;
  6400. b->h = y1 - b->y;
  6401. } else {
  6402. b->x = x;
  6403. b->y = y;
  6404. b->w = w;
  6405. b->h = h;
  6406. b->valid = 1;
  6407. }
  6408. inline_box_pass[node] = inline_box_pass_id;
  6409. inline_box_flush[node] = inline_box_flush_id;
  6410. inline_box_y[node] = y;
  6411. owner = inline_box_parent[node];
  6412. }
  6413. }
  6414. static void flush_line(struct lay *l)
  6415. {
  6416. int total, x, i, vis;
  6417. inline_box_flush_id++;
  6418. if (!l->nruns && l->line_x == l->line_left) {
  6419. l->line_h = 0;
  6420. return;
  6421. }
  6422. total = l->line_x - l->line_left;
  6423. x = l->line_left;
  6424. vis = 1;
  6425. if (l->draw) {
  6426. int lh = l->line_h ? l->line_h : 16;
  6427. vis = l->line_y + lh >= page_rect.y &&
  6428. l->line_y <= page_rect.y + page_rect.h;
  6429. }
  6430. if (l->align == BR_ALIGN_CENTER)
  6431. x += (l->line_right - l->line_left - total) / 2;
  6432. else if (l->align == BR_ALIGN_RIGHT)
  6433. x = l->line_right - total;
  6434. if (x < l->line_left)
  6435. x = l->line_left;
  6436. for (i = 0; i < l->nruns; i++) {
  6437. struct lay_run *r = &l->runs[i];
  6438. int w = run_width(r);
  6439. int ry = l->line_y + r->dy;
  6440. x += r->gap;
  6441. if (l->draw && vis) {
  6442. if (r->form) {
  6443. unsigned int node = r->form - 1;
  6444. struct form_state *fs = form_get(node, 1);
  6445. int hh = r->ih ? r->ih : 20;
  6446. int focused = form_focus == node;
  6447. int disabled = r->form_disabled;
  6448. unsigned short bg = l->ui->theme.panel_alt;
  6449. unsigned short fg = disabled ? 0x8410 : r->color;
  6450. struct ngui_rect box = {x, ry, w, hh};
  6451. if (r->form_kind == FORM_CHECKBOX ||
  6452. r->form_kind == FORM_RADIO) {
  6453. ngui_fill_rect(l->ui, box, bg);
  6454. ngui_frame(l->ui, box,
  6455. focused ? l->ui->theme.accent :
  6456. l->ui->theme.border);
  6457. if (fs && fs->checked) {
  6458. struct ngui_rect dot = {
  6459. x + 4, ry + 4,
  6460. w > 8 ? w - 8 : 1,
  6461. hh > 8 ? hh - 8 : 1
  6462. };
  6463. if (r->form_kind == FORM_RADIO)
  6464. ngui_fill_round_rect(
  6465. l->ui, dot, 4,
  6466. 4, 4, 4,
  6467. l->ui->theme.accent);
  6468. else
  6469. ngui_fill_rect(l->ui,
  6470. dot,
  6471. l->ui->theme.accent);
  6472. }
  6473. } else {
  6474. int editable =
  6475. r->form_kind == FORM_TEXT ||
  6476. r->form_kind == FORM_PASSWORD ||
  6477. r->form_kind == FORM_TEXTAREA;
  6478. int scroll = 0;
  6479. /* Editable fields draw the live value
  6480. * (r->lit is a short copy). */
  6481. static char shown[FORM_VALUE_MAX + 1];
  6482. const char *txt = r->lit;
  6483. unsigned int tl = s_len(r->lit);
  6484. if (editable && fs && fs->len) {
  6485. unsigned int k;
  6486. if (r->form_kind == FORM_PASSWORD) {
  6487. for (k = 0; k < fs->len; k++)
  6488. shown[k] = '*';
  6489. shown[k] = '\0';
  6490. txt = shown;
  6491. } else {
  6492. txt = fs->value;
  6493. }
  6494. tl = fs->len;
  6495. }
  6496. struct br_style fst;
  6497. int author, tx = x + 6, pr = 6;
  6498. style_for_node(node, &fst);
  6499. author = form_author_styled(&fst);
  6500. if (author) {
  6501. /* The page styled the control:
  6502. * its background, border, radius
  6503. * and text colour. */
  6504. form_paint_author(l->ui, box, &fst,
  6505. focused);
  6506. tx = x + fst.border_w[3] +
  6507. mp_px(&fst, 7, w);
  6508. pr = fst.border_w[1] +
  6509. mp_px(&fst, 5, w);
  6510. if (tx < x + 2 && !editable)
  6511. tx = x + 2;
  6512. if (!disabled)
  6513. fg = editable && fs &&
  6514. !fs->len ?
  6515. 0x8410 : fst.color;
  6516. if (!editable) {
  6517. int tw0 = (int)
  6518. run_text_width(l->ui,
  6519. r, txt, tl);
  6520. tx = x + (w - tw0) / 2;
  6521. }
  6522. } else {
  6523. /* The box is drawn in theme colours, so
  6524. * the text is too: the page's CSS colour
  6525. * (dark on a light page) would vanish on
  6526. * the dark field. */
  6527. if (!disabled)
  6528. fg = editable && fs && !fs->len ?
  6529. l->ui->theme.text_dim :
  6530. l->ui->theme.text;
  6531. ngui_fill_rect(l->ui, box, bg);
  6532. ngui_frame(l->ui, box,
  6533. focused ? l->ui->theme.accent :
  6534. l->ui->theme.border);
  6535. }
  6536. /* A value wider than the field shows its
  6537. * tail (where typing happens). */
  6538. if (editable && fs && fs->len &&
  6539. w > (tx - x) + pr) {
  6540. int tw = (int)run_text_width(l->ui,
  6541. r, txt, tl);
  6542. int room = w - (tx - x) - pr;
  6543. if (tw > room)
  6544. scroll = tw - room;
  6545. }
  6546. ngui_push_clip(l->ui, (struct ngui_rect){
  6547. x + 1, ry + 1,
  6548. w > 2 ? w - 2 : 1,
  6549. hh > 2 ? hh - 2 : 1 });
  6550. ngui_text_px_face(l->ui, run_face(r),
  6551. tx - scroll,
  6552. ry + (hh - r->font_px) / 2 - 1,
  6553. txt, tl, fg, r->font_px,
  6554. r->bold, r->italic, r->mono);
  6555. if (focused && fs && editable) {
  6556. int cw = 0;
  6557. if (fs->len && fs->caret)
  6558. cw = (int)run_text_width(
  6559. l->ui, r, txt,
  6560. fs->caret < fs->len ?
  6561. fs->caret : fs->len);
  6562. ngui_fill_rect(l->ui,
  6563. (struct ngui_rect){
  6564. tx + cw - scroll,
  6565. ry + 4, 1,
  6566. hh > 8 ? hh - 8 : 1
  6567. },
  6568. l->ui->theme.accent);
  6569. }
  6570. ngui_pop_clip(l->ui);
  6571. if (r->form_kind == FORM_SELECT) {
  6572. ngui_text_px(l->ui, x + w - 12,
  6573. ry + 2, "v", 1, fg,
  6574. r->font_px, 0, 0, 0);
  6575. }
  6576. }
  6577. } else if (r->img == RUN_PBOX) {
  6578. struct ngui_rect bx = { x, ry, w, r->ih };
  6579. ngui_push_clip(l->ui, bx);
  6580. if (r->pb_has_bg)
  6581. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6582. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6583. images[r->pb_img].state == 1) {
  6584. /* Rotate about the box centre: the
  6585. * image is centred in it here. */
  6586. draw_image_transformed(l->ui,
  6587. &images[r->pb_img].img,
  6588. x + r->pb_x, ry + r->pb_y,
  6589. r->pb_w, r->pb_h,
  6590. r->transform_scale ?
  6591. r->scale_x : 100,
  6592. r->transform_scale ?
  6593. r->scale_y : 100,
  6594. r->transform_scale ?
  6595. r->rotate_x100 : 0,
  6596. 50, 50, 1, 1);
  6597. }
  6598. ngui_pop_clip(l->ui);
  6599. } else if (r->img == RUN_SVG) {
  6600. struct br_style sst;
  6601. style_for_node(r->off, &sst);
  6602. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6603. r->ih);
  6604. } else if (r->img == -2) {
  6605. int hh = r->ih ? r->ih : 20;
  6606. ngui_fill_rect(l->ui,
  6607. (struct ngui_rect){x, ry, w, hh},
  6608. l->ui->theme.panel_alt);
  6609. ngui_frame(l->ui,
  6610. (struct ngui_rect){x, ry, w, hh},
  6611. l->ui->theme.border);
  6612. ngui_text_px_face(l->ui, run_face(r),
  6613. x + 6, ry + 2, r->lit,
  6614. s_len(r->lit), r->color,
  6615. r->font_px, r->bold, r->italic,
  6616. r->mono);
  6617. } else if (r->img >= 0) {
  6618. struct br_image *bi = &images[r->img];
  6619. if (bi->state == 1 && r->transform_scale) {
  6620. draw_image_transformed(l->ui, &bi->img,
  6621. x, ry, r->iw, r->ih,
  6622. r->scale_x, r->scale_y,
  6623. r->rotate_x100, r->origin_x,
  6624. r->origin_y, r->origin_x_kind,
  6625. r->origin_y_kind);
  6626. } else if (bi->state == 1) {
  6627. struct img_image *src =
  6628. image_display_get(bi, r->iw, r->ih);
  6629. struct img_blit b;
  6630. if (!src)
  6631. src = &bi->img;
  6632. b.dst = l->ui->px;
  6633. b.dst_w = l->ui->w;
  6634. b.dst_h = l->ui->h;
  6635. b.clip_x = page_rect.x;
  6636. b.clip_y = page_rect.y;
  6637. b.clip_w = page_rect.w - 12;
  6638. b.clip_h = page_rect.h;
  6639. b.x = x;
  6640. b.y = ry;
  6641. b.scale = ((unsigned int)r->iw << 16) /
  6642. src->w;
  6643. b.bg = ui.theme.bg;
  6644. b.bg2 = ui.theme.bg;
  6645. b.dst_a = 0;
  6646. b.flags = src->alpha ?
  6647. IMG_BLIT_OVER_DST : 0;
  6648. img_draw(src, &b);
  6649. }
  6650. } else {
  6651. const char *s = r->has_lit ? r->lit :
  6652. doc.text + r->off;
  6653. unsigned int n = r->has_lit ? s_len(r->lit) :
  6654. r->len;
  6655. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6656. s, n, r->color, r->font_px,
  6657. r->bold, r->italic, r->mono);
  6658. if (r->underline)
  6659. ngui_fill_rect(l->ui,
  6660. (struct ngui_rect){x,
  6661. ry + run_ascent(l->ui, r) + 2,
  6662. w, 1}, r->color);
  6663. if (r->strike)
  6664. ngui_fill_rect(l->ui,
  6665. (struct ngui_rect){x,
  6666. ry + run_ascent(l->ui, r) -
  6667. (r->font_px > 3 ?
  6668. r->font_px / 3 : 1),
  6669. w, 1}, r->color);
  6670. if (r->overline)
  6671. ngui_fill_rect(l->ui,
  6672. (struct ngui_rect){x, ry,
  6673. w, 1}, r->color);
  6674. }
  6675. if (r->form || r->href) {
  6676. if (nhits < HIT_MAX) {
  6677. struct hit *h = &hits[nhits];
  6678. unsigned int target = r->form ?
  6679. r->form - 1 : r->href;
  6680. int hh = (r->form || r->img >= 0 ||
  6681. r->img == RUN_SVG) ?
  6682. r->ih :
  6683. run_line_height(l->ui, r);
  6684. int merge = nhits > 0 &&
  6685. hits[nhits - 1].node == target &&
  6686. hits[nhits - 1].y == ry &&
  6687. hits[nhits - 1].h == hh &&
  6688. x <= hits[nhits - 1].x +
  6689. hits[nhits - 1].w + 2;
  6690. if (merge) {
  6691. struct hit *p = &hits[nhits - 1];
  6692. int end = x + w;
  6693. if (end > p->x + p->w)
  6694. p->w = end - p->x;
  6695. } else {
  6696. h->x = x;
  6697. h->y = ry;
  6698. h->w = w;
  6699. h->h = hh;
  6700. h->node = (unsigned short)target;
  6701. nhits++;
  6702. }
  6703. }
  6704. }
  6705. }
  6706. if (r->box)
  6707. inline_box_add(l, r->box, x, w);
  6708. x += w;
  6709. }
  6710. l->y += l->line_h + 2;
  6711. if (l->float_active && l->y >= l->float_bottom)
  6712. l->float_active = 0;
  6713. l->nruns = 0;
  6714. l->line_x = l->left;
  6715. l->run_x = l->left;
  6716. l->line_left = l->left;
  6717. l->line_right = l->right;
  6718. l->line_h = 0;
  6719. l->space_pending = 0;
  6720. }
  6721. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6722. const struct br_style *st, unsigned short href,
  6723. const char *lit)
  6724. {
  6725. unsigned int n = lit ? s_len(lit) : len;
  6726. const char *tp = lit ? lit : doc.text + off;
  6727. int w = (int)face_text_width(l->ui, st, tp, n);
  6728. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6729. flush_line(l);
  6730. if (l->nruns == 0) {
  6731. l->line_y = l->y;
  6732. l->line_h = 0;
  6733. start_line(l, st);
  6734. }
  6735. {
  6736. struct lay_run *r = &l->runs[l->nruns++];
  6737. int gap = l->line_x - l->run_x;
  6738. if (gap < 0)
  6739. gap = 0;
  6740. r->box = l->box_owner;
  6741. r->gap = (unsigned short)gap;
  6742. r->off = off;
  6743. r->len = len;
  6744. r->color = st->color;
  6745. r->href = href;
  6746. r->dy = 0;
  6747. r->has_lit = 0;
  6748. r->form = 0;
  6749. r->form_kind = 0;
  6750. r->form_disabled = 0;
  6751. r->lit[0] = '\0';
  6752. if (lit && lit[0]) {
  6753. unsigned int i;
  6754. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6755. r->lit[i] = lit[i];
  6756. r->lit[i] = '\0';
  6757. r->has_lit = 1;
  6758. }
  6759. r->img = -1;
  6760. r->iw = r->ih = 0;
  6761. r->font_px = st->font_px;
  6762. r->bold = st->bold;
  6763. r->italic = st->italic;
  6764. r->mono = st->mono;
  6765. r->font_face = st->font_face;
  6766. /* A control with its own background is a button, not body copy;
  6767. * an inherited link underline would strike through the fill. */
  6768. r->underline = st->underline && !st->has_bg;
  6769. r->strike = st->strike && !st->has_bg;
  6770. r->overline = st->overline && !st->has_bg;
  6771. r->w = (unsigned short)w;
  6772. if (r->has_lit)
  6773. r->w = (unsigned short)run_text_width(
  6774. l->ui, r, r->lit, s_len(r->lit));
  6775. w = r->w;
  6776. }
  6777. l->line_x += w;
  6778. l->run_x = l->line_x;
  6779. {
  6780. int lh = face_line_height(l->ui, st);
  6781. if (st->line_h_px)
  6782. lh = st->line_h_px;
  6783. else if (st->line_h_pct)
  6784. lh = st->font_px * st->line_h_pct / 100;
  6785. if (lh < face_line_height(l->ui, st))
  6786. lh = face_line_height(l->ui, st);
  6787. if (l->line_h < lh)
  6788. l->line_h = lh;
  6789. }
  6790. }
  6791. static void add_image_run(struct lay *l, unsigned int node,
  6792. const struct br_style *st, unsigned short href)
  6793. {
  6794. struct br_image *bi = 0;
  6795. int idx = doc.nodes[node].img_index;
  6796. int dw, dh, maxw;
  6797. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6798. bi = &images[idx];
  6799. if (l->nruns == 0)
  6800. start_line(l, st);
  6801. if (l->space_pending &&
  6802. (l->nruns > 0 || l->line_x > l->line_left)) {
  6803. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6804. if (l->line_x + sp <= l->line_right)
  6805. l->line_x += sp;
  6806. }
  6807. l->space_pending = 0;
  6808. if (!bi) {
  6809. const char *alt = br_alt(&doc, node);
  6810. struct br_style gs = *st;
  6811. char tmp[96];
  6812. unsigned int n = 0;
  6813. int w;
  6814. gs.color = BR_GRAY;
  6815. gs.underline = 0;
  6816. s_append(tmp, &n, "[", sizeof(tmp));
  6817. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6818. s_append(tmp, &n, "]", sizeof(tmp));
  6819. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6820. if (l->line_x + w > l->line_right &&
  6821. (l->nruns > 0 || l->line_x > l->line_left))
  6822. flush_line(l);
  6823. add_run(l, 0, 0, &gs, href, tmp);
  6824. if (!l->draw) {
  6825. int t = l->line_y < 0 ? 0 : l->line_y;
  6826. int hh = face_line_height(l->ui, &gs);
  6827. if (t > 65535)
  6828. t = 65535;
  6829. if (hh > 65535)
  6830. hh = 65535;
  6831. img_top[node] = (unsigned short)t;
  6832. img_h[node] = (unsigned short)hh;
  6833. }
  6834. return;
  6835. }
  6836. maxw = l->line_right - l->line_left;
  6837. if (maxw < 8)
  6838. maxw = 8;
  6839. {
  6840. int iw = bi->native_w, ih = bi->native_h;
  6841. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6842. if (iw <= 0 || ih <= 0) {
  6843. iw = (int)bi->img.w;
  6844. ih = (int)bi->img.h;
  6845. }
  6846. dw = iw;
  6847. dh = ih;
  6848. if (doc.nodes[node].width_attr) {
  6849. int want = doc.nodes[node].width_attr;
  6850. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6851. have_w = 1;
  6852. }
  6853. if (doc.nodes[node].height_attr) {
  6854. int want = doc.nodes[node].height_attr;
  6855. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6856. have_h = 1;
  6857. }
  6858. if (have_w && !have_h)
  6859. dh = ih ? ih * dw / iw : 0;
  6860. if (have_h && !have_w)
  6861. dw = iw ? iw * dh / ih : 0;
  6862. if (st->width_kind) {
  6863. css_w = 1;
  6864. if (st->width_kind == 3)
  6865. dw = maxw * st->width_calc_pct / 100 +
  6866. st->width_calc_px;
  6867. else
  6868. dw = st->width_kind == 2 ?
  6869. maxw * (int)st->width / 100 :
  6870. (int)st->width;
  6871. }
  6872. /* Percentage heights resolve against the containing block's
  6873. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6874. * 2rem }` holding an `img { height: 100% }`), and are auto
  6875. * when it has none; they used to use the width. */
  6876. if (st->height_kind == 1 ||
  6877. ((st->height_kind == 2 || st->height_kind == 3) &&
  6878. l->cb_h > 0)) {
  6879. css_h = 1;
  6880. if (st->height_kind == 3)
  6881. dh = l->cb_h * st->height_calc_pct / 100 +
  6882. st->height_calc_px;
  6883. else
  6884. dh = st->height_kind == 2 ?
  6885. l->cb_h * (int)st->height / 100 :
  6886. (int)st->height;
  6887. }
  6888. if (css_w && !css_h)
  6889. dh = ih ? ih * dw / iw : 0;
  6890. if (css_h && !css_w)
  6891. dw = iw ? iw * dh / ih : 0;
  6892. if (st->max_width_kind) {
  6893. int mw = st->max_width_kind == 3 ?
  6894. maxw * st->max_width_calc_pct / 100 +
  6895. st->max_width_calc_px :
  6896. st->max_width_kind == 2 ?
  6897. maxw * (int)st->max_width / 100 :
  6898. (int)st->max_width;
  6899. if (mw > 0 && dw > mw) {
  6900. dh = iw ? ih * mw / iw : 0;
  6901. dw = mw;
  6902. }
  6903. }
  6904. }
  6905. if (dw < 8)
  6906. dw = 8;
  6907. if (dh < 8)
  6908. dh = 8;
  6909. if (dw > maxw) {
  6910. dh = dw ? dh * maxw / dw : dh;
  6911. dw = maxw;
  6912. }
  6913. if (!l->draw) {
  6914. int t = l->line_y < 0 ? 0 : l->line_y;
  6915. if (t > 65535)
  6916. t = 65535;
  6917. if (dh > 65535)
  6918. dh = 65535;
  6919. img_top[node] = (unsigned short)t;
  6920. img_h[node] = (unsigned short)dh;
  6921. }
  6922. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6923. l->line_x > l->line_left))
  6924. flush_line(l);
  6925. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6926. flush_line(l);
  6927. if (l->nruns == 0) {
  6928. l->line_y = l->y;
  6929. l->line_h = 0;
  6930. start_line(l, st);
  6931. }
  6932. {
  6933. struct lay_run *r = &l->runs[l->nruns++];
  6934. int gap = l->line_x - l->run_x;
  6935. if (gap < 0)
  6936. gap = 0;
  6937. r->box = l->box_owner;
  6938. r->gap = (unsigned short)gap;
  6939. r->off = 0;
  6940. r->len = 0;
  6941. r->color = 0;
  6942. r->href = href;
  6943. r->form = 0;
  6944. r->form_kind = 0;
  6945. r->form_disabled = 0;
  6946. /* Inline replaced elements honour their vertical margins; this
  6947. * is how Bootstrap's negative logo margins centre the wordmark. */
  6948. {
  6949. int idy = mp_px(st, 0, l->right - l->left);
  6950. if (idy < -2048)
  6951. idy = -2048;
  6952. if (idy > 2048)
  6953. idy = 2048;
  6954. r->dy = (signed short)idy;
  6955. }
  6956. r->has_lit = 0;
  6957. r->lit[0] = '\0';
  6958. r->img = (short)idx;
  6959. r->iw = (unsigned short)dw;
  6960. r->ih = (unsigned short)dh;
  6961. r->w = (unsigned short)dw;
  6962. r->font_px = st->font_px;
  6963. r->bold = st->bold;
  6964. r->italic = st->italic;
  6965. r->mono = st->mono;
  6966. r->font_face = st->font_face;
  6967. r->transform_scale = st->transform_scale;
  6968. r->scale_x = st->scale_x;
  6969. r->scale_y = st->scale_y;
  6970. r->rotate_x100 = st->rotate_x100;
  6971. r->origin_x = st->origin_x;
  6972. r->origin_y = st->origin_y;
  6973. r->origin_x_kind = st->origin_x_kind;
  6974. r->origin_y_kind = st->origin_y_kind;
  6975. r->underline = 0;
  6976. }
  6977. if (node < BR_MAX_NODES) {
  6978. layout_boxes[node].x = l->line_x;
  6979. layout_boxes[node].y = l->line_y +
  6980. mp_px(st, 0, l->right - l->left);
  6981. layout_boxes[node].w = dw;
  6982. layout_boxes[node].h = dh;
  6983. layout_boxes[node].valid = 1;
  6984. }
  6985. l->line_x += dw;
  6986. l->run_x = l->line_x;
  6987. if (l->line_h < dh)
  6988. l->line_h = dh;
  6989. }
  6990. /* An inline (or inline-block) <svg> is a replaced element in the text
  6991. * line, like an <img>: comment bubbles and arrows sit next to their label
  6992. * instead of starting a block of their own. */
  6993. static void add_svg_run(struct lay *l, unsigned int node,
  6994. const struct br_style *st, unsigned short href)
  6995. {
  6996. struct lay_run *r;
  6997. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6998. if (lw < 8)
  6999. lw = 8;
  7000. cw = st->width_kind ? style_width_px(st, lw) : lw;
  7001. if (cw < 1)
  7002. cw = 1;
  7003. svg_size(node, st, cw, &dw, &dh);
  7004. if (dw > lw)
  7005. dw = lw;
  7006. ml = mp_px(st, 3, lw);
  7007. mr = mp_px(st, 1, lw);
  7008. if (ml < 0)
  7009. ml = 0;
  7010. if (mr < 0)
  7011. mr = 0;
  7012. if (l->line_x + ml + dw > l->line_right &&
  7013. (l->nruns > 0 || l->line_x > l->line_left))
  7014. flush_line(l);
  7015. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  7016. flush_line(l);
  7017. if (l->nruns == 0) {
  7018. l->line_y = l->y;
  7019. l->line_h = 0;
  7020. start_line(l, st);
  7021. }
  7022. l->line_x += ml;
  7023. r = &l->runs[l->nruns++];
  7024. memset(r, 0, sizeof(*r));
  7025. r->box = l->box_owner;
  7026. r->gap = (unsigned short)(l->line_x > l->run_x ?
  7027. l->line_x - l->run_x : 0);
  7028. r->off = node;
  7029. r->color = st->color;
  7030. r->href = href;
  7031. r->img = RUN_SVG;
  7032. r->iw = (unsigned short)dw;
  7033. r->ih = (unsigned short)dh;
  7034. r->w = (unsigned short)dw;
  7035. r->font_px = st->font_px;
  7036. if (node < BR_MAX_NODES) {
  7037. layout_boxes[node].x = l->line_x;
  7038. layout_boxes[node].y = l->line_y;
  7039. layout_boxes[node].w = dw;
  7040. layout_boxes[node].h = dh;
  7041. layout_boxes[node].valid = 1;
  7042. }
  7043. l->line_x += dw + mr;
  7044. l->run_x = l->line_x;
  7045. if (l->line_h < dh)
  7046. l->line_h = dh;
  7047. }
  7048. static int text_width(struct lay *l, const char *s, unsigned int n,
  7049. const struct br_style *st)
  7050. {
  7051. return (int)face_text_width(l->ui, st, s, n);
  7052. }
  7053. /* Longest prefix that fits in maxw, at least one byte. */
  7054. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  7055. const struct br_style *st, int maxw)
  7056. {
  7057. unsigned int take = 0;
  7058. while (take < n) {
  7059. if (text_width(l, s, take + 1, st) > maxw)
  7060. break;
  7061. take++;
  7062. }
  7063. return take ? take : 1;
  7064. }
  7065. static void emit_word(struct lay *l, const char *s, unsigned int start,
  7066. unsigned int n, unsigned int base,
  7067. const struct br_style *st, unsigned short href)
  7068. {
  7069. int avail;
  7070. int w = text_width(l, s + start, n, st);
  7071. unsigned int off = start;
  7072. if (l->nruns == 0)
  7073. start_line(l, st);
  7074. avail = l->line_right - l->line_left;
  7075. if (st->nowrap) {
  7076. if (n)
  7077. add_run(l, base + start,
  7078. (unsigned short)n, st, href, 0);
  7079. return;
  7080. }
  7081. /* A padded/bordered one-word button can be a few pixels wider than
  7082. * the content box; keep it on one line instead of splitting it. */
  7083. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7084. add_run(l, base + start,
  7085. (unsigned short)n, st, href, 0);
  7086. return;
  7087. }
  7088. if (l->line_x + w > l->line_right &&
  7089. (l->nruns > 0 || l->line_x > l->line_left)) {
  7090. flush_line(l);
  7091. start_line(l, st);
  7092. avail = l->line_right - l->line_left;
  7093. }
  7094. if (w <= avail) {
  7095. if (n)
  7096. add_run(l, base + start,
  7097. (unsigned short)n, st, href, 0);
  7098. return;
  7099. }
  7100. while (n > 0) {
  7101. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7102. add_run(l, base + off,
  7103. (unsigned short)take, st, href, 0);
  7104. off += take;
  7105. n -= take;
  7106. if (n) {
  7107. flush_line(l);
  7108. start_line(l, st);
  7109. avail = l->line_right - l->line_left;
  7110. }
  7111. }
  7112. }
  7113. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7114. const struct br_style *st, unsigned short href, int pre)
  7115. {
  7116. unsigned int i = 0;
  7117. unsigned int base;
  7118. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7119. if (!s || !len)
  7120. return;
  7121. if (space_w <= 0)
  7122. space_w = 8;
  7123. if (l->nruns == 0)
  7124. start_line(l, st);
  7125. base = (unsigned int)(s - doc.text);
  7126. if (st->uppercase) {
  7127. char *p = (char *)s;
  7128. unsigned int j;
  7129. for (j = 0; j < len; j++)
  7130. if (p[j] >= 'a' && p[j] <= 'z')
  7131. p[j] = (char)(p[j] - 'a' + 'A');
  7132. }
  7133. if (pre) {
  7134. while (i < len) {
  7135. unsigned int start;
  7136. if (s[i] == '\n') {
  7137. flush_line(l);
  7138. start_line(l, st);
  7139. i++;
  7140. continue;
  7141. }
  7142. if (s[i] == ' ') {
  7143. if (l->line_x + space_w > l->line_right &&
  7144. (l->nruns > 0 || l->line_x > l->line_left)) {
  7145. flush_line(l);
  7146. start_line(l, st);
  7147. } else {
  7148. l->line_x += space_w;
  7149. }
  7150. i++;
  7151. continue;
  7152. }
  7153. start = i;
  7154. while (i < len && s[i] != ' ' && s[i] != '\n')
  7155. i++;
  7156. emit_word(l, s, start, i - start, base, st, href);
  7157. }
  7158. return;
  7159. }
  7160. while (i < len) {
  7161. unsigned int start, n;
  7162. if (s[i] == ' ') {
  7163. l->space_pending = 1;
  7164. i++;
  7165. continue;
  7166. }
  7167. start = i;
  7168. while (i < len && s[i] != ' ')
  7169. i++;
  7170. n = i - start;
  7171. if (l->space_pending &&
  7172. (l->nruns > 0 || l->line_x > l->line_left)) {
  7173. if (st->nowrap ||
  7174. l->line_x + space_w <= l->line_right)
  7175. l->line_x += space_w;
  7176. }
  7177. l->space_pending = 0;
  7178. emit_word(l, s, start, n, base, st, href);
  7179. }
  7180. }
  7181. static int list_index(unsigned int parent, unsigned int node)
  7182. {
  7183. unsigned int n = 0, i;
  7184. for (i = doc.nodes[parent].first; i && i != node;
  7185. i = doc.nodes[i].next)
  7186. if (doc.nodes[i].tag == BR_TAG_LI)
  7187. n++;
  7188. return (int)n + 1;
  7189. }
  7190. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7191. unsigned int cap)
  7192. {
  7193. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7194. 50, 40, 10, 9, 5, 4, 1 };
  7195. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7196. "l", "xl", "x", "ix", "v", "iv", "i" };
  7197. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7198. "L", "XL", "X", "IX", "V", "IV", "I" };
  7199. unsigned int i;
  7200. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7201. while (v >= val[i] && *n + 1 < cap) {
  7202. const char *s = upper ? up[i] : lo[i];
  7203. while (*s && *n + 1 < cap)
  7204. m[(*n)++] = *s++;
  7205. v -= val[i];
  7206. }
  7207. }
  7208. }
  7209. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7210. {
  7211. unsigned int n = 0;
  7212. if (style == BR_LIST_DISC) {
  7213. m[n++] = '-';
  7214. } else if (style == BR_LIST_CIRCLE) {
  7215. m[n++] = 'o';
  7216. } else if (style == BR_LIST_SQUARE) {
  7217. m[n++] = '+';
  7218. } else if (style == BR_LIST_LOWER_ALPHA ||
  7219. style == BR_LIST_UPPER_ALPHA) {
  7220. if (idx >= 1 && idx <= 26)
  7221. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7222. 'A' : 'a') + idx - 1);
  7223. else
  7224. m[n++] = '?';
  7225. m[n++] = '.';
  7226. } else if (style == BR_LIST_LOWER_ROMAN ||
  7227. style == BR_LIST_UPPER_ROMAN) {
  7228. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7229. if (n + 1 < cap)
  7230. m[n++] = '.';
  7231. } else {
  7232. s_append_dec(m, &n, (unsigned int)idx, cap);
  7233. if (n + 1 < cap)
  7234. m[n++] = '.';
  7235. }
  7236. m[n] = '\0';
  7237. }
  7238. /* A control the page styled itself (background, border or radius in author
  7239. * CSS -- `background:transparent;border:none` counts) is painted with that
  7240. * style, sized from its padding/height and keeps the page's text colour.
  7241. * Unstyled controls keep the ngui theme look. */
  7242. static int form_author_styled(const struct br_style *st)
  7243. {
  7244. int i;
  7245. if (st->bg_set)
  7246. return 1;
  7247. for (i = 0; i < 4; i++)
  7248. if (st->border_w[i] || st->radius[i])
  7249. return 1;
  7250. return 0;
  7251. }
  7252. /* Set by the layout when the control is stretched to its line: a flex item
  7253. * (its box width was assigned by the flex row) or a child of a flex column,
  7254. * whose default align-items: stretch makes inputs full width. */
  7255. static int form_fill_line;
  7256. static void add_form_run(struct lay *l, unsigned int node,
  7257. const struct br_style *st, unsigned short href)
  7258. {
  7259. struct form_state *fs = form_get(node, 1);
  7260. char shown[FORM_VALUE_MAX + 1];
  7261. char opt[64];
  7262. const char *text = "";
  7263. struct lay_run *r;
  7264. int kind = form_kind_of(node);
  7265. int disabled = form_disabled(node);
  7266. int author = form_author_styled(st);
  7267. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7268. int ml = 0, mr = 0, mt = 0, mb = 0;
  7269. if (!fs)
  7270. return;
  7271. if (l->nruns == 0)
  7272. start_line(l, st);
  7273. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7274. text = "";
  7275. w = 16;
  7276. h = 16;
  7277. } else if (kind == FORM_SELECT) {
  7278. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7279. s_copy(opt, "Select", sizeof(opt));
  7280. text = opt;
  7281. w = 120;
  7282. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7283. kind == FORM_RESET) {
  7284. if (fs->len)
  7285. text = fs->value;
  7286. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7287. /* A <button>'s label is its content: an empty one
  7288. * (Docusaurus' sidebar caret, drawn by a CSS
  7289. * ::before icon) shows none. Only <input> buttons
  7290. * get the UA's default label. */
  7291. text = "";
  7292. else
  7293. text = kind == FORM_SUBMIT ? "Submit" :
  7294. kind == FORM_RESET ? "Reset" : "Button";
  7295. } else if (kind == FORM_PASSWORD) {
  7296. for (i = 0; i < fs->len; i++)
  7297. shown[i] = '*';
  7298. shown[fs->len] = '\0';
  7299. text = fs->len ? shown : br_placeholder(&doc, node);
  7300. } else {
  7301. if (fs->len)
  7302. text = fs->value;
  7303. else
  7304. text = br_placeholder(&doc, node);
  7305. if (kind == FORM_TEXTAREA) {
  7306. w = 180;
  7307. h = 40;
  7308. }
  7309. }
  7310. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7311. line_w = l->line_right - l->line_left;
  7312. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7313. st->border_w[1] + st->border_w[3];
  7314. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7315. st->border_w[0] + st->border_w[2];
  7316. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7317. /* Buttons are border-box in every UA stylesheet: an
  7318. * explicit width/height is the whole box. */
  7319. if (author || pad_x) {
  7320. w = tw + pad_x;
  7321. } else {
  7322. w = tw + 18;
  7323. if (w < 64)
  7324. w = 64;
  7325. }
  7326. if (st->width_kind)
  7327. w = style_width_px(st, line_w);
  7328. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7329. w = st->min_width;
  7330. if (st->height_kind == 1)
  7331. h = st->height;
  7332. else if (author)
  7333. h = st->font_px + 6 + pad_y;
  7334. else
  7335. h = 22;
  7336. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7337. kind == FORM_TEXTAREA) {
  7338. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7339. st->display == BR_DISPLAY_FLEX;
  7340. int boxed = st->box_sizing ? 0 : pad_x;
  7341. if (st->width_kind)
  7342. w = style_width_px(st, line_w) + boxed;
  7343. else if (fill)
  7344. w = line_w - (l->line_x - l->line_left);
  7345. else
  7346. w = kind == FORM_TEXTAREA ? 180 : 120;
  7347. if (kind == FORM_TEXTAREA) {
  7348. const char *ra = br_find_attr(&doc, node, "rows");
  7349. int rows = 0;
  7350. int lh = st->line_h_px ? st->line_h_px :
  7351. st->font_px * 5 / 4;
  7352. while (ra && *ra >= '0' && *ra <= '9')
  7353. rows = rows * 10 + (*ra++ - '0');
  7354. if (rows < 1 || rows > 40)
  7355. rows = 2;
  7356. h = author ? rows * lh + pad_y : 40;
  7357. } else if (author) {
  7358. h = st->font_px + 8 + pad_y;
  7359. } else if (st->font_px + 8 > h) {
  7360. /* Taller fields for large text (min-height/padding
  7361. * on login pages): keep the box around the glyphs. */
  7362. h = st->font_px + 8;
  7363. }
  7364. if (st->height_kind == 1)
  7365. h = st->height + (st->box_sizing ? 0 : pad_y);
  7366. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7367. h = st->min_height;
  7368. } else if (kind == FORM_SELECT) {
  7369. w = st->width_kind == 1 ? st->width : 120;
  7370. }
  7371. if (author) {
  7372. /* Inline margins (Google's `margin:11px 4px` between its
  7373. * two submit buttons). */
  7374. ml = mp_px(st, 3, line_w);
  7375. mr = mp_px(st, 1, line_w);
  7376. mt = mp_px(st, 0, line_w);
  7377. mb = mp_px(st, 2, line_w);
  7378. if (ml < 0 || ml > 64) ml = 0;
  7379. if (mr < 0 || mr > 64) mr = 0;
  7380. if (mt < 0 || mt > 64) mt = 0;
  7381. if (mb < 0 || mb > 64) mb = 0;
  7382. }
  7383. if (w > line_w - ml - mr)
  7384. w = line_w - ml - mr;
  7385. if (w < 8)
  7386. w = 8;
  7387. if (h > 400)
  7388. h = 400;
  7389. if (l->line_x + ml + w > l->line_right &&
  7390. (l->nruns > 0 || l->line_x > l->line_left))
  7391. flush_line(l);
  7392. if (l->nruns >= 96)
  7393. return;
  7394. if (l->nruns == 0) {
  7395. l->line_y = l->y;
  7396. l->line_h = 0;
  7397. start_line(l, st);
  7398. }
  7399. l->line_x += ml;
  7400. r = &l->runs[l->nruns++];
  7401. r->box = l->box_owner;
  7402. r->gap = (unsigned short)(l->line_x - l->run_x);
  7403. r->off = r->len = 0;
  7404. r->color = st->color;
  7405. r->href = href;
  7406. r->dy = (signed short)mt;
  7407. r->has_lit = 1;
  7408. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7409. r->lit[i] = text[i];
  7410. r->lit[i] = '\0';
  7411. r->img = -2;
  7412. r->iw = (unsigned short)w;
  7413. r->ih = (unsigned short)h;
  7414. r->w = (unsigned short)w;
  7415. r->font_px = st->font_px;
  7416. r->bold = st->bold;
  7417. r->italic = st->italic;
  7418. r->mono = st->mono;
  7419. r->font_face = st->font_face;
  7420. r->underline = 0;
  7421. r->form = node + 1;
  7422. r->form_kind = (unsigned char)kind;
  7423. r->form_disabled = (unsigned char)disabled;
  7424. if (node < BR_MAX_NODES) {
  7425. layout_boxes[node].x = l->line_x;
  7426. layout_boxes[node].y = l->line_y + mt;
  7427. layout_boxes[node].w = w;
  7428. layout_boxes[node].h = h;
  7429. layout_boxes[node].valid = 1;
  7430. }
  7431. l->line_x += w;
  7432. l->run_x = l->line_x;
  7433. l->line_x += mr;
  7434. if (l->line_h < h + mt + mb)
  7435. l->line_h = h + mt + mb;
  7436. }
  7437. /* Background, border and corner radius of an author-styled control, the
  7438. * same decoration rules as a block box. */
  7439. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7440. const struct br_style *st, int focused)
  7441. {
  7442. int rtl = css_radius(st, 0, box.w, box.h);
  7443. int rtr = css_radius(st, 1, box.w, box.h);
  7444. int rbr = css_radius(st, 2, box.w, box.h);
  7445. int rbl = css_radius(st, 3, box.w, box.h);
  7446. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7447. (void)focused;
  7448. if (box.w <= 0 || box.h <= 0)
  7449. return;
  7450. if (rtl || rtr || rbr || rbl) {
  7451. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7452. box.w > bw * 2 && box.h > bw * 2) {
  7453. struct ngui_rect in = { box.x + bw, box.y + bw,
  7454. box.w - bw * 2,
  7455. box.h - bw * 2 };
  7456. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7457. st->border_c[0]);
  7458. ngui_fill_round_rect(ui, in,
  7459. rtl > bw ? rtl - bw : 0,
  7460. rtr > bw ? rtr - bw : 0,
  7461. rbr > bw ? rbr - bw : 0,
  7462. rbl > bw ? rbl - bw : 0, st->bg);
  7463. } else if (st->has_bg) {
  7464. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7465. st->bg);
  7466. } else if (bw > 0) {
  7467. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7468. st->border_c[0]);
  7469. }
  7470. return;
  7471. }
  7472. if (st->has_bg)
  7473. ngui_fill_rect(ui, box, st->bg);
  7474. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7475. st->border_w[3])
  7476. draw_border_box(ui, box, st);
  7477. }
  7478. /* A poster wrapper is absolutely positioned over the media slot; the
  7479. * measured height of its picture is normally added back to the flow. When a
  7480. * loading-skeleton sibling already reserves that slot, adding both doubles
  7481. * the media height and pushes the article text a full screen down. */
  7482. static int has_skeleton_sibling(unsigned int node)
  7483. {
  7484. unsigned int p = doc.nodes[node].parent, c;
  7485. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7486. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7487. continue;
  7488. if (doc.nodes[c].class_off &&
  7489. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7490. "skeleton"))
  7491. return 1;
  7492. }
  7493. return 0;
  7494. }
  7495. static void layout_children(struct lay *l, unsigned int parent,
  7496. const struct br_style *pst, int depth,
  7497. unsigned short link);
  7498. static void layout_flex_children(struct lay *l, unsigned int parent,
  7499. const struct br_style *pst, int depth,
  7500. unsigned short link);
  7501. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7502. struct br_style *ps, int base);
  7503. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7504. const struct br_style *ps, unsigned short link);
  7505. static void layout_grid_children(struct lay *l, unsigned int parent,
  7506. const struct br_style *pst, int depth,
  7507. unsigned short link);
  7508. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7509. const struct br_style *pst, int depth,
  7510. unsigned short link);
  7511. static int flex_item_width(struct lay *l, unsigned int n,
  7512. const struct br_style *cs, int avail);
  7513. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7514. const struct br_style *pst, int depth,
  7515. unsigned short link);
  7516. static void layout_table_row(struct lay *l, unsigned int row,
  7517. const struct br_style *pst, int depth,
  7518. unsigned short link);
  7519. static int table_has_rowspan(unsigned int table);
  7520. static void layout_table(struct lay *l, unsigned int table,
  7521. const struct br_style *st, int depth,
  7522. unsigned short link);
  7523. /* A flex container whose items are only inline spans is usually just a
  7524. * heading/icon pair. Our flex row positions such items without emitting
  7525. * their inline text in some deep page contexts; normal inline flow renders
  7526. * the same content correctly. */
  7527. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7528. const struct br_style *cs, int depth,
  7529. unsigned short lk);
  7530. static void layout_flex_column(struct lay *l, unsigned int parent,
  7531. const struct br_style *pst, int depth,
  7532. unsigned short link);
  7533. static void emit_pseudo(struct lay *l, unsigned int node,
  7534. const struct br_style *st, int pe, unsigned short link);
  7535. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7536. {
  7537. unsigned int c;
  7538. int items = 0;
  7539. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7540. struct br_node *nd = &doc.nodes[c];
  7541. struct br_style cs;
  7542. if (nd->type == BR_NODE_TEXT)
  7543. continue;
  7544. br_style_for(&doc, c, pst, &cs);
  7545. if (cs.display == BR_DISPLAY_NONE)
  7546. continue;
  7547. /* `justify-content: space-between` spreads even two plain
  7548. * inline items (a "Password ... Reset password" label row)
  7549. * across the line; inline flow would set them side by side. */
  7550. if (++items >= 2 && pst->justify >= 3)
  7551. return 1;
  7552. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7553. cs.width_kind || cs.has_bg ||
  7554. cs.border_w[0] || cs.border_w[1] ||
  7555. cs.border_w[2] || cs.border_w[3] ||
  7556. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7557. return 1;
  7558. }
  7559. return 0;
  7560. }
  7561. static int css_radius(const struct br_style *st, int corner,
  7562. int w, int h)
  7563. {
  7564. int r = st->radius[corner];
  7565. if (r <= 0)
  7566. return 0;
  7567. if (r > w / 2)
  7568. r = w / 2;
  7569. if (r > h / 2)
  7570. r = h / 2;
  7571. return r;
  7572. }
  7573. /* ---- inline SVG ----
  7574. *
  7575. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7576. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7577. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7578. * opacity and solid paint; a gradient paints the average of its stops) and
  7579. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7580. #define SVG_CACHE_MAX 48
  7581. #define SVG_CACHE_PIXELS (640 * 1024)
  7582. #define SVG_MAX_POINTS 24576
  7583. struct svg_cache_ent {
  7584. unsigned int node;
  7585. int w, h;
  7586. unsigned short *px;
  7587. unsigned char *a;
  7588. unsigned int stamp;
  7589. };
  7590. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7591. static unsigned int svg_cache_pixels, svg_cache_clock;
  7592. static struct svgr svg_geom;
  7593. static void *svg_geom_buf;
  7594. /* Current viewport in user units: percentage lengths resolve against it
  7595. * (the viewBox size, not the device pixels). */
  7596. static double svg_vp_w = 300, svg_vp_h = 150;
  7597. /* The layers live in the page heap: forget them before heap_reset(). */
  7598. static void svg_cache_clear(void)
  7599. {
  7600. memset(svg_cache, 0, sizeof(svg_cache));
  7601. svg_cache_pixels = 0;
  7602. svg_geom_buf = 0;
  7603. }
  7604. static int svg_name_is(const char *a, const char *b)
  7605. {
  7606. while (*a && *b) {
  7607. char x = *a, y = *b;
  7608. if (x >= 'A' && x <= 'Z')
  7609. x = (char)(x - 'A' + 'a');
  7610. if (x != y)
  7611. return 0;
  7612. a++;
  7613. b++;
  7614. }
  7615. return *a == *b;
  7616. }
  7617. static const char *svg_elem_name(unsigned int node)
  7618. {
  7619. const struct br_node *nd = &doc.nodes[node];
  7620. if (nd->name_off)
  7621. return doc.attrs + nd->name_off;
  7622. return br_tag_name(nd->tag);
  7623. }
  7624. /* A numeric attribute; a percentage resolves against `base`. */
  7625. static double svg_attr_num(unsigned int node, const char *name, double def,
  7626. double base)
  7627. {
  7628. const char *v = br_find_attr(&doc, node, name);
  7629. const char *p = v;
  7630. int ok = 0;
  7631. double x;
  7632. if (!v)
  7633. return def;
  7634. x = svgr_num(&p, &ok);
  7635. if (!ok)
  7636. return def;
  7637. if (*p == '%')
  7638. x = x * base / 100.0;
  7639. return x;
  7640. }
  7641. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7642. static int svg_viewbox4(unsigned int node, double vb[4])
  7643. {
  7644. const char *v = br_find_attr(&doc, node, "viewbox");
  7645. const char *p = v;
  7646. int i, ok = 1;
  7647. if (!v)
  7648. return 0;
  7649. for (i = 0; i < 4 && ok; i++)
  7650. vb[i] = svgr_num(&p, &ok);
  7651. return ok && vb[2] > 0 && vb[3] > 0;
  7652. }
  7653. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7654. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7655. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7656. double w, double h, double m[6])
  7657. {
  7658. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7659. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7660. int ax = 1, ay = 1;
  7661. if (par && contains_ci(par, "none")) {
  7662. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7663. m[4] = -vb[0] * sx;
  7664. m[5] = -vb[1] * sy;
  7665. return;
  7666. }
  7667. if (par) {
  7668. if (contains_ci(par, "xmin"))
  7669. ax = 0;
  7670. else if (contains_ci(par, "xmax"))
  7671. ax = 2;
  7672. if (contains_ci(par, "ymin"))
  7673. ay = 0;
  7674. else if (contains_ci(par, "ymax"))
  7675. ay = 2;
  7676. }
  7677. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7678. (sx < sy ? sx : sy);
  7679. tx = (w - vb[2] * s) * ax / 2.0;
  7680. ty = (h - vb[3] * s) * ay / 2.0;
  7681. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7682. m[4] = tx - vb[0] * s;
  7683. m[5] = ty - vb[1] * s;
  7684. }
  7685. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7686. * the paint attribute, then average the gradient's stops. */
  7687. static int svg_url_paint(unsigned int node, const char *attr,
  7688. unsigned short *color, unsigned int *alpha)
  7689. {
  7690. const char *v = 0, *h;
  7691. char id[64];
  7692. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7693. for (k = 0; node && k < 32 && !v; k++) {
  7694. v = br_find_attr(&doc, node, attr);
  7695. if (!v) {
  7696. const char *style = br_find_attr(&doc, node, "style");
  7697. if (style && contains_ci(style, "url(#"))
  7698. v = strstr(style, "url(#");
  7699. }
  7700. if (v && !contains_ci(v, "url("))
  7701. v = 0;
  7702. node = doc.nodes[node].parent;
  7703. }
  7704. if (!v || !(h = strstr(v, "#")))
  7705. return 0;
  7706. h++;
  7707. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7708. id[n++] = *h++;
  7709. id[n] = '\0';
  7710. g = br_find_id(&doc, id);
  7711. /* Follow href chains (a gradient that only references another one's
  7712. * stops), at most a few hops. */
  7713. for (k = 0; g && k < 4; k++) {
  7714. unsigned int gi = g - 1;
  7715. const char *ref;
  7716. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7717. const char *nm, *sc, *so;
  7718. unsigned short col = 0;
  7719. double op = 1;
  7720. if (doc.nodes[c].type != BR_NODE_ELEM)
  7721. continue;
  7722. nm = svg_elem_name(c);
  7723. if (!svg_name_is(nm, "stop"))
  7724. continue;
  7725. sc = br_find_attr(&doc, c, "stop-color");
  7726. so = br_find_attr(&doc, c, "stop-opacity");
  7727. {
  7728. const char *st = br_find_attr(&doc, c, "style");
  7729. const char *q;
  7730. if (st && (q = strstr(st, "stop-color:")) != 0)
  7731. sc = q + 11;
  7732. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7733. so = q + 13;
  7734. }
  7735. if (sc) {
  7736. unsigned int L = 0;
  7737. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7738. L++;
  7739. if (!br_parse_color(sc, L, &col))
  7740. col = 0;
  7741. }
  7742. if (so) {
  7743. const char *p = so;
  7744. int ok = 0;
  7745. double x = svgr_num(&p, &ok);
  7746. if (ok)
  7747. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7748. }
  7749. sr += (col >> 11) & 31;
  7750. sg += (col >> 5) & 63;
  7751. sb += col & 31;
  7752. sa += (unsigned int)(op * 255);
  7753. cnt++;
  7754. }
  7755. if (cnt)
  7756. break;
  7757. ref = br_find_attr(&doc, gi, "href");
  7758. if (!ref)
  7759. ref = br_find_attr(&doc, gi, "xlink:href");
  7760. if (!ref || ref[0] != '#')
  7761. break;
  7762. g = br_find_id(&doc, ref + 1);
  7763. }
  7764. if (!cnt)
  7765. return 0;
  7766. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7767. (sb / cnt));
  7768. *alpha = sa / cnt;
  7769. return 1;
  7770. }
  7771. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7772. unsigned short *color, unsigned int *alpha)
  7773. {
  7774. int mode = fill ? st->fill_mode : st->stroke_mode;
  7775. const char *op = br_find_attr(&doc, node,
  7776. fill ? "fill-opacity" : "stroke-opacity");
  7777. *alpha = 255;
  7778. switch (mode) {
  7779. case BR_PAINT_UNSET:
  7780. if (!fill)
  7781. return 0;
  7782. *color = 0;
  7783. break;
  7784. case BR_PAINT_COLOR:
  7785. *color = fill ? st->fill : st->stroke;
  7786. break;
  7787. case BR_PAINT_CURRENT:
  7788. *color = st->color;
  7789. break;
  7790. case BR_PAINT_URL:
  7791. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7792. alpha))
  7793. return 0;
  7794. break;
  7795. default:
  7796. return 0;
  7797. }
  7798. if (op) {
  7799. const char *p = op;
  7800. int ok = 0;
  7801. double x = svgr_num(&p, &ok);
  7802. if (ok)
  7803. *alpha = (unsigned int)(*alpha *
  7804. (x < 0 ? 0 : x > 1 ? 1 : x));
  7805. }
  7806. return *alpha > 0;
  7807. }
  7808. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7809. const double m[6], const struct br_style *pst,
  7810. unsigned int alpha, int depth);
  7811. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7812. const double m[6], const struct br_style *st,
  7813. unsigned int alpha, int depth)
  7814. {
  7815. unsigned int c;
  7816. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7817. if (doc.nodes[c].type == BR_NODE_ELEM)
  7818. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7819. }
  7820. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7821. const double pm[6], const struct br_style *pst,
  7822. unsigned int alpha, int depth)
  7823. {
  7824. struct br_style st;
  7825. const char *nm = svg_elem_name(node);
  7826. const char *tf;
  7827. double m[6];
  7828. unsigned short color;
  7829. unsigned int pa;
  7830. int shape = 0, fillable = 1;
  7831. if (depth > 24 || !nm)
  7832. return;
  7833. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7834. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7835. svg_name_is(nm, "lineargradient") ||
  7836. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7837. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7838. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7839. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7840. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7841. svg_name_is(nm, "foreignobject"))
  7842. return;
  7843. br_style_for(&doc, node, pst, &st);
  7844. if (st.display == BR_DISPLAY_NONE)
  7845. return;
  7846. memcpy(m, pm, sizeof(m));
  7847. tf = br_find_attr(&doc, node, "transform");
  7848. if (tf)
  7849. svgr_transform(m, tf);
  7850. {
  7851. const char *op = br_find_attr(&doc, node, "opacity");
  7852. if (op) {
  7853. const char *p = op;
  7854. int ok = 0;
  7855. double x = svgr_num(&p, &ok);
  7856. if (ok)
  7857. alpha = (unsigned int)(alpha *
  7858. (x < 0 ? 0 :
  7859. x > 1 ? 1 : x));
  7860. }
  7861. }
  7862. if (!alpha)
  7863. return;
  7864. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7865. svg_name_is(nm, "switch")) {
  7866. svg_draw_children(L, node, m, &st, alpha, depth);
  7867. return;
  7868. }
  7869. if (svg_name_is(nm, "svg")) {
  7870. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7871. y = svg_attr_num(node, "y", 0, 0);
  7872. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7873. t[4] = x;
  7874. t[5] = y;
  7875. svgr_mat_mul(m, m, t);
  7876. double ow = svg_vp_w, oh = svg_vp_h;
  7877. if (svg_viewbox4(node, vb)) {
  7878. double w = svg_attr_num(node, "width", vb[2], ow);
  7879. double h = svg_attr_num(node, "height", vb[3], oh);
  7880. double vm[6];
  7881. svg_viewport_matrix(node, vb, w, h, vm);
  7882. svgr_mat_mul(m, m, vm);
  7883. svg_vp_w = vb[2];
  7884. svg_vp_h = vb[3];
  7885. }
  7886. svg_draw_children(L, node, m, &st, alpha, depth);
  7887. svg_vp_w = ow;
  7888. svg_vp_h = oh;
  7889. return;
  7890. }
  7891. if (svg_name_is(nm, "use")) {
  7892. const char *ref = br_find_attr(&doc, node, "href");
  7893. unsigned int tgt;
  7894. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7895. if (!ref)
  7896. ref = br_find_attr(&doc, node, "xlink:href");
  7897. if (!ref || ref[0] != '#')
  7898. return;
  7899. tgt = br_find_id(&doc, ref + 1);
  7900. if (!tgt || tgt - 1 == node)
  7901. return;
  7902. tgt--;
  7903. t[4] = svg_attr_num(node, "x", 0, 0);
  7904. t[5] = svg_attr_num(node, "y", 0, 0);
  7905. svgr_mat_mul(m, m, t);
  7906. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7907. double vb[4];
  7908. double ow = svg_vp_w, oh = svg_vp_h;
  7909. if (svg_viewbox4(tgt, vb)) {
  7910. /* A <use> without width/height sizes the
  7911. * symbol to 100% of the viewport: Docusaurus'
  7912. * 13.5px external-link icon references a
  7913. * 24-unit symbol and showed only its corner. */
  7914. double w = svg_attr_num(node, "width",
  7915. ow > 0 ? ow : vb[2], ow);
  7916. double h = svg_attr_num(node, "height",
  7917. oh > 0 ? oh : vb[3], oh);
  7918. double vm[6];
  7919. svg_viewport_matrix(tgt, vb, w, h, vm);
  7920. svgr_mat_mul(m, m, vm);
  7921. svg_vp_w = vb[2];
  7922. svg_vp_h = vb[3];
  7923. }
  7924. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7925. svg_vp_w = ow;
  7926. svg_vp_h = oh;
  7927. } else {
  7928. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7929. }
  7930. return;
  7931. }
  7932. svgr_reset(&svg_geom, m);
  7933. if (svg_name_is(nm, "path")) {
  7934. const char *d = br_find_attr(&doc, node, "d");
  7935. if (d) {
  7936. svgr_path(&svg_geom, d);
  7937. shape = 1;
  7938. }
  7939. } else if (svg_name_is(nm, "rect")) {
  7940. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7941. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7942. double rx = svg_attr_num(node, "rx", -1, w);
  7943. double ry = svg_attr_num(node, "ry", -1, h);
  7944. if (rx < 0)
  7945. rx = ry < 0 ? 0 : ry;
  7946. if (ry < 0)
  7947. ry = rx;
  7948. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7949. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7950. shape = 1;
  7951. } else if (svg_name_is(nm, "circle")) {
  7952. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7953. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7954. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7955. shape = 1;
  7956. } else if (svg_name_is(nm, "ellipse")) {
  7957. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7958. svg_attr_num(node, "cy", 0, svg_vp_h),
  7959. svg_attr_num(node, "rx", 0, svg_vp_w),
  7960. svg_attr_num(node, "ry", 0, svg_vp_h));
  7961. shape = 1;
  7962. } else if (svg_name_is(nm, "line")) {
  7963. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7964. svg_attr_num(node, "y1", 0, svg_vp_h));
  7965. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7966. svg_attr_num(node, "y2", 0, svg_vp_h));
  7967. shape = 1;
  7968. fillable = 0;
  7969. } else if (svg_name_is(nm, "polyline") ||
  7970. svg_name_is(nm, "polygon")) {
  7971. const char *pts = br_find_attr(&doc, node, "points");
  7972. if (pts) {
  7973. svgr_points(&svg_geom, pts,
  7974. svg_name_is(nm, "polygon"));
  7975. shape = 1;
  7976. }
  7977. }
  7978. if (!shape)
  7979. return;
  7980. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7981. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7982. st.fill_evenodd);
  7983. if (svg_paint(node, &st, 0, &color, &pa)) {
  7984. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7985. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7986. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7987. }
  7988. }
  7989. /* <text> elements: drawn straight onto the page every frame (the glyph
  7990. * renderer targets the ngui canvas, not a layer). x/y map through the
  7991. * accumulated transform; the font size scales with it. */
  7992. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7993. const double pm[6], const struct br_style *pst,
  7994. int ox, int oy, int depth)
  7995. {
  7996. unsigned int c;
  7997. if (depth > 24)
  7998. return;
  7999. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8000. struct br_style st;
  8001. const char *nm, *tf;
  8002. double m[6];
  8003. if (doc.nodes[c].type != BR_NODE_ELEM)
  8004. continue;
  8005. nm = svg_elem_name(c);
  8006. if (!nm || svg_name_is(nm, "defs") ||
  8007. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  8008. svg_name_is(nm, "clippath"))
  8009. continue;
  8010. br_style_for(&doc, c, pst, &st);
  8011. if (st.display == BR_DISPLAY_NONE)
  8012. continue;
  8013. memcpy(m, pm, sizeof(m));
  8014. tf = br_find_attr(&doc, c, "transform");
  8015. if (tf)
  8016. svgr_transform(m, tf);
  8017. if (svg_name_is(nm, "text")) {
  8018. unsigned int t = doc.nodes[c].first;
  8019. const char *s;
  8020. unsigned int n, tw;
  8021. double x = svg_attr_num(c, "x", 0, 0),
  8022. y = svg_attr_num(c, "y", 0, 0);
  8023. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8024. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  8025. int tx, ty, anchor;
  8026. unsigned short col;
  8027. unsigned int pa;
  8028. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  8029. continue;
  8030. if (px < 6)
  8031. px = 6;
  8032. if (px > 72)
  8033. px = 72;
  8034. if (!svg_paint(c, &st, 1, &col, &pa))
  8035. continue;
  8036. s = doc.text + doc.nodes[t].text_off;
  8037. n = doc.nodes[t].text_len;
  8038. st.font_px = (unsigned char)px;
  8039. tw = face_text_width(ui, &st, s, n);
  8040. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  8041. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  8042. ngui_text_ascent_face(ui, style_face(&st), px,
  8043. st.mono);
  8044. anchor = st.align;
  8045. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  8046. anchor = BR_ALIGN_CENTER;
  8047. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  8048. anchor = BR_ALIGN_RIGHT;
  8049. if (anchor == BR_ALIGN_CENTER)
  8050. tx -= (int)tw / 2;
  8051. else if (anchor == BR_ALIGN_RIGHT)
  8052. tx -= (int)tw;
  8053. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  8054. col, px, st.bold, st.italic,
  8055. st.mono);
  8056. } else {
  8057. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  8058. }
  8059. }
  8060. }
  8061. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  8062. {
  8063. double vb[4];
  8064. if (svg_viewbox4(node, vb)) {
  8065. svg_viewport_matrix(node, vb, w, h, m);
  8066. } else {
  8067. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  8068. }
  8069. }
  8070. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  8071. const struct br_style *st)
  8072. {
  8073. struct svg_cache_ent *e = 0;
  8074. struct svgr_layer L;
  8075. double m[6];
  8076. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  8077. svg_cache_clock++;
  8078. for (i = 0; i < SVG_CACHE_MAX; i++)
  8079. if (svg_cache[i].px && svg_cache[i].node == node &&
  8080. svg_cache[i].w == w && svg_cache[i].h == h) {
  8081. svg_cache[i].stamp = svg_cache_clock;
  8082. return &svg_cache[i];
  8083. }
  8084. if (need > SVG_CACHE_PIXELS)
  8085. return 0;
  8086. /* Evict least recently used layers until this one fits. */
  8087. for (;;) {
  8088. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8089. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8090. if (!svg_cache[i].px) {
  8091. if (!free_slot)
  8092. free_slot = &svg_cache[i];
  8093. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8094. lru = &svg_cache[i];
  8095. }
  8096. }
  8097. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8098. e = free_slot;
  8099. break;
  8100. }
  8101. if (!lru)
  8102. return 0;
  8103. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8104. free(lru->px);
  8105. free(lru->a);
  8106. memset(lru, 0, sizeof(*lru));
  8107. }
  8108. if (!svg_geom_buf) {
  8109. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8110. if (!svg_geom_buf)
  8111. return 0;
  8112. }
  8113. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8114. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8115. e->a = (unsigned char *)calloc(need, 1);
  8116. if (!e->px || !e->a) {
  8117. free(e->px);
  8118. free(e->a);
  8119. memset(e, 0, sizeof(*e));
  8120. return 0;
  8121. }
  8122. e->node = node;
  8123. e->w = w;
  8124. e->h = h;
  8125. e->stamp = svg_cache_clock;
  8126. svg_cache_pixels += need;
  8127. L.px = e->px;
  8128. L.a = e->a;
  8129. L.w = w;
  8130. L.h = h;
  8131. svg_root_matrix(node, w, h, m);
  8132. {
  8133. double vb[4];
  8134. if (svg_viewbox4(node, vb)) {
  8135. svg_vp_w = vb[2];
  8136. svg_vp_h = vb[3];
  8137. } else {
  8138. svg_vp_w = w;
  8139. svg_vp_h = h;
  8140. }
  8141. }
  8142. svg_draw_children(&L, node, m, st, 255, 0);
  8143. return e;
  8144. }
  8145. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8146. *
  8147. * The markup is parsed into a detached subtree of the page document and
  8148. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8149. * bitmap, which then behaves like any decoded image. currentColor is
  8150. * black (an image has no inherited text colour); <text> is not drawn. */
  8151. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8152. {
  8153. unsigned int i = 0;
  8154. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8155. i = 3;
  8156. while (i < len) {
  8157. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8158. d[i] == '\r' || d[i] == '\n'))
  8159. i++;
  8160. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8161. return 1;
  8162. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8163. i += 4;
  8164. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8165. i++;
  8166. i += 3;
  8167. continue;
  8168. }
  8169. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8170. while (i < len && d[i] != '>')
  8171. i++;
  8172. i++;
  8173. continue;
  8174. }
  8175. return 0;
  8176. }
  8177. return 0;
  8178. }
  8179. static int svg_len_attr(unsigned int node, const char *name)
  8180. {
  8181. const char *v = br_find_attr(&doc, node, name);
  8182. int n = 0, any = 0;
  8183. if (!v)
  8184. return 0;
  8185. while (*v == ' ')
  8186. v++;
  8187. while (*v >= '0' && *v <= '9') {
  8188. n = n * 10 + (*v++ - '0');
  8189. any = 1;
  8190. }
  8191. if (*v == '.')
  8192. while (*++v >= '0' && *v <= '9')
  8193. ;
  8194. if (!any || *v == '%')
  8195. return 0;
  8196. return n;
  8197. }
  8198. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8199. struct br_image *bi, int box_w, int box_h)
  8200. {
  8201. unsigned int holder, svg = 0, c, need, i;
  8202. struct br_style base = base_style(), st;
  8203. struct svgr_layer L;
  8204. double vb[4], m[6];
  8205. int w, h, have_vb, nat_w, nat_h;
  8206. holder = br_create_element(&doc, "div", 3);
  8207. if (!holder) {
  8208. s_copy(bi->err, "page is full", sizeof(bi->err));
  8209. return -1;
  8210. }
  8211. holder--;
  8212. br_set_inner_html(&doc, holder, (const char *)data, len);
  8213. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8214. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8215. doc.nodes[c].tag == BR_TAG_SVG) {
  8216. svg = c;
  8217. break;
  8218. }
  8219. if (!svg) {
  8220. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8221. return -1;
  8222. }
  8223. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8224. w = svg_len_attr(svg, "width");
  8225. h = svg_len_attr(svg, "height");
  8226. if (box_w > 0 && box_h > 0) {
  8227. w = box_w;
  8228. h = box_h;
  8229. } else if (!w && !h) {
  8230. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8231. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8232. } else if (!w) {
  8233. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8234. } else if (!h) {
  8235. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8236. }
  8237. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8238. * so CSS scaling stays crisp. */
  8239. nat_w = w;
  8240. nat_h = h;
  8241. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8242. w *= 2;
  8243. h *= 2;
  8244. }
  8245. if (w > BR_IMG_LAYOUT_W) {
  8246. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8247. w = BR_IMG_LAYOUT_W;
  8248. }
  8249. if (h > 2048)
  8250. h = 2048;
  8251. if (w < 1)
  8252. w = 1;
  8253. if (h < 1)
  8254. h = 1;
  8255. need = (unsigned int)w * (unsigned int)h;
  8256. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8257. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8258. return -1;
  8259. }
  8260. if (!svg_geom_buf) {
  8261. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8262. if (!svg_geom_buf) {
  8263. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8264. return -1;
  8265. }
  8266. }
  8267. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8268. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8269. L.a = (unsigned char *)calloc(need, 1);
  8270. if (!L.px || !L.a) {
  8271. free(L.px);
  8272. free(L.a);
  8273. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8274. return -1;
  8275. }
  8276. for (i = 0; i < need; i++)
  8277. L.px[i] = 0xFFFF;
  8278. L.w = w;
  8279. L.h = h;
  8280. base.color = 0x0000;
  8281. br_style_for(&doc, svg, &base, &st);
  8282. svg_root_matrix(svg, w, h, m);
  8283. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8284. /* No viewBox: user units are CSS pixels of the natural size,
  8285. * so the up-to-4x raster (and a box size) must scale them.
  8286. * A 40x20 icon used to fill only the top-left quarter of its
  8287. * 160x80 bitmap and was drawn at a quarter of its size. */
  8288. m[0] = (double)w / nat_w;
  8289. m[3] = (double)h / nat_h;
  8290. }
  8291. svg_vp_w = have_vb ? vb[2] : nat_w;
  8292. svg_vp_h = have_vb ? vb[3] : nat_h;
  8293. svg_draw_children(&L, svg, m, &st, 255, 0);
  8294. bi->native_w = nat_w;
  8295. bi->native_h = nat_h;
  8296. bi->img.format = 0;
  8297. bi->img.w = (unsigned int)w;
  8298. bi->img.h = (unsigned int)h;
  8299. bi->img.px = L.px;
  8300. bi->img.alpha = L.a;
  8301. bi->img.flags = 0;
  8302. bi->state = 1;
  8303. image_pixels += need;
  8304. return 0;
  8305. }
  8306. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8307. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8308. int *out_w, int *out_h)
  8309. {
  8310. double vb[4];
  8311. int has_vb = svg_viewbox4(node, vb);
  8312. double aw = svg_attr_num(node, "width", -1, cw);
  8313. double ah = svg_attr_num(node, "height", -1, 0);
  8314. int w, h;
  8315. if (st->width_kind)
  8316. w = cw;
  8317. else if (aw > 0)
  8318. w = (int)(aw + 0.5);
  8319. else if (st->height_kind == 1 && has_vb)
  8320. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8321. else if (ah > 0 && has_vb)
  8322. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8323. else if (has_vb)
  8324. w = cw;
  8325. else
  8326. w = 300;
  8327. if (st->max_width_kind == 1 && w > st->max_width)
  8328. w = st->max_width;
  8329. if (w > cw && cw > 0 && !(aw > 0))
  8330. w = cw;
  8331. if (w < 1)
  8332. w = 1;
  8333. if (w > 2000)
  8334. w = 2000;
  8335. if (st->height_kind == 1)
  8336. h = st->height;
  8337. else if (ah > 0)
  8338. h = (int)(ah + 0.5);
  8339. else if (has_vb)
  8340. h = (int)(w * vb[3] / vb[2] + 0.5);
  8341. else
  8342. h = 150;
  8343. if (h < 1)
  8344. h = 1;
  8345. if (h > 1400)
  8346. h = 1400;
  8347. *out_w = w;
  8348. *out_h = h;
  8349. }
  8350. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8351. const struct br_style *st, int x, int y, int w, int h)
  8352. {
  8353. struct svg_cache_ent *e;
  8354. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8355. int cx0, cy0, cx1, cy1, px, py;
  8356. double m[6];
  8357. if (ui->nclip > 0)
  8358. clip = ui->clip[ui->nclip - 1];
  8359. cx0 = r.x > clip.x ? r.x : clip.x;
  8360. cy0 = r.y > clip.y ? r.y : clip.y;
  8361. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8362. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8363. if (cx0 >= cx1 || cy0 >= cy1)
  8364. return;
  8365. e = svg_layer(node, w, h, st);
  8366. if (e) {
  8367. for (py = cy0; py < cy1; py++) {
  8368. unsigned int srow = (unsigned int)(py - y) *
  8369. (unsigned int)w;
  8370. unsigned short *dst = ui->px + py * ui->w;
  8371. for (px = cx0; px < cx1; px++) {
  8372. unsigned int si = srow + (unsigned int)(px - x);
  8373. unsigned int a = e->a[si];
  8374. if (!a)
  8375. continue;
  8376. dst[px] = a >= 255 ? e->px[si] :
  8377. blend_rgb565(dst[px], e->px[si], a);
  8378. }
  8379. }
  8380. }
  8381. svg_root_matrix(node, w, h, m);
  8382. ngui_push_clip(ui, r);
  8383. svg_draw_text(ui, node, m, st, x, y, 0);
  8384. ngui_pop_clip(ui);
  8385. }
  8386. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8387. * keep using add_image_run(); this covers the CSS `position:absolute;
  8388. * width:100%` poster pattern used by news sites. */
  8389. static void image_block_size(unsigned int node, const struct br_style *st,
  8390. int cbw, int *out_w, int *out_h)
  8391. {
  8392. struct br_node *nd = &doc.nodes[node];
  8393. int idx = nd->img_index;
  8394. int iw = 0, ih = 0, w, h, aw, ah;
  8395. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8396. iw = (int)images[idx].img.w;
  8397. ih = (int)images[idx].img.h;
  8398. if (iw <= 0 || ih <= 0) {
  8399. iw = (int)images[idx].native_w;
  8400. ih = (int)images[idx].native_h;
  8401. }
  8402. }
  8403. if (st->width_kind)
  8404. w = style_width_px(st, cbw);
  8405. else if (nd->width_attr)
  8406. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8407. (int)nd->width_attr;
  8408. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8409. w = iw * (int)nd->height_attr / ih;
  8410. else if (iw)
  8411. w = iw;
  8412. else
  8413. w = 64;
  8414. /* max-width/min-width against the containing block: Tailwind's
  8415. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8416. * 300x300 thumbnail to its 75 px avatar box. */
  8417. if (st->max_width_kind) {
  8418. int mw = st->max_width_kind == 3 ?
  8419. cbw * st->max_width_calc_pct / 100 +
  8420. st->max_width_calc_px :
  8421. st->max_width_kind == 2 ?
  8422. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8423. if (mw > 0 && w > mw)
  8424. w = mw;
  8425. }
  8426. if (st->min_width_kind) {
  8427. int mn = st->min_width_kind == 3 ?
  8428. cbw * st->min_width_calc_pct / 100 +
  8429. st->min_width_calc_px :
  8430. st->min_width_kind == 2 ?
  8431. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8432. if (mn > w)
  8433. w = mn;
  8434. }
  8435. if (w < 8)
  8436. w = 8;
  8437. if (cbw > 0 && w > cbw)
  8438. w = cbw;
  8439. /* Without a CSS height the attributes (or the bitmap) only give the
  8440. * aspect ratio: a width clamped by max-width scales the height too,
  8441. * instead of letterboxing the image into its attribute height. */
  8442. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8443. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8444. if (st->height_kind)
  8445. h = style_height_px(st, cbw);
  8446. else if (aw > 0 && ah > 0)
  8447. h = w * ah / aw;
  8448. else if (nd->height_attr)
  8449. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8450. (int)nd->height_attr;
  8451. else
  8452. h = 64;
  8453. if (h < 8)
  8454. h = 8;
  8455. *out_w = w;
  8456. *out_h = h;
  8457. }
  8458. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8459. int dw, int dh)
  8460. {
  8461. int idx = doc.nodes[node].img_index;
  8462. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8463. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8464. struct img_blit b;
  8465. if (!src)
  8466. src = &images[idx].img;
  8467. b.dst = l->ui->px;
  8468. b.dst_w = l->ui->w;
  8469. b.dst_h = l->ui->h;
  8470. b.clip_x = page_rect.x;
  8471. b.clip_y = page_rect.y;
  8472. b.clip_w = page_rect.w - 12;
  8473. b.clip_h = page_rect.h;
  8474. b.x = x;
  8475. b.y = y;
  8476. b.scale = ((unsigned int)dw << 16) / src->w;
  8477. b.bg = ui.theme.bg;
  8478. b.bg2 = ui.theme.bg;
  8479. b.dst_a = 0;
  8480. /* OVER_DST is only needed for an alpha source; an opaque one can
  8481. * take img_draw's 1:1 copy path. */
  8482. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8483. img_draw(src, &b);
  8484. } else if (l->draw) {
  8485. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8486. 0xD69A);
  8487. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8488. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8489. }
  8490. }
  8491. static void layout_block(struct lay *l, unsigned int node,
  8492. const struct br_style *st, int depth,
  8493. unsigned short link)
  8494. {
  8495. int old_left = l->left, old_right = l->right, old_align = l->align;
  8496. int parent_cb_h = l->cb_h;
  8497. int saved_parent_top = l->parent_top;
  8498. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8499. int saved_cb_top = l->cb_top;
  8500. int top, l0, r0;
  8501. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8502. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8503. int deco_w, deco_h, content_w, content_h, box_h;
  8504. int img_dh = 0;
  8505. int definite_w = 0;
  8506. int normal_top = 0;
  8507. int rel_dx = 0, rel_dy = 0;
  8508. int clip_pushed = 0;
  8509. struct ngui_rect clip_rect;
  8510. /* A DOM level costs about two depth units (layout_block ->
  8511. * layout_children), so 48 covers a ~24-level page. Real news pages
  8512. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8513. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8514. return;
  8515. flow_y = l->y;
  8516. flow_left = l->left;
  8517. flow_right = l->right;
  8518. positioned = st->pos == 1 || st->pos == 2;
  8519. relative = st->pos == 3;
  8520. sticky = st->pos == 4;
  8521. shifted = relative || sticky || st->transform_set;
  8522. if (positioned) {
  8523. int def_w = st->width_kind == 1 ? st->width : -1;
  8524. if (st->pos == 2) {
  8525. int avail_w = page_rect.w - 12;
  8526. if (st->right_set && def_w >= 0)
  8527. l->left = page_rect.x + avail_w - st->right -
  8528. def_w;
  8529. else if (!st->left_set && !st->right_set)
  8530. l->left = flow_left; /* static position */
  8531. else
  8532. l->left = page_rect.x +
  8533. (st->left_set ? st->left : 0);
  8534. l->right = def_w >= 0 ? l->left + def_w :
  8535. st->width_kind == 2 ?
  8536. l->left + avail_w * (int)st->width / 100 :
  8537. page_rect.x + avail_w;
  8538. /* Placed by `bottom` (a page footer): an auto
  8539. * height is the measured one. */
  8540. if (st->bottom_set && st->height_kind)
  8541. l->y = page_rect.y + page_rect.h -
  8542. st->bottom -
  8543. style_height_px(st, page_rect.w);
  8544. else if (st->bottom_set && !st->top_set &&
  8545. block_h[node])
  8546. l->y = page_rect.y + page_rect.h -
  8547. st->bottom - (int)block_h[node] -
  8548. mp_px(st, 0, avail_w) -
  8549. mp_px(st, 2, avail_w);
  8550. else
  8551. l->y = page_rect.y +
  8552. (st->top_set ? st->top : 0);
  8553. } else {
  8554. int left = flow_left + (st->left_set ? st->left : 0);
  8555. unsigned int parent = doc.nodes[node].parent;
  8556. if (st->right_set && def_w >= 0)
  8557. left = flow_right - st->right - def_w;
  8558. l->left = left;
  8559. l->right = def_w >= 0 ? left + def_w :
  8560. flow_right +
  8561. (st->left_set ? st->left : 0);
  8562. l->y = flow_y + (st->top_set ? st->top : 0);
  8563. if (st->bottom_set && st->height_kind &&
  8564. parent < BR_MAX_NODES && block_h[parent] > 0)
  8565. l->y = flow_y + block_h[parent] - st->bottom -
  8566. style_height_px(st, old_right - old_left);
  8567. else if (st->bottom_set && !st->top_set &&
  8568. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8569. block_h[node] > 0)
  8570. l->y = flow_y + block_h[parent] - st->bottom -
  8571. (int)block_h[node] -
  8572. mp_px(st, 0, old_right - old_left) -
  8573. mp_px(st, 2, old_right - old_left);
  8574. }
  8575. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8576. * content" link) past the containing block's right edge
  8577. * until it is focused. An auto width then has no room: it
  8578. * used to collapse to 8 px and wrap one word per line into a
  8579. * tall column painted over the page. Lay it out at the
  8580. * containing block's width so it stays one line and
  8581. * overflows (off-screen) like in a real browser. */
  8582. if (def_w < 0 && l->right - l->left < 8) {
  8583. int avail = st->pos == 2 ? page_rect.w - 12 :
  8584. flow_right - flow_left;
  8585. l->right = l->left + (avail > 8 ? avail : 8);
  8586. }
  8587. old_left = l->left;
  8588. old_right = l->right;
  8589. } else if (relative) {
  8590. rel_dx = st->left_set ? st->left :
  8591. (st->right_set ? -st->right : 0);
  8592. rel_dy = st->top_set ? st->top :
  8593. (st->bottom_set ? -st->bottom : 0);
  8594. }
  8595. if (st->transform_set) {
  8596. rel_dx += st->tx;
  8597. rel_dy += st->ty;
  8598. }
  8599. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8600. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8601. doc.nodes[node].tag == BR_TAG_SELECT ||
  8602. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8603. !button_has_elements(node)) {
  8604. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8605. s_eq(br_type(&doc, node), "hidden"))
  8606. return;
  8607. /* Reached as a block-level box (a flex item): the control
  8608. * fills the box the caller assigned, and its line is flushed
  8609. * here; flex layout resets the run list for the next item, so
  8610. * a queued run would never be drawn. */
  8611. form_fill_line = 1;
  8612. add_form_run(l, node, st, link);
  8613. form_fill_line = 0;
  8614. flush_line(l);
  8615. return;
  8616. }
  8617. flush_line(l);
  8618. cbw = old_right - old_left;
  8619. if (cbw < 8)
  8620. cbw = 8;
  8621. l->y += mp_px(st, 0, cbw);
  8622. top = l->y;
  8623. ml = mp_px(st, 3, cbw);
  8624. mr = mp_px(st, 1, cbw);
  8625. bl = st->border_w[3];
  8626. br = st->border_w[1];
  8627. pl = mp_px(st, 7, cbw);
  8628. pr = mp_px(st, 5, cbw);
  8629. bt = st->border_w[0];
  8630. bb = st->border_w[2];
  8631. pt = mp_px(st, 4, cbw);
  8632. pb = mp_px(st, 6, cbw);
  8633. deco_w = bl + br + pl + pr;
  8634. deco_h = bt + bb + pt + pb;
  8635. if (st->width_kind) {
  8636. int w;
  8637. if (st->width_kind == 3)
  8638. w = cbw * st->width_calc_pct / 100 +
  8639. st->width_calc_px;
  8640. else
  8641. w = css_size(st->width_kind, st->width, cbw);
  8642. if (w < 0)
  8643. w = 0;
  8644. content_w = st->box_sizing ? w - deco_w : w;
  8645. definite_w = 1;
  8646. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8647. doc.nodes[node].tag == BR_TAG_TD ||
  8648. doc.nodes[node].tag == BR_TAG_TH) &&
  8649. doc.nodes[node].width_attr) {
  8650. /* Legacy table/cell width attributes: percentages resolve
  8651. * against the containing block, bare numbers are pixels. */
  8652. int w = doc.nodes[node].width_pct ?
  8653. cbw * doc.nodes[node].width_attr / 100 :
  8654. doc.nodes[node].width_attr;
  8655. if (w < 0)
  8656. w = 0;
  8657. content_w = st->box_sizing ? w - deco_w : w;
  8658. definite_w = 1;
  8659. } else {
  8660. content_w = cbw - ml - mr - deco_w;
  8661. }
  8662. if (content_w < 0)
  8663. content_w = 0;
  8664. if (st->max_width_kind) {
  8665. int mw = st->max_width_kind == 3 ?
  8666. cbw * st->max_width_calc_pct / 100 +
  8667. st->max_width_calc_px :
  8668. css_size(st->max_width_kind, st->max_width, cbw);
  8669. int max_box = st->box_sizing ? mw : mw + deco_w;
  8670. /* A clamped auto width is used as the width, so auto
  8671. * margins share the rest (Google's 688 px search box). */
  8672. if (content_w + deco_w > max_box) {
  8673. content_w = max_box - deco_w;
  8674. definite_w = 1;
  8675. }
  8676. }
  8677. if (st->min_width_kind) {
  8678. int mw = st->min_width_kind == 3 ?
  8679. cbw * st->min_width_calc_pct / 100 +
  8680. st->min_width_calc_px :
  8681. css_size(st->min_width_kind, st->min_width, cbw);
  8682. int min_box = st->box_sizing ? mw : mw + deco_w;
  8683. if (content_w + deco_w < min_box) {
  8684. content_w = min_box - deco_w;
  8685. definite_w = 1;
  8686. }
  8687. }
  8688. if (content_w < 8)
  8689. content_w = 8;
  8690. if (definite_w) {
  8691. int free_w = cbw - ml - mr - deco_w - content_w;
  8692. if (free_w < 0)
  8693. free_w = 0;
  8694. if (st->ml_auto && st->mr_auto) {
  8695. ml = free_w / 2;
  8696. mr = free_w - ml;
  8697. } else if (st->ml_auto) {
  8698. ml = free_w;
  8699. } else if (st->mr_auto) {
  8700. mr = free_w;
  8701. }
  8702. }
  8703. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8704. int iw, ih;
  8705. image_block_size(node, st, cbw, &iw, &ih);
  8706. content_w = iw;
  8707. img_dh = ih;
  8708. }
  8709. l0 = old_left + ml;
  8710. r0 = l0 + deco_w + content_w;
  8711. if (r0 < l0 + 8)
  8712. r0 = l0 + 8;
  8713. normal_top = top;
  8714. if (sticky) {
  8715. if (st->top_set) {
  8716. int stick = page_rect.y + st->top;
  8717. if (normal_top < stick)
  8718. rel_dy += stick - normal_top;
  8719. } else if (st->bottom_set && block_h[node]) {
  8720. int stick = page_rect.y + page_rect.h - st->bottom -
  8721. block_h[node];
  8722. if (normal_top > stick)
  8723. rel_dy += stick - normal_top;
  8724. }
  8725. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8726. block_h[doc.nodes[node].parent]) {
  8727. unsigned int p = doc.nodes[node].parent;
  8728. int ptop = l->parent_top;
  8729. int pbottom = ptop + block_h[p];
  8730. int eh = block_h[node];
  8731. int moved_top = normal_top + rel_dy;
  8732. int moved_bottom = moved_top + eh;
  8733. if (moved_bottom > pbottom)
  8734. rel_dy -= moved_bottom - pbottom;
  8735. moved_top = normal_top + rel_dy;
  8736. if (moved_top < ptop)
  8737. rel_dy += ptop - moved_top;
  8738. }
  8739. }
  8740. if (shifted && l->draw) {
  8741. top += rel_dy;
  8742. l0 += rel_dx;
  8743. r0 += rel_dx;
  8744. }
  8745. l->parent_top = top;
  8746. if (st->pos != 0) {
  8747. /* Positioned boxes establish the containing block for their
  8748. * absolutely positioned descendants. */
  8749. l->cb_left = l0;
  8750. l->cb_right = r0;
  8751. l->cb_top = top;
  8752. }
  8753. if (l->draw && block_h[node] &&
  8754. top < page_rect.y + page_rect.h &&
  8755. top + block_h[node] > page_rect.y) {
  8756. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8757. int rtl = css_radius(st, 0, box.w, box.h);
  8758. int rtr = css_radius(st, 1, box.w, box.h);
  8759. int rbr = css_radius(st, 2, box.w, box.h);
  8760. int rbl = css_radius(st, 3, box.w, box.h);
  8761. if (st->transform_scale) {
  8762. if (st->has_bg)
  8763. fill_transformed_rect(l->ui, box, st->bg, st);
  8764. } else if (rtl || rtr || rbr || rbl) {
  8765. if (st->has_bg) {
  8766. int bw = st->border_w[0];
  8767. if (bw > 0 && !st->border_t[0] &&
  8768. st->border_c[0] != st->bg &&
  8769. box.w > bw * 2 && box.h > bw * 2) {
  8770. struct ngui_rect inner = {
  8771. box.x + bw, box.y + bw,
  8772. box.w - bw * 2, box.h - bw * 2
  8773. };
  8774. int itl = rtl > bw ? rtl - bw : 0;
  8775. int itr = rtr > bw ? rtr - bw : 0;
  8776. int ibr = rbr > bw ? rbr - bw : 0;
  8777. int ibl = rbl > bw ? rbl - bw : 0;
  8778. ngui_fill_round_rect(l->ui, box, rtl,
  8779. rtr, rbr, rbl,
  8780. st->border_c[0]);
  8781. ngui_fill_round_rect(l->ui, inner,
  8782. itl, itr, ibr,
  8783. ibl, st->bg);
  8784. } else {
  8785. ngui_fill_round_rect(l->ui, box, rtl,
  8786. rtr, rbr, rbl,
  8787. st->bg);
  8788. }
  8789. } else if (st->border_w[0] && !st->border_t[0]) {
  8790. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8791. rbl, st->border_w[0],
  8792. st->border_c[0]);
  8793. }
  8794. /* Rounded boxes paint their background image too
  8795. * (app icons are rounded squares), kept inside the
  8796. * corner arcs. */
  8797. if (st->bg_image)
  8798. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8799. rbr, rbl);
  8800. } else {
  8801. if (st->has_bg)
  8802. ngui_fill_rect(l->ui, box, st->bg);
  8803. if (st->bg_image)
  8804. draw_bg_image(l, box, node, st);
  8805. if (st->border_w[0] || st->border_w[1] ||
  8806. st->border_w[2] || st->border_w[3])
  8807. draw_border_box(l->ui, box, st);
  8808. }
  8809. }
  8810. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8811. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8812. content_w, img_dh);
  8813. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8814. l->ui && l->ui->nclip < 4) {
  8815. clip_rect.x = l0 + bl;
  8816. clip_rect.y = top + bt;
  8817. clip_rect.w = (r0 - l0) - bl - br;
  8818. clip_rect.h = (int)block_h[node] - bt - bb;
  8819. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8820. ngui_push_clip(l->ui, clip_rect);
  8821. clip_pushed = 1;
  8822. }
  8823. }
  8824. l->left = l0 + bl + pl;
  8825. l->right = l->left + content_w;
  8826. if (l->right < l->left + 8)
  8827. l->right = l->left + 8;
  8828. l->align = st->align;
  8829. l->line_left = l->left;
  8830. l->line_right = l->right;
  8831. l->y = top + bt + pt;
  8832. if (doc.nodes[node].tag == BR_TAG_HR) {
  8833. if (l->draw)
  8834. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8835. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8836. l->y += 8;
  8837. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8838. int vw = l->right - l->left;
  8839. int vh;
  8840. if (doc.nodes[node].width_pct)
  8841. vw = vw * doc.nodes[node].width_attr / 100;
  8842. else if (doc.nodes[node].width_attr)
  8843. vw = doc.nodes[node].width_attr;
  8844. if (vw > l->right - l->left)
  8845. vw = l->right - l->left;
  8846. if (vw < 8)
  8847. vw = 8;
  8848. vh = vw * 9 / 16;
  8849. if (vh > 240)
  8850. vh = 240;
  8851. if (vh < 80)
  8852. vh = 80;
  8853. if (l->draw) {
  8854. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8855. vw, vh}, 0xD69A);
  8856. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8857. vw, vh}, 0x8410);
  8858. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8859. 0x4208);
  8860. }
  8861. l->y += vh + 4;
  8862. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8863. int dw, dh, cw = l->right - l->left;
  8864. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8865. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8866. l->y + dh > page_rect.y)
  8867. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8868. l->y += dh;
  8869. } else {
  8870. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8871. !st->no_bullet) {
  8872. char *m = li_marker[node];
  8873. if (!m[0]) {
  8874. unsigned int parent = doc.nodes[node].parent;
  8875. int style = st->list_style;
  8876. int idx = parent ? list_index(parent, node) : 1;
  8877. if (style == BR_LIST_AUTO)
  8878. style = (parent &&
  8879. doc.nodes[parent].tag ==
  8880. BR_TAG_OL) ?
  8881. BR_LIST_DECIMAL : BR_LIST_DISC;
  8882. list_marker_text(m, sizeof(li_marker[node]),
  8883. style, idx);
  8884. }
  8885. if (l->draw && m[0]) {
  8886. int mw = (int)ngui_text_width_ui(l->ui, m);
  8887. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8888. st->color);
  8889. }
  8890. }
  8891. /* This box's definite content height, for its children's
  8892. * percentage heights. */
  8893. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8894. doc.nodes[node].tag == BR_TAG_BODY)
  8895. l->cb_h = layout_view_h;
  8896. else if (st->height_kind == 1)
  8897. l->cb_h = (int)st->height -
  8898. (st->box_sizing ? deco_h : 0);
  8899. else if (st->height_kind == 2 && parent_cb_h > 0)
  8900. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8901. (st->box_sizing ? deco_h : 0);
  8902. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8903. l->cb_h = content_w * (int)st->aspect_h /
  8904. (int)st->aspect_w;
  8905. else if (!st->height_kind && node < BR_MAX_NODES &&
  8906. flex_stretch_h[node] > deco_h)
  8907. l->cb_h = flex_stretch_h[node] - deco_h;
  8908. else
  8909. l->cb_h = 0;
  8910. if (l->cb_h < 0)
  8911. l->cb_h = 0;
  8912. if (doc.nodes[node].tag == BR_TAG_TR)
  8913. layout_table_row(l, node, st, depth + 1, link);
  8914. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8915. table_has_rowspan(node))
  8916. layout_table(l, node, st, depth + 1, link);
  8917. else if (st->grid_auto)
  8918. layout_grid_auto(l, node, st, depth + 1, link);
  8919. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8920. st->grid_gap > 0)
  8921. layout_grid_children(l, node, st, depth + 1, link);
  8922. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8923. flex_wants_row(node, st))
  8924. layout_flex_children(l, node, st, depth + 1, link);
  8925. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8926. layout_flex_column(l, node, st, depth + 1, link);
  8927. else
  8928. layout_children(l, node, st, depth + 1, link);
  8929. l->cb_h = parent_cb_h;
  8930. }
  8931. flush_line(l);
  8932. if (clip_pushed)
  8933. ngui_pop_clip(l->ui);
  8934. if (l->float_active) {
  8935. if (l->y < l->float_bottom)
  8936. l->y = l->float_bottom;
  8937. l->float_active = 0;
  8938. }
  8939. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8940. content_h = img_dh;
  8941. } else if (st->height_kind == 2 &&
  8942. doc.nodes[node].tag != BR_TAG_HTML &&
  8943. doc.nodes[node].tag != BR_TAG_BODY) {
  8944. /* A percentage of the containing block's definite height, or
  8945. * auto when it has none (it used to resolve against the
  8946. * width). The result is a minimum: without scrollable inner
  8947. * boxes, an app shell's height:100%; overflow:hidden column
  8948. * would otherwise clip everything past the first screen. */
  8949. int auto_h = l->y - (top + bt + pt);
  8950. content_h = parent_cb_h > 0 ?
  8951. parent_cb_h * (int)st->height / 100 -
  8952. (st->box_sizing ? deco_h : 0) : 0;
  8953. if (content_h < auto_h)
  8954. content_h = auto_h;
  8955. } else if (st->height_kind &&
  8956. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8957. doc.nodes[node].tag == BR_TAG_BODY) &&
  8958. st->height_kind == 2)) {
  8959. content_h = style_height_px(st, cbw);
  8960. if (st->box_sizing)
  8961. content_h -= deco_h;
  8962. } else {
  8963. /* Percentage heights on html/body resolve against the
  8964. * viewport, but their content still defines the document
  8965. * scroll height. Treating them as auto avoids collapsing
  8966. * the measured page to the containing block width. */
  8967. content_h = l->y - (top + bt + pt);
  8968. /* aspect-ratio: the preferred height of an auto-height box
  8969. * (Tailwind aspect-video image frames); content can still
  8970. * make it taller, as with min-height: auto. */
  8971. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8972. int ah = content_w * (int)st->aspect_h /
  8973. (int)st->aspect_w;
  8974. if (content_h < ah)
  8975. content_h = ah;
  8976. }
  8977. }
  8978. if (content_h < 0)
  8979. content_h = 0;
  8980. if (!st->height_kind && node < BR_MAX_NODES &&
  8981. content_h + deco_h < flex_stretch_h[node])
  8982. content_h = flex_stretch_h[node] - deco_h;
  8983. if (st->max_height_kind) {
  8984. int mh = st->max_height_kind == 3 ?
  8985. cbw * st->max_height_calc_pct / 100 +
  8986. st->max_height_calc_px :
  8987. css_size(st->max_height_kind, st->max_height, cbw);
  8988. int max_box = st->box_sizing ? mh : mh + deco_h;
  8989. if (content_h + deco_h > max_box)
  8990. content_h = max_box - deco_h;
  8991. }
  8992. if (st->min_height_kind &&
  8993. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8994. doc.nodes[node].tag == BR_TAG_BODY) &&
  8995. st->min_height_kind == 2)) {
  8996. int mh = st->min_height_kind == 3 ?
  8997. cbw * st->min_height_calc_pct / 100 +
  8998. st->min_height_calc_px :
  8999. css_size(st->min_height_kind, st->min_height, cbw);
  9000. int min_box = st->box_sizing ? mh : mh + deco_h;
  9001. if (content_h + deco_h < min_box)
  9002. content_h = min_box - deco_h;
  9003. }
  9004. if (content_h < 0)
  9005. content_h = 0;
  9006. box_h = deco_h + content_h;
  9007. if (box_h < 0)
  9008. box_h = 0;
  9009. l->y = (shifted ? normal_top : top) + box_h;
  9010. if (node < BR_MAX_NODES) {
  9011. layout_boxes[node].x = l0;
  9012. layout_boxes[node].y = top;
  9013. layout_boxes[node].w = r0 - l0;
  9014. layout_boxes[node].h = box_h;
  9015. layout_boxes[node].valid = r0 > l0;
  9016. }
  9017. l->left = old_left;
  9018. l->right = old_right;
  9019. l->align = old_align;
  9020. l->y += mp_px(st, 2, cbw);
  9021. if (!l->draw) {
  9022. if (box_h > 65535)
  9023. box_h = 65535;
  9024. block_h[node] = (unsigned short)box_h;
  9025. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9026. top > 65535 ? 65535 : top);
  9027. }
  9028. if (positioned) {
  9029. l->y = flow_y;
  9030. l->left = flow_left;
  9031. l->right = flow_right;
  9032. }
  9033. l->parent_top = saved_parent_top;
  9034. l->cb_left = saved_cb_left;
  9035. l->cb_right = saved_cb_right;
  9036. l->cb_top = saved_cb_top;
  9037. }
  9038. static int text_node_blank(const struct br_node *nd)
  9039. {
  9040. const char *t = doc.text + nd->text_off;
  9041. unsigned int i;
  9042. for (i = 0; i < nd->text_len; i++)
  9043. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9044. t[i] != '\r')
  9045. return 0;
  9046. return 1;
  9047. }
  9048. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9049. * text/image widths in the subtree, plus padding and margins. This keeps
  9050. * Bootstrap's floated nav items on one line instead of giving each the whole
  9051. * row. */
  9052. static int text_space(char c)
  9053. {
  9054. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  9055. }
  9056. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9057. const struct br_style *pst, int depth, int base)
  9058. {
  9059. unsigned int c;
  9060. int line_w = 0, max_w = 0;
  9061. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  9062. if (depth > 32)
  9063. return 0;
  9064. if (doc.npe_rules) {
  9065. struct br_style ps;
  9066. /* Icon boxes (::before/::after with a size) are inline
  9067. * content of the element. */
  9068. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  9069. pseudo_box_w(node, pst, 2, &ps, base);
  9070. }
  9071. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9072. struct br_node *nd = &doc.nodes[c];
  9073. struct br_style cs;
  9074. if (nd->type == BR_NODE_TEXT) {
  9075. const char *t = doc.text + nd->text_off;
  9076. unsigned int tn = nd->text_len;
  9077. if (doc.nodes[node].tag == BR_TAG_PRE) {
  9078. line_w += (int)face_text_width(ui, pst, t, tn);
  9079. } else {
  9080. unsigned int ti = 0;
  9081. int first = 1;
  9082. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  9083. int sp = (int)face_text_width(ui, pst, " ", 1);
  9084. while (ti < tn) {
  9085. unsigned int ts;
  9086. while (ti < tn && text_space(t[ti]))
  9087. ti++;
  9088. ts = ti;
  9089. while (ti < tn && !text_space(t[ti]))
  9090. ti++;
  9091. if (ti == ts)
  9092. break;
  9093. if (!first || lead)
  9094. line_w += sp;
  9095. lead = 0;
  9096. line_w += (int)face_text_width(ui, pst,
  9097. t + ts, ti - ts);
  9098. first = 0;
  9099. }
  9100. }
  9101. continue;
  9102. }
  9103. br_style_for(&doc, c, pst, &cs);
  9104. if (cs.display == BR_DISPLAY_NONE)
  9105. continue;
  9106. if (nd->tag == BR_TAG_BR) {
  9107. if (line_w > max_w)
  9108. max_w = line_w;
  9109. line_w = 0;
  9110. continue;
  9111. }
  9112. if (nd->tag == BR_TAG_IMG) {
  9113. /* Measure the image as layout will draw it: a CSS or
  9114. * attribute height keeps the intrinsic aspect ratio, and
  9115. * a CSS width overrides the native pixel width. Bootstrap
  9116. * sizes the Cloudron logo with height:40px only. */
  9117. int idx = nd->img_index;
  9118. int iw = 0, ih = 0;
  9119. if (idx >= 0 && idx < image_count &&
  9120. images[idx].state == 1) {
  9121. iw = (int)images[idx].native_w;
  9122. ih = (int)images[idx].native_h;
  9123. if (iw <= 0 || ih <= 0) {
  9124. iw = (int)images[idx].img.w;
  9125. ih = (int)images[idx].img.h;
  9126. }
  9127. }
  9128. if (cs.width_kind) {
  9129. int ww = style_width_px(&cs, base);
  9130. line_w += ww > 0 ? ww : 64;
  9131. } else if (nd->width_attr) {
  9132. line_w += nd->width_attr;
  9133. } else if (nd->height_attr && iw && ih) {
  9134. line_w += iw * (int)nd->height_attr / ih;
  9135. } else if (cs.height_kind && iw && ih) {
  9136. /* A percentage height needs the parent's
  9137. * definite height (the logo's 2rem box), as in
  9138. * add_image_run(); otherwise it is auto. */
  9139. int hh = cs.height_kind == 1 ?
  9140. style_height_px(&cs, base) :
  9141. cs.height_kind == 2 &&
  9142. pst->height_kind == 1 ?
  9143. (int)pst->height * (int)cs.height / 100 :
  9144. 0;
  9145. line_w += hh > 0 ? iw * hh / ih : iw;
  9146. } else if (iw) {
  9147. line_w += iw;
  9148. } else {
  9149. line_w += 64;
  9150. }
  9151. continue;
  9152. }
  9153. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9154. nd->tag == BR_TAG_TEXTAREA) &&
  9155. !s_eq(br_type(&doc, c), "hidden")) {
  9156. /* Form controls are replaced: CSS width applies even
  9157. * when they are inline (add_form_run's sizes). */
  9158. int fw = cs.width_kind ? style_width_px(&cs, base) :
  9159. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  9160. if (s_eq(br_type(&doc, c), "checkbox") ||
  9161. s_eq(br_type(&doc, c), "radio"))
  9162. fw = 16;
  9163. line_w += (fw > 0 ? fw : 120) +
  9164. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  9165. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  9166. continue;
  9167. }
  9168. if (nd->tag == BR_TAG_SVG) {
  9169. /* A replaced element: its own size, like add_svg_run()
  9170. * (its path children have no width). */
  9171. int sw, sh, sb = cs.width_kind ?
  9172. style_width_px(&cs, base) : base;
  9173. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  9174. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9175. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  9176. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9177. line_w += sw;
  9178. } else {
  9179. if (line_w > max_w)
  9180. max_w = line_w;
  9181. line_w = 0;
  9182. if (sw > max_w)
  9183. max_w = sw;
  9184. }
  9185. continue;
  9186. }
  9187. {
  9188. int cw = mp_px(&cs, 7, base) +
  9189. mp_px(&cs, 5, base) +
  9190. mp_px(&cs, 3, base) +
  9191. mp_px(&cs, 1, base) +
  9192. cs.border_w[1] + cs.border_w[3];
  9193. /* width/height do not apply to non-replaced inline
  9194. * boxes. The tagesschau home label is an inline span
  9195. * with width:1px for the mobile icon-only header; using
  9196. * that width made the whole subnav collapse to a
  9197. * one-character column. */
  9198. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  9199. cw += cs.width_kind == 1 ? cs.width :
  9200. style_width_px(&cs, base);
  9201. else
  9202. cw += intrinsic_width(ui, c, &cs, depth + 1,
  9203. base);
  9204. if (flex_row || cs.float_left ||
  9205. cs.display == BR_DISPLAY_INLINE ||
  9206. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9207. line_w += cw;
  9208. } else {
  9209. if (line_w > max_w)
  9210. max_w = line_w;
  9211. line_w = 0;
  9212. if (cw > max_w)
  9213. max_w = cw;
  9214. }
  9215. }
  9216. if (line_w > 4096 || max_w > 4096)
  9217. break;
  9218. }
  9219. return line_w > max_w ? line_w : max_w;
  9220. }
  9221. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  9222. * the main user: .row > .col-md-* with float:left and a percentage width.
  9223. * Each column is laid out with its own left/right edge and the row advances
  9224. * to the tallest column. Returns the first child not consumed. */
  9225. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  9226. const struct br_style *pst, int depth,
  9227. unsigned short link)
  9228. {
  9229. unsigned int n = first;
  9230. int row_left = l->left, row_right = l->right;
  9231. int row_top, row_bottom, xl, xr, any = 0;
  9232. int fl_left = row_left, fl_right = row_right, fl_bottom;
  9233. flush_line(l);
  9234. row_top = l->y;
  9235. row_bottom = l->y;
  9236. fl_bottom = row_top;
  9237. xl = row_left;
  9238. xr = row_right;
  9239. while (n) {
  9240. struct br_node *nd = &doc.nodes[n];
  9241. struct br_style cs;
  9242. unsigned short lk = link;
  9243. int colw, right;
  9244. if (nd->type == BR_NODE_TEXT) {
  9245. if (text_node_blank(nd)) {
  9246. n = nd->next;
  9247. continue;
  9248. }
  9249. break;
  9250. }
  9251. br_style_for(&doc, n, pst, &cs);
  9252. if (cs.display == BR_DISPLAY_NONE) {
  9253. n = nd->next;
  9254. continue;
  9255. }
  9256. /* A float blockifies its box: Bootstrap floats inline
  9257. * anchors too (the navbar brand and its text links), and
  9258. * their padding must be honoured. */
  9259. if (!cs.float_left)
  9260. break;
  9261. if (nd->tag == BR_TAG_A && nd->href_off)
  9262. lk = (unsigned short)n;
  9263. right = cs.float_left == 2;
  9264. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  9265. cs.width_kind == 3) {
  9266. /* The column is the margin box: `width` is the
  9267. * content (or, with border-box, the border) box,
  9268. * and layout_block() takes margins, padding and
  9269. * borders back out of the column. A 200px float
  9270. * with margin-right:20px used to get 180px of
  9271. * content. */
  9272. int base = row_right - row_left;
  9273. colw = cs.width_kind == 1 ? (int)cs.width :
  9274. style_width_px(&cs, base);
  9275. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9276. if (!cs.box_sizing)
  9277. colw += mp_px(&cs, 7, base) +
  9278. mp_px(&cs, 5, base) +
  9279. cs.border_w[1] + cs.border_w[3];
  9280. } else {
  9281. int base = row_right - row_left;
  9282. /* Shrink-to-fit outer width: borders too (Google's
  9283. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9284. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9285. mp_px(&cs, 7, base) +
  9286. mp_px(&cs, 5, base) +
  9287. mp_px(&cs, 3, base) +
  9288. mp_px(&cs, 1, base) +
  9289. cs.border_w[1] + cs.border_w[3];
  9290. if (colw < 8)
  9291. colw = 8;
  9292. }
  9293. if (colw < 8)
  9294. colw = 8;
  9295. if (colw > row_right - row_left)
  9296. colw = row_right - row_left;
  9297. /* The float column width is already resolved. */
  9298. cs.width_kind = 0;
  9299. cs.max_width_kind = 0;
  9300. if (right) {
  9301. if (any && xr - colw < xl) {
  9302. row_top = row_bottom;
  9303. row_bottom = row_top;
  9304. xl = row_left;
  9305. xr = row_right;
  9306. }
  9307. if (xr - colw < xl)
  9308. colw = xr - xl;
  9309. if (colw < 8)
  9310. colw = 8;
  9311. l->left = xr - colw;
  9312. if (l->left < row_left)
  9313. l->left = row_left;
  9314. l->right = xr;
  9315. xr = l->left;
  9316. if (xr < fl_right)
  9317. fl_right = xr;
  9318. } else {
  9319. if (any && xl + colw > xr) {
  9320. row_top = row_bottom;
  9321. row_bottom = row_top;
  9322. xl = row_left;
  9323. xr = row_right;
  9324. }
  9325. l->left = xl;
  9326. l->right = xl + colw;
  9327. xl += colw;
  9328. if (xl > fl_left)
  9329. fl_left = xl;
  9330. }
  9331. if (l->right < l->left + 8)
  9332. l->right = l->left + 8;
  9333. l->y = row_top;
  9334. l->line_left = l->line_x = l->left;
  9335. l->run_x = l->left;
  9336. l->line_y = l->y;
  9337. l->line_h = 0;
  9338. l->nruns = 0;
  9339. l->space_pending = 0;
  9340. l->align = cs.align;
  9341. layout_block(l, n, &cs, depth + 1, lk);
  9342. if (l->y > row_bottom)
  9343. row_bottom = l->y;
  9344. if (l->y > fl_bottom)
  9345. fl_bottom = l->y;
  9346. any = 1;
  9347. n = nd->next;
  9348. }
  9349. l->left = row_left;
  9350. l->right = row_right;
  9351. if (n && any) {
  9352. struct br_node *nd = &doc.nodes[n];
  9353. int inline_next = 0;
  9354. if (nd->type == BR_NODE_TEXT) {
  9355. inline_next = 1;
  9356. } else if (nd->type == BR_NODE_ELEM) {
  9357. struct br_style cs;
  9358. br_style_for(&doc, n, pst, &cs);
  9359. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9360. cs.display != BR_DISPLAY_NONE &&
  9361. !br_tag_is_block(nd->tag);
  9362. }
  9363. if (inline_next) {
  9364. if (l->float_active) {
  9365. if (l->float_left > fl_left)
  9366. fl_left = l->float_left;
  9367. if (l->float_right < fl_right)
  9368. fl_right = l->float_right;
  9369. if (l->float_bottom > fl_bottom)
  9370. fl_bottom = l->float_bottom;
  9371. }
  9372. l->float_active = 1;
  9373. l->float_left = fl_left;
  9374. l->float_right = fl_right;
  9375. l->float_bottom = fl_bottom;
  9376. l->y = row_top;
  9377. } else {
  9378. l->float_active = 0;
  9379. l->y = row_bottom;
  9380. }
  9381. } else {
  9382. l->float_active = 0;
  9383. l->y = row_bottom;
  9384. }
  9385. l->line_x = l->left;
  9386. l->run_x = l->left;
  9387. l->line_left = l->left;
  9388. l->line_right = l->right;
  9389. l->line_y = l->y;
  9390. l->line_h = 0;
  9391. l->nruns = 0;
  9392. l->space_pending = 0;
  9393. return n;
  9394. }
  9395. static int flex_item_width(struct lay *l, unsigned int n,
  9396. const struct br_style *cs, int avail)
  9397. {
  9398. struct br_node *nd = &doc.nodes[n];
  9399. (void)l;
  9400. int w;
  9401. if (cs->width_kind == 2 || cs->width_kind == 3)
  9402. w = style_width_px(cs, avail);
  9403. else if (cs->width_kind == 1)
  9404. w = (int)cs->width;
  9405. else if (nd->tag == BR_TAG_IMG) {
  9406. int idx = nd->img_index;
  9407. if (idx >= 0 && idx < image_count &&
  9408. images[idx].state == 1)
  9409. w = (int)images[idx].img.w;
  9410. else if (nd->width_attr)
  9411. w = (int)nd->width_attr;
  9412. else
  9413. w = 64;
  9414. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9415. nd->tag == BR_TAG_TEXTAREA) {
  9416. /* A control has no content to measure: its default size
  9417. * (a search field in a filter bar). */
  9418. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9419. } else {
  9420. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9421. }
  9422. /* Explicit widths are content-box sizes; the flex item's outer width
  9423. * must include padding, borders and margins. */
  9424. w += mp_px(cs, 7, avail);
  9425. w += mp_px(cs, 5, avail);
  9426. w += mp_px(cs, 3, avail);
  9427. w += mp_px(cs, 1, avail);
  9428. w += cs->border_w[1] + cs->border_w[3];
  9429. if (w < 24)
  9430. w = 24;
  9431. if (w > avail)
  9432. w = avail;
  9433. return w;
  9434. }
  9435. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9436. int depth);
  9437. /* An inline child of a text-only inline-block: the same test minus the
  9438. * display check (an inline <span> may have padding/background in CSS, but
  9439. * the inline path paints those for spans anyway). */
  9440. static int inline_block_flows_inline(unsigned int node,
  9441. const struct br_style *cs, int depth)
  9442. {
  9443. unsigned int c;
  9444. if (depth > 3 || cs->pos)
  9445. return 0;
  9446. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9447. const struct br_node *nd = &doc.nodes[c];
  9448. struct br_style ch;
  9449. if (nd->type != BR_NODE_ELEM)
  9450. continue;
  9451. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9452. br_tag_is_block(nd->tag))
  9453. return 0;
  9454. br_style_for(&doc, c, cs, &ch);
  9455. if (ch.display == BR_DISPLAY_NONE)
  9456. continue;
  9457. if (ch.display != BR_DISPLAY_INLINE ||
  9458. !inline_block_flows_inline(c, &ch, depth + 1))
  9459. return 0;
  9460. }
  9461. return 1;
  9462. }
  9463. /* An inline-block that is only text in a line (a <time> in a byline, a
  9464. * label) with no box of its own -- no size, background, border or padding
  9465. * -- lays out exactly like an inline element, so it stays in the text line
  9466. * instead of ending it. Boxes with any of those keep the row path. */
  9467. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9468. int depth)
  9469. {
  9470. unsigned int c;
  9471. int i;
  9472. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9473. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9474. cs->pos || depth > 3)
  9475. return 0;
  9476. for (i = 0; i < 4; i++)
  9477. if (cs->border_w[i])
  9478. return 0;
  9479. for (i = 4; i < 8; i++)
  9480. if (mp_px(cs, i, 0) > 0)
  9481. return 0;
  9482. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9483. const struct br_node *nd = &doc.nodes[c];
  9484. struct br_style ch;
  9485. if (nd->type != BR_NODE_ELEM)
  9486. continue;
  9487. if (nd->tag == BR_TAG_SVG) {
  9488. /* An icon box (Docusaurus' admonition heading:
  9489. * `<span inline-block><svg/></span>Note`): the SVG
  9490. * is an inline replaced run, so the box can stay in
  9491. * the text line. */
  9492. br_style_for(&doc, c, cs, &ch);
  9493. if (ch.display == BR_DISPLAY_NONE ||
  9494. ch.display == BR_DISPLAY_INLINE ||
  9495. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9496. continue;
  9497. return 0;
  9498. }
  9499. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9500. return 0;
  9501. br_style_for(&doc, c, cs, &ch);
  9502. if (ch.display == BR_DISPLAY_NONE)
  9503. continue;
  9504. if (ch.display != BR_DISPLAY_INLINE ||
  9505. !inline_block_flows_inline(c, &ch, depth + 1))
  9506. return 0;
  9507. }
  9508. return 1;
  9509. }
  9510. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9511. * on one line, not one full-width block each. Place intrinsic widths from
  9512. * left to right and wrap when the row is full. */
  9513. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9514. const struct br_style *pst, int depth,
  9515. unsigned short link)
  9516. {
  9517. unsigned int n = first;
  9518. int row_left = l->left, row_right = l->right;
  9519. int avail = row_right - row_left;
  9520. int x = row_left, y = l->y, row_h = 0, any = 0;
  9521. /* Each box sets l->align from its own style; the text after the row
  9522. * must keep the container's (a centred .fa-fw icon centred the menu
  9523. * label that followed it). */
  9524. unsigned char row_align = l->align;
  9525. flush_line(l);
  9526. y = l->y;
  9527. while (n) {
  9528. struct br_node *nd = &doc.nodes[n];
  9529. struct br_style cs;
  9530. unsigned short lk = link;
  9531. int colw, h;
  9532. if (nd->type == BR_NODE_TEXT) {
  9533. if (!text_node_blank(nd))
  9534. break;
  9535. if (any)
  9536. x += 4;
  9537. n = nd->next;
  9538. continue;
  9539. }
  9540. br_style_for(&doc, n, pst, &cs);
  9541. if (cs.display == BR_DISPLAY_NONE) {
  9542. n = nd->next;
  9543. continue;
  9544. }
  9545. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9546. break;
  9547. if (nd->tag == BR_TAG_A && nd->href_off)
  9548. lk = (unsigned short)n;
  9549. colw = flex_item_width(l, n, &cs, avail);
  9550. /* A few pixels of slack keep a single long token (boot.S)
  9551. * from wrapping at the exact content width. */
  9552. colw += 8;
  9553. if (colw > avail)
  9554. colw = avail;
  9555. cs.width_kind = 0;
  9556. cs.max_width_kind = 0;
  9557. if (any && x + colw > row_right) {
  9558. y += row_h + 2;
  9559. x = row_left;
  9560. row_h = 0;
  9561. any = 0;
  9562. }
  9563. if (any && x > row_left)
  9564. x += 4;
  9565. l->left = x;
  9566. l->right = x + colw;
  9567. if (l->right < l->left + 8)
  9568. l->right = l->left + 8;
  9569. l->y = y;
  9570. l->line_left = l->line_x = l->left;
  9571. l->run_x = l->left;
  9572. l->line_y = l->y;
  9573. l->line_h = 0;
  9574. l->nruns = 0;
  9575. l->space_pending = 0;
  9576. l->align = cs.align;
  9577. layout_block(l, n, &cs, depth + 1, lk);
  9578. h = l->y - y;
  9579. if (h > row_h)
  9580. row_h = h;
  9581. x += colw;
  9582. any = 1;
  9583. n = nd->next;
  9584. }
  9585. if (any)
  9586. y += row_h;
  9587. l->left = row_left;
  9588. l->right = row_right;
  9589. l->align = row_align;
  9590. l->y = y;
  9591. l->line_left = l->line_x = l->left;
  9592. l->run_x = l->left;
  9593. l->line_y = l->y;
  9594. l->line_h = 0;
  9595. l->nruns = 0;
  9596. l->space_pending = 0;
  9597. return n;
  9598. }
  9599. struct flex_item {
  9600. unsigned int node;
  9601. unsigned short link;
  9602. int w;
  9603. };
  9604. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9605. * row, or -1 when unset. Percentages and calc() resolve against the
  9606. * container width. */
  9607. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9608. {
  9609. unsigned char kind = which_max ? cs->max_width_kind :
  9610. cs->min_width_kind;
  9611. int w;
  9612. if (kind == 3)
  9613. w = which_max ?
  9614. avail * cs->max_width_calc_pct / 100 +
  9615. cs->max_width_calc_px :
  9616. avail * cs->min_width_calc_pct / 100 +
  9617. cs->min_width_calc_px;
  9618. else
  9619. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9620. avail);
  9621. if (w < 0)
  9622. return -1;
  9623. if (!cs->box_sizing)
  9624. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9625. cs->border_w[1] + cs->border_w[3];
  9626. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9627. }
  9628. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9629. {
  9630. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9631. if (mx >= 0 && w > mx)
  9632. w = mx;
  9633. if (mn >= 0 && w < mn)
  9634. w = mn;
  9635. return w;
  9636. }
  9637. /* Does a flex row stretch this item to the line height? Only items with
  9638. * no height of their own and align-self/align-items stretch; replaced
  9639. * content (images, icons) keeps its aspect ratio. */
  9640. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9641. const struct br_style *pst)
  9642. {
  9643. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9644. unsigned char tag = doc.nodes[node].tag;
  9645. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9646. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9647. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9648. tag != BR_TAG_BUTTON;
  9649. }
  9650. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9651. int line_h, int cbw)
  9652. {
  9653. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9654. if (node >= BR_MAX_NODES || h <= 0)
  9655. return;
  9656. if (h > 65535)
  9657. h = 65535;
  9658. flex_stretch_h[node] = (unsigned short)h;
  9659. if (block_h[node] < h)
  9660. block_h[node] = (unsigned short)h;
  9661. }
  9662. static void layout_flex_children(struct lay *l, unsigned int parent,
  9663. const struct br_style *pst, int depth,
  9664. unsigned short link)
  9665. {
  9666. struct flex_item it[32];
  9667. unsigned int c;
  9668. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9669. int grow_need = 0; /* growing items at their content width */
  9670. int row_left = l->left, row_right = l->right;
  9671. int avail = row_right - row_left;
  9672. int idx, row_top;
  9673. unsigned char row_align = l->align;
  9674. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9675. int bw = 0, aw = 0, first_h = -1;
  9676. int cont_h = l->cb_h; /* the container's definite content height */
  9677. struct br_style bps, aps;
  9678. if (avail < 8 || depth > 48) {
  9679. layout_children(l, parent, pst, depth, link);
  9680. return;
  9681. }
  9682. /* If direct text is not just whitespace, normal block flow handles it
  9683. * better than pretending it is a flex item. */
  9684. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9685. struct br_node *nd = &doc.nodes[c];
  9686. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9687. layout_children(l, parent, pst, depth, link);
  9688. return;
  9689. }
  9690. }
  9691. /* ::before/::after icon boxes are the row's first and last items
  9692. * (Docusaurus' sidebar chevron): reserve their columns. */
  9693. if (doc.npe_rules) {
  9694. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9695. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9696. if (bw + aw > avail - 8) {
  9697. bw = 0;
  9698. aw = 0;
  9699. }
  9700. row_left += bw;
  9701. row_right -= aw;
  9702. avail = row_right - row_left;
  9703. }
  9704. for (c = doc.nodes[parent].first;
  9705. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9706. c = doc.nodes[c].next) {
  9707. struct br_node *nd = &doc.nodes[c];
  9708. struct br_style cs;
  9709. if (nd->type == BR_NODE_TEXT)
  9710. continue;
  9711. br_style_for(&doc, c, pst, &cs);
  9712. if (cs.display == BR_DISPLAY_NONE)
  9713. continue;
  9714. if ((cs.pos == 1 || cs.pos == 2) &&
  9715. layout_out_of_flow(l, c, &cs, depth,
  9716. (nd->tag == BR_TAG_A && nd->href_off) ?
  9717. (unsigned short)c : link))
  9718. continue; /* absolutely positioned: not an item */
  9719. it[nitem].node = c;
  9720. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9721. (unsigned short)c : link;
  9722. it[nitem].w = 0;
  9723. if (cs.flex_grow && !cs.width_kind) {
  9724. grow_count++;
  9725. grow_need += flex_item_width(l, c, &cs, avail);
  9726. } else
  9727. fixed += flex_clamp_w(&cs,
  9728. flex_item_width(l, c, &cs, avail),
  9729. avail);
  9730. nitem++;
  9731. }
  9732. /* A narrow container (an icon row sized to its content, Google's
  9733. * mic + lens buttons) is still a row when its items fit; only a
  9734. * narrow one that would overflow or squeeze growing items falls
  9735. * back to block flow. */
  9736. if (avail < 160 && fixed + grow_need > avail) {
  9737. layout_children(l, parent, pst, depth, link);
  9738. return;
  9739. }
  9740. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9741. /* A growing item capped by max-width (Docusaurus' doc column,
  9742. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9743. * keeps its cap and leaves the rest of the free space to the other
  9744. * growing items. */
  9745. if (grow_count) {
  9746. int pass, capped[32] = { 0 };
  9747. for (pass = 0; pass < nitem; pass++) {
  9748. int changed = 0;
  9749. for (idx = 0; idx < nitem; idx++) {
  9750. struct br_style cs;
  9751. int lim;
  9752. if (capped[idx])
  9753. continue;
  9754. br_style_for(&doc, it[idx].node, pst, &cs);
  9755. if (!cs.flex_grow || cs.width_kind)
  9756. continue;
  9757. lim = flex_clamp_w(&cs, grow_w, avail);
  9758. if (lim == grow_w)
  9759. continue;
  9760. capped[idx] = lim + 1;
  9761. fixed += lim;
  9762. grow_count--;
  9763. changed = 1;
  9764. }
  9765. if (!changed || !grow_count)
  9766. break;
  9767. grow_w = (avail - fixed) / grow_count;
  9768. }
  9769. for (idx = 0; idx < nitem; idx++)
  9770. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9771. }
  9772. if (grow_w < 96 && avail >= 160)
  9773. grow_w = 96;
  9774. for (idx = 0; idx < nitem; idx++) {
  9775. struct br_style cs;
  9776. if (it[idx].w)
  9777. continue; /* capped growing item */
  9778. br_style_for(&doc, it[idx].node, pst, &cs);
  9779. if (cs.flex_grow && !cs.width_kind)
  9780. it[idx].w = grow_w;
  9781. else
  9782. it[idx].w = flex_clamp_w(&cs,
  9783. flex_item_width(l,
  9784. it[idx].node,
  9785. &cs, avail),
  9786. avail);
  9787. if (it[idx].w > avail)
  9788. it[idx].w = avail;
  9789. if (it[idx].w < 8)
  9790. it[idx].w = 8;
  9791. }
  9792. row_top = l->y;
  9793. idx = 0;
  9794. while (idx < nitem) {
  9795. int start = idx, count = 0, row_w = 0;
  9796. int free_w, x, extra = 0, row_h = 0, k;
  9797. while (idx < nitem) {
  9798. int add = it[idx].w + (count ? gap : 0);
  9799. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9800. * starts a new row. */
  9801. if (count && pst->flex_wrap == 1 &&
  9802. row_w + add > avail)
  9803. break;
  9804. row_w += add;
  9805. count++;
  9806. idx++;
  9807. }
  9808. if (!count) {
  9809. count = 1;
  9810. row_w = it[start].w;
  9811. idx = start + 1;
  9812. }
  9813. free_w = avail - row_w;
  9814. if (free_w < 0)
  9815. free_w = 0;
  9816. x = row_left;
  9817. if (pst->justify == 1) {
  9818. x += free_w / 2;
  9819. } else if (pst->justify == 2) {
  9820. x += free_w;
  9821. } else if (pst->justify == 3) {
  9822. extra = count > 1 ? free_w / (count - 1) : 0;
  9823. } else if (pst->justify == 4) {
  9824. extra = count ? free_w / count : 0;
  9825. x += extra / 2;
  9826. } else if (pst->justify == 5) {
  9827. extra = count ? free_w / (count + 1) : 0;
  9828. x += extra;
  9829. }
  9830. for (k = 0; k < count; k++) {
  9831. int node = (int)it[start + k].node;
  9832. int h = block_h[node];
  9833. if (h > row_h)
  9834. row_h = h;
  9835. }
  9836. /* A single line fills a definite container height (an app
  9837. * shell's `height: 100%` sidebar + content row). */
  9838. if (pst->flex_wrap != 1 && cont_h > row_h)
  9839. row_h = cont_h;
  9840. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9841. row_h = pst->height;
  9842. for (k = 0; k < count; k++) {
  9843. struct br_style cs;
  9844. int node = (int)it[start + k].node;
  9845. int yoff = 0;
  9846. br_style_for(&doc, node, pst, &cs);
  9847. cs.width_kind = 0;
  9848. cs.max_width_kind = 0;
  9849. /* align-items: stretch. With a definite line height
  9850. * the item is laid out at it, so its own children see
  9851. * a definite height; otherwise the measure pass
  9852. * stretches it once the line is known (below). */
  9853. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9854. &cs, pst))
  9855. flex_set_stretch(node, &cs, row_h, avail);
  9856. {
  9857. int ai = cs.align_self ? cs.align_self - 1 :
  9858. pst->align_items;
  9859. if (l->draw && ai && row_h > block_h[node]) {
  9860. if (ai == 1)
  9861. yoff = (row_h -
  9862. block_h[node]) / 2;
  9863. else if (ai == 2)
  9864. yoff = row_h - block_h[node];
  9865. }
  9866. }
  9867. l->left = x;
  9868. l->right = x + it[start + k].w;
  9869. if (l->right < l->left + 8)
  9870. l->right = l->left + 8;
  9871. l->y = row_top + yoff;
  9872. /* line_left too: a stale one from the previous item
  9873. * made flush_line() see a non-empty line and push
  9874. * every later item down by an empty line's height. */
  9875. l->line_left = l->line_x = l->run_x = l->left;
  9876. l->line_right = l->right;
  9877. l->line_y = l->y;
  9878. l->line_h = 0;
  9879. l->nruns = 0;
  9880. l->space_pending = 0;
  9881. l->align = cs.align;
  9882. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9883. {
  9884. /* Both passes: a form control item has no
  9885. * block_h of its own, so the draw pass would
  9886. * otherwise end a row of only an <input> at
  9887. * height 0 and pull the content below up. */
  9888. int h = l->y - row_top;
  9889. if (h > row_h)
  9890. row_h = h;
  9891. }
  9892. x += it[start + k].w;
  9893. if (k + 1 < count)
  9894. x += gap + extra;
  9895. }
  9896. if (!l->draw) {
  9897. for (k = 0; k < count; k++) {
  9898. struct br_style cs;
  9899. int node = (int)it[start + k].node;
  9900. br_style_for(&doc, node, pst, &cs);
  9901. if (!flex_item_stretches(node, &cs, pst))
  9902. continue;
  9903. /* To the line's bottom edge from where the
  9904. * item really starts (its top margin, or a
  9905. * line box above it). */
  9906. if (layout_boxes[node].valid)
  9907. flex_set_stretch(node, &cs,
  9908. row_top + row_h -
  9909. layout_boxes[node].y +
  9910. mp_px(&cs, 0, avail), avail);
  9911. else
  9912. flex_set_stretch(node, &cs, row_h, avail);
  9913. }
  9914. }
  9915. if (first_h < 0)
  9916. first_h = row_h;
  9917. row_top += row_h;
  9918. }
  9919. if (bw || aw) {
  9920. int pass;
  9921. for (pass = 0; pass < 2; pass++) {
  9922. const struct br_style *ps = pass ? &aps : &bps;
  9923. int a = pass ? row_right : box_left;
  9924. int b = pass ? box_right : row_left;
  9925. int h = ps->height_kind ?
  9926. style_height_px(ps, box_right - box_left) : 0;
  9927. if (!(pass ? aw : bw))
  9928. continue;
  9929. l->left = l->line_left = l->line_x = l->run_x = a;
  9930. l->right = l->line_right = b;
  9931. l->y = row_top0;
  9932. if (pst->align_items == 1 && first_h > h)
  9933. l->y += (first_h - h) / 2;
  9934. l->line_y = l->y;
  9935. l->line_h = 0;
  9936. l->nruns = 0;
  9937. l->space_pending = 0;
  9938. emit_pseudo_box(l, pst, ps, link);
  9939. flush_line(l);
  9940. /* The box sits inside the first row; it only makes
  9941. * the row taller when it is taller itself. */
  9942. if (row_top0 + h > row_top)
  9943. row_top = row_top0 + h;
  9944. }
  9945. }
  9946. l->left = box_left;
  9947. l->right = box_right;
  9948. l->align = row_align;
  9949. l->y = row_top;
  9950. l->line_left = l->line_x = l->run_x = l->left;
  9951. l->line_right = l->right;
  9952. l->line_y = l->y;
  9953. l->line_h = 0;
  9954. l->nruns = 0;
  9955. l->space_pending = 0;
  9956. }
  9957. /* flex-direction: column. Items stack in order with the gap and never
  9958. * collapse margins. In the draw pass justify-content shares out the free
  9959. * height of the container's measured box (a definite or min-height, or a
  9960. * row stretch), and align-items places each item: stretch (the default)
  9961. * fills the line, start/center/end shrink an item to its content width
  9962. * (a login form's "Log in" button, a centred logo and name). */
  9963. static void layout_flex_column(struct lay *l, unsigned int parent,
  9964. const struct br_style *pst, int depth,
  9965. unsigned short link)
  9966. {
  9967. unsigned int c;
  9968. int box_left = l->left, box_right = l->right;
  9969. int avail = box_right - box_left;
  9970. int gap = pst->grid_gap, y0 = l->y;
  9971. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  9972. unsigned char row_align = l->align;
  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. break;
  9977. }
  9978. if (c || avail < 8 || depth > 48) {
  9979. /* Loose text: block flow, with centred lines standing in
  9980. * for align-items: center. */
  9981. struct br_style cst = *pst;
  9982. if (pst->align_items == 1) {
  9983. cst.align = BR_ALIGN_CENTER;
  9984. l->align = BR_ALIGN_CENTER;
  9985. }
  9986. layout_children(l, parent, &cst, depth, link);
  9987. return;
  9988. }
  9989. emit_pseudo(l, parent, pst, 1, link);
  9990. flush_line(l);
  9991. y0 = l->y;
  9992. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  9993. int inner = (int)block_h[parent] - pst->border_w[0] -
  9994. pst->border_w[2] - mp_px(pst, 4, avail) -
  9995. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  9996. pst->border_w[0] - mp_px(pst, 4, avail));
  9997. int free_h;
  9998. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9999. struct br_style cs;
  10000. if (doc.nodes[c].type != BR_NODE_ELEM)
  10001. continue;
  10002. br_style_for(&doc, c, pst, &cs);
  10003. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  10004. cs.pos == 2)
  10005. continue;
  10006. total += block_h[c] + mp_px(&cs, 0, avail) +
  10007. mp_px(&cs, 2, avail);
  10008. n++;
  10009. }
  10010. if (n > 1)
  10011. total += gap * (n - 1);
  10012. free_h = inner - total;
  10013. if (n && free_h > 0) {
  10014. if (pst->justify == 1) {
  10015. lead = free_h / 2;
  10016. } else if (pst->justify == 2) {
  10017. lead = free_h;
  10018. } else if (pst->justify == 3) {
  10019. extra = n > 1 ? free_h / (n - 1) : 0;
  10020. } else if (pst->justify == 4) {
  10021. extra = free_h / n;
  10022. lead = extra / 2;
  10023. } else if (pst->justify == 5) {
  10024. extra = free_h / (n + 1);
  10025. lead = extra;
  10026. }
  10027. }
  10028. }
  10029. l->y = y0 + lead;
  10030. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10031. struct br_node *nd = &doc.nodes[c];
  10032. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10033. (unsigned short)c : link;
  10034. struct br_style cs;
  10035. int ai, left = box_left, right = box_right;
  10036. if (nd->type != BR_NODE_ELEM)
  10037. continue;
  10038. br_style_for(&doc, c, pst, &cs);
  10039. if (cs.display == BR_DISPLAY_NONE)
  10040. continue;
  10041. if ((cs.pos == 1 || cs.pos == 2) &&
  10042. layout_out_of_flow(l, c, &cs, depth, lk))
  10043. continue;
  10044. if (k++)
  10045. l->y += gap + extra;
  10046. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  10047. if (ai) {
  10048. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  10049. avail),
  10050. avail);
  10051. if (ai == 1)
  10052. left += (avail - w) / 2;
  10053. else if (ai == 2)
  10054. left += avail - w;
  10055. right = left + w;
  10056. cs.width_kind = 0;
  10057. cs.max_width_kind = 0;
  10058. }
  10059. l->left = l->line_left = l->line_x = l->run_x = left;
  10060. l->right = l->line_right = right;
  10061. l->line_y = l->y;
  10062. l->line_h = 0;
  10063. l->nruns = 0;
  10064. l->space_pending = 0;
  10065. l->align = cs.align;
  10066. layout_block(l, c, &cs, depth + 1, lk);
  10067. }
  10068. l->left = l->line_left = l->line_x = l->run_x = box_left;
  10069. l->right = l->line_right = box_right;
  10070. l->align = row_align;
  10071. l->line_y = l->y;
  10072. l->line_h = 0;
  10073. l->nruns = 0;
  10074. l->space_pending = 0;
  10075. emit_pseudo(l, parent, pst, 2, link);
  10076. }
  10077. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  10078. * plus the grid-area hints used by site shells (site notice/footer full
  10079. * width, column-start left, page-content right). Anything more elaborate
  10080. * falls back to normal block flow. */
  10081. static int grid_track_width(unsigned char kind, unsigned short val,
  10082. int avail, int other)
  10083. {
  10084. if (kind == 2)
  10085. return avail * (int)val / 100;
  10086. if (kind == 1)
  10087. return val;
  10088. return other;
  10089. }
  10090. static void layout_grid_children(struct lay *l, unsigned int parent,
  10091. const struct br_style *pst, int depth,
  10092. unsigned short link)
  10093. {
  10094. unsigned int n;
  10095. int row_left = l->left, row_right = l->right;
  10096. int avail = row_right - row_left;
  10097. int gap = pst->grid_gap;
  10098. int track_total = avail - gap;
  10099. int col0, col1, x0, x1;
  10100. int row_y, row_bottom, have_left = 0, have_right = 0;
  10101. unsigned int c;
  10102. if (avail < 32 || depth > 48)
  10103. return;
  10104. if (track_total < 16)
  10105. track_total = 16;
  10106. col0 = grid_track_width((unsigned char)(pst->width_kind),
  10107. pst->width, track_total, 0);
  10108. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  10109. pst->max_width, track_total, 0);
  10110. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  10111. int w0 = pst->width ? pst->width : 1;
  10112. int w1 = pst->max_width ? pst->max_width : 1;
  10113. col0 = track_total * w0 / (w0 + w1);
  10114. col1 = track_total - col0;
  10115. } else if (pst->width_kind == 3) {
  10116. col0 = track_total - col1;
  10117. if (col0 < 24)
  10118. col0 = 24;
  10119. } else if (pst->max_width_kind == 3) {
  10120. col1 = track_total - col0;
  10121. if (col1 < 24)
  10122. col1 = 24;
  10123. }
  10124. if (col0 < 24)
  10125. col0 = 24;
  10126. if (col1 < 24)
  10127. col1 = 24;
  10128. if (col0 + col1 > track_total) {
  10129. col1 = track_total - col0;
  10130. if (col1 < 24)
  10131. col1 = 24;
  10132. }
  10133. x0 = row_left;
  10134. x1 = row_left + col0 + gap;
  10135. /* Direct text makes a grid ambiguous; use block flow instead. */
  10136. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10137. struct br_node *nd = &doc.nodes[c];
  10138. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10139. layout_children(l, parent, pst, depth, link);
  10140. return;
  10141. }
  10142. }
  10143. row_y = row_bottom = l->y;
  10144. n = doc.nodes[parent].first;
  10145. while (n) {
  10146. struct br_node *nd = &doc.nodes[n];
  10147. struct br_style cs;
  10148. unsigned short lk = link;
  10149. int slot, x, w;
  10150. if (nd->type == BR_NODE_TEXT) {
  10151. n = nd->next;
  10152. continue;
  10153. }
  10154. br_style_for(&doc, n, pst, &cs);
  10155. if (cs.display == BR_DISPLAY_NONE) {
  10156. n = nd->next;
  10157. continue;
  10158. }
  10159. if (nd->tag == BR_TAG_A && nd->href_off)
  10160. lk = (unsigned short)n;
  10161. slot = cs.grid_slot;
  10162. if (!slot) {
  10163. if (!have_left)
  10164. slot = 2;
  10165. else if (!have_right)
  10166. slot = 3;
  10167. else
  10168. slot = 2;
  10169. }
  10170. if (slot == 1) {
  10171. if (have_left || have_right) {
  10172. row_y = row_bottom;
  10173. have_left = have_right = 0;
  10174. }
  10175. x = row_left;
  10176. w = avail;
  10177. } else if (slot == 2) {
  10178. if (have_left) {
  10179. row_y = row_bottom;
  10180. have_left = have_right = 0;
  10181. }
  10182. x = x0;
  10183. w = col0;
  10184. have_left = 1;
  10185. } else {
  10186. if (have_right) {
  10187. row_y = row_bottom;
  10188. have_left = have_right = 0;
  10189. }
  10190. x = x1;
  10191. w = col1;
  10192. have_right = 1;
  10193. }
  10194. cs.width_kind = 0;
  10195. cs.max_width_kind = 0;
  10196. l->left = x;
  10197. l->right = x + w;
  10198. if (l->right < l->left + 8)
  10199. l->right = l->left + 8;
  10200. l->y = row_y;
  10201. l->line_left = l->line_x = l->left;
  10202. l->run_x = l->left;
  10203. l->line_y = l->y;
  10204. l->line_h = 0;
  10205. l->nruns = 0;
  10206. l->space_pending = 0;
  10207. l->align = cs.align;
  10208. layout_block(l, n, &cs, depth + 1, lk);
  10209. if (l->y > row_bottom)
  10210. row_bottom = l->y;
  10211. n = nd->next;
  10212. }
  10213. l->left = row_left;
  10214. l->right = row_right;
  10215. l->y = row_bottom;
  10216. l->line_left = l->line_x = l->left;
  10217. l->run_x = l->left;
  10218. l->line_y = l->y;
  10219. l->line_h = 0;
  10220. l->nruns = 0;
  10221. l->space_pending = 0;
  10222. }
  10223. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  10224. * capped at four. Used by the project docs' card grids. A fixed
  10225. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  10226. static void layout_grid_auto(struct lay *l, unsigned int parent,
  10227. const struct br_style *pst, int depth,
  10228. unsigned short link)
  10229. {
  10230. unsigned int n, c;
  10231. int row_left = l->left, row_right = l->right;
  10232. int avail = row_right - row_left;
  10233. int gap = pst->grid_gap;
  10234. int minw = pst->width_kind == 1 ? pst->width : 200;
  10235. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  10236. if (avail < 32 || depth > 48) {
  10237. layout_children(l, parent, pst, depth, link);
  10238. return;
  10239. }
  10240. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10241. struct br_node *nd = &doc.nodes[c];
  10242. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10243. layout_children(l, parent, pst, depth, link);
  10244. return;
  10245. }
  10246. }
  10247. if (minw < 80)
  10248. minw = 80;
  10249. ncols = (avail + gap) / (minw + gap);
  10250. if (ncols < 1)
  10251. ncols = 1;
  10252. if (ncols > 4)
  10253. ncols = 4;
  10254. if (pst->grid_auto > BR_GRID_FIXED) {
  10255. /* grid-template-columns: repeat(N, 1fr) */
  10256. ncols = pst->grid_auto - BR_GRID_FIXED;
  10257. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  10258. ncols--;
  10259. }
  10260. colw = (avail - gap * (ncols - 1)) / ncols;
  10261. if (colw < 24)
  10262. colw = 24;
  10263. x = row_left;
  10264. n = doc.nodes[parent].first;
  10265. while (n) {
  10266. struct br_node *nd = &doc.nodes[n];
  10267. struct br_style cs;
  10268. unsigned short lk = link;
  10269. int h;
  10270. if (nd->type == BR_NODE_TEXT) {
  10271. n = nd->next;
  10272. continue;
  10273. }
  10274. br_style_for(&doc, n, pst, &cs);
  10275. if (cs.display == BR_DISPLAY_NONE) {
  10276. n = nd->next;
  10277. continue;
  10278. }
  10279. if (nd->tag == BR_TAG_A && nd->href_off)
  10280. lk = (unsigned short)n;
  10281. cs.width_kind = 0;
  10282. cs.max_width_kind = 0;
  10283. l->left = x;
  10284. l->right = x + colw;
  10285. if (l->right < l->left + 8)
  10286. l->right = l->left + 8;
  10287. l->y = y;
  10288. l->line_left = l->line_x = l->left;
  10289. l->run_x = l->left;
  10290. l->line_y = l->y;
  10291. l->line_h = 0;
  10292. l->nruns = 0;
  10293. l->space_pending = 0;
  10294. l->align = cs.align;
  10295. layout_block(l, n, &cs, depth + 1, lk);
  10296. h = l->y - y;
  10297. if (h > row_h)
  10298. row_h = h;
  10299. col++;
  10300. n = nd->next;
  10301. if (col == ncols) {
  10302. y += row_h + gap;
  10303. x = row_left;
  10304. row_h = 0;
  10305. col = 0;
  10306. } else {
  10307. x += colw + gap;
  10308. }
  10309. }
  10310. if (col)
  10311. y += row_h;
  10312. else if (y > start_y)
  10313. y -= gap;
  10314. l->left = row_left;
  10315. l->right = row_right;
  10316. l->y = y;
  10317. l->line_left = l->line_x = l->left;
  10318. l->run_x = l->left;
  10319. l->line_y = l->y;
  10320. l->line_h = 0;
  10321. l->nruns = 0;
  10322. l->space_pending = 0;
  10323. }
  10324. /* Column widths are the widest cell in each column across every row, so all
  10325. * rows line up. The table model is still deliberately basic: no colspan,
  10326. * border-collapse or percentage columns. */
  10327. static void table_columns(struct lay *l, unsigned int table,
  10328. const struct br_style *pst, int avail,
  10329. int *raw, int maxcols, int *out_cols,
  10330. int *out_total)
  10331. {
  10332. unsigned int r, c;
  10333. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10334. int fixed[12];
  10335. for (c = 0; c < (unsigned int)maxcols; c++) {
  10336. raw[c] = 0;
  10337. fixed[c] = 0;
  10338. }
  10339. /* Intrinsic widths of single-column cells. */
  10340. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10341. struct br_node *rn = &doc.nodes[r];
  10342. int col = 0;
  10343. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10344. continue;
  10345. for (c = rn->first; c; c = doc.nodes[c].next) {
  10346. struct br_node *cn = &doc.nodes[c];
  10347. struct br_style cs;
  10348. int w, span;
  10349. if (cn->type != BR_NODE_ELEM ||
  10350. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10351. continue;
  10352. span = cn->colspan ? cn->colspan : 1;
  10353. br_style_for(&doc, c, pst, &cs);
  10354. if (cs.display == BR_DISPLAY_NONE)
  10355. continue;
  10356. if (col + span > maxcols)
  10357. span = maxcols - col;
  10358. if (span < 1)
  10359. break;
  10360. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10361. mp_px(&cs, 7, avail) +
  10362. mp_px(&cs, 5, avail) +
  10363. mp_px(&cs, 3, avail) +
  10364. mp_px(&cs, 1, avail) +
  10365. cs.border_w[0] + cs.border_w[1] +
  10366. cs.border_w[2] + cs.border_w[3];
  10367. if (w < 24)
  10368. w = 24;
  10369. if (span == 1) {
  10370. if (w > raw[col])
  10371. raw[col] = w;
  10372. }
  10373. if (col + span > cols)
  10374. cols = col + span;
  10375. col += span;
  10376. }
  10377. }
  10378. /* A colspan cell only has to be as wide as the sum of its columns. */
  10379. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10380. struct br_node *rn = &doc.nodes[r];
  10381. int col = 0;
  10382. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10383. continue;
  10384. for (c = rn->first; c; c = doc.nodes[c].next) {
  10385. struct br_node *cn = &doc.nodes[c];
  10386. struct br_style cs;
  10387. int span, w, sum, i;
  10388. if (cn->type != BR_NODE_ELEM ||
  10389. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10390. continue;
  10391. span = cn->colspan ? cn->colspan : 1;
  10392. if (col + span > maxcols)
  10393. span = maxcols - col;
  10394. if (span < 1)
  10395. break;
  10396. if (span > 1) {
  10397. br_style_for(&doc, c, pst, &cs);
  10398. if (cs.display != BR_DISPLAY_NONE) {
  10399. w = intrinsic_width(l->ui, c, &cs,
  10400. 0, avail) +
  10401. mp_px(&cs, 7, avail) +
  10402. mp_px(&cs, 5, avail) +
  10403. mp_px(&cs, 3, avail) +
  10404. mp_px(&cs, 1, avail) +
  10405. cs.border_w[0] + cs.border_w[1] +
  10406. cs.border_w[2] + cs.border_w[3];
  10407. sum = 0;
  10408. for (i = 0; i < span; i++)
  10409. sum += raw[col + i];
  10410. if (w > sum)
  10411. raw[col + span - 1] += w - sum;
  10412. }
  10413. }
  10414. col += span;
  10415. }
  10416. }
  10417. /* Explicit and percentage widths override intrinsic widths. */
  10418. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10419. struct br_node *rn = &doc.nodes[r];
  10420. int col = 0;
  10421. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10422. continue;
  10423. for (c = rn->first; c; c = doc.nodes[c].next) {
  10424. struct br_node *cn = &doc.nodes[c];
  10425. struct br_style cs;
  10426. int span;
  10427. if (cn->type != BR_NODE_ELEM ||
  10428. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10429. continue;
  10430. span = cn->colspan ? cn->colspan : 1;
  10431. if (col + span > maxcols)
  10432. span = maxcols - col;
  10433. if (span < 1)
  10434. break;
  10435. if (span == 1) {
  10436. br_style_for(&doc, c, pst, &cs);
  10437. if (cs.display != BR_DISPLAY_NONE) {
  10438. if (cs.width_kind == 1) {
  10439. raw[col] = cs.width;
  10440. fixed[col] = 1;
  10441. } else if (cs.width_kind == 2 ||
  10442. cs.width_kind == 3) {
  10443. raw[col] = style_width_px(&cs,
  10444. avail);
  10445. fixed[col] = 1;
  10446. }
  10447. }
  10448. }
  10449. col += span;
  10450. }
  10451. }
  10452. for (c = 0; c < (unsigned int)cols; c++) {
  10453. if (raw[c] < 8)
  10454. raw[c] = 8;
  10455. total += raw[c];
  10456. if (fixed[c])
  10457. fixed_sum += raw[c];
  10458. else {
  10459. free_raw += raw[c];
  10460. free_cols++;
  10461. }
  10462. }
  10463. if (fixed_sum > 0 && fixed_sum < avail) {
  10464. int free_avail = avail - fixed_sum;
  10465. int i;
  10466. if (free_raw > 0) {
  10467. for (i = 0; i < cols; i++)
  10468. if (!fixed[i])
  10469. raw[i] = free_avail * raw[i] /
  10470. free_raw;
  10471. } else if (free_cols > 0) {
  10472. for (i = 0; i < cols; i++)
  10473. if (!fixed[i])
  10474. raw[i] = free_avail / free_cols;
  10475. }
  10476. total = 0;
  10477. for (i = 0; i < cols; i++)
  10478. total += raw[i];
  10479. } else if (total < avail && total > 0) {
  10480. int i;
  10481. for (i = 0; i < cols; i++)
  10482. raw[i] = raw[i] * avail / total;
  10483. total = 0;
  10484. for (i = 0; i < cols; i++)
  10485. total += raw[i];
  10486. }
  10487. *out_cols = cols;
  10488. *out_total = total;
  10489. }
  10490. static void layout_table_row(struct lay *l, unsigned int row,
  10491. const struct br_style *pst, int depth,
  10492. unsigned short link)
  10493. {
  10494. unsigned int n, cell[12];
  10495. int raw[12], colstart[12], colspan[12];
  10496. int prefix[13];
  10497. int ncell = 0, total = 0, cols = 0, col = 0;
  10498. int row_left = l->left, row_right = l->right;
  10499. int avail = row_right - row_left;
  10500. int y = l->y, bottom = l->y;
  10501. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10502. struct br_node *nd = &doc.nodes[n];
  10503. struct br_style cs;
  10504. int span;
  10505. if (nd->type == BR_NODE_TEXT) {
  10506. if (text_node_blank(nd))
  10507. continue;
  10508. layout_children(l, row, pst, depth, link);
  10509. return;
  10510. }
  10511. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10512. layout_children(l, row, pst, depth, link);
  10513. return;
  10514. }
  10515. br_style_for(&doc, n, pst, &cs);
  10516. if (cs.display == BR_DISPLAY_NONE)
  10517. continue;
  10518. if (ncell >= 12) {
  10519. layout_children(l, row, pst, depth, link);
  10520. return;
  10521. }
  10522. span = nd->colspan ? nd->colspan : 1;
  10523. if (span > 12 - col)
  10524. span = 12 - col;
  10525. if (span < 1)
  10526. continue;
  10527. cell[ncell] = n;
  10528. colstart[ncell] = col;
  10529. colspan[ncell] = span;
  10530. col += span;
  10531. ncell++;
  10532. }
  10533. if (ncell < 1 || avail < 32) {
  10534. layout_children(l, row, pst, depth, link);
  10535. return;
  10536. }
  10537. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10538. &total);
  10539. if (cols < 2 || total <= 0) {
  10540. int c;
  10541. total = 0;
  10542. for (c = 0; c < ncell; c++) {
  10543. struct br_style cs;
  10544. br_style_for(&doc, cell[c], pst, &cs);
  10545. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10546. avail) +
  10547. mp_px(&cs, 7, avail) +
  10548. mp_px(&cs, 5, avail) +
  10549. mp_px(&cs, 3, avail) +
  10550. mp_px(&cs, 1, avail);
  10551. if (raw[c] < 24)
  10552. raw[c] = 24;
  10553. total += raw[c];
  10554. }
  10555. /* A one-column table still has to fill its own width; the
  10556. * intrinsic fallback above otherwise leaves the cell at its
  10557. * text width (HN's outer table and nested story table). */
  10558. if (total > 0 && total < avail) {
  10559. int c;
  10560. for (c = 0; c < ncell; c++)
  10561. raw[c] = raw[c] * avail / total;
  10562. total = avail;
  10563. }
  10564. }
  10565. prefix[0] = row_left;
  10566. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10567. prefix[n + 1] = prefix[n] + raw[n];
  10568. for (n = 0; n < (unsigned int)ncell; n++) {
  10569. struct br_style cs;
  10570. int start = colstart[n];
  10571. int end = start + colspan[n];
  10572. int w;
  10573. if (end > cols)
  10574. end = cols;
  10575. if (start >= cols)
  10576. continue;
  10577. w = prefix[end] - prefix[start];
  10578. br_style_for(&doc, cell[n], pst, &cs);
  10579. /* The column width already reflects the cell's width property. */
  10580. cs.width_kind = 0;
  10581. cs.max_width_kind = 0;
  10582. if (w < 24)
  10583. w = 24;
  10584. if (w < 8)
  10585. w = 8;
  10586. l->left = prefix[start];
  10587. l->right = l->left + w;
  10588. l->y = y;
  10589. l->line_left = l->line_x = l->left;
  10590. l->run_x = l->left;
  10591. l->line_y = l->y;
  10592. l->line_h = 0;
  10593. l->nruns = 0;
  10594. l->space_pending = 0;
  10595. l->align = cs.align;
  10596. layout_block(l, cell[n], &cs, depth + 1, link);
  10597. if (l->y > bottom)
  10598. bottom = l->y;
  10599. }
  10600. l->left = row_left;
  10601. l->right = row_right;
  10602. l->y = bottom;
  10603. l->line_left = l->line_x = l->left;
  10604. l->run_x = l->left;
  10605. l->line_y = l->y;
  10606. l->line_h = 0;
  10607. l->nruns = 0;
  10608. l->space_pending = 0;
  10609. }
  10610. #define TBL_MAX_ROWS 32
  10611. #define TBL_MAX_COLS 12
  10612. #define TBL_MAX_CELLS 128
  10613. struct tbl_cell {
  10614. unsigned int node;
  10615. unsigned char row, col, rowspan, colspan;
  10616. int height;
  10617. };
  10618. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10619. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10620. static int table_active;
  10621. static int table_has_rowspan(unsigned int table)
  10622. {
  10623. unsigned int r, c;
  10624. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10625. struct br_node *rn = &doc.nodes[r];
  10626. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10627. continue;
  10628. for (c = rn->first; c; c = doc.nodes[c].next) {
  10629. struct br_node *cn = &doc.nodes[c];
  10630. if (cn->type == BR_NODE_ELEM &&
  10631. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10632. cn->rowspan > 1)
  10633. return 1;
  10634. }
  10635. }
  10636. return 0;
  10637. }
  10638. static void table_cell_style(unsigned int row, unsigned int cell,
  10639. const struct br_style *st, struct br_style *out)
  10640. {
  10641. struct br_style trs;
  10642. br_style_for(&doc, row, st, &trs);
  10643. br_style_for(&doc, cell, &trs, out);
  10644. }
  10645. /* Tables that use rowspan need row heights before anything is painted. This
  10646. * path builds a small occupancy grid, measures the natural cell heights, then
  10647. * lays every cell out at its row/column position. Tables without rowspan
  10648. * keep the lighter per-row path in layout_table_row(). */
  10649. static void layout_table(struct lay *l, unsigned int table,
  10650. const struct br_style *st, int depth,
  10651. unsigned short link)
  10652. {
  10653. unsigned int rows[TBL_MAX_ROWS];
  10654. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10655. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10656. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10657. int free_raw = 0, free_cols = 0;
  10658. int table_left = l->left, table_right = l->right;
  10659. int top = l->y, avail = table_right - table_left;
  10660. unsigned int r, c;
  10661. int i, rr, cc;
  10662. if (depth > 48 || table_active) {
  10663. layout_children(l, table, st, depth, link);
  10664. return;
  10665. }
  10666. table_active = 1;
  10667. for (r = doc.nodes[table].first;
  10668. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10669. struct br_node *rn = &doc.nodes[r];
  10670. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10671. rows[nrows++] = r;
  10672. }
  10673. if (!nrows) {
  10674. table_active = 0;
  10675. layout_children(l, table, st, depth, link);
  10676. return;
  10677. }
  10678. for (rr = 0; rr < nrows; rr++)
  10679. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10680. tbl_at[rr][cc] = 0;
  10681. for (rr = 0; rr < nrows; rr++) {
  10682. int col = 0;
  10683. for (c = doc.nodes[rows[rr]].first; c;
  10684. c = doc.nodes[c].next) {
  10685. struct br_node *cn = &doc.nodes[c];
  10686. struct br_style cs;
  10687. int rs, csn;
  10688. if (cn->type != BR_NODE_ELEM ||
  10689. (cn->tag != BR_TAG_TD &&
  10690. cn->tag != BR_TAG_TH))
  10691. continue;
  10692. table_cell_style(rows[rr], c, st, &cs);
  10693. if (cs.display == BR_DISPLAY_NONE)
  10694. continue;
  10695. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10696. col++;
  10697. if (col >= TBL_MAX_COLS)
  10698. break;
  10699. rs = cn->rowspan ? cn->rowspan : 1;
  10700. csn = cn->colspan ? cn->colspan : 1;
  10701. if (rr + rs > nrows)
  10702. rs = nrows - rr;
  10703. if (col + csn > TBL_MAX_COLS)
  10704. csn = TBL_MAX_COLS - col;
  10705. if (rs < 1 || csn < 1)
  10706. continue;
  10707. if (ncells >= TBL_MAX_CELLS)
  10708. break;
  10709. tbl_cells[ncells].node = c;
  10710. tbl_cells[ncells].row = (unsigned char)rr;
  10711. tbl_cells[ncells].col = (unsigned char)col;
  10712. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10713. tbl_cells[ncells].colspan = (unsigned char)csn;
  10714. tbl_cells[ncells].height = 0;
  10715. for (i = rr; i < rr + rs; i++)
  10716. for (int j = col; j < col + csn; j++)
  10717. tbl_at[i][j] =
  10718. (unsigned short)(ncells + 1);
  10719. ncells++;
  10720. col += csn;
  10721. if (col > cols)
  10722. cols = col;
  10723. }
  10724. }
  10725. if (!ncells || cols < 1) {
  10726. table_active = 0;
  10727. layout_children(l, table, st, depth, link);
  10728. return;
  10729. }
  10730. for (i = 0; i < cols; i++) {
  10731. raw[i] = 0;
  10732. fixed[i] = 0;
  10733. }
  10734. /* Intrinsic widths of single-column cells. */
  10735. for (i = 0; i < ncells; i++) {
  10736. struct br_style cs;
  10737. int w;
  10738. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10739. st, &cs);
  10740. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10741. mp_px(&cs, 7, avail) +
  10742. mp_px(&cs, 5, avail) +
  10743. mp_px(&cs, 3, avail) +
  10744. mp_px(&cs, 1, avail) +
  10745. cs.border_w[0] + cs.border_w[1] +
  10746. cs.border_w[2] + cs.border_w[3];
  10747. if (w < 24)
  10748. w = 24;
  10749. if (tbl_cells[i].colspan == 1) {
  10750. int col = tbl_cells[i].col;
  10751. if (w > raw[col])
  10752. raw[col] = w;
  10753. }
  10754. }
  10755. /* A spanning cell only needs the sum of its columns to be large
  10756. * enough; put the deficit in the last column. */
  10757. for (i = 0; i < ncells; i++) {
  10758. struct br_style cs;
  10759. int w, sum, col, span;
  10760. if (tbl_cells[i].colspan < 2)
  10761. continue;
  10762. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10763. st, &cs);
  10764. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10765. mp_px(&cs, 7, avail) +
  10766. mp_px(&cs, 5, avail) +
  10767. mp_px(&cs, 3, avail) +
  10768. mp_px(&cs, 1, avail) +
  10769. cs.border_w[0] + cs.border_w[1] +
  10770. cs.border_w[2] + cs.border_w[3];
  10771. col = tbl_cells[i].col;
  10772. span = tbl_cells[i].colspan;
  10773. sum = 0;
  10774. for (int j = 0; j < span; j++)
  10775. sum += raw[col + j];
  10776. if (w > sum)
  10777. raw[col + span - 1] += w - sum;
  10778. }
  10779. /* Explicit/percentage widths, as in table_columns(). */
  10780. for (i = 0; i < ncells; i++) {
  10781. struct br_style cs;
  10782. int col;
  10783. if (tbl_cells[i].colspan != 1)
  10784. continue;
  10785. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10786. st, &cs);
  10787. col = tbl_cells[i].col;
  10788. if (cs.width_kind == 1) {
  10789. raw[col] = cs.width;
  10790. fixed[col] = 1;
  10791. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10792. raw[col] = style_width_px(&cs, avail);
  10793. fixed[col] = 1;
  10794. }
  10795. }
  10796. for (i = 0; i < cols; i++) {
  10797. if (raw[i] < 8)
  10798. raw[i] = 8;
  10799. total += raw[i];
  10800. if (fixed[i])
  10801. fixed_sum += raw[i];
  10802. else {
  10803. free_raw += raw[i];
  10804. free_cols++;
  10805. }
  10806. }
  10807. if (fixed_sum > 0 && fixed_sum < avail) {
  10808. int free_avail = avail - fixed_sum;
  10809. if (free_raw > 0) {
  10810. for (i = 0; i < cols; i++)
  10811. if (!fixed[i])
  10812. raw[i] = free_avail * raw[i] /
  10813. free_raw;
  10814. } else if (free_cols > 0) {
  10815. for (i = 0; i < cols; i++)
  10816. if (!fixed[i])
  10817. raw[i] = free_avail / free_cols;
  10818. }
  10819. } else if (total < avail && total > 0) {
  10820. for (i = 0; i < cols; i++)
  10821. raw[i] = raw[i] * avail / total;
  10822. }
  10823. prefix[0] = table_left;
  10824. for (i = 0; i < cols; i++)
  10825. prefix[i + 1] = prefix[i] + raw[i];
  10826. /* Measure natural cell heights with the column widths. */
  10827. for (i = 0; i < ncells; i++) {
  10828. struct br_style cs;
  10829. int col = tbl_cells[i].col;
  10830. int span = tbl_cells[i].colspan;
  10831. int w = prefix[col + span] - prefix[col];
  10832. int sl = l->left, sr = l->right, sy = l->y;
  10833. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10834. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10835. int sal = l->align, sdraw = l->draw;
  10836. struct ngui *sui = l->ui;
  10837. if (w < 8)
  10838. w = 8;
  10839. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10840. st, &cs);
  10841. cs.width_kind = 0;
  10842. cs.max_width_kind = 0;
  10843. l->draw = 0;
  10844. l->ui = 0;
  10845. l->left = prefix[col];
  10846. l->right = l->left + w;
  10847. l->y = 0;
  10848. l->line_left = l->line_x = l->left;
  10849. l->run_x = l->left;
  10850. l->line_y = 0;
  10851. l->line_h = 0;
  10852. l->nruns = 0;
  10853. l->space_pending = 0;
  10854. l->align = cs.align;
  10855. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10856. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10857. l->left = sl;
  10858. l->right = sr;
  10859. l->y = sy;
  10860. l->line_x = slx;
  10861. l->run_x = srx;
  10862. l->line_y = sly;
  10863. l->line_h = slh;
  10864. l->nruns = snr;
  10865. l->space_pending = ssp;
  10866. l->align = sal;
  10867. l->draw = sdraw;
  10868. l->ui = sui;
  10869. }
  10870. for (i = 0; i < nrows; i++)
  10871. rowh[i] = 0;
  10872. for (i = 0; i < ncells; i++) {
  10873. int row = tbl_cells[i].row;
  10874. if (tbl_cells[i].rowspan == 1) {
  10875. if (tbl_cells[i].height > rowh[row])
  10876. rowh[row] = tbl_cells[i].height;
  10877. }
  10878. }
  10879. for (i = 0; i < ncells; i++) {
  10880. int row = tbl_cells[i].row;
  10881. int span = tbl_cells[i].rowspan;
  10882. int sum = 0;
  10883. if (span < 2)
  10884. continue;
  10885. for (int j = 0; j < span; j++)
  10886. sum += rowh[row + j];
  10887. if (sum < tbl_cells[i].height)
  10888. rowh[row + span - 1] +=
  10889. tbl_cells[i].height - sum;
  10890. }
  10891. for (i = 0; i < nrows; i++)
  10892. if (rowh[i] < 8)
  10893. rowh[i] = 8;
  10894. rowy[0] = top;
  10895. for (i = 1; i < nrows; i++)
  10896. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10897. if (!l->draw) {
  10898. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10899. table_active = 0;
  10900. return;
  10901. }
  10902. for (i = 0; i < ncells; i++) {
  10903. struct br_style cs;
  10904. int col = tbl_cells[i].col;
  10905. int span = tbl_cells[i].colspan;
  10906. int row = tbl_cells[i].row;
  10907. int rspan = tbl_cells[i].rowspan;
  10908. int w = prefix[col + span] - prefix[col];
  10909. int h = 0;
  10910. int sl = l->left, sr = l->right, sy = l->y;
  10911. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10912. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10913. int sal = l->align;
  10914. int deco;
  10915. for (int j = 0; j < rspan; j++)
  10916. h += rowh[row + j];
  10917. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10918. cs.width_kind = 0;
  10919. cs.max_width_kind = 0;
  10920. cs.box_sizing = 0;
  10921. deco = mp_px(&cs, 4, avail) +
  10922. mp_px(&cs, 6, avail) +
  10923. cs.border_w[0] + cs.border_w[2];
  10924. cs.height_kind = 1;
  10925. cs.height = h > deco ? h - deco : 0;
  10926. /* The block painter reads block_h[] from the measure pass; make
  10927. * the table cell fill its row/rowspan, not just its content. */
  10928. if (h > 0 && h < 65536)
  10929. block_h[tbl_cells[i].node] = (unsigned short)h;
  10930. l->left = prefix[col];
  10931. l->right = l->left + w;
  10932. l->y = rowy[row];
  10933. l->line_left = l->line_x = l->left;
  10934. l->run_x = l->left;
  10935. l->line_y = l->y;
  10936. l->line_h = 0;
  10937. l->nruns = 0;
  10938. l->space_pending = 0;
  10939. l->align = cs.align;
  10940. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10941. l->left = sl;
  10942. l->right = sr;
  10943. l->y = sy;
  10944. l->line_x = slx;
  10945. l->run_x = srx;
  10946. l->line_y = sly;
  10947. l->line_h = slh;
  10948. l->nruns = snr;
  10949. l->space_pending = ssp;
  10950. l->align = sal;
  10951. }
  10952. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10953. table_active = 0;
  10954. }
  10955. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10956. * flow so they sit above it, like CSS painting order. Their flow origin is
  10957. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10958. struct br_deferred {
  10959. unsigned int node;
  10960. int flow_y, flow_left, flow_right;
  10961. int parent_top; /* the parent box top, for sticky clamping */
  10962. unsigned short link;
  10963. signed short z_index;
  10964. unsigned char z_set;
  10965. unsigned int order;
  10966. };
  10967. /* Positioned boxes painted after the flow. News front pages have one or two
  10968. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10969. * old 16 entries the rest fell back into the flow, so a hero image landed
  10970. * below its padding-top aspect box instead of on top of it. */
  10971. #define BR_MAX_DEFERRED 256
  10972. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10973. static int ndeferred;
  10974. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10975. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10976. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10977. struct br_style *ps, int base)
  10978. {
  10979. char buf[8];
  10980. int w, h;
  10981. if (!doc.npe_rules ||
  10982. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10983. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10984. return 0;
  10985. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10986. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10987. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10988. w = (int)ps->min_width;
  10989. if (w <= 0)
  10990. w = h;
  10991. if (w <= 0 || w > 512)
  10992. return 0;
  10993. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10994. }
  10995. /* An empty ::before/::after with a size and a background: one run the
  10996. * size of the box. Only data: background images are drawn (decoded at
  10997. * the background-size); `margin-left: auto` inside a flex parent pushes
  10998. * the box to the line's right edge like the flex row would. */
  10999. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  11000. const struct br_style *ps, unsigned short link)
  11001. {
  11002. struct lay_run *r;
  11003. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  11004. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  11005. if (lw < 8)
  11006. lw = 8;
  11007. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  11008. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  11009. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  11010. w = (int)ps->min_width;
  11011. if (w <= 0)
  11012. w = h;
  11013. if (h <= 0)
  11014. h = w;
  11015. if (w <= 0 || w > 512 || h > 512)
  11016. return;
  11017. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  11018. mr = mp_px(ps, 1, lw);
  11019. if (ml < 0)
  11020. ml = 0;
  11021. if (mr < 0)
  11022. mr = 0;
  11023. if (l->line_x + ml + w > l->line_right &&
  11024. (l->nruns > 0 || l->line_x > l->line_left))
  11025. flush_line(l);
  11026. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11027. flush_line(l);
  11028. if (l->nruns == 0) {
  11029. l->line_y = l->y;
  11030. l->line_h = 0;
  11031. start_line(l, ps);
  11032. }
  11033. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11034. l->line_right - w - mr > l->line_x)
  11035. l->line_x = l->line_right - w - mr;
  11036. else
  11037. l->line_x += ml;
  11038. r = &l->runs[l->nruns++];
  11039. memset(r, 0, sizeof(*r));
  11040. r->box = l->box_owner;
  11041. r->gap = (unsigned short)(l->line_x > l->run_x ?
  11042. l->line_x - l->run_x : 0);
  11043. r->img = RUN_PBOX;
  11044. r->href = link;
  11045. r->iw = (unsigned short)w;
  11046. r->ih = (unsigned short)h;
  11047. r->w = (unsigned short)w;
  11048. r->font_px = ps->font_px;
  11049. r->pb_has_bg = ps->has_bg;
  11050. r->pb_bg = ps->bg;
  11051. r->pb_img = -1;
  11052. if (ps->transform_set) {
  11053. r->transform_scale = 1;
  11054. r->scale_x = ps->scale_x;
  11055. r->scale_y = ps->scale_y;
  11056. r->rotate_x100 = ps->rotate_x100;
  11057. }
  11058. /* Background size and position, as draw_bg_image() resolves them. */
  11059. tw = w;
  11060. th = h;
  11061. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  11062. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  11063. if (ps->bg_size_kind == 2) {
  11064. bw = bw ? w * bw / 100 : 0;
  11065. bh = bh ? h * bh / 100 : 0;
  11066. }
  11067. tw = bw ? bw : (bh ? bh : w);
  11068. th = bh ? bh : tw;
  11069. }
  11070. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  11071. r->pb_img = (short)data_url_image(url, tw, th);
  11072. r->pb_w = (short)tw;
  11073. r->pb_h = (short)th;
  11074. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  11075. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  11076. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  11077. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  11078. l->line_x += w + mr;
  11079. l->run_x = l->line_x;
  11080. if (l->line_h < h)
  11081. l->line_h = h;
  11082. }
  11083. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  11084. * element's line. A block-level pseudo-element gets its own line; its box
  11085. * (margins, padding, background) is not drawn. */
  11086. static void emit_pseudo(struct lay *l, unsigned int node,
  11087. const struct br_style *st, int pe, unsigned short link)
  11088. {
  11089. char buf[160];
  11090. struct br_style ps;
  11091. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  11092. unsigned int i = 0;
  11093. int block, space_w;
  11094. if (!n && ps.content == BR_CONTENT_EMPTY &&
  11095. ps.display != BR_DISPLAY_NONE) {
  11096. emit_pseudo_box(l, st, &ps, link);
  11097. return;
  11098. }
  11099. if (!n)
  11100. return;
  11101. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  11102. if (block)
  11103. flush_line(l);
  11104. if (ps.uppercase)
  11105. for (i = 0; i < n; i++)
  11106. if (buf[i] >= 'a' && buf[i] <= 'z')
  11107. buf[i] = (char)(buf[i] - 'a' + 'A');
  11108. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  11109. if (space_w <= 0)
  11110. space_w = 8;
  11111. i = 0;
  11112. while (i < n) {
  11113. char word[28];
  11114. unsigned int k = 0;
  11115. int w;
  11116. if (buf[i] == ' ') {
  11117. l->space_pending = 1;
  11118. i++;
  11119. continue;
  11120. }
  11121. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  11122. word[k++] = buf[i++];
  11123. word[k] = '\0';
  11124. if (l->space_pending &&
  11125. (l->nruns > 0 || l->line_x > l->line_left) &&
  11126. l->line_x + space_w <= l->line_right)
  11127. l->line_x += space_w;
  11128. l->space_pending = 0;
  11129. w = (int)face_text_width(l->ui, &ps, word, k);
  11130. if (l->line_x + w > l->line_right &&
  11131. (l->nruns > 0 || l->line_x > l->line_left))
  11132. flush_line(l);
  11133. add_run(l, 0, 0, &ps, link, word);
  11134. }
  11135. if (block)
  11136. flush_line(l);
  11137. }
  11138. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  11139. * z-index): measured in place, painted from the deferred stacked pass
  11140. * against its containing block. Shared by block and flex layout, so an
  11141. * absolute icon inside a flex row (a password field's reveal button) is
  11142. * not laid out as one of the row's items. Returns 1 when it handled n. */
  11143. static int layout_out_of_flow(struct lay *l, unsigned int n,
  11144. const struct br_style *cs, int depth,
  11145. unsigned short lk)
  11146. {
  11147. if (!(cs->pos == 1 || cs->pos == 2 ||
  11148. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  11149. return 0;
  11150. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  11151. ndeferred < BR_MAX_DEFERRED) {
  11152. /* Relative or sticky z-index (a sticky site
  11153. * header): measure and advance the flow without
  11154. * painting, then paint it in the deferred
  11155. * (stacked) pass, above the content after it. */
  11156. int fy = l->y, fl = l->left, fr = l->right;
  11157. int save_draw = l->draw;
  11158. l->draw = 0;
  11159. layout_block(l, n, cs, depth + 1, lk);
  11160. l->draw = save_draw;
  11161. deferred[ndeferred].node = n;
  11162. deferred[ndeferred].parent_top = l->parent_top;
  11163. deferred[ndeferred].flow_y = fy;
  11164. deferred[ndeferred].flow_left = fl;
  11165. deferred[ndeferred].flow_right = fr;
  11166. deferred[ndeferred].link = lk;
  11167. deferred[ndeferred].z_index = cs->z_index;
  11168. deferred[ndeferred].z_set = cs->z_set;
  11169. deferred[ndeferred].order = (unsigned int)ndeferred;
  11170. ndeferred++;
  11171. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  11172. deferred[ndeferred].node = n;
  11173. deferred[ndeferred].parent_top = l->parent_top;
  11174. deferred[ndeferred].flow_y =
  11175. cs->pos == 1 ? l->cb_top : l->y;
  11176. deferred[ndeferred].flow_left =
  11177. cs->pos == 1 ? l->cb_left : l->left;
  11178. deferred[ndeferred].flow_right =
  11179. cs->pos == 1 ? l->cb_right : l->right;
  11180. deferred[ndeferred].link = lk;
  11181. deferred[ndeferred].z_index = cs->z_index;
  11182. deferred[ndeferred].z_set = cs->z_set;
  11183. deferred[ndeferred].order = (unsigned int)ndeferred;
  11184. ndeferred++;
  11185. } else if (l->draw && cs->pos == 1) {
  11186. /* Deferred list full: paint in place, but still
  11187. * against the containing block, not the flow. */
  11188. int fy = l->y, fl = l->left, fr = l->right;
  11189. l->y = l->cb_top;
  11190. l->left = l->cb_left;
  11191. l->right = l->cb_right;
  11192. layout_block(l, n, cs, depth + 1, lk);
  11193. l->y = fy;
  11194. l->left = fl;
  11195. l->right = fr;
  11196. } else {
  11197. layout_block(l, n, cs, depth + 1, lk);
  11198. }
  11199. if (cs->pos == 1 && block_h[n] &&
  11200. doc.nodes[n].class_off) {
  11201. const char *cl = doc.attrs +
  11202. doc.nodes[n].class_off;
  11203. if ((contains_ci(cl, "poster-wrapper") ||
  11204. contains_ci(cl, "ts-picture")) &&
  11205. !has_skeleton_sibling(n))
  11206. l->y += block_h[n];
  11207. }
  11208. return 1;
  11209. }
  11210. /* An element laid out in the text line (an inline span, or an inline-block
  11211. * that flows like one): its runs are tagged with it, so flush_line() can
  11212. * record its box for getBoundingClientRect() and click targeting. */
  11213. static void layout_inline_box(struct lay *l, unsigned int node,
  11214. const struct br_style *cs, int depth,
  11215. unsigned short link)
  11216. {
  11217. unsigned short saved = l->box_owner;
  11218. if (node < BR_MAX_NODES) {
  11219. inline_box_parent[node] = saved;
  11220. l->box_owner = (unsigned short)(node + 1);
  11221. }
  11222. layout_children(l, node, cs, depth + 1, link);
  11223. l->box_owner = saved;
  11224. }
  11225. static void layout_children(struct lay *l, unsigned int parent,
  11226. const struct br_style *pst, int depth,
  11227. unsigned short link)
  11228. {
  11229. unsigned int n;
  11230. if (depth > 48)
  11231. return;
  11232. emit_pseudo(l, parent, pst, 1, link);
  11233. n = doc.nodes[parent].first;
  11234. while (n) {
  11235. struct br_node *nd = &doc.nodes[n];
  11236. struct br_style cs;
  11237. unsigned short lk = link;
  11238. if (nd->type == BR_NODE_TEXT) {
  11239. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  11240. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  11241. n = nd->next;
  11242. continue;
  11243. }
  11244. br_style_for(&doc, n, pst, &cs);
  11245. if (cs.display == BR_DISPLAY_NONE) {
  11246. n = nd->next;
  11247. continue;
  11248. }
  11249. if (cs.clear && l->float_active) {
  11250. flush_line(l);
  11251. if (l->y < l->float_bottom)
  11252. l->y = l->float_bottom;
  11253. l->float_active = 0;
  11254. l->line_x = l->left;
  11255. l->run_x = l->left;
  11256. l->line_left = l->left;
  11257. l->line_right = l->right;
  11258. l->line_y = l->y;
  11259. l->line_h = 0;
  11260. l->nruns = 0;
  11261. l->space_pending = 0;
  11262. }
  11263. if (nd->tag == BR_TAG_A && nd->href_off)
  11264. lk = (unsigned short)n;
  11265. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  11266. n = nd->next;
  11267. continue;
  11268. }
  11269. if (nd->tag == BR_TAG_BR) {
  11270. flush_line(l);
  11271. n = nd->next;
  11272. continue;
  11273. }
  11274. if (nd->tag == BR_TAG_HR) {
  11275. flush_line(l);
  11276. if (l->draw)
  11277. ngui_fill_rect(l->ui,
  11278. (struct ngui_rect){l->left, l->y + 2,
  11279. l->right - l->left, 1}, BR_GRAY);
  11280. l->y += 8;
  11281. n = nd->next;
  11282. continue;
  11283. }
  11284. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11285. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11286. !button_has_elements(n)) {
  11287. if (!(nd->tag == BR_TAG_INPUT &&
  11288. s_eq(br_type(&doc, n), "hidden"))) {
  11289. form_fill_line = pst->display ==
  11290. BR_DISPLAY_FLEX &&
  11291. pst->flex_col;
  11292. add_form_run(l, n, &cs, lk);
  11293. form_fill_line = 0;
  11294. }
  11295. n = nd->next;
  11296. continue;
  11297. }
  11298. if (nd->tag == BR_TAG_IMG) {
  11299. add_image_run(l, n, &cs, lk);
  11300. n = nd->next;
  11301. continue;
  11302. }
  11303. if (nd->tag == BR_TAG_SVG &&
  11304. (cs.display == BR_DISPLAY_INLINE ||
  11305. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11306. !cs.float_left) {
  11307. add_svg_run(l, n, &cs, lk);
  11308. n = nd->next;
  11309. continue;
  11310. }
  11311. if (nd->tag == BR_TAG_VIDEO) {
  11312. layout_block(l, n, &cs, depth + 1, lk);
  11313. n = nd->next;
  11314. continue;
  11315. }
  11316. if (cs.float_left) {
  11317. n = layout_float_group(l, n, pst, depth, lk);
  11318. continue;
  11319. }
  11320. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11321. inline_block_flows(n, &cs, 0)) {
  11322. layout_inline_box(l, n, &cs, depth, lk);
  11323. n = nd->next;
  11324. continue;
  11325. }
  11326. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11327. n = layout_inline_blocks(l, n, pst, depth, link);
  11328. continue;
  11329. }
  11330. /* A flex container is block-level like any block box even when
  11331. * the element is an inline tag such as <a> (a link card with
  11332. * display:flex is common on news sites). Without the block box
  11333. * its children were laid out in the parent flow with a 0x0 box
  11334. * of their own. */
  11335. /* inline-flex around inline content only ("| mehr" link
  11336. * tails, icon+label pills) stays in the text line. */
  11337. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11338. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11339. !flex_wants_row(n, &cs)) {
  11340. layout_children(l, n, &cs, depth + 1, lk);
  11341. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11342. cs.display == BR_DISPLAY_FLEX ||
  11343. br_tag_is_block(nd->tag))
  11344. layout_block(l, n, &cs, depth + 1, lk);
  11345. else if (cs.display == BR_DISPLAY_INLINE &&
  11346. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  11347. layout_inline_box(l, n, &cs, depth, lk);
  11348. else {
  11349. layout_children(l, n, &cs, depth + 1, lk);
  11350. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11351. l->space_pending = 1;
  11352. }
  11353. n = nd->next;
  11354. }
  11355. emit_pseudo(l, parent, pst, 2, link);
  11356. }
  11357. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11358. * runs and a recursive page can otherwise overflow the stack. */
  11359. static struct lay layout_state;
  11360. static int measure_page(int left, int right)
  11361. {
  11362. struct lay *l = &layout_state;
  11363. struct br_style base = base_style();
  11364. unsigned int i;
  11365. for (i = 0; i < BR_MAX_NODES; i++) {
  11366. block_h[i] = 0;
  11367. flex_stretch_h[i] = 0;
  11368. img_top[i] = 0;
  11369. block_top[i] = 0;
  11370. img_h[i] = 0;
  11371. layout_boxes[i].valid = 0;
  11372. }
  11373. memset(li_marker, 0, sizeof(li_marker));
  11374. inline_box_pass_id++;
  11375. l->box_owner = 0;
  11376. l->draw = 0;
  11377. l->ui = &ui;
  11378. l->left = left;
  11379. l->right = right;
  11380. l->y = 0;
  11381. l->line_x = left;
  11382. l->run_x = left;
  11383. l->line_left = left;
  11384. l->line_right = right;
  11385. l->line_y = 0;
  11386. l->line_h = 0;
  11387. l->align = BR_ALIGN_LEFT;
  11388. l->cb_h = layout_view_h;
  11389. l->float_active = 0;
  11390. l->parent_top = 0;
  11391. l->cb_left = left;
  11392. l->cb_right = right;
  11393. l->cb_top = 0;
  11394. l->depth = 0;
  11395. l->nruns = 0;
  11396. l->space_pending = 0;
  11397. base = root_style();
  11398. layout_children(l, doc.root, &base, 0, 0);
  11399. return l->y + 8;
  11400. }
  11401. static int deferred_cmp(const struct br_deferred *a,
  11402. const struct br_deferred *b)
  11403. {
  11404. int az = a->z_set ? a->z_index : 0;
  11405. int bz = b->z_set ? b->z_index : 0;
  11406. if (az != bz)
  11407. return az < bz ? -1 : 1;
  11408. if (a->order != b->order)
  11409. return a->order < b->order ? -1 : 1;
  11410. return 0;
  11411. }
  11412. static void sort_deferred(void)
  11413. {
  11414. int i;
  11415. for (i = 1; i < ndeferred; i++) {
  11416. struct br_deferred key = deferred[i];
  11417. int j = i;
  11418. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11419. deferred[j] = deferred[j - 1];
  11420. j--;
  11421. }
  11422. deferred[j] = key;
  11423. }
  11424. }
  11425. static void render_page(int left, int right, int y0)
  11426. {
  11427. struct lay *l = &layout_state;
  11428. struct br_style base = base_style();
  11429. inline_box_pass_id++;
  11430. l->box_owner = 0;
  11431. l->draw = 1;
  11432. l->ui = &ui;
  11433. l->left = left;
  11434. l->right = right;
  11435. l->y = y0;
  11436. l->line_x = left;
  11437. l->run_x = left;
  11438. l->line_left = left;
  11439. l->line_right = right;
  11440. l->line_y = y0;
  11441. l->line_h = 0;
  11442. l->align = BR_ALIGN_LEFT;
  11443. l->cb_h = layout_view_h;
  11444. l->float_active = 0;
  11445. l->parent_top = 0;
  11446. l->cb_left = left;
  11447. l->cb_right = right;
  11448. l->cb_top = y0;
  11449. l->depth = 0;
  11450. l->nruns = 0;
  11451. l->space_pending = 0;
  11452. nhits = 0;
  11453. ndeferred = 0;
  11454. base = root_style();
  11455. layout_children(l, doc.root, &base, 0, 0);
  11456. sort_deferred();
  11457. {
  11458. int i;
  11459. for (i = 0; i < ndeferred; i++) {
  11460. struct br_style st;
  11461. br_style_for(&doc, deferred[i].node, &base, &st);
  11462. if (st.display == BR_DISPLAY_NONE)
  11463. continue;
  11464. l->draw = 1;
  11465. l->left = deferred[i].flow_left;
  11466. l->right = deferred[i].flow_right;
  11467. l->y = deferred[i].flow_y;
  11468. l->parent_top = deferred[i].parent_top;
  11469. l->line_left = l->line_x = l->left;
  11470. l->run_x = l->left;
  11471. l->line_y = l->y;
  11472. l->line_h = 0;
  11473. l->nruns = 0;
  11474. l->space_pending = 0;
  11475. l->align = st.align;
  11476. if (st.pos == 2 && block_h[deferred[i].node]) {
  11477. struct ngui_rect clip;
  11478. int ch = block_h[deferred[i].node] + 24;
  11479. int pr = page_rect.x + page_rect.w - 12;
  11480. int x0 = page_rect.x, x1 = pr;
  11481. int y0 = page_rect.y;
  11482. /* A box placed by `bottom` (a page footer) is
  11483. * clipped and filled where layout_block puts
  11484. * it, against the bottom edge. */
  11485. if (st.bottom_set && !st.top_set) {
  11486. ch = block_h[deferred[i].node] +
  11487. mp_px(&st, 0, pr - page_rect.x) +
  11488. mp_px(&st, 2, pr - page_rect.x);
  11489. y0 = page_rect.y + page_rect.h -
  11490. st.bottom - ch;
  11491. }
  11492. /* The background pre-fill spans the box's own
  11493. * columns, not the whole page: Docusaurus parks
  11494. * a white "Skip to main content" link at
  11495. * `left: 100%` with a z-index above the navbar,
  11496. * and a full-width fill painted over the bar. */
  11497. if (st.left_set)
  11498. x0 = page_rect.x + st.left;
  11499. else if (!st.right_set)
  11500. x0 = deferred[i].flow_left;
  11501. if (st.width_kind == 1) {
  11502. if (st.right_set && !st.left_set)
  11503. x0 = pr - st.right - st.width;
  11504. x1 = x0 + st.width;
  11505. } else if (st.right_set) {
  11506. x1 = pr - st.right;
  11507. }
  11508. if (x0 >= pr || x1 <= page_rect.x)
  11509. continue; /* entirely off-screen */
  11510. if (x0 < page_rect.x)
  11511. x0 = page_rect.x;
  11512. if (x1 > pr)
  11513. x1 = pr;
  11514. if (y0 < page_rect.y) {
  11515. ch -= page_rect.y - y0;
  11516. y0 = page_rect.y;
  11517. }
  11518. clip.x = x0;
  11519. clip.y = y0;
  11520. clip.w = x1 - x0;
  11521. if (ch > page_rect.h)
  11522. ch = page_rect.h;
  11523. if (ch <= 0)
  11524. continue;
  11525. clip.h = ch;
  11526. ngui_push_clip(&ui, clip);
  11527. if (st.has_bg)
  11528. ngui_fill_rect(&ui, clip, st.bg);
  11529. layout_block(l, deferred[i].node, &st, 0,
  11530. deferred[i].link);
  11531. ngui_pop_clip(&ui);
  11532. } else {
  11533. layout_block(l, deferred[i].node, &st, 0,
  11534. deferred[i].link);
  11535. }
  11536. }
  11537. }
  11538. }
  11539. /* ---- UI ---- */
  11540. static int find_hit(int x, int y)
  11541. {
  11542. int i;
  11543. for (i = nhits - 1; i >= 0; i--) {
  11544. struct hit *h = &hits[i];
  11545. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11546. y < h->y + h->h)
  11547. return (int)h->node;
  11548. }
  11549. return 0;
  11550. }
  11551. /* ---- URL-bar autocomplete ----
  11552. *
  11553. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11554. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11555. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11556. * without the scheme and "www.") above substring matches of the URL, then
  11557. * of the title, and adds visit count and recency. Typing at the end of the
  11558. * text also completes inline to the next '/' of the best prefix match
  11559. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11560. * keystroke replaces it; Enter on that text opens the history URL it came
  11561. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11562. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11563. * bar), and a click on a row opens it. */
  11564. #define SUG_MAX 6
  11565. #define SUG_ROW_H 36
  11566. static int sug_idx[SUG_MAX];
  11567. static int sug_n, sug_sel = -1, sug_open;
  11568. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11569. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11570. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11571. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11572. static struct ngui_rect url_rect, sug_rect;
  11573. static int url_had_focus;
  11574. static char lc(char c)
  11575. {
  11576. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11577. }
  11578. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11579. {
  11580. for (; *p; s++, p++)
  11581. if (lc(*s) != *p)
  11582. return 0;
  11583. return 1;
  11584. }
  11585. static unsigned int url_scheme_len(const char *url)
  11586. {
  11587. if (starts_with(url, "https://"))
  11588. return 8;
  11589. if (starts_with(url, "http://"))
  11590. return 7;
  11591. return 0;
  11592. }
  11593. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11594. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11595. static int hist_prefix_at(const char *url, const char *t)
  11596. {
  11597. unsigned int s = url_scheme_len(url);
  11598. if (prefix_ci(url, t))
  11599. return 0;
  11600. if (s && prefix_ci(url + s, t))
  11601. return (int)s;
  11602. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11603. return (int)s + 4;
  11604. return -1;
  11605. }
  11606. static int hist_score(const struct hist_ent *e, const char *t,
  11607. unsigned int next)
  11608. {
  11609. unsigned int age = next - e->stamp;
  11610. int sc, at;
  11611. if (!t[0]) {
  11612. sc = 0;
  11613. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11614. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11615. int rest = (int)s_len(e->url + at);
  11616. sc = 4000 - (rest > 400 ? 400 : rest);
  11617. } else if (contains_ci(e->url, t)) {
  11618. sc = 1000;
  11619. } else if (contains_ci(e->title, t)) {
  11620. sc = 600;
  11621. } else {
  11622. return -1;
  11623. }
  11624. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11625. sc += age >= 500 ? 0 : (int)(500 - age);
  11626. return sc;
  11627. }
  11628. static void sug_lower(char *t, unsigned int cap)
  11629. {
  11630. unsigned int k;
  11631. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11632. t[k] = lc(sug_typed[k]);
  11633. t[k] = '\0';
  11634. }
  11635. static void sug_refresh(void)
  11636. {
  11637. char t[NGUI_INPUT_MAX];
  11638. int sc[SUG_MAX], i, j;
  11639. unsigned int next = hist_next_stamp();
  11640. sug_lower(t, sizeof(t));
  11641. sug_n = 0;
  11642. for (i = 0; i < hist_n; i++) {
  11643. int s = hist_score(&hist_tab[i], t, next);
  11644. if (s < 0)
  11645. continue;
  11646. j = sug_n;
  11647. if (j == SUG_MAX) {
  11648. if (sc[SUG_MAX - 1] >= s)
  11649. continue;
  11650. j = SUG_MAX - 1;
  11651. }
  11652. while (j > 0 && sc[j - 1] < s) {
  11653. sc[j] = sc[j - 1];
  11654. sug_idx[j] = sug_idx[j - 1];
  11655. j--;
  11656. }
  11657. sc[j] = s;
  11658. sug_idx[j] = i;
  11659. if (sug_n < SUG_MAX)
  11660. sug_n++;
  11661. }
  11662. if (sug_sel >= sug_n)
  11663. sug_sel = -1;
  11664. }
  11665. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11666. static void sug_inline(void)
  11667. {
  11668. char t[NGUI_INPUT_MAX];
  11669. const char *url, *rest;
  11670. unsigned int L, start, end, hs, tn, n = 0;
  11671. unsigned int next = hist_next_stamp();
  11672. int i, best = -1, best_sc = -1, at = 0;
  11673. sug_lower(t, sizeof(t));
  11674. L = s_len(t);
  11675. if (!L)
  11676. return;
  11677. for (i = 0; i < hist_n; i++) {
  11678. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11679. if (a < 0)
  11680. continue;
  11681. s = hist_score(&hist_tab[i], t, next);
  11682. if (s > best_sc) {
  11683. best_sc = s;
  11684. best = i;
  11685. at = a;
  11686. }
  11687. }
  11688. if (best < 0)
  11689. return;
  11690. url = hist_tab[best].url;
  11691. rest = url + at;
  11692. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11693. hs = at == 0 ? url_scheme_len(url) : 0;
  11694. start = L > hs ? L : hs;
  11695. end = start;
  11696. while (rest[end] && rest[end] != '/')
  11697. end++;
  11698. if (rest[end] == '/')
  11699. end++;
  11700. tn = s_len(sug_typed);
  11701. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11702. return;
  11703. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11704. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11705. ac_text[n++] = rest[L];
  11706. ac_text[n] = '\0';
  11707. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11708. ngui_input_set(&url_in, ac_text);
  11709. url_in.anchor = tn; /* select the completed part */
  11710. }
  11711. static void sug_close(void)
  11712. {
  11713. sug_open = 0;
  11714. sug_sel = -1;
  11715. ac_text[0] = '\0';
  11716. }
  11717. static int sug_visible(void)
  11718. {
  11719. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11720. }
  11721. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11722. * start page) lists the top sites until something is typed. */
  11723. static int sug_focus_check(void)
  11724. {
  11725. int focused = ngui_focus(&ui) == ID_URL;
  11726. if (focused && !url_had_focus) {
  11727. sug_typed[0] = '\0';
  11728. sug_close();
  11729. sug_open = 1;
  11730. sug_refresh();
  11731. }
  11732. url_had_focus = focused;
  11733. return focused;
  11734. }
  11735. static void url_submit(unsigned int *action)
  11736. {
  11737. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11738. s_copy(click_url, ac_url, sizeof(click_url));
  11739. *action |= ACT_NAV;
  11740. sug_close();
  11741. }
  11742. /* The bar text changed through typing or editing. */
  11743. static void sug_changed(void)
  11744. {
  11745. unsigned int pl = s_len(sug_typed);
  11746. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11747. !memcmp(url_in.text, sug_typed, pl);
  11748. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11749. ac_text[0] = '\0';
  11750. sug_sel = -1;
  11751. sug_open = 1;
  11752. sug_refresh();
  11753. if (grew)
  11754. sug_inline();
  11755. }
  11756. /* Keys for the list, taken off the queue before the text field sees them.
  11757. * Only a leading run is handled; the rest goes to the field. */
  11758. static void sug_keys(void)
  11759. {
  11760. int k;
  11761. while ((k = ngui_key_peek(&ui)) != 0) {
  11762. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11763. ngui_key(&ui);
  11764. if (!sug_open) {
  11765. sug_open = 1;
  11766. continue;
  11767. }
  11768. if (sug_sel < 0)
  11769. s_copy(sug_restore, url_in.text,
  11770. sizeof(sug_restore));
  11771. if (k == NGUI_KEY_DOWN)
  11772. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11773. else
  11774. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11775. ngui_input_set(&url_in, sug_sel >= 0 ?
  11776. hist_tab[sug_idx[sug_sel]].url :
  11777. sug_restore);
  11778. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11779. ngui_key(&ui);
  11780. if (sug_sel >= 0)
  11781. ngui_input_set(&url_in, sug_restore);
  11782. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11783. ngui_input_set(&url_in, sug_typed);
  11784. sug_close();
  11785. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11786. sug_sel >= 0) {
  11787. ngui_key(&ui);
  11788. hist_forget(sug_idx[sug_sel]);
  11789. ngui_input_set(&url_in, sug_restore);
  11790. sug_sel = -1;
  11791. sug_refresh();
  11792. } else {
  11793. break;
  11794. }
  11795. }
  11796. }
  11797. /* A press on a row of last frame's list opens it; any press on the list is
  11798. * swallowed so the page underneath does not see it. */
  11799. static void sug_click(unsigned int *action)
  11800. {
  11801. int row;
  11802. if (!(ui.pressed & 1) || !sug_rect.w ||
  11803. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11804. return;
  11805. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11806. if (row >= 0 && row < sug_n) {
  11807. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11808. sizeof(click_url));
  11809. *action |= ACT_NAV;
  11810. sug_close();
  11811. }
  11812. ui.pressed = 0;
  11813. }
  11814. static void draw_suggest(struct ngui_rect page)
  11815. {
  11816. struct ngui_rect r;
  11817. int i, rows = sug_n, hover = -1;
  11818. r.x = url_rect.x;
  11819. r.y = url_rect.y + url_rect.h + 1;
  11820. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11821. if (r.x + r.w > ui.w - 2)
  11822. r.w = ui.w - 2 - r.x;
  11823. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11824. rows--;
  11825. if (rows <= 0 || r.w < 60) {
  11826. sug_rect.w = 0;
  11827. return;
  11828. }
  11829. r.h = rows * SUG_ROW_H + 2;
  11830. sug_rect = r;
  11831. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11832. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11833. ngui_set_cursor(&ui, CURSOR_POINTER);
  11834. }
  11835. ngui_fill_rect(&ui, r, ui.theme.border);
  11836. for (i = 0; i < rows; i++) {
  11837. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11838. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11839. r.w - 2, SUG_ROW_H};
  11840. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11841. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11842. i == hover ? ui.theme.panel_alt :
  11843. ui.theme.panel;
  11844. ngui_fill_rect(&ui, rr, bg);
  11845. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11846. e->title[0] ? e->title : e->url,
  11847. ui.theme.text);
  11848. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11849. i == sug_sel ? ui.theme.text :
  11850. ui.theme.text_dim);
  11851. }
  11852. }
  11853. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11854. {
  11855. int x = r.x + 4, y = r.y + 4, h = 22;
  11856. int compact = r.w < 560;
  11857. int go_w = r.w < 420 ? 32 : 42;
  11858. int in_x, in_w, res;
  11859. ngui_fill_rect(&ui, r, ui.theme.panel);
  11860. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11861. ui.theme.border);
  11862. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11863. NGUI_ICON_CHEVRON_LEFT))
  11864. *action |= ACT_BACK;
  11865. x += 32;
  11866. if (!compact) {
  11867. if (ngui_icon_button(&ui, ID_FORWARD,
  11868. (struct ngui_rect){x, y, 28, h},
  11869. NGUI_ICON_CHEVRON_RIGHT))
  11870. *action |= ACT_FORWARD;
  11871. x += 32;
  11872. }
  11873. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11874. NGUI_ICON_REFRESH))
  11875. *action |= ACT_RELOAD;
  11876. x += 32;
  11877. if (!compact) {
  11878. if (ngui_icon_button(&ui, ID_HOME,
  11879. (struct ngui_rect){x, y, 28, h},
  11880. NGUI_ICON_HOME))
  11881. *action |= ACT_HOME;
  11882. x += 32;
  11883. }
  11884. in_x = x + 2;
  11885. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11886. if (in_w < 60)
  11887. in_w = 60;
  11888. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11889. if (sug_focus_check())
  11890. sug_keys();
  11891. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11892. sug_focus_check(); /* a click into the bar focuses it here */
  11893. if (res & NGUI_INPUT_CHANGED)
  11894. sug_changed();
  11895. if (res & NGUI_INPUT_SUBMIT)
  11896. url_submit(action);
  11897. if (res & NGUI_INPUT_CANCEL)
  11898. ngui_set_focus(&ui, 0);
  11899. if (ngui_button(&ui, ID_GO,
  11900. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11901. "Go"))
  11902. url_submit(action);
  11903. if (!sug_focus_check())
  11904. sug_close();
  11905. }
  11906. static int page_hover_node(void)
  11907. {
  11908. if (!ui.inside)
  11909. return 0;
  11910. if (ui.mouse_x < page_rect.x ||
  11911. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11912. ui.mouse_y < page_rect.y ||
  11913. ui.mouse_y >= page_rect.y + page_rect.h)
  11914. return 0;
  11915. return find_hit(ui.mouse_x, ui.mouse_y);
  11916. }
  11917. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11918. {
  11919. int x, y, w = page.w, h = page.h;
  11920. if (!src || w <= 0 || h <= 0)
  11921. return;
  11922. for (y = 0; y < h; y++) {
  11923. unsigned short *s = src + (page.y + y) * sw + page.x;
  11924. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11925. for (x = 0; x + 1 < w; x += 2) {
  11926. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11927. }
  11928. if (x < w)
  11929. d[x] = s[x];
  11930. }
  11931. }
  11932. static void draw_page(struct ngui_rect page)
  11933. {
  11934. int left, right, ch;
  11935. int old_panel, old_dim;
  11936. unsigned short *saved_px;
  11937. unsigned short page_bg = ui.theme.bg;
  11938. int saved_w, saved_h, use_buf;
  11939. unsigned int t0 = u_ticks_ms();
  11940. page_rect = page;
  11941. {
  11942. unsigned int root = doc.nnode > 1 ?
  11943. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11944. unsigned int body = doc.nnode > 1 ?
  11945. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11946. struct br_style bs;
  11947. int bg_found = 0;
  11948. if (root) {
  11949. style_for_node(root - 1, &bs);
  11950. if (bs.has_bg) {
  11951. page_bg = bs.bg;
  11952. bg_found = 1;
  11953. }
  11954. }
  11955. if (body) {
  11956. style_for_node(body - 1, &bs);
  11957. if (bs.has_bg) {
  11958. page_bg = bs.bg;
  11959. bg_found = 1;
  11960. }
  11961. }
  11962. /* No canvas colour, but the author made the text dark
  11963. * (Infima's light theme: `--ifm-background-color:
  11964. * transparent` on html, #1c1e21 text): the page expects the
  11965. * white canvas of a normal browser, and dark text on the
  11966. * dark default canvas is unreadable. */
  11967. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11968. unsigned int c = bs.color;
  11969. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11970. ((c >> 5) & 63) * 4 * 587 +
  11971. (c & 31) * 8 * 114;
  11972. if (lum < 100 * 1000)
  11973. page_bg = 0xFFFF;
  11974. }
  11975. }
  11976. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11977. page_cache_valid && layout_valid &&
  11978. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11979. !(ui.scroll_y &&
  11980. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11981. page_scroll.offset == page_cache_scroll &&
  11982. page_cache_nnode == doc.nnode &&
  11983. page_cache_x == page.x && page_cache_y == page.y &&
  11984. page_cache_w == page.w && page_cache_h == page.h) {
  11985. blit_page(page, page_backbuf, pagebuf_w);
  11986. if (img_stat_n)
  11987. img_stat_paint += u_ticks_ms() - t0;
  11988. return;
  11989. }
  11990. ngui_fill_rect(&ui, page, page_bg);
  11991. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11992. const char *s = page_loading ? "Loading..." : "No page";
  11993. int w = (int)ngui_text_width_ui(&ui, s);
  11994. ngui_text(&ui, page.x + (page.w - w) / 2,
  11995. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11996. page_scroll.content_h = 0;
  11997. page_scroll.view_h = page.h;
  11998. page_cache_valid = 0;
  11999. return;
  12000. }
  12001. if (page.w < 40 || page.h < 40) {
  12002. page_cache_valid = 0;
  12003. return;
  12004. }
  12005. saved_px = ui.px;
  12006. saved_w = ui.w;
  12007. saved_h = ui.h;
  12008. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  12009. if (use_buf) {
  12010. ui.px = page_backbuf;
  12011. ui.w = pagebuf_w;
  12012. ui.h = pagebuf_h;
  12013. ngui_fill_rect(&ui, page, page_bg);
  12014. }
  12015. /* No gutter of our own: the body's UA margin provides it. The
  12016. * right 12 px stay clear for the scrollbar, like every viewport
  12017. * width below (page_rect.w - 12). */
  12018. left = page.x;
  12019. right = page.x + page.w - 12;
  12020. if (!layout_valid || left != layout_left || right != layout_right ||
  12021. layout_nnode != doc.nnode) {
  12022. unsigned int tm = u_ticks_ms();
  12023. layout_view_h = page.h;
  12024. layout_content_h = measure_page(left, right);
  12025. if (img_stat_n)
  12026. img_stat_reflow += u_ticks_ms() - tm;
  12027. layout_valid = 1;
  12028. layout_left = left;
  12029. layout_right = right;
  12030. layout_nnode = doc.nnode;
  12031. /* Scripts that measured before any layout (offsetWidth on
  12032. * mount) get a resize event once real boxes exist, and again
  12033. * whenever the page width changes. */
  12034. if (js_browser_active() && right - left != resize_sent_w)
  12035. resize_pending = 1;
  12036. }
  12037. ch = layout_content_h;
  12038. page_scroll.content_h = ch;
  12039. page_scroll.view_h = page.h;
  12040. t0 = u_ticks_ms();
  12041. ngui_scroll_begin(&ui, page, &page_scroll);
  12042. ngui_scroll_wheel(&ui, page, &page_scroll);
  12043. render_page(left, right, page.y - page_scroll.offset);
  12044. old_panel = ui.theme.panel_alt;
  12045. old_dim = ui.theme.text_dim;
  12046. ui.theme.panel_alt = 0xC618;
  12047. ui.theme.text_dim = 0x8410;
  12048. ngui_scroll_end(&ui, page, &page_scroll);
  12049. ui.theme.panel_alt = old_panel;
  12050. ui.theme.text_dim = old_dim;
  12051. if (use_buf) {
  12052. ui.px = saved_px;
  12053. ui.w = saved_w;
  12054. ui.h = saved_h;
  12055. blit_page(page, page_backbuf, pagebuf_w);
  12056. page_cache_valid = 1;
  12057. page_cache_scroll = page_scroll.offset;
  12058. page_cache_nnode = doc.nnode;
  12059. page_cache_x = page.x;
  12060. page_cache_y = page.y;
  12061. page_cache_w = page.w;
  12062. page_cache_h = page.h;
  12063. } else {
  12064. page_cache_valid = 0;
  12065. }
  12066. if (img_stat_n)
  12067. img_stat_paint += u_ticks_ms() - t0;
  12068. }
  12069. static void draw_status(struct ngui_rect r)
  12070. {
  12071. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  12072. unsigned int n = 0;
  12073. int hover = page_hover_node();
  12074. unsigned short color;
  12075. const char *kind;
  12076. ngui_fill_rect(&ui, r, ui.theme.panel);
  12077. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  12078. ui.theme.border);
  12079. /* Only a real link target is shown: a form control, or an element
  12080. * that is merely clickable through a script listener (google.com's
  12081. * jsaction wrapper around its search field), is not a link. */
  12082. if (hover && !br_href(&doc, (unsigned int)hover))
  12083. hover = 0;
  12084. if (hover) {
  12085. const char *href = br_href(&doc, (unsigned int)hover);
  12086. char url[BR_URL_MAX];
  12087. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  12088. s_append(msg, &n, "Link: ", sizeof(msg));
  12089. s_append(msg, &n, url, sizeof(msg));
  12090. } else {
  12091. s_copy(msg, "Link", sizeof(msg));
  12092. }
  12093. color = ui.theme.accent;
  12094. } else if (status_text[0]) {
  12095. s_copy(msg, status_text, sizeof(msg));
  12096. color = status_error ? ui.theme.error : ui.theme.text;
  12097. } else if (page_title[0]) {
  12098. s_copy(msg, page_title, sizeof(msg));
  12099. color = ui.theme.text;
  12100. } else {
  12101. s_copy(msg, "Ready", sizeof(msg));
  12102. color = ui.theme.text_dim;
  12103. }
  12104. kind = s_eq(page_url, "about:home") ? "HOME" :
  12105. page_is_local ? "FILE" :
  12106. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  12107. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  12108. {
  12109. int kw = (int)ngui_text_width_ui(&ui, kind);
  12110. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  12111. ui.theme.text_dim);
  12112. }
  12113. }
  12114. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  12115. * for `auto`, a hand over links, the I-beam over text fields, and the
  12116. * progress arrow anywhere on the page while it is still loading. The
  12117. * toolbar's URL field sets its own I-beam through ngui. */
  12118. static void page_cursor(void)
  12119. {
  12120. int hover = page_hover_node();
  12121. struct br_style st;
  12122. if (!hover) {
  12123. if (page_loading && ui.inside &&
  12124. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  12125. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12126. return;
  12127. }
  12128. style_for_node((unsigned int)hover, &st);
  12129. if (st.cursor != BR_CURSOR_AUTO) {
  12130. ngui_set_cursor(&ui, (int)st.cursor - 1);
  12131. return;
  12132. }
  12133. if (br_href(&doc, (unsigned int)hover)) {
  12134. ngui_set_cursor(&ui, CURSOR_POINTER);
  12135. return;
  12136. }
  12137. if (form_is_control((unsigned int)hover)) {
  12138. int k = form_kind_of((unsigned int)hover);
  12139. if (form_disabled((unsigned int)hover))
  12140. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  12141. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  12142. k == FORM_TEXTAREA)
  12143. ngui_set_cursor(&ui, CURSOR_TEXT);
  12144. return;
  12145. }
  12146. if (page_loading)
  12147. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12148. }
  12149. static void draw(unsigned int *action)
  12150. {
  12151. struct ngui_rect r = {0, 0, ui.w, ui.h};
  12152. struct ngui_rect toolbar, status, page;
  12153. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  12154. status = ngui_cut_bottom(&r, BR_STATUS_H);
  12155. page = r;
  12156. if (sug_visible())
  12157. sug_click(action);
  12158. draw_toolbar(toolbar, action);
  12159. draw_page(page);
  12160. draw_status(status);
  12161. page_cursor();
  12162. if (sug_visible())
  12163. draw_suggest(page);
  12164. else
  12165. sug_rect.w = 0;
  12166. }
  12167. static void redraw_now(void)
  12168. {
  12169. unsigned int action = 0;
  12170. ngui_begin(&ui);
  12171. draw(&action);
  12172. ngui_end(&ui);
  12173. }
  12174. static void handle_keys(unsigned int *action)
  12175. {
  12176. int k, scrolled = 0;
  12177. if (form_focus >= doc.nnode)
  12178. form_focus = 0;
  12179. if (form_focus && !ngui_focus(&ui)) {
  12180. while ((k = ngui_key(&ui)) != 0)
  12181. form_key(k);
  12182. return;
  12183. }
  12184. /* Batch queued page keys: a slow full-page render must not make a
  12185. * held Page Down advance only once every few frames. */
  12186. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  12187. scrolled++;
  12188. if (scrolled)
  12189. ngui_invalidate(&ui);
  12190. if (ngui_focus(&ui))
  12191. return;
  12192. while ((k = ngui_key(&ui)) != 0) {
  12193. switch (k) {
  12194. case NGUI_KEY_ESC:
  12195. *action |= ACT_CLOSE;
  12196. break;
  12197. case NGUI_KEY_TAB:
  12198. case 0x0C: /* Ctrl+L */
  12199. ngui_set_focus(&ui, ID_URL);
  12200. break;
  12201. case 0x12: /* Ctrl+R */
  12202. *action |= ACT_RELOAD;
  12203. break;
  12204. case NGUI_KEY_BACKSPACE:
  12205. *action |= ACT_BACK;
  12206. break;
  12207. case NGUI_KEY_UP:
  12208. ngui_scroll_to(&page_scroll,
  12209. page_scroll.offset - 24);
  12210. ngui_invalidate(&ui);
  12211. break;
  12212. case NGUI_KEY_DOWN:
  12213. ngui_scroll_to(&page_scroll,
  12214. page_scroll.offset + 24);
  12215. ngui_invalidate(&ui);
  12216. break;
  12217. case NGUI_KEY_HOME:
  12218. ngui_scroll_to(&page_scroll, 0);
  12219. ngui_invalidate(&ui);
  12220. break;
  12221. case NGUI_KEY_END:
  12222. ngui_scroll_to(&page_scroll,
  12223. page_scroll.content_h -
  12224. page_scroll.view_h);
  12225. ngui_invalidate(&ui);
  12226. break;
  12227. default:
  12228. break;
  12229. }
  12230. }
  12231. }
  12232. static unsigned int form_ancestor(unsigned int node)
  12233. {
  12234. unsigned int p = node;
  12235. while (p && p < doc.nnode) {
  12236. if (doc.nodes[p].tag == BR_TAG_FORM &&
  12237. doc.nodes[p].type == BR_NODE_ELEM)
  12238. return p;
  12239. p = doc.nodes[p].parent;
  12240. }
  12241. return 0;
  12242. }
  12243. static int form_descendant(unsigned int node, unsigned int form)
  12244. {
  12245. unsigned int p = node;
  12246. while (p && p < doc.nnode) {
  12247. if (p == form)
  12248. return 1;
  12249. p = doc.nodes[p].parent;
  12250. }
  12251. return 0;
  12252. }
  12253. static void form_reset_form(unsigned int form)
  12254. {
  12255. unsigned int i;
  12256. for (i = 0; i < FORM_MAX; i++)
  12257. if (form_states[i].used &&
  12258. form_descendant(form_states[i].node, form))
  12259. form_states[i].used = 0;
  12260. form_focus = 0;
  12261. }
  12262. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  12263. const char *s)
  12264. {
  12265. static const char hex[] = "0123456789ABCDEF";
  12266. while (s && *s && *n + 1 < cap) {
  12267. unsigned char c = (unsigned char)*s++;
  12268. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  12269. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  12270. c == '.' || c == '~') {
  12271. dst[(*n)++] = (char)c;
  12272. } else if (c == ' ') {
  12273. dst[(*n)++] = '+';
  12274. } else if (*n + 3 < cap) {
  12275. dst[(*n)++] = '%';
  12276. dst[(*n)++] = hex[c >> 4];
  12277. dst[(*n)++] = hex[c & 15];
  12278. }
  12279. }
  12280. dst[*n] = '\0';
  12281. }
  12282. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  12283. const char *name, const char *value, int *first)
  12284. {
  12285. if (!name || !name[0])
  12286. return;
  12287. if (!*first && *n + 1 < cap)
  12288. dst[(*n)++] = '&';
  12289. *first = 0;
  12290. form_url_append(dst, n, cap, name);
  12291. if (*n + 1 < cap)
  12292. dst[(*n)++] = '=';
  12293. form_url_append(dst, n, cap, value ? value : "");
  12294. dst[*n] = '\0';
  12295. }
  12296. static int form_submit_form(unsigned int node, int fire_event)
  12297. {
  12298. unsigned int form = form_ancestor(node);
  12299. char action[BR_URL_MAX], query[2048];
  12300. unsigned int qn = 0, i;
  12301. int first = 1, is_post = 0;
  12302. const char *a, *method;
  12303. if (!form)
  12304. return 0;
  12305. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12306. return 0;
  12307. method = br_find_attr(&doc, form, "method");
  12308. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12309. is_post = 1;
  12310. a = br_find_attr(&doc, form, "action");
  12311. if (a && a[0]) {
  12312. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12313. return 0;
  12314. } else {
  12315. s_copy(action, page_url, sizeof(action));
  12316. }
  12317. query[0] = '\0';
  12318. for (i = 0; i < doc.nnode; i++) {
  12319. struct br_node *nd = &doc.nodes[i];
  12320. struct form_state *fs;
  12321. const char *name;
  12322. const char *value = "";
  12323. if (nd->type != BR_NODE_ELEM || i == form ||
  12324. !form_descendant(i, form))
  12325. continue;
  12326. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12327. nd->tag != BR_TAG_SELECT)
  12328. continue;
  12329. if (form_disabled(i))
  12330. continue;
  12331. name = br_find_attr(&doc, i, "name");
  12332. if (!name || !name[0])
  12333. continue;
  12334. fs = form_get(i, 1);
  12335. if (!fs)
  12336. continue;
  12337. if (nd->tag == BR_TAG_SELECT) {
  12338. char opt[64];
  12339. if (!form_option_text(i, fs->selected, opt,
  12340. sizeof(opt)))
  12341. s_copy(opt, "", sizeof(opt));
  12342. value = opt;
  12343. {
  12344. unsigned int c, oi = 0;
  12345. for (c = nd->first; c;
  12346. c = doc.nodes[c].next) {
  12347. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12348. doc.nodes[c].tag != BR_TAG_OPTION)
  12349. continue;
  12350. if (oi == fs->selected) {
  12351. const char *v =
  12352. br_value(&doc, c);
  12353. if (v && v[0])
  12354. value = v;
  12355. break;
  12356. }
  12357. oi++;
  12358. }
  12359. }
  12360. } else if (nd->tag == BR_TAG_INPUT) {
  12361. int kind = form_kind_of(i);
  12362. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12363. if (!fs->checked)
  12364. continue;
  12365. value = br_value(&doc, i);
  12366. if (!value || !value[0])
  12367. value = "on";
  12368. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12369. kind == FORM_BUTTON) {
  12370. if (i != node)
  12371. continue;
  12372. value = fs->value;
  12373. } else {
  12374. value = fs->value;
  12375. }
  12376. } else {
  12377. value = fs->value;
  12378. }
  12379. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12380. }
  12381. if (is_post) {
  12382. if (action[0] == '/') {
  12383. set_status("POST forms need an HTTP action URL", 1, 4000);
  12384. ngui_invalidate(&ui);
  12385. return 0;
  12386. }
  12387. if (qn >= sizeof(pending_post))
  12388. qn = sizeof(pending_post) - 1;
  12389. if (qn)
  12390. memcpy(pending_post, query, qn);
  12391. pending_post[qn] = '\0';
  12392. pending_post_len = qn;
  12393. pending_post_is = 1;
  12394. } else {
  12395. pending_post_len = 0;
  12396. pending_post_is = 0;
  12397. if (qn) {
  12398. unsigned int an = s_len(action);
  12399. if (an + qn + 2 < sizeof(action)) {
  12400. action[an++] = strchr(action, '?') ? '&' : '?';
  12401. action[an] = '\0';
  12402. s_copy(action + an, query,
  12403. sizeof(action) - an);
  12404. }
  12405. }
  12406. }
  12407. s_copy(pending_url, action, sizeof(pending_url));
  12408. pending_action |= ACT_NAV;
  12409. cancel_fetch = 1;
  12410. ngui_invalidate(&ui);
  12411. return 1;
  12412. }
  12413. static void form_reset_event(unsigned int form)
  12414. {
  12415. if (form && !js_browser_event(form, "reset", 1, 1))
  12416. return;
  12417. if (form)
  12418. form_reset_form(form);
  12419. else
  12420. form_reset_state();
  12421. form_dirty = 0;
  12422. layout_valid = 0;
  12423. ngui_invalidate(&ui);
  12424. }
  12425. static void form_blur(void)
  12426. {
  12427. unsigned int node = form_focus;
  12428. form_focus = 0;
  12429. if (node && form_dirty) {
  12430. form_dirty = 0;
  12431. js_browser_event(node, "change", 1, 0);
  12432. }
  12433. }
  12434. static void form_click(unsigned int node)
  12435. {
  12436. struct form_state *fs;
  12437. int kind, changed = 0;
  12438. if (!form_is_control(node) || form_disabled(node))
  12439. return;
  12440. if (form_focus != node)
  12441. form_blur();
  12442. fs = form_get(node, 1);
  12443. if (!fs)
  12444. return;
  12445. kind = form_kind_of(node);
  12446. /* Focus moves on the press, before `click` is dispatched: a page
  12447. * that cancels the click (a framework's root listener) suppresses
  12448. * the activation behaviour below, never the focus (as in other
  12449. * browsers, where focus follows mousedown). */
  12450. form_focus = node;
  12451. form_dirty = 0;
  12452. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12453. kind == FORM_TEXTAREA)
  12454. fs->caret = fs->len;
  12455. layout_valid = 0;
  12456. ngui_invalidate(&ui);
  12457. if (!js_browser_event(node, "click", 1, 1))
  12458. return;
  12459. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12460. if (!fs)
  12461. return;
  12462. if (kind == FORM_CHECKBOX) {
  12463. fs->checked = !fs->checked;
  12464. changed = 1;
  12465. } else if (kind == FORM_RADIO) {
  12466. const char *name = br_find_attr(&doc, node, "name");
  12467. unsigned int i;
  12468. fs->checked = 1;
  12469. changed = 1;
  12470. if (name) {
  12471. for (i = 0; i < FORM_MAX; i++) {
  12472. struct form_state *o = &form_states[i];
  12473. if (!o->used || o->node == node)
  12474. continue;
  12475. if (form_kind_of(o->node) == FORM_RADIO) {
  12476. const char *on = br_find_attr(&doc,
  12477. o->node,
  12478. "name");
  12479. if (on && s_eq(on, name))
  12480. o->checked = 0;
  12481. }
  12482. }
  12483. }
  12484. } else if (kind == FORM_SELECT) {
  12485. unsigned int n = form_option_count(node);
  12486. if (n) {
  12487. fs->selected = (unsigned char)
  12488. ((fs->selected + 1) % n);
  12489. changed = 1;
  12490. }
  12491. } else if (kind == FORM_SUBMIT) {
  12492. form_submit_form(node, 1);
  12493. return;
  12494. } else if (kind == FORM_RESET) {
  12495. form_reset_event(form_ancestor(node));
  12496. return;
  12497. }
  12498. if (changed) {
  12499. js_browser_event(node, "input", 1, 0);
  12500. js_browser_event(node, "change", 1, 0);
  12501. }
  12502. layout_valid = 0;
  12503. ngui_invalidate(&ui);
  12504. }
  12505. static void form_focus_next(void)
  12506. {
  12507. unsigned int start = form_focus ? form_focus + 1 : 0;
  12508. unsigned int i;
  12509. form_blur();
  12510. for (i = start; i < doc.nnode; i++) {
  12511. if (form_is_control(i) && !form_disabled(i) &&
  12512. !s_eq(br_type(&doc, i), "hidden")) {
  12513. form_focus = i;
  12514. layout_valid = 0;
  12515. ngui_invalidate(&ui);
  12516. return;
  12517. }
  12518. }
  12519. form_focus = 0;
  12520. layout_valid = 0;
  12521. ngui_invalidate(&ui);
  12522. }
  12523. static void form_key(int k)
  12524. {
  12525. struct form_state *fs;
  12526. int kind;
  12527. if (!form_focus || form_focus >= doc.nnode) {
  12528. form_focus = 0;
  12529. return;
  12530. }
  12531. fs = form_get(form_focus, 1);
  12532. if (!fs || form_disabled(form_focus))
  12533. return;
  12534. kind = form_kind_of(form_focus);
  12535. if (kind == FORM_SELECT) {
  12536. unsigned int n = form_option_count(form_focus);
  12537. int changed = 0;
  12538. if (k == NGUI_KEY_UP && n) {
  12539. fs->selected = (unsigned char)
  12540. ((fs->selected + n - 1) % n);
  12541. changed = 1;
  12542. } else if (k == NGUI_KEY_DOWN && n) {
  12543. fs->selected = (unsigned char)
  12544. ((fs->selected + 1) % n);
  12545. changed = 1;
  12546. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12547. form_blur();
  12548. layout_valid = 0;
  12549. ngui_invalidate(&ui);
  12550. return;
  12551. } else {
  12552. return;
  12553. }
  12554. if (changed) {
  12555. js_browser_event(form_focus, "input", 1, 0);
  12556. js_browser_event(form_focus, "change", 1, 0);
  12557. }
  12558. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12559. if (k == ' ') {
  12560. form_click(form_focus);
  12561. return;
  12562. }
  12563. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12564. form_blur();
  12565. layout_valid = 0;
  12566. ngui_invalidate(&ui);
  12567. }
  12568. return;
  12569. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12570. kind == FORM_RESET) {
  12571. if (k == NGUI_KEY_ESC) {
  12572. form_blur();
  12573. layout_valid = 0;
  12574. ngui_invalidate(&ui);
  12575. } else if (k == '\r' || k == '\n' || k == ' ') {
  12576. form_click(form_focus);
  12577. }
  12578. return;
  12579. } else if (k == NGUI_KEY_TAB) {
  12580. form_focus_next();
  12581. return;
  12582. } else if (k == NGUI_KEY_ESC) {
  12583. form_blur();
  12584. layout_valid = 0;
  12585. ngui_invalidate(&ui);
  12586. return;
  12587. } else if (k == '\r' || k == '\n') {
  12588. unsigned int node = form_focus;
  12589. form_blur();
  12590. if (form_ancestor(node))
  12591. form_submit_form(node, 1);
  12592. layout_valid = 0;
  12593. ngui_invalidate(&ui);
  12594. return;
  12595. } else if (k == NGUI_KEY_BACKSPACE) {
  12596. if (fs->caret) {
  12597. unsigned int i = --fs->caret;
  12598. for (; i < fs->len; i++)
  12599. fs->value[i] = fs->value[i + 1];
  12600. if (fs->len)
  12601. fs->len--;
  12602. form_dirty = 1;
  12603. js_browser_event(form_focus, "input", 1, 0);
  12604. }
  12605. } else if (k == NGUI_KEY_DELETE) {
  12606. if (fs->caret < fs->len) {
  12607. unsigned int i;
  12608. for (i = fs->caret; i < fs->len; i++)
  12609. fs->value[i] = fs->value[i + 1];
  12610. fs->len--;
  12611. form_dirty = 1;
  12612. js_browser_event(form_focus, "input", 1, 0);
  12613. }
  12614. } else if (k == NGUI_KEY_LEFT) {
  12615. if (fs->caret)
  12616. fs->caret--;
  12617. } else if (k == NGUI_KEY_RIGHT) {
  12618. if (fs->caret < fs->len)
  12619. fs->caret++;
  12620. } else if (k == NGUI_KEY_HOME) {
  12621. fs->caret = 0;
  12622. } else if (k == NGUI_KEY_END) {
  12623. fs->caret = fs->len;
  12624. } else if (k >= 32 && k < 127) {
  12625. if (fs->len < FORM_VALUE_MAX) {
  12626. unsigned int i;
  12627. for (i = fs->len; i > fs->caret; i--)
  12628. fs->value[i] = fs->value[i - 1];
  12629. fs->value[fs->caret++] = (char)k;
  12630. fs->len++;
  12631. form_dirty = 1;
  12632. js_browser_event(form_focus, "input", 1, 0);
  12633. }
  12634. } else {
  12635. return;
  12636. }
  12637. fs->value[fs->len] = '\0';
  12638. layout_valid = 0;
  12639. ngui_invalidate(&ui);
  12640. }
  12641. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12642. * a same-document navigation: update the URL and fire hashchange. Returns
  12643. * 1 when handled. */
  12644. static int link_fragment_nav(unsigned int node)
  12645. {
  12646. const char *href = br_href(&doc, node);
  12647. char url[BR_URL_MAX];
  12648. unsigned int n = 0;
  12649. if (!href || !href[0] || !js_browser_active())
  12650. return 0;
  12651. if (href[0] == '#') {
  12652. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12653. url[n] = page_url[n];
  12654. n++;
  12655. }
  12656. url[n] = '\0';
  12657. s_append(url, &n, href, sizeof(url));
  12658. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12659. return 0;
  12660. }
  12661. if (!same_doc_fragment(url))
  12662. return href[0] == '#';
  12663. page_set_fragment(url, 1);
  12664. js_browser_hashchange();
  12665. return 1;
  12666. }
  12667. /* The innermost laid-out box under a screen point: the smallest valid box
  12668. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12669. * Used to deliver clicks to elements that are neither links nor controls
  12670. * (a Vue <div role="button">, a card with a click listener). */
  12671. static unsigned int find_box_hit(int x, int y)
  12672. {
  12673. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12674. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12675. const struct br_layout_box *b = &layout_boxes[i];
  12676. unsigned int area;
  12677. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12678. x < b->x || y < b->y || x >= b->x + b->w ||
  12679. y >= b->y + b->h)
  12680. continue;
  12681. area = (unsigned int)b->w * (unsigned int)b->h;
  12682. if (area <= best_area) {
  12683. best = i;
  12684. best_area = area;
  12685. }
  12686. }
  12687. return best;
  12688. }
  12689. static void handle_page_click(unsigned int *action)
  12690. {
  12691. int node;
  12692. char url[BR_URL_MAX];
  12693. if (!ui.pressed)
  12694. return;
  12695. if (ui.press_x < page_rect.x ||
  12696. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12697. ui.press_y < page_rect.y ||
  12698. ui.press_y >= page_rect.y + page_rect.h)
  12699. return;
  12700. node = find_hit(ui.press_x, ui.press_y);
  12701. if (!node) {
  12702. unsigned int box;
  12703. if (!js_browser_active())
  12704. return;
  12705. box = find_box_hit(ui.press_x, ui.press_y);
  12706. if (box) {
  12707. form_blur();
  12708. js_browser_event(box, "click", 1, 1);
  12709. }
  12710. return;
  12711. }
  12712. if (form_is_control((unsigned int)node)) {
  12713. form_click((unsigned int)node);
  12714. return;
  12715. }
  12716. form_blur();
  12717. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12718. return;
  12719. if (link_fragment_nav((unsigned int)node))
  12720. return;
  12721. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12722. sizeof(url)) != 0)
  12723. return;
  12724. s_copy(click_url, url, sizeof(click_url));
  12725. *action |= ACT_NAV;
  12726. }
  12727. void _start(const char *arg)
  12728. {
  12729. struct win_info wi;
  12730. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12731. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12732. u_win_create(780, 540, "Browser", &wi) != 0) {
  12733. u_puts("browser: no graphics window\n");
  12734. u_exit(1);
  12735. }
  12736. ufont_set_arena_bytes(BR_FONT_ARENA);
  12737. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12738. url_in.placeholder = "http://...";
  12739. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12740. ui.theme.accent);
  12741. br_set_viewport(wi.width);
  12742. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12743. s_copy(cwd, "/", sizeof(cwd));
  12744. heap_clear();
  12745. origin_cache_load();
  12746. css_cache_init();
  12747. script_cache_init();
  12748. font_cache_init();
  12749. persist_restore();
  12750. hist_load();
  12751. page_scroll.offset = 0;
  12752. page_scroll.content_h = 0;
  12753. if (arg && arg[0]) {
  12754. navigate(arg, 1);
  12755. } else {
  12756. load_home(1);
  12757. /* Start ready to type: keep the home page, but leave the address
  12758. * bar empty instead of showing "about:home". */
  12759. ngui_input_set(&url_in, "");
  12760. ngui_set_focus(&ui, ID_URL);
  12761. }
  12762. for (;;) {
  12763. unsigned int action = 0;
  12764. unsigned int now;
  12765. click_url[0] = '\0';
  12766. if (pending_action) {
  12767. action |= pending_action & ACT_WAIT_NAV;
  12768. if (pending_url[0])
  12769. s_copy(click_url, pending_url, sizeof(click_url));
  12770. pending_action = 0;
  12771. pending_url[0] = '\0';
  12772. cancel_fetch = 0;
  12773. } else if (preload_active) {
  12774. if (preload_wait)
  12775. preload_wait = 0;
  12776. else
  12777. preload_step();
  12778. } else if ((preload_pending &&
  12779. page_scroll.offset != preload_scroll) ||
  12780. (preload_rescan && layout_valid)) {
  12781. preload_scroll = page_scroll.offset;
  12782. preload_rescan = 0;
  12783. preload_pending = 0;
  12784. preload_node = 0;
  12785. preload_active = 1;
  12786. }
  12787. js_browser_tick();
  12788. if (resize_pending && !pending_action) {
  12789. resize_pending = 0;
  12790. resize_sent_w = layout_right - layout_left;
  12791. js_browser_window_event("resize");
  12792. }
  12793. persist_tick();
  12794. if (pending_action)
  12795. continue;
  12796. now = u_ticks_ms();
  12797. if (status_until && (int)(now - status_until) >= 0) {
  12798. status_text[0] = '\0';
  12799. status_until = 0;
  12800. status_error = 0;
  12801. ngui_invalidate(&ui);
  12802. }
  12803. if (!ngui_begin(&ui)) {
  12804. /* A queued navigation (e.g. Enter in the URL bar during
  12805. * a slow fetch) must be handled even when this frame
  12806. * needs no redraw. */
  12807. if (!action) {
  12808. fetch_workers_stop_if_unfocused();
  12809. u_sleep_ms(10);
  12810. continue;
  12811. }
  12812. } else {
  12813. draw(&action);
  12814. handle_keys(&action);
  12815. handle_page_click(&action);
  12816. ngui_end(&ui);
  12817. }
  12818. if (action & ACT_NAV) {
  12819. if (click_url[0]) {
  12820. navigate(click_url, 1);
  12821. click_url[0] = '\0';
  12822. } else {
  12823. navigate(url_in.text, 1);
  12824. }
  12825. }
  12826. if (action & ACT_BACK) {
  12827. if (hist_pos > 0) {
  12828. hist_pos--;
  12829. if (same_doc_fragment(history[hist_pos])) {
  12830. page_set_fragment(history[hist_pos], 0);
  12831. js_browser_hashchange();
  12832. } else {
  12833. navigate(history[hist_pos], 0);
  12834. }
  12835. }
  12836. }
  12837. if (action & ACT_FORWARD) {
  12838. if (hist_pos + 1 < hist_len) {
  12839. hist_pos++;
  12840. if (same_doc_fragment(history[hist_pos])) {
  12841. page_set_fragment(history[hist_pos], 0);
  12842. js_browser_hashchange();
  12843. } else {
  12844. navigate(history[hist_pos], 0);
  12845. }
  12846. }
  12847. }
  12848. if (action & ACT_RELOAD) {
  12849. if (s_eq(page_url, "about:home"))
  12850. load_home(0);
  12851. else
  12852. navigate(page_url, 0);
  12853. }
  12854. if (action & ACT_HOME)
  12855. load_home(1);
  12856. if (action & ACT_CLOSE)
  12857. quit = 1;
  12858. if (quit)
  12859. break;
  12860. if (pending_action)
  12861. continue;
  12862. fetch_workers_stop_if_unfocused();
  12863. u_sleep_ms(10);
  12864. }
  12865. fetch_workers_stop_all();
  12866. u_win_close();
  12867. u_exit(0);
  12868. }