browser.c 370 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887
  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. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3186. unsigned int cap, const char *method,
  3187. const char *ctype, const char *post,
  3188. unsigned int post_len, unsigned int node,
  3189. int bg, unsigned int dec_w,
  3190. unsigned int dec_h, char *err,
  3191. unsigned int errcap);
  3192. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3193. unsigned int cap, const char *post,
  3194. unsigned int post_len, unsigned int node,
  3195. int bg, char *err, unsigned int errcap)
  3196. {
  3197. /* A body pointer with no bytes is still a POST: the classic request
  3198. * line would turn it into a GET. */
  3199. if (post && !post_len)
  3200. return fetch_worker_submit_req(w, url, cap, "POST",
  3201. "application/x-www-form-urlencoded", post, 0, node,
  3202. bg, 0, 0, err, errcap);
  3203. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3204. node, bg, 0, 0, err, errcap);
  3205. }
  3206. /* Image job: ask the helper to decode at these display bounds as well. */
  3207. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3208. unsigned int cap, unsigned int node,
  3209. int bg, unsigned int dec_w,
  3210. unsigned int dec_h, char *err,
  3211. unsigned int errcap)
  3212. {
  3213. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3214. dec_w, dec_h, err, errcap);
  3215. }
  3216. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3217. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3218. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3219. unsigned int cap, const char *method,
  3220. const char *ctype, const char *post,
  3221. unsigned int post_len, unsigned int node,
  3222. int bg, unsigned int dec_w,
  3223. unsigned int dec_h, char *err,
  3224. unsigned int errcap)
  3225. {
  3226. static char req[BR_URL_MAX + 256];
  3227. unsigned int n = 0;
  3228. fetch_seq++;
  3229. if (!fetch_seq)
  3230. fetch_seq = 1;
  3231. w->seq = fetch_seq;
  3232. w->ready = 0;
  3233. w->image_job = 0;
  3234. w->retried = 0;
  3235. w->m.error = 0;
  3236. w->node = node;
  3237. w->bg = bg;
  3238. w->dec_w = dec_w;
  3239. w->dec_h = dec_h;
  3240. w->dec_retried = 0;
  3241. s_copy(w->url, url, sizeof(w->url));
  3242. s_append_dec(req, &n, w->seq, sizeof(req));
  3243. s_append(req, &n, " ", sizeof(req));
  3244. s_append_dec(req, &n, cap, sizeof(req));
  3245. s_append(req, &n, " ", sizeof(req));
  3246. if (dec_w || dec_h) {
  3247. s_append(req, &n, "D ", sizeof(req));
  3248. s_append_dec(req, &n, dec_w, sizeof(req));
  3249. s_append(req, &n, " ", sizeof(req));
  3250. s_append_dec(req, &n, dec_h, sizeof(req));
  3251. s_append(req, &n, " ", sizeof(req));
  3252. } else if (method) {
  3253. unsigned int k;
  3254. s_append(req, &n, "X ", sizeof(req));
  3255. s_append(req, &n, method, sizeof(req));
  3256. s_append(req, &n, " ", sizeof(req));
  3257. s_append_dec(req, &n, post_len, sizeof(req));
  3258. s_append(req, &n, " ", sizeof(req));
  3259. if (!ctype || !ctype[0])
  3260. s_append(req, &n, "-", sizeof(req));
  3261. /* One token on the request line: drop the spaces
  3262. * ("application/json; charset=utf-8" stays valid). */
  3263. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3264. if (ctype[k] != ' ')
  3265. req[n++] = ctype[k];
  3266. req[n] = '\0';
  3267. s_append(req, &n, " ", sizeof(req));
  3268. } else if (post_len) {
  3269. s_append(req, &n, "POST ", sizeof(req));
  3270. s_append_dec(req, &n, post_len, sizeof(req));
  3271. s_append(req, &n, " ", sizeof(req));
  3272. }
  3273. s_append(req, &n, url, sizeof(req));
  3274. s_append(req, &n, "\n", sizeof(req));
  3275. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3276. (int)post, (int)post_len) < 0) {
  3277. s_copy(err, "cannot queue form body", errcap);
  3278. return -1;
  3279. }
  3280. u_syscall1(SYS_UNLINK, (int)w->done);
  3281. u_syscall1(SYS_UNLINK, (int)w->meta);
  3282. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3283. s_copy(err, "cannot queue network request", errcap);
  3284. return -1;
  3285. }
  3286. if (fetch_worker_start(w, err, errcap) != 0)
  3287. return -1;
  3288. w->busy = 1;
  3289. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3290. return 0;
  3291. }
  3292. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3293. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3294. unsigned int errcap)
  3295. {
  3296. static char meta[BR_URL_MAX + 1024];
  3297. char *p;
  3298. int rn, mseq;
  3299. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3300. (int)(sizeof(meta) - 1));
  3301. if (rn <= 0) {
  3302. s_copy(err, "network helper failed", errcap);
  3303. return -1;
  3304. }
  3305. meta[rn] = '\0';
  3306. p = meta;
  3307. mseq = (int)meta_uint(&p);
  3308. if (mseq != (int)w->seq) {
  3309. s_copy(err, "stale network response", errcap);
  3310. return -1;
  3311. }
  3312. w->m.status = (int)meta_uint(&p);
  3313. w->m.error = (int)meta_uint(&p);
  3314. w->m.trunc = (int)meta_uint(&p);
  3315. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3316. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3317. meta_str(&p, w->m.final, sizeof(w->m.final));
  3318. w->m.len = meta_uint(&p);
  3319. w->m.open_ms = 0;
  3320. w->m.first_ms = 0;
  3321. w->m.total_ms = 0;
  3322. if (*p) {
  3323. w->m.open_ms = meta_uint(&p);
  3324. w->m.first_ms = meta_uint(&p);
  3325. w->m.total_ms = meta_uint(&p);
  3326. }
  3327. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3328. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3329. w->m.dec_err = 0;
  3330. if (*p) {
  3331. w->m.dw = meta_uint(&p);
  3332. w->m.dh = meta_uint(&p);
  3333. w->m.nw = meta_uint(&p);
  3334. w->m.nh = meta_uint(&p);
  3335. w->m.alpha = meta_uint(&p);
  3336. w->m.px_len = meta_uint(&p);
  3337. w->m.dec_err = (int)meta_uint(&p);
  3338. w->m.dec_ms = meta_uint(&p);
  3339. }
  3340. if (w->m.error) {
  3341. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3342. return -1;
  3343. }
  3344. w->ready = 1;
  3345. return 0;
  3346. }
  3347. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3348. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3349. unsigned int errcap)
  3350. {
  3351. static char done[24];
  3352. char *p;
  3353. int rn, mseq;
  3354. fetch_tty_drain();
  3355. if (!w->busy)
  3356. return -1;
  3357. if (w->ready)
  3358. return 1;
  3359. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3360. (int)(sizeof(done) - 1));
  3361. if (rn > 0) {
  3362. done[rn] = '\0';
  3363. p = done;
  3364. mseq = (int)meta_uint(&p);
  3365. if (mseq == (int)w->seq) {
  3366. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3367. fetch_worker_stop(w);
  3368. return -1;
  3369. }
  3370. return 1;
  3371. }
  3372. }
  3373. if (!u_alive((unsigned int)w->pid)) {
  3374. w->pid = -1;
  3375. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3376. w->retried = 1;
  3377. return 0;
  3378. }
  3379. s_copy(err, "network helper stopped", errcap);
  3380. fetch_worker_stop(w);
  3381. return -1;
  3382. }
  3383. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3384. s_copy(err, "network request timed out", errcap);
  3385. fetch_worker_stop(w);
  3386. return -1;
  3387. }
  3388. return 0;
  3389. }
  3390. /* Copy the completed body, inflating it if the server ignored our identity
  3391. * request. Mirrors the old fetch_remote body path. */
  3392. static int fetch_worker_read_body(struct fetch_worker *w,
  3393. unsigned char *plain,
  3394. unsigned int plaincap,
  3395. unsigned char *comp,
  3396. unsigned int compcap,
  3397. int *truncated, char *err,
  3398. unsigned int errcap)
  3399. {
  3400. int rv, zr, was_trunc;
  3401. if (contains_ci(w->m.encoding, "gzip") ||
  3402. contains_ci(w->m.encoding, "deflate")) {
  3403. unsigned int comp_len = 0, plen = 0;
  3404. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3405. (int)compcap);
  3406. if (rv < 0) {
  3407. s_copy(err, "empty response", errcap);
  3408. return -1;
  3409. }
  3410. comp_len = (unsigned int)rv;
  3411. if (comp_len < w->m.len) {
  3412. s_copy(err, "compressed response is too large", errcap);
  3413. return -1;
  3414. }
  3415. if (contains_ci(w->m.encoding, "deflate"))
  3416. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3417. &plen, 0, &was_trunc);
  3418. else
  3419. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3420. &plen, 1, &was_trunc);
  3421. if (zr != 0) {
  3422. s_copy(err, "compressed response is corrupt", errcap);
  3423. return -1;
  3424. }
  3425. *truncated = w->m.trunc || was_trunc;
  3426. return (int)plen;
  3427. }
  3428. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3429. if (rv < 0) {
  3430. s_copy(err, "empty response", errcap);
  3431. return -1;
  3432. }
  3433. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3434. return rv;
  3435. }
  3436. static void fetch_worker_release(struct fetch_worker *w)
  3437. {
  3438. u_syscall1(SYS_UNLINK, (int)w->done);
  3439. u_syscall1(SYS_UNLINK, (int)w->meta);
  3440. u_syscall1(SYS_UNLINK, (int)w->body);
  3441. u_syscall1(SYS_UNLINK, (int)w->post);
  3442. u_syscall1(SYS_UNLINK, (int)w->px);
  3443. u_syscall1(SYS_UNLINK, (int)w->req);
  3444. w->busy = 0;
  3445. w->ready = 0;
  3446. w->image_job = 0;
  3447. w->dec_w = 0;
  3448. w->dec_h = 0;
  3449. w->dec_retried = 0;
  3450. }
  3451. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3452. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3453. unsigned int errcap)
  3454. {
  3455. for (;;) {
  3456. int rv;
  3457. if (!fetch_wait_passive)
  3458. worker_wait_ui();
  3459. if (cancel_fetch || pending_action) {
  3460. fetch_workers_cancel_busy();
  3461. return FETCH_ABORT;
  3462. }
  3463. rv = fetch_worker_poll(w, err, errcap);
  3464. if (rv != 0)
  3465. return rv == 1 ? 0 : -1;
  3466. u_sleep_ms(10);
  3467. }
  3468. }
  3469. static int fetch_remote(const char *url, unsigned int cap,
  3470. const char *post, unsigned int post_len,
  3471. unsigned char *plain, unsigned int plaincap,
  3472. unsigned char *comp, unsigned int compcap,
  3473. struct fetch_meta *m, int *truncated,
  3474. char *err, unsigned int errcap)
  3475. {
  3476. struct fetch_worker *w = fetch_worker_alloc();
  3477. int rv;
  3478. fetch_last_error = 0;
  3479. if (!w) {
  3480. s_copy(err, "network busy", errcap);
  3481. return -1;
  3482. }
  3483. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3484. err, errcap) != 0) {
  3485. fetch_worker_release(w);
  3486. return -1;
  3487. }
  3488. rv = fetch_worker_wait(w, err, errcap);
  3489. if (rv == FETCH_ABORT) {
  3490. fetch_worker_release(w);
  3491. return FETCH_ABORT;
  3492. }
  3493. if (rv != 0) {
  3494. fetch_last_error = w->m.error;
  3495. fetch_worker_release(w);
  3496. return -1;
  3497. }
  3498. *m = w->m;
  3499. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3500. truncated, err, errcap);
  3501. fetch_worker_release(w);
  3502. if (rv >= 0 && (cancel_fetch || pending_action))
  3503. return FETCH_ABORT;
  3504. return rv;
  3505. }
  3506. static int fetch_worker_status(const struct fetch_worker *w)
  3507. {
  3508. return w->m.status;
  3509. }
  3510. /* fetch()/XHR through a helper: one request, the status and body come back
  3511. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3512. static int js_worker_http(const char *method, const char *url,
  3513. const char *ctype, const char *body,
  3514. unsigned int body_len, struct js_http_resp *r,
  3515. char *err, int errcap)
  3516. {
  3517. struct fetch_worker *w = fetch_worker_alloc();
  3518. unsigned char *plain;
  3519. int rv, tr = 0;
  3520. if (!w) {
  3521. s_copy(err, "network busy", (unsigned int)errcap);
  3522. return -1;
  3523. }
  3524. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3525. body_len, 0, 0, 0, 0, err,
  3526. (unsigned int)errcap) != 0) {
  3527. fetch_worker_release(w);
  3528. return -1;
  3529. }
  3530. fetch_wait_passive++;
  3531. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3532. fetch_wait_passive--;
  3533. if (rv != 0) {
  3534. if (rv == FETCH_ABORT)
  3535. s_copy(err, "page is navigating", (unsigned int)errcap);
  3536. fetch_worker_release(w);
  3537. return -1;
  3538. }
  3539. r->status = w->m.status;
  3540. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3541. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3542. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3543. if (!plain) {
  3544. fetch_worker_release(w);
  3545. s_copy(err, "out of memory", (unsigned int)errcap);
  3546. return -1;
  3547. }
  3548. if (w->m.len == 0) {
  3549. rv = 0; /* 204, an empty 200: no body file */
  3550. } else {
  3551. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3552. image_io_buf, BR_PAGE_COMP_MAX,
  3553. &tr, err, (unsigned int)errcap);
  3554. }
  3555. fetch_worker_release(w);
  3556. if (rv < 0) {
  3557. free(plain);
  3558. return -1;
  3559. }
  3560. plain[rv] = '\0';
  3561. r->body = (char *)plain;
  3562. r->len = (unsigned int)rv;
  3563. return 0;
  3564. }
  3565. /* ---- HTTP / file fetch ---- */
  3566. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3567. unsigned int *outlen, int *is_local, char *ctype,
  3568. unsigned int ctcap, char *final, unsigned int finalcap,
  3569. char *err, unsigned int errcap, int *truncated,
  3570. const char *post, unsigned int post_len)
  3571. {
  3572. unsigned char *buf;
  3573. unsigned int len;
  3574. int tr = 0;
  3575. int rv;
  3576. *out = 0;
  3577. *outlen = 0;
  3578. *truncated = 0;
  3579. if (final && finalcap)
  3580. final[0] = '\0';
  3581. if (ctype && ctcap)
  3582. ctype[0] = '\0';
  3583. if (url[0] == '/') {
  3584. char pathbuf[BR_URL_MAX];
  3585. const char *open_url = url;
  3586. unsigned int i = 0;
  3587. /* A local form GET keeps ?query in the address bar but the
  3588. * file lookup uses the path alone, like a real browser. */
  3589. while (url[i] && url[i] != '?' && url[i] != '#')
  3590. i++;
  3591. if (url[i]) {
  3592. s_copy(pathbuf, url, i + 1);
  3593. open_url = pathbuf;
  3594. }
  3595. buf = (unsigned char *)malloc(cap);
  3596. if (!buf) {
  3597. s_copy(err, "out of memory", errcap);
  3598. return -1;
  3599. }
  3600. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3601. if (rv < 0) {
  3602. free(buf);
  3603. s_copy(err, "file not found", errcap);
  3604. return -1;
  3605. }
  3606. *out = buf;
  3607. *outlen = (unsigned int)rv;
  3608. *is_local = 1;
  3609. if (ctype)
  3610. s_copy(ctype, "text/html", ctcap);
  3611. if (final)
  3612. s_copy(final, url, finalcap);
  3613. if ((unsigned int)rv == cap)
  3614. *truncated = 1;
  3615. return 0;
  3616. }
  3617. buf = (unsigned char *)malloc(cap);
  3618. if (!buf) {
  3619. s_copy(err, "out of memory", errcap);
  3620. return -1;
  3621. }
  3622. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3623. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3624. if (rv == FETCH_ABORT) {
  3625. free(buf);
  3626. return FETCH_ABORT;
  3627. }
  3628. if (rv < 0) {
  3629. free(buf);
  3630. return -1;
  3631. }
  3632. len = (unsigned int)rv;
  3633. if (len == 0) {
  3634. free(buf);
  3635. s_copy(err, "empty response", errcap);
  3636. return -1;
  3637. }
  3638. if (ctype)
  3639. s_copy(ctype, fetch_meta.ctype, ctcap);
  3640. if (final && fetch_meta.final[0])
  3641. s_copy(final, fetch_meta.final, finalcap);
  3642. *is_local = 0;
  3643. *out = buf;
  3644. *outlen = len;
  3645. *truncated = tr;
  3646. return 0;
  3647. }
  3648. static unsigned int css_cache_hash(const char *s);
  3649. /* Remote fonts are cached under /share for the current boot like the
  3650. * stylesheets, as the raw response (a WOFF stays compressed). */
  3651. static int font_cache_count;
  3652. static void font_cache_path(const char *url, char *out, unsigned int cap)
  3653. {
  3654. unsigned int n = 0;
  3655. s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
  3656. s_append_dec(out, &n, css_cache_hash(url), cap);
  3657. }
  3658. static void font_cache_init(void)
  3659. {
  3660. struct sys_dirent d;
  3661. int i;
  3662. font_cache_count = 0;
  3663. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3664. (int)&d) == 1; i++)
  3665. if (starts_with(d.name, FONT_CACHE_PREFIX))
  3666. font_cache_count++;
  3667. }
  3668. /* Read one font file (local path, boot cache or network) into a fresh
  3669. * malloc'ed buffer. Returns its length, or -1. */
  3670. static int font_fetch(const char *abs, unsigned char **out)
  3671. {
  3672. unsigned char *buf;
  3673. char path[96];
  3674. int rv;
  3675. *out = 0;
  3676. buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
  3677. if (!buf)
  3678. return -1;
  3679. if (abs[0] == '/') {
  3680. struct sys_stat st;
  3681. /* FAT reads may write past the length: the 512 bytes of
  3682. * slack above cover the final partial sector. */
  3683. if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
  3684. st.size > UFONT_MAX_FILE) {
  3685. free(buf);
  3686. return -1;
  3687. }
  3688. rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
  3689. (int)st.size);
  3690. if (rv != (int)st.size) {
  3691. free(buf);
  3692. return -1;
  3693. }
  3694. *out = buf;
  3695. return rv;
  3696. }
  3697. if (!is_http(abs)) {
  3698. free(buf);
  3699. return -1;
  3700. }
  3701. font_cache_path(abs, path, sizeof(path));
  3702. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
  3703. (int)UFONT_MAX_FILE);
  3704. if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
  3705. *out = buf;
  3706. return rv;
  3707. }
  3708. {
  3709. char err[64];
  3710. int tr = 0;
  3711. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3712. UFONT_MAX_FILE, image_io_buf,
  3713. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
  3714. sizeof(err));
  3715. /* An error page is not a font: never parse or cache it. */
  3716. if (rv > 0 && !tr && fetch_meta.status >= 300) {
  3717. snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
  3718. rv = 0;
  3719. }
  3720. if (rv <= 0 || tr) {
  3721. u_puts("[font] failed: ");
  3722. u_puts(abs);
  3723. u_puts(rv <= 0 ? " " : " truncated ");
  3724. u_puts(rv <= 0 ? err : "");
  3725. u_putc('\n');
  3726. free(buf);
  3727. return -1;
  3728. }
  3729. }
  3730. if (font_cache_count < FONT_CACHE_MAX &&
  3731. u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
  3732. font_cache_count++;
  3733. *out = buf;
  3734. return rv;
  3735. }
  3736. /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
  3737. * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
  3738. static struct ufont_face *font_open_entry(int id)
  3739. {
  3740. const char *url = br_font_face_url(id);
  3741. const char *base = br_font_face_base(id);
  3742. char abs[BR_URL_MAX];
  3743. unsigned char *buf, *sfnt;
  3744. unsigned int slen = 0;
  3745. struct ufont_face *f = 0;
  3746. const char *why = 0;
  3747. int n;
  3748. if (!url || !url[0] ||
  3749. resolve_link(base && base[0] ? base : page_url, url, abs,
  3750. sizeof(abs)) != 0)
  3751. return 0;
  3752. n = font_fetch(abs, &buf);
  3753. if (n <= 0)
  3754. return 0;
  3755. sfnt = buf;
  3756. slen = (unsigned int)n;
  3757. if (ufont_is_woff2(buf, slen)) {
  3758. why = "WOFF2 not supported";
  3759. } else if (ufont_is_woff(buf, slen)) {
  3760. sfnt = ufont_woff_decode(buf, slen, &slen);
  3761. if (!sfnt)
  3762. why = "bad WOFF";
  3763. }
  3764. if (!why) {
  3765. f = ufont_face_open_mem(sfnt, slen);
  3766. if (!f)
  3767. why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
  3768. sfnt[2] == 'T' && sfnt[3] == 'O') ?
  3769. "CFF outlines not supported" :
  3770. "not a TrueType font or arena full";
  3771. }
  3772. if (sfnt && sfnt != buf)
  3773. free(sfnt);
  3774. free(buf);
  3775. u_puts(f ? "[font] loaded " : "[font] skipped ");
  3776. u_puts(br_font_face_family(id));
  3777. u_puts(": ");
  3778. u_puts(abs);
  3779. if (why) {
  3780. u_puts(" (");
  3781. u_puts(why);
  3782. u_putc(')');
  3783. }
  3784. u_putc('\n');
  3785. return f;
  3786. }
  3787. /* Distance of a face from the requested weight: 0 inside its range. A
  3788. * bold request prefers heavier faces and a normal one lighter faces, as
  3789. * the CSS font-matching steps do. */
  3790. static unsigned int font_weight_dist(const struct br_font_face_info *fi,
  3791. unsigned int want)
  3792. {
  3793. if (want >= fi->wmin && want <= fi->wmax)
  3794. return 0;
  3795. if (want > fi->wmax)
  3796. return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
  3797. return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
  3798. }
  3799. /* Load the @font-face entries a font-family declaration named: per family
  3800. * the regular face first, then bold, italic and the rest, so a full arena
  3801. * drops the least common variants. Then precompute, for every family and
  3802. * (bold, italic) combination, the loaded face CSS font matching picks;
  3803. * layout reads only that table. A family with no loaded face keeps
  3804. * font_pick 0, and its text uses the built-in set. */
  3805. static void load_font_faces(void)
  3806. {
  3807. int n = br_font_face_count(), pass, id;
  3808. memset(font_faces, 0, sizeof(font_faces));
  3809. memset(font_pick, 0, sizeof(font_pick));
  3810. if (n > BR_MAX_FACES)
  3811. n = BR_MAX_FACES;
  3812. for (pass = 0; pass < 4; pass++) {
  3813. for (id = 1; id <= n; id++) {
  3814. struct br_font_face_info fi;
  3815. int cls;
  3816. if (br_font_face_info(id, &fi) != 0 || !fi.used)
  3817. continue;
  3818. if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
  3819. cls = 0;
  3820. else if (!fi.italic && fi.wmin <= 700 &&
  3821. fi.wmax >= 700)
  3822. cls = 1;
  3823. else if (fi.italic && fi.wmin <= 400 &&
  3824. fi.wmax >= 400)
  3825. cls = 2;
  3826. else
  3827. cls = 3;
  3828. if (cls == pass)
  3829. font_faces[id - 1] = font_open_entry(id);
  3830. }
  3831. }
  3832. for (id = 1; id <= n; id++) {
  3833. struct br_font_face_info fam;
  3834. int combo;
  3835. if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
  3836. continue;
  3837. for (combo = 0; combo < 4; combo++) {
  3838. unsigned int want = (combo & 2) ? 700u : 400u;
  3839. int italic = combo & 1, k, best = 0;
  3840. unsigned int best_score = 0;
  3841. for (k = 1; k <= n; k++) {
  3842. struct br_font_face_info fi;
  3843. unsigned int score;
  3844. if (!font_faces[k - 1] ||
  3845. br_font_face_info(k, &fi) != 0 ||
  3846. fi.family_id != id)
  3847. continue;
  3848. score = font_weight_dist(&fi, want) +
  3849. ((fi.italic != 0) != (italic != 0) ?
  3850. 100000u : 0u);
  3851. if (!best || score < best_score) {
  3852. best = k;
  3853. best_score = score;
  3854. }
  3855. }
  3856. font_pick[id - 1][combo] = (unsigned char)best;
  3857. }
  3858. }
  3859. }
  3860. /* Remote scripts are cached under /share for the current boot, like the
  3861. * stylesheet cache, so reloads and later visits skip the network. */
  3862. static int script_cache_count;
  3863. static unsigned int script_cache_hash(const char *s)
  3864. {
  3865. unsigned int h = 2166136261u;
  3866. while (*s) {
  3867. h ^= (unsigned char)*s++;
  3868. h *= 16777619u;
  3869. }
  3870. return h;
  3871. }
  3872. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3873. {
  3874. unsigned int n = 0;
  3875. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3876. s_append_dec(out, &n, script_cache_hash(url), cap);
  3877. }
  3878. static void script_cache_clear(void)
  3879. {
  3880. struct sys_dirent d;
  3881. char path[96];
  3882. for (;;) {
  3883. int i, found = 0;
  3884. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3885. (int)&d) == 1; i++) {
  3886. unsigned int n = 0;
  3887. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3888. continue;
  3889. s_append(path, &n, "/share/", sizeof(path));
  3890. s_append(path, &n, d.name, sizeof(path));
  3891. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3892. return;
  3893. found = 1;
  3894. break;
  3895. }
  3896. if (!found)
  3897. break;
  3898. }
  3899. script_cache_count = 0;
  3900. }
  3901. static void script_cache_init(void)
  3902. {
  3903. struct sys_dirent d;
  3904. int i, count = 0;
  3905. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3906. (int)&d) == 1; i++)
  3907. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3908. count++;
  3909. if (count >= SCRIPT_CACHE_MAX) {
  3910. script_cache_clear();
  3911. return;
  3912. }
  3913. script_cache_count = count;
  3914. }
  3915. static int script_cache_get(const char *url, unsigned char **out,
  3916. unsigned int *outlen)
  3917. {
  3918. char path[96];
  3919. struct sys_stat st;
  3920. unsigned char *buf;
  3921. int rn;
  3922. script_cache_path(url, path, sizeof(path));
  3923. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3924. st.size >= SCRIPT_CACHE_FILE_MAX)
  3925. return 0;
  3926. buf = (unsigned char *)malloc(st.size + 1);
  3927. if (!buf)
  3928. return 0;
  3929. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3930. if (rn != (int)st.size) {
  3931. free(buf);
  3932. return 0;
  3933. }
  3934. buf[st.size] = '\0';
  3935. *out = buf;
  3936. *outlen = st.size;
  3937. return 1;
  3938. }
  3939. static void script_cache_put(const char *url, const unsigned char *data,
  3940. unsigned int len)
  3941. {
  3942. char path[96];
  3943. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3944. len >= SCRIPT_CACHE_FILE_MAX)
  3945. return;
  3946. script_cache_path(url, path, sizeof(path));
  3947. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3948. (int)len) >= 0)
  3949. script_cache_count++;
  3950. }
  3951. static int script_cache_has(const char *url)
  3952. {
  3953. char path[96];
  3954. struct sys_stat st;
  3955. script_cache_path(url, path, sizeof(path));
  3956. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3957. st.size < SCRIPT_CACHE_FILE_MAX;
  3958. }
  3959. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3960. static int fetch_script_text(const char *url, unsigned char **out,
  3961. unsigned int *outlen, char *err,
  3962. unsigned int errcap)
  3963. {
  3964. unsigned char *buf;
  3965. unsigned int len;
  3966. int local, truncated = 0;
  3967. char ctype[64], final[BR_URL_MAX];
  3968. int rv;
  3969. *out = 0;
  3970. *outlen = 0;
  3971. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3972. return 0;
  3973. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3974. sizeof(ctype), final, sizeof(final), err, errcap,
  3975. &truncated, 0, 0);
  3976. if (rv != 0)
  3977. return rv;
  3978. if (truncated || len >= BR_SCRIPT_MAX) {
  3979. free(buf);
  3980. s_copy(err, "script is too large", errcap);
  3981. return -1;
  3982. }
  3983. buf[len] = '\0';
  3984. if (!local)
  3985. script_cache_put(url, buf, len);
  3986. *out = buf;
  3987. *outlen = len;
  3988. return 0;
  3989. }
  3990. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3991. * the heap, so images must not allocate their file body from it as well. */
  3992. static int fetch_image(const char *url, unsigned int cap,
  3993. unsigned char **out, unsigned int *outlen,
  3994. char *err, unsigned int errcap)
  3995. {
  3996. unsigned int len;
  3997. int tr = 0;
  3998. int rv;
  3999. *out = 0;
  4000. *outlen = 0;
  4001. if (cap > BR_IMG_FILE_MAX)
  4002. cap = BR_IMG_FILE_MAX;
  4003. if (url[0] == '/') {
  4004. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  4005. (int)cap);
  4006. if (rv < 0) {
  4007. s_copy(err, "file not found", errcap);
  4008. return -1;
  4009. }
  4010. *out = image_file_buf;
  4011. *outlen = (unsigned int)rv;
  4012. return 0;
  4013. }
  4014. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  4015. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  4016. if (rv == FETCH_ABORT)
  4017. return FETCH_ABORT;
  4018. if (rv < 0)
  4019. return -1;
  4020. len = (unsigned int)rv;
  4021. if (len == 0) {
  4022. s_copy(err, "empty image", errcap);
  4023. return -1;
  4024. }
  4025. *out = image_file_buf;
  4026. *outlen = len;
  4027. return 0;
  4028. }
  4029. /* Remote stylesheets are immutable enough for the current boot: keep
  4030. * successful responses under /share so a reload, a second visit or a fresh
  4031. * browser launch does not fetch the same five sheets over the network again.
  4032. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  4033. static int css_cache_count;
  4034. static unsigned int css_cache_hash(const char *s)
  4035. {
  4036. unsigned int h = 2166136261u;
  4037. while (*s) {
  4038. h ^= (unsigned char)*s++;
  4039. h *= 16777619u;
  4040. }
  4041. return h;
  4042. }
  4043. static void css_cache_path(const char *url, char *out, unsigned int cap)
  4044. {
  4045. unsigned int n = 0;
  4046. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  4047. s_append_dec(out, &n, css_cache_hash(url), cap);
  4048. }
  4049. static void css_cache_clear(void)
  4050. {
  4051. struct sys_dirent d;
  4052. char path[96];
  4053. for (;;) {
  4054. int i, found = 0;
  4055. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4056. (int)&d) == 1; i++) {
  4057. unsigned int n = 0;
  4058. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  4059. continue;
  4060. s_append(path, &n, "/share/", sizeof(path));
  4061. s_append(path, &n, d.name, sizeof(path));
  4062. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  4063. return;
  4064. found = 1;
  4065. break;
  4066. }
  4067. if (!found)
  4068. break;
  4069. }
  4070. css_cache_count = 0;
  4071. }
  4072. static void css_cache_init(void)
  4073. {
  4074. struct sys_dirent d;
  4075. int i, count = 0;
  4076. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  4077. (int)&d) == 1; i++)
  4078. if (starts_with(d.name, CSS_CACHE_PREFIX))
  4079. count++;
  4080. if (count >= CSS_CACHE_MAX) {
  4081. css_cache_clear();
  4082. return;
  4083. }
  4084. css_cache_count = count;
  4085. }
  4086. static int css_cache_get(const char *url, unsigned char **out,
  4087. unsigned int *outlen)
  4088. {
  4089. char path[96];
  4090. int rn;
  4091. css_cache_path(url, path, sizeof(path));
  4092. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  4093. (int)CSS_CACHE_FILE_MAX);
  4094. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  4095. return 0;
  4096. *out = image_io_buf;
  4097. *outlen = (unsigned int)rn;
  4098. return 1;
  4099. }
  4100. static void css_cache_put(const char *url, const unsigned char *data,
  4101. unsigned int len)
  4102. {
  4103. char path[96];
  4104. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  4105. len >= CSS_CACHE_FILE_MAX)
  4106. return;
  4107. css_cache_path(url, path, sizeof(path));
  4108. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  4109. (int)len) >= 0)
  4110. css_cache_count++;
  4111. }
  4112. static int css_cache_has(const char *url)
  4113. {
  4114. char path[96];
  4115. struct sys_stat st;
  4116. css_cache_path(url, path, sizeof(path));
  4117. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  4118. st.size < CSS_CACHE_FILE_MAX;
  4119. }
  4120. /* Read one stylesheet into the shared static buffer. CSS is parsed
  4121. * immediately, so it does not need the page heap; this leaves the heap for
  4122. * the 2 MB page body, the rules and the scaled image bitmaps. */
  4123. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  4124. char *err, unsigned int errcap)
  4125. {
  4126. unsigned int len;
  4127. int tr = 0;
  4128. int rv;
  4129. *out = 0;
  4130. *outlen = 0;
  4131. if (url[0] == '/') {
  4132. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  4133. (int)BR_CSS_MAX);
  4134. if (rv < 0) {
  4135. s_copy(err, "stylesheet not found", errcap);
  4136. return -1;
  4137. }
  4138. *out = image_io_buf;
  4139. *outlen = (unsigned int)rv;
  4140. return 0;
  4141. }
  4142. if (css_cache_get(url, out, outlen))
  4143. return 0;
  4144. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  4145. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  4146. &fetch_meta, &tr, err, errcap);
  4147. if (rv == FETCH_ABORT)
  4148. return FETCH_ABORT;
  4149. if (rv < 0)
  4150. return -1;
  4151. len = (unsigned int)rv;
  4152. if (len == 0) {
  4153. s_copy(err, "empty stylesheet", errcap);
  4154. return -1;
  4155. }
  4156. *out = image_io_buf;
  4157. *outlen = len;
  4158. css_cache_put(url, image_io_buf, len);
  4159. return 0;
  4160. }
  4161. static void redraw_now(void);
  4162. static char error_page[1024];
  4163. static void show_error(const char *title, const char *detail)
  4164. {
  4165. char *page = error_page;
  4166. unsigned int n = 0;
  4167. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  4168. s_append(page, &n, title, sizeof(error_page));
  4169. s_append(page, &n, "</h2><p>", sizeof(error_page));
  4170. {
  4171. const char *p = detail;
  4172. while (*p && n + 1 < sizeof(error_page)) {
  4173. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  4174. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  4175. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  4176. else page[n++] = *p;
  4177. p++;
  4178. }
  4179. }
  4180. page[n] = '\0';
  4181. s_append(page, &n, "</p><p>", sizeof(error_page));
  4182. s_append(page, &n, page_url, sizeof(error_page));
  4183. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  4184. sizeof(error_page));
  4185. br_parse(&doc, page, n);
  4186. layout_valid = 0;
  4187. preload_active = 0;
  4188. preload_pending = 0;
  4189. preload_wait = 0;
  4190. fetch_workers_cancel_busy();
  4191. s_copy(page_title, title, sizeof(page_title));
  4192. page_loading = 0;
  4193. set_status(title, 1, 0);
  4194. ngui_invalidate(&ui);
  4195. }
  4196. static int decode_direct_image(const unsigned char *data, unsigned int len,
  4197. unsigned int node)
  4198. {
  4199. if (image_count >= BR_MAX_IMAGES)
  4200. return -1;
  4201. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  4202. return -1;
  4203. doc.nodes[node].img_index = 0;
  4204. image_count = 1;
  4205. return 0;
  4206. }
  4207. static int ancestor_is(unsigned int node, unsigned int tag)
  4208. {
  4209. unsigned int p = doc.nodes[node].parent;
  4210. while (p) {
  4211. if (doc.nodes[p].tag == tag)
  4212. return 1;
  4213. p = doc.nodes[p].parent;
  4214. }
  4215. return 0;
  4216. }
  4217. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  4218. * parallel but parsed in document order, so the cascade is unchanged. */
  4219. static int load_stylesheets(void)
  4220. {
  4221. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  4222. static unsigned char remote[BR_MAX_SHEETS];
  4223. struct fetch_worker *slot[BR_MAX_SHEETS];
  4224. unsigned int i, n = 0, next = 0, k;
  4225. char err[64];
  4226. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  4227. struct br_node *nd = &doc.nodes[i];
  4228. const char *rel, *href;
  4229. char url[BR_URL_MAX];
  4230. int dup = 0;
  4231. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  4232. continue;
  4233. rel = br_rel(&doc, i);
  4234. if (!contains_ci(rel, "stylesheet"))
  4235. continue;
  4236. href = br_href(&doc, i);
  4237. if (!href[0])
  4238. continue;
  4239. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  4240. continue;
  4241. for (k = 0; k < n; k++)
  4242. if (s_eq(urls[k], url)) {
  4243. dup = 1;
  4244. break;
  4245. }
  4246. if (dup)
  4247. continue;
  4248. s_copy(urls[n], url, BR_URL_MAX);
  4249. remote[n] = url[0] != '/' && !css_cache_has(url);
  4250. n++;
  4251. }
  4252. for (i = 0; i < BR_MAX_SHEETS; i++)
  4253. slot[i] = 0;
  4254. /* Start as many remote sheets as there are free workers. */
  4255. for (; next < n; next++) {
  4256. struct fetch_worker *w;
  4257. if (!remote[next])
  4258. continue;
  4259. w = fetch_worker_alloc();
  4260. if (!w)
  4261. break;
  4262. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4263. err, sizeof(err)) != 0) {
  4264. fetch_worker_release(w);
  4265. remote[next] = 0;
  4266. continue;
  4267. }
  4268. slot[next] = w;
  4269. }
  4270. for (i = 0; i < n; i++) {
  4271. unsigned char *data = 0;
  4272. unsigned int len = 0;
  4273. int rv;
  4274. if (!remote[i]) {
  4275. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4276. if (rv == FETCH_ABORT) {
  4277. fetch_workers_stop_all();
  4278. return FETCH_ABORT;
  4279. }
  4280. if (rv != 0 || !len)
  4281. continue;
  4282. } else {
  4283. struct fetch_worker *w = slot[i];
  4284. int tr = 0;
  4285. if (!w) {
  4286. w = fetch_worker_alloc();
  4287. if (!w) {
  4288. rv = -1;
  4289. goto css_failed;
  4290. }
  4291. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4292. 0, 0, 0, 0, err,
  4293. sizeof(err)) != 0) {
  4294. fetch_worker_release(w);
  4295. remote[i] = 0;
  4296. if (i == next)
  4297. next++;
  4298. continue;
  4299. }
  4300. slot[i] = w;
  4301. if (i == next)
  4302. next++;
  4303. }
  4304. rv = fetch_worker_wait(w, err, sizeof(err));
  4305. if (rv == FETCH_ABORT) {
  4306. fetch_workers_stop_all();
  4307. return FETCH_ABORT;
  4308. }
  4309. if (rv == 0)
  4310. rv = fetch_worker_read_body(w, image_io_buf,
  4311. BR_CSS_MAX,
  4312. image_io_buf + BR_CSS_MAX,
  4313. BR_CSS_COMP_MAX, &tr,
  4314. err, sizeof(err));
  4315. else
  4316. rv = -1;
  4317. fetch_worker_release(w);
  4318. slot[i] = 0;
  4319. /* Refill the worker window before parsing this sheet. */
  4320. for (; next < n; next++) {
  4321. struct fetch_worker *nw;
  4322. if (!remote[next])
  4323. continue;
  4324. nw = fetch_worker_alloc();
  4325. if (!nw)
  4326. break;
  4327. if (fetch_worker_submit(nw, urls[next],
  4328. BR_CSS_MAX, 0, 0, 0, 0,
  4329. err, sizeof(err)) != 0) {
  4330. fetch_worker_release(nw);
  4331. remote[next] = 0;
  4332. continue;
  4333. }
  4334. slot[next] = nw;
  4335. }
  4336. css_failed:
  4337. if (rv <= 0) {
  4338. /* One synchronous retry: a dropped sheet leaves the
  4339. * whole page unstyled (seen intermittently on
  4340. * arstechnica's CDN). */
  4341. u_puts("[css] retry ");
  4342. u_puts(urls[i]);
  4343. u_puts(": ");
  4344. u_puts(err[0] ? err : "no worker/empty body");
  4345. u_putc('\n');
  4346. err[0] = '\0';
  4347. rv = fetch_css(urls[i], &data, &len, err,
  4348. sizeof(err));
  4349. if (rv == FETCH_ABORT) {
  4350. fetch_workers_stop_all();
  4351. return FETCH_ABORT;
  4352. }
  4353. if (rv != 0 || !len) {
  4354. u_puts("[css] failed: ");
  4355. u_puts(err);
  4356. u_putc('\n');
  4357. continue;
  4358. }
  4359. } else {
  4360. len = (unsigned int)rv;
  4361. data = image_io_buf;
  4362. css_cache_put(urls[i], data, len);
  4363. }
  4364. }
  4365. if (len) {
  4366. br_set_font_base(urls[i]);
  4367. br_parse_css_text(&doc, (const char *)data, len);
  4368. }
  4369. }
  4370. br_set_font_base(page_url);
  4371. br_parse_inline_css(&doc);
  4372. load_font_faces();
  4373. br_reset_styles(&doc);
  4374. layout_valid = 0;
  4375. return 0;
  4376. }
  4377. static void preload_begin(void)
  4378. {
  4379. preload_active = 1;
  4380. preload_pending = 0;
  4381. preload_wait = 1;
  4382. preload_max_jobs = FETCH_WORKERS;
  4383. preload_node = 0;
  4384. preload_loaded = 0;
  4385. preload_scroll = 0;
  4386. img_stat_start = u_ticks_ms();
  4387. img_stat_wall = 0;
  4388. img_stat_net = img_stat_open = img_stat_first = 0;
  4389. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4390. img_stat_paint = img_stat_reflow = 0;
  4391. img_stat_bytes = 0;
  4392. img_stat_n = 0;
  4393. img_stat_log_len = 0;
  4394. if (img_stat_log[0])
  4395. img_stat_log[0] = '\0';
  4396. img_repaint_ms = 0;
  4397. img_repaint_pending = 0;
  4398. }
  4399. /* Styles are computed top-down during layout, but images inside a hidden
  4400. * menu/carousel are never visited and keep img_top == 0. Without this check
  4401. * the preloader walks the DOM in node order and spends the whole image
  4402. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4403. static struct br_style base_style(void);
  4404. static int node_hidden(unsigned int node)
  4405. {
  4406. unsigned int path[32], n = 0, p = node, i;
  4407. struct br_style st, parent;
  4408. while (p && n < sizeof(path) / sizeof(path[0])) {
  4409. path[n++] = p;
  4410. p = doc.nodes[p].parent;
  4411. }
  4412. /* Node 0 is the <html> element when the page starts with one: it
  4413. * is an ancestor too. Styles are cached per node, so the chain
  4414. * must start from the same base as style_for_node(); seeding it
  4415. * with a zeroed style left <body> cached with black text and no
  4416. * line-height once an image job ran (docs.cloudron.io). */
  4417. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4418. doc.nodes[0].type == BR_NODE_ELEM &&
  4419. doc.nodes[0].tag == BR_TAG_HTML &&
  4420. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4421. path[n++] = 0;
  4422. parent = base_style();
  4423. for (i = n; i > 0; i--) {
  4424. br_style_for(&doc, path[i - 1], &parent, &st);
  4425. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4426. st.opacity_hidden)
  4427. return 1;
  4428. parent = st;
  4429. }
  4430. return 0;
  4431. }
  4432. static struct br_style base_style(void);
  4433. static int style_width_px(const struct br_style *st, int base);
  4434. static int style_height_px(const struct br_style *st, int base);
  4435. static void style_for_node(unsigned int node, struct br_style *out)
  4436. {
  4437. unsigned int p = doc.nodes[node].parent;
  4438. struct br_style parent;
  4439. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4440. * starts with one (see root_style()), but also the parent field of a
  4441. * detached subtree root. */
  4442. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4443. doc.nodes[0].tag == BR_TAG_HTML &&
  4444. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4445. style_for_node(p, &parent);
  4446. br_style_for(&doc, node, &parent, out);
  4447. } else {
  4448. parent = base_style();
  4449. br_style_for(&doc, node, &parent, out);
  4450. }
  4451. }
  4452. /* ---- parallel image preloading ---- *
  4453. *
  4454. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4455. * preload_step() only starts jobs and harvests completed ones; the browser
  4456. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4457. */
  4458. static int preload_active_jobs(void)
  4459. {
  4460. int i, n = 0;
  4461. for (i = 0; i < FETCH_WORKERS; i++)
  4462. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4463. n++;
  4464. return n;
  4465. }
  4466. static void preload_job_error(struct fetch_worker *w)
  4467. {
  4468. if (w->node < doc.nnode) {
  4469. if (w->bg)
  4470. doc.nodes[w->node].bg_img_index = -2;
  4471. else
  4472. doc.nodes[w->node].img_index = -2;
  4473. image_repaint();
  4474. }
  4475. }
  4476. /* Is the image's box anywhere near the visible page? A decode below the
  4477. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4478. * so it does not need a repaint. top/h come from the last layout; treat an
  4479. * unknown box as visible to stay safe. */
  4480. static int image_preload_visible(unsigned int node, int bg)
  4481. {
  4482. int top, h, scroll;
  4483. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4484. return 1;
  4485. if (bg) {
  4486. top = (int)block_top[node];
  4487. h = (int)block_h[node];
  4488. } else {
  4489. top = (int)img_top[node];
  4490. h = (int)img_h[node];
  4491. }
  4492. if (!top && !h)
  4493. return 1;
  4494. scroll = (int)page_scroll.offset;
  4495. if (top > scroll + page_rect.h + 160)
  4496. return 0;
  4497. if (top + h + 160 < scroll)
  4498. return 0;
  4499. return 1;
  4500. }
  4501. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4502. * decode_image_data applies one scale to both axes so the aspect ratio is
  4503. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4504. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4505. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4506. {
  4507. struct br_style st;
  4508. struct br_node *nd;
  4509. unsigned int p;
  4510. int cw, w = 0, h = 0;
  4511. *out_w = *out_h = 0;
  4512. if (node >= doc.nnode)
  4513. return;
  4514. nd = &doc.nodes[node];
  4515. style_for_node(node, &st);
  4516. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4517. p = doc.nodes[node].parent;
  4518. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4519. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4520. cw = layout_boxes[p].w;
  4521. if (st.width_kind)
  4522. w = style_width_px(&st, cw);
  4523. else if (nd->width_attr)
  4524. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4525. (int)nd->width_attr;
  4526. if (st.height_kind)
  4527. h = style_height_px(&st, cw);
  4528. else if (nd->height_attr)
  4529. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4530. (int)nd->height_attr;
  4531. if (st.max_width_kind) {
  4532. int mw = st.max_width_kind == 3 ?
  4533. cw * st.max_width_calc_pct / 100 +
  4534. st.max_width_calc_px :
  4535. st.max_width_kind == 2 ?
  4536. cw * (int)st.max_width / 100 :
  4537. (int)st.max_width;
  4538. if (mw > 0 && (w == 0 || w > mw))
  4539. w = mw;
  4540. }
  4541. if (st.max_height_kind) {
  4542. int mh = st.max_height_kind == 3 ?
  4543. cw * st.max_height_calc_pct / 100 +
  4544. st.max_height_calc_px :
  4545. st.max_height_kind == 2 ?
  4546. cw * (int)st.max_height / 100 :
  4547. (int)st.max_height;
  4548. if (mh > 0 && (h == 0 || h > mh))
  4549. h = mh;
  4550. }
  4551. if (w > BR_IMG_LAYOUT_W)
  4552. w = BR_IMG_LAYOUT_W;
  4553. if (h > 4096)
  4554. h = 4096;
  4555. if (w < 0)
  4556. w = 0;
  4557. if (h < 0)
  4558. h = 0;
  4559. *out_w = w;
  4560. *out_h = h;
  4561. }
  4562. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4563. {
  4564. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4565. * same source reuses it (heise repeats one comment icon 85 times).
  4566. * Backgrounds are scaled to their box and are not shared. */
  4567. images[image_count].url_hash =
  4568. !bg && url ? script_cache_hash(url) | 1u : 0;
  4569. if (bg)
  4570. doc.nodes[node].bg_img_index = (short)image_count;
  4571. else
  4572. doc.nodes[node].img_index = (short)image_count;
  4573. image_count++;
  4574. preload_loaded++;
  4575. /* A background bitmap never changes its box, so keep the (expensive)
  4576. * measured layout and only repaint the pixels. */
  4577. if (bg)
  4578. page_cache_valid = 0;
  4579. else
  4580. layout_valid = 0;
  4581. if (image_preload_visible(node, bg))
  4582. image_repaint();
  4583. }
  4584. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4585. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4586. * on the UI thread instead of a decode. */
  4587. static int preload_store_helper(unsigned int node, int bg,
  4588. unsigned char *px, unsigned int pxlen,
  4589. unsigned int dw, unsigned int dh,
  4590. int alpha, unsigned int nw, unsigned int nh,
  4591. const char *url)
  4592. {
  4593. struct br_image *bi;
  4594. unsigned int npx;
  4595. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4596. dw > 4096 || dh > 4096) {
  4597. free(px);
  4598. return -1;
  4599. }
  4600. npx = dw * dh;
  4601. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4602. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4603. free(px);
  4604. return -1;
  4605. }
  4606. bi = &images[image_count];
  4607. bi->img.format = 0;
  4608. bi->img.w = dw;
  4609. bi->img.h = dh;
  4610. bi->img.px = (unsigned short *)px;
  4611. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4612. bi->img.flags = 0;
  4613. bi->native_w = nw ? (int)nw : (int)dw;
  4614. bi->native_h = nh ? (int)nh : (int)dh;
  4615. bi->state = 1;
  4616. image_pixels += npx;
  4617. preload_accept_image(node, bg, url);
  4618. return 0;
  4619. }
  4620. static void preload_decode(unsigned int node, int bg,
  4621. const unsigned char *data, unsigned int len,
  4622. const char *url)
  4623. {
  4624. int fit_w = 0, fit_h = 0;
  4625. if (image_count >= BR_MAX_IMAGES) {
  4626. if (bg)
  4627. doc.nodes[node].bg_img_index = -2;
  4628. else
  4629. doc.nodes[node].img_index = -2;
  4630. return;
  4631. }
  4632. if (!bg)
  4633. image_fit_size(node, &fit_w, &fit_h);
  4634. if (decode_image_data(data, len, &images[image_count],
  4635. bg && node < BR_MAX_NODES &&
  4636. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4637. bg && node < BR_MAX_NODES &&
  4638. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4639. fit_w, fit_h) == 0) {
  4640. preload_accept_image(node, bg, url);
  4641. } else {
  4642. if (bg)
  4643. doc.nodes[node].bg_img_index = -2;
  4644. else
  4645. doc.nodes[node].img_index = -2;
  4646. layout_valid = 0;
  4647. }
  4648. if (image_preload_visible(node, bg))
  4649. image_repaint();
  4650. }
  4651. /* ---- data: URLs ----
  4652. *
  4653. * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
  4654. * (the caller frees them). The payload is percent-decoded, then base64-
  4655. * decoded when the header says so. Infima's menu chevron and many icon
  4656. * fonts' fallbacks are inline SVGs written this way. */
  4657. static int b64_val(int c)
  4658. {
  4659. if (c >= 'A' && c <= 'Z') return c - 'A';
  4660. if (c >= 'a' && c <= 'z') return c - 'a' + 26;
  4661. if (c >= '0' && c <= '9') return c - '0' + 52;
  4662. if (c == '+' || c == '-') return 62;
  4663. if (c == '/' || c == '_') return 63;
  4664. return -1;
  4665. }
  4666. static int hex_val(int c)
  4667. {
  4668. if (c >= '0' && c <= '9') return c - '0';
  4669. c |= 32;
  4670. if (c >= 'a' && c <= 'f') return c - 'a' + 10;
  4671. return -1;
  4672. }
  4673. static int data_url_decode(const char *url, unsigned char **out,
  4674. unsigned int *out_len)
  4675. {
  4676. const char *comma, *p;
  4677. unsigned int n = 0, len, i;
  4678. unsigned char *buf;
  4679. int base64 = 0;
  4680. *out = 0;
  4681. *out_len = 0;
  4682. if (!starts_with(url, "data:"))
  4683. return -1;
  4684. comma = url + 5;
  4685. while (*comma && *comma != ',')
  4686. comma++;
  4687. if (!*comma)
  4688. return -1;
  4689. for (p = url + 5; p + 7 <= comma; p++)
  4690. if (!strncmp(p, ";base64", 7))
  4691. base64 = 1;
  4692. len = s_len(comma + 1);
  4693. buf = (unsigned char *)malloc(len + 1);
  4694. if (!buf)
  4695. return -1;
  4696. for (i = 0, p = comma + 1; i < len; i++) {
  4697. int c = (unsigned char)p[i];
  4698. if (c == '%' && i + 2 < len &&
  4699. hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
  4700. c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
  4701. i += 2;
  4702. }
  4703. buf[n++] = (unsigned char)c;
  4704. }
  4705. if (base64) {
  4706. unsigned int acc = 0, o = 0;
  4707. int bits = 0;
  4708. for (i = 0; i < n; i++) {
  4709. int v = b64_val(buf[i]);
  4710. if (v < 0)
  4711. continue; /* padding, whitespace */
  4712. acc = (acc << 6) | (unsigned int)v;
  4713. bits += 6;
  4714. if (bits >= 8) {
  4715. bits -= 8;
  4716. buf[o++] = (unsigned char)(acc >> bits);
  4717. }
  4718. }
  4719. n = o;
  4720. }
  4721. buf[n] = 0;
  4722. *out = buf;
  4723. *out_len = n;
  4724. return 0;
  4725. }
  4726. static unsigned int data_img_key(const char *url, int w, int h)
  4727. {
  4728. return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
  4729. ((unsigned int)h * 40503u)) | 1u;
  4730. }
  4731. /* The image index of a data: URL decoded for a w x h box (an SVG is
  4732. * rasterized at that size), decoding it on first use; -1 on failure.
  4733. * Decoded bitmaps are found again through url_hash, which is distinct
  4734. * from the <img> sharing hash because it mixes in the size. */
  4735. static int data_url_image(const char *url, int w, int h)
  4736. {
  4737. unsigned int key, len;
  4738. unsigned char *data;
  4739. int i;
  4740. if (!starts_with(url, "data:") || w <= 0 || h <= 0)
  4741. return -1;
  4742. key = data_img_key(url, w, h);
  4743. for (i = 0; i < image_count; i++)
  4744. if (images[i].state == 1 && images[i].url_hash == key)
  4745. return i;
  4746. for (i = 0; i < data_img_nfail; i++)
  4747. if (data_img_fail[i] == key)
  4748. return -1;
  4749. if (image_count < BR_MAX_IMAGES &&
  4750. data_url_decode(url, &data, &len) == 0) {
  4751. int r = decode_image_data(data, len, &images[image_count],
  4752. w, h, w, h);
  4753. free(data);
  4754. if (r == 0) {
  4755. images[image_count].url_hash = key;
  4756. return image_count++;
  4757. }
  4758. }
  4759. if (data_img_nfail < DATA_IMG_FAIL_MAX)
  4760. data_img_fail[data_img_nfail++] = key;
  4761. return -1;
  4762. }
  4763. /* A local file image bypasses the helpers: count its decode so a page opened
  4764. * from /share or /data still produces the same timing breakdown. */
  4765. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4766. {
  4767. img_stat_n++;
  4768. img_stat_bytes += bytes;
  4769. img_stat_io += io_ms;
  4770. if (image_count > before) {
  4771. struct br_image *bi = &images[image_count - 1];
  4772. img_stat_dec += img_last_dec_ms;
  4773. img_stat_scale += img_last_scale_ms;
  4774. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4775. unsigned int n = img_stat_log_len;
  4776. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4777. s_append_dec(img_stat_log, &n, bytes,
  4778. sizeof(img_stat_log));
  4779. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4780. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4781. sizeof(img_stat_log));
  4782. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4783. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4784. sizeof(img_stat_log));
  4785. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4786. s_append_dec(img_stat_log, &n,
  4787. (unsigned int)bi->native_w,
  4788. sizeof(img_stat_log));
  4789. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4790. s_append_dec(img_stat_log, &n,
  4791. (unsigned int)bi->native_h,
  4792. sizeof(img_stat_log));
  4793. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4794. s_append_dec(img_stat_log, &n, bi->img.w,
  4795. sizeof(img_stat_log));
  4796. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4797. s_append_dec(img_stat_log, &n, bi->img.h,
  4798. sizeof(img_stat_log));
  4799. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4800. s_append_dec(img_stat_log, &n,
  4801. bi->img.alpha ? 1u : 0u,
  4802. sizeof(img_stat_log));
  4803. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4804. img_stat_log_len = n;
  4805. }
  4806. }
  4807. }
  4808. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4809. static int preload_finish_worker(struct fetch_worker *w)
  4810. {
  4811. char err[64];
  4812. int rv, tr = 0;
  4813. unsigned int t0, io_ms;
  4814. int before;
  4815. int used_px = 0;
  4816. rv = fetch_worker_poll(w, err, sizeof(err));
  4817. if (rv < 0) {
  4818. /* A helper from an older pack does not understand the image
  4819. * decode request; retry once without it and decode in-process. */
  4820. if (w->image_job && w->dec_w && !w->dec_retried &&
  4821. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4822. 0, 0, 0, 0, w->node, w->bg,
  4823. 0, 0, err, sizeof(err)) == 0) {
  4824. w->image_job = 1;
  4825. w->dec_retried = 1;
  4826. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4827. return 0;
  4828. }
  4829. preload_job_error(w);
  4830. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4831. unsigned int n = img_stat_log_len;
  4832. char u[48];
  4833. s_copy(u, w->url, sizeof(u));
  4834. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4835. s_append(img_stat_log, &n, " error\n",
  4836. sizeof(img_stat_log));
  4837. img_stat_log_len = n;
  4838. }
  4839. img_stat_n++;
  4840. fetch_worker_release(w);
  4841. return 1;
  4842. }
  4843. if (rv == 0)
  4844. return 0;
  4845. t0 = u_ticks_ms();
  4846. rv = -1;
  4847. before = image_count;
  4848. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4849. w->m.px_len <= 8u * 1024u * 1024u) {
  4850. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4851. int pr = -1;
  4852. if (px)
  4853. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4854. (int)w->m.px_len);
  4855. if (pr == (int)w->m.px_len) {
  4856. if (preload_store_helper(w->node, w->bg, px,
  4857. w->m.px_len, w->m.dw,
  4858. w->m.dh, (int)w->m.alpha,
  4859. w->m.nw, w->m.nh,
  4860. w->url) == 0) {
  4861. rv = (int)w->m.len;
  4862. img_last_dec_ms = w->m.dec_ms;
  4863. img_last_scale_ms = 0;
  4864. used_px = 1;
  4865. } else {
  4866. px = 0; /* the helper freed it */
  4867. }
  4868. }
  4869. if (px && !(pr == (int)w->m.px_len))
  4870. free(px);
  4871. }
  4872. io_ms = u_ticks_ms() - t0;
  4873. if (rv < 0) {
  4874. t0 = u_ticks_ms();
  4875. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4876. image_comp_buf, BR_IMG_FILE_MAX,
  4877. &tr, err, sizeof(err));
  4878. io_ms += u_ticks_ms() - t0;
  4879. before = image_count;
  4880. if (rv >= 0)
  4881. preload_decode(w->node, w->bg, image_file_buf,
  4882. (unsigned int)rv, w->url);
  4883. else
  4884. preload_job_error(w);
  4885. }
  4886. img_stat_n++;
  4887. img_stat_net += w->m.total_ms;
  4888. img_stat_open += w->m.open_ms;
  4889. img_stat_first += w->m.first_ms;
  4890. img_stat_io += io_ms;
  4891. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4892. img_stat_dec += w->m.dec_ms;
  4893. if (rv >= 0 && !used_px) {
  4894. img_stat_dec += img_last_dec_ms;
  4895. img_stat_scale += img_last_scale_ms;
  4896. }
  4897. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4898. unsigned int n = img_stat_log_len;
  4899. char u[48];
  4900. s_copy(u, w->url, sizeof(u));
  4901. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4902. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4903. s_append_dec(img_stat_log, &n,
  4904. rv > 0 ? (unsigned int)rv : 0,
  4905. sizeof(img_stat_log));
  4906. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4907. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4908. sizeof(img_stat_log));
  4909. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4910. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4911. sizeof(img_stat_log));
  4912. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4913. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4914. sizeof(img_stat_log));
  4915. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4916. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4917. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4918. s_append_dec(img_stat_log, &n,
  4919. rv >= 0 ? img_last_dec_ms : 0,
  4920. sizeof(img_stat_log));
  4921. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4922. s_append_dec(img_stat_log, &n,
  4923. rv >= 0 ? img_last_scale_ms : 0,
  4924. sizeof(img_stat_log));
  4925. if (image_count > before) {
  4926. struct br_image *bi = &images[image_count - 1];
  4927. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4928. s_append_dec(img_stat_log, &n,
  4929. (unsigned int)bi->native_w,
  4930. sizeof(img_stat_log));
  4931. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4932. s_append_dec(img_stat_log, &n,
  4933. (unsigned int)bi->native_h,
  4934. sizeof(img_stat_log));
  4935. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4936. s_append_dec(img_stat_log, &n, bi->img.w,
  4937. sizeof(img_stat_log));
  4938. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4939. s_append_dec(img_stat_log, &n, bi->img.h,
  4940. sizeof(img_stat_log));
  4941. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4942. s_append_dec(img_stat_log, &n,
  4943. bi->img.alpha ? 1u : 0u,
  4944. sizeof(img_stat_log));
  4945. }
  4946. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4947. img_stat_log_len = n;
  4948. }
  4949. fetch_worker_release(w);
  4950. return 1;
  4951. }
  4952. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4953. * the number of jobs started. */
  4954. static int preload_fill_jobs(void)
  4955. {
  4956. int started = 0;
  4957. char err[64];
  4958. while (preload_active && preload_node < doc.nnode) {
  4959. unsigned int i = preload_node;
  4960. struct br_node *nd = &doc.nodes[i];
  4961. const char *src;
  4962. char url[BR_URL_MAX];
  4963. struct fetch_worker *w;
  4964. if (preload_active_jobs() >= preload_max_jobs)
  4965. break;
  4966. if (nd->type != BR_NODE_ELEM) {
  4967. preload_node++;
  4968. continue;
  4969. }
  4970. if (nd->tag != BR_TAG_IMG) {
  4971. if (nd->bg_img_index == -1) {
  4972. struct br_style bs;
  4973. style_for_node(i, &bs);
  4974. if (bs.display != BR_DISPLAY_NONE &&
  4975. !bs.vis_hidden && bs.bg_image) {
  4976. const char *bsrc =
  4977. br_bg_image_url(bs.bg_image - 1);
  4978. /* Lazy like <img>: a background box
  4979. * below the viewport (or not laid
  4980. * out yet) waits for the next scan. */
  4981. if (bsrc[0] &&
  4982. (!layout_boxes[i].valid ||
  4983. block_top[i] >
  4984. (unsigned int)(page_scroll.offset +
  4985. page_rect.h + 160))) {
  4986. preload_pending = 1;
  4987. preload_node++;
  4988. continue;
  4989. }
  4990. if (starts_with(bsrc, "data:")) {
  4991. /* Inline image: decode now,
  4992. * no fetch helper. */
  4993. unsigned char *data;
  4994. unsigned int len;
  4995. preload_node = i + 1;
  4996. if (data_url_decode(bsrc, &data,
  4997. &len) == 0) {
  4998. preload_decode(i, 1, data,
  4999. len, 0);
  5000. free(data);
  5001. } else {
  5002. nd->bg_img_index = -2;
  5003. }
  5004. continue;
  5005. }
  5006. if (bsrc[0] &&
  5007. resolve_link(page_url, bsrc, url,
  5008. sizeof(url)) == 0) {
  5009. if (image_count +
  5010. preload_active_jobs() >=
  5011. BR_MAX_IMAGES) {
  5012. preload_node = doc.nnode;
  5013. break;
  5014. }
  5015. if (url[0] == '/') {
  5016. unsigned char *data = 0;
  5017. unsigned int len = 0;
  5018. unsigned int t0;
  5019. int before;
  5020. preload_node = i + 1;
  5021. before = image_count;
  5022. t0 = u_ticks_ms();
  5023. if (fetch_image(url,
  5024. BR_IMG_FILE_MAX,
  5025. &data, &len,
  5026. err,
  5027. sizeof(err)) == 0) {
  5028. preload_decode(i, 1, data, len, 0);
  5029. img_stat_local(before, len,
  5030. u_ticks_ms() - t0);
  5031. } else {
  5032. nd->bg_img_index = -2;
  5033. }
  5034. continue;
  5035. }
  5036. w = fetch_worker_alloc();
  5037. if (!w)
  5038. return started;
  5039. preload_node = i + 1;
  5040. if (fetch_worker_submit(w, url,
  5041. BR_IMG_FILE_MAX,
  5042. 0, 0, i, 1,
  5043. err,
  5044. sizeof(err)) != 0) {
  5045. nd->bg_img_index = -2;
  5046. fetch_worker_release(w);
  5047. continue;
  5048. }
  5049. w->image_job = 1;
  5050. w->deadline = u_ticks_ms() +
  5051. BR_IMG_JOB_TIMEOUT_MS;
  5052. /* in flight: rescans skip it */
  5053. nd->bg_img_index = -3;
  5054. started++;
  5055. continue;
  5056. }
  5057. }
  5058. nd->bg_img_index = -2;
  5059. }
  5060. preload_node++;
  5061. continue;
  5062. }
  5063. if (nd->img_index != -1) {
  5064. preload_node++;
  5065. continue;
  5066. }
  5067. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  5068. preload_node++;
  5069. continue;
  5070. }
  5071. src = br_src(&doc, i);
  5072. if (starts_with(src, "data:")) {
  5073. unsigned char *data;
  5074. unsigned int len;
  5075. preload_node = i + 1;
  5076. if (data_url_decode(src, &data, &len) == 0) {
  5077. preload_decode(i, 0, data, len, 0);
  5078. free(data);
  5079. } else {
  5080. doc.nodes[i].img_index = -2;
  5081. }
  5082. continue;
  5083. }
  5084. if (!src[0]) {
  5085. preload_node++;
  5086. continue;
  5087. }
  5088. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  5089. preload_node++;
  5090. continue;
  5091. }
  5092. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  5093. preload_node = doc.nnode;
  5094. break;
  5095. }
  5096. /* Do not stop at the first below-fold image: DOM order is
  5097. * not visual order, and a footer/ad image early in the DOM
  5098. * used to hide every later article image from the loader. */
  5099. if (img_top[i] >
  5100. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  5101. preload_pending = 1;
  5102. preload_node++;
  5103. continue;
  5104. }
  5105. {
  5106. unsigned int uh = script_cache_hash(url) | 1u;
  5107. int k;
  5108. for (k = 0; k < image_count; k++)
  5109. if (images[k].state == 1 &&
  5110. images[k].url_hash == uh)
  5111. break;
  5112. if (k < image_count) {
  5113. nd->img_index = (short)k;
  5114. layout_valid = 0;
  5115. preload_node = i + 1;
  5116. image_repaint();
  5117. continue;
  5118. }
  5119. }
  5120. if (url[0] == '/') {
  5121. unsigned char *data = 0;
  5122. unsigned int len = 0;
  5123. unsigned int t0;
  5124. int before;
  5125. preload_node = i + 1;
  5126. before = image_count;
  5127. t0 = u_ticks_ms();
  5128. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  5129. err, sizeof(err)) == 0) {
  5130. preload_decode(i, 0, data, len, url);
  5131. img_stat_local(before, len, u_ticks_ms() - t0);
  5132. } else {
  5133. nd->img_index = -2;
  5134. }
  5135. continue;
  5136. }
  5137. w = fetch_worker_alloc();
  5138. if (!w)
  5139. return started;
  5140. preload_node = i + 1;
  5141. {
  5142. char msg[64];
  5143. unsigned int n = 0;
  5144. s_append(msg, &n, "Loading images ", sizeof(msg));
  5145. s_append_dec(msg, &n,
  5146. (unsigned int)preload_loaded + 1,
  5147. sizeof(msg));
  5148. s_append(msg, &n, "...", sizeof(msg));
  5149. set_status_quiet(msg);
  5150. image_repaint();
  5151. }
  5152. {
  5153. int fit_w = 0, fit_h = 0;
  5154. image_fit_size(i, &fit_w, &fit_h);
  5155. if (!fit_w)
  5156. fit_w = BR_IMG_LAYOUT_W;
  5157. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  5158. i, 0,
  5159. (unsigned int)fit_w,
  5160. (unsigned int)fit_h,
  5161. err, sizeof(err)) != 0) {
  5162. nd->img_index = -2;
  5163. fetch_worker_release(w);
  5164. continue;
  5165. }
  5166. }
  5167. w->image_job = 1;
  5168. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  5169. nd->img_index = -3; /* in flight: rescans skip it */
  5170. started++;
  5171. }
  5172. return started;
  5173. }
  5174. /* Report where the image batch spent its time: status bar for the headline,
  5175. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  5176. static void img_stats_report(void)
  5177. {
  5178. char msg[80];
  5179. static char out[BR_IMG_STAT_LOG + 512];
  5180. unsigned int n = 0, o = 0;
  5181. if (!img_stat_n)
  5182. return;
  5183. img_stat_wall = img_stat_start ?
  5184. u_ticks_ms() - img_stat_start : 1;
  5185. if (!img_stat_wall)
  5186. img_stat_wall = 1;
  5187. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  5188. s_append(msg, &n, "img ", sizeof(msg));
  5189. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  5190. s_append(msg, &n, " ", sizeof(msg));
  5191. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  5192. s_append(msg, &n, "ms net ", sizeof(msg));
  5193. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  5194. s_append(msg, &n, " dec ", sizeof(msg));
  5195. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  5196. s_append(msg, &n, " sc ", sizeof(msg));
  5197. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  5198. s_append(msg, &n, " paint ", sizeof(msg));
  5199. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  5200. /* Keep the page's phase breakdown and append the image summary when
  5201. * it fits; never hide a JS error or a truncation notice. */
  5202. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  5203. unsigned int plen = s_len(post_status_text);
  5204. if (!plen) {
  5205. s_copy(post_status_text, msg, sizeof(post_status_text));
  5206. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  5207. unsigned int pn = plen;
  5208. s_append(post_status_text, &pn, " | ",
  5209. sizeof(post_status_text));
  5210. s_append(post_status_text, &pn, msg,
  5211. sizeof(post_status_text));
  5212. } else {
  5213. s_copy(post_status_text, msg, sizeof(post_status_text));
  5214. }
  5215. post_status_ttl = 12000;
  5216. }
  5217. s_append(out, &o, "browser image stats\n", sizeof(out));
  5218. s_append(out, &o, "n=", sizeof(out));
  5219. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  5220. s_append(out, &o, " wall=", sizeof(out));
  5221. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  5222. s_append(out, &o, " net=", sizeof(out));
  5223. s_append_dec(out, &o, img_stat_net, sizeof(out));
  5224. s_append(out, &o, " open=", sizeof(out));
  5225. s_append_dec(out, &o, img_stat_open, sizeof(out));
  5226. s_append(out, &o, " first=", sizeof(out));
  5227. s_append_dec(out, &o, img_stat_first, sizeof(out));
  5228. s_append(out, &o, " io=", sizeof(out));
  5229. s_append_dec(out, &o, img_stat_io, sizeof(out));
  5230. s_append(out, &o, " dec=", sizeof(out));
  5231. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  5232. s_append(out, &o, " scale=", sizeof(out));
  5233. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  5234. s_append(out, &o, " paint=", sizeof(out));
  5235. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  5236. s_append(out, &o, " reflow=", sizeof(out));
  5237. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  5238. s_append(out, &o, " bytes=", sizeof(out));
  5239. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  5240. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  5241. sizeof(out));
  5242. s_append(out, &o, img_stat_log, sizeof(out));
  5243. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  5244. (int)s_len(out));
  5245. }
  5246. static void preload_step(void)
  5247. {
  5248. int i;
  5249. unsigned int t0;
  5250. if (!preload_active)
  5251. return;
  5252. if (cancel_fetch || pending_action) {
  5253. preload_active = 0;
  5254. preload_pending = 0;
  5255. fetch_workers_cancel_busy();
  5256. return;
  5257. }
  5258. preload_fill_jobs();
  5259. /* Decode completed images in a short batch instead of one per pass.
  5260. * A pass used to decode one image and then sleep 10 ms, so a page of
  5261. * small icons trickled in at the decode rate. The budget keeps a
  5262. * single huge JPEG from monopolising the UI while small images
  5263. * finish together. */
  5264. t0 = u_ticks_ms();
  5265. for (i = 0; i < FETCH_WORKERS; i++) {
  5266. if (!fetch_workers[i].busy)
  5267. continue;
  5268. if (preload_finish_worker(&fetch_workers[i]) &&
  5269. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  5270. break;
  5271. }
  5272. if (preload_active && preload_node >= doc.nnode &&
  5273. preload_active_jobs() == 0) {
  5274. preload_active = 0;
  5275. if (preload_pending)
  5276. preload_scroll = page_scroll.offset;
  5277. else
  5278. preload_pending = 0;
  5279. /* Keep the now idle helpers and their connections; a later
  5280. * navigation reuses them. They exit after ten idle seconds,
  5281. * and losing window focus stops them at once. */
  5282. if (img_repaint_pending) {
  5283. img_repaint_pending = 0;
  5284. ngui_invalidate(&ui);
  5285. }
  5286. img_stats_report();
  5287. set_status(post_status_text, post_status_error, post_status_ttl);
  5288. ngui_invalidate(&ui);
  5289. }
  5290. }
  5291. /* Set by navigate() when it turned a typed bare host into https://; the next
  5292. * load_page() consumes it and may retry over http. */
  5293. static int nav_https_upgraded;
  5294. /* Errors that mean "https is not served here" rather than "the site is
  5295. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  5296. static int https_fallback_error(int e)
  5297. {
  5298. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  5299. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  5300. e == UHTTP_ERR_RESET;
  5301. }
  5302. static void history_push(const char *url)
  5303. {
  5304. if (!url || !url[0])
  5305. return;
  5306. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  5307. s_eq(history[hist_pos], url))
  5308. return;
  5309. if (hist_len > 0 && hist_pos + 1 < hist_len)
  5310. hist_len = hist_pos + 1;
  5311. if (hist_len < BR_HISTORY) {
  5312. s_copy(history[hist_len], url, BR_URL_MAX);
  5313. hist_pos = hist_len;
  5314. hist_len++;
  5315. } else {
  5316. int i;
  5317. for (i = 1; i < BR_HISTORY; i++)
  5318. s_copy(history[i - 1], history[i], BR_URL_MAX);
  5319. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  5320. hist_pos = BR_HISTORY - 1;
  5321. }
  5322. }
  5323. static void load_page(const char *url, int local, int push)
  5324. {
  5325. unsigned char *body = 0;
  5326. unsigned int len = 0;
  5327. int truncated = 0;
  5328. struct img_info image_info;
  5329. char ctype[64];
  5330. char final[BR_URL_MAX];
  5331. char err[80];
  5332. const char *detail = 0;
  5333. const char *post = pending_post_is ? pending_post : 0;
  5334. unsigned int post_len = pending_post_len;
  5335. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  5336. /* Phase timings for the status line: where a slow load spends it. */
  5337. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  5338. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  5339. int upgraded = nav_https_upgraded;
  5340. int retried = 0;
  5341. int rv;
  5342. nav_https_upgraded = 0;
  5343. final[0] = '\0';
  5344. pending_post_len = 0;
  5345. pending_post_is = 0;
  5346. cancel_fetch = 0;
  5347. preload_active = 0;
  5348. preload_pending = 0;
  5349. fetch_workers_prepare_nav(url);
  5350. js_browser_stop();
  5351. js_last_status[0] = '\0';
  5352. js_last_error = 0;
  5353. heap_clear();
  5354. image_reset();
  5355. form_reset_state();
  5356. layout_valid = 0;
  5357. page_scroll.offset = 0;
  5358. page_scroll.dragging = 0;
  5359. page_title[0] = '\0';
  5360. page_loading = 1;
  5361. page_is_local = local;
  5362. s_copy(page_url, url, sizeof(page_url));
  5363. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5364. url_in.len = s_len(url_in.text);
  5365. url_in.cursor = url_in.len;
  5366. url_in.scroll = 0;
  5367. ngui_set_focus(&ui, 0);
  5368. if (final[0])
  5369. final[0] = '\0';
  5370. if (push)
  5371. history_push(url);
  5372. set_status("Loading...", 0, 0);
  5373. ngui_invalidate(&ui);
  5374. /* heap_clear() detaches the fonts, so attach them again before the
  5375. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  5376. if (heap_start() != 0) {
  5377. show_error("Out of memory", "Cannot allocate the page buffer");
  5378. return;
  5379. }
  5380. br_parse_plain(&doc, "", 0); /* blank while loading */
  5381. ngui_font_attach(&ui);
  5382. redraw_now();
  5383. browser_rules_alloc();
  5384. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5385. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5386. &truncated, post, post_len);
  5387. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5388. fetch_last_error == UHTTP_ERR_DNS) {
  5389. /* A busy previous page can leave the receiver ring full just
  5390. * long enough to lose a DNS reply. Tear the old helpers down
  5391. * and try once more before giving up. */
  5392. retried = 1;
  5393. fetch_workers_stop_all();
  5394. u_sleep_ms(500);
  5395. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5396. sizeof(ctype), final, sizeof(final), err,
  5397. sizeof(err), &truncated, post, post_len);
  5398. }
  5399. if (rv == FETCH_ABORT)
  5400. return;
  5401. t_fetch = u_ticks_ms() - t_start;
  5402. /* Capture the page timing before CSS/script/image fetches overwrite the
  5403. * shared fetch_meta block. */
  5404. if (rv == 0 && !local) {
  5405. page_open_ms = fetch_meta.open_ms;
  5406. page_first_ms = fetch_meta.first_ms;
  5407. page_total_ms = fetch_meta.total_ms;
  5408. }
  5409. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5410. https_fallback_error(fetch_last_error)) {
  5411. char http_url[BR_URL_MAX];
  5412. unsigned int n = 0;
  5413. s_append(http_url, &n, "http://", sizeof(http_url));
  5414. s_append(http_url, &n, url + 8, sizeof(http_url));
  5415. /* Replace the https entry instead of adding a second one. */
  5416. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5417. s_eq(history[hist_pos], url))
  5418. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5419. load_page(http_url, 0, 0);
  5420. return;
  5421. }
  5422. if (rv != 0) {
  5423. detail = err;
  5424. show_error("Cannot load this page", detail);
  5425. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5426. url_in.len = s_len(url_in.text);
  5427. url_in.cursor = url_in.len;
  5428. url_in.scroll = 0;
  5429. return;
  5430. }
  5431. if (!local)
  5432. origin_cache_learn(url, final[0] ? final : url);
  5433. page_is_local = local;
  5434. if (final[0]) {
  5435. s_copy(page_url, final, sizeof(page_url));
  5436. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5437. url_in.len = s_len(url_in.text);
  5438. url_in.cursor = url_in.len;
  5439. url_in.scroll = 0;
  5440. }
  5441. if (contains_ci(ctype, "text/plain")) {
  5442. br_parse_plain(&doc, (const char *)body, len);
  5443. } else if (contains_ci(ctype, "image/") ||
  5444. (!contains_ci(ctype, "text/html") &&
  5445. img_sniff(body, len, &image_info) == 0)) {
  5446. unsigned int node = br_parse_image_doc(&doc, page_url);
  5447. if (node)
  5448. decode_direct_image(body, len, node);
  5449. s_copy(page_title, "Image", sizeof(page_title));
  5450. } else {
  5451. br_set_viewport(ui.w);
  5452. t_mark = u_ticks_ms();
  5453. br_parse(&doc, (const char *)body, len);
  5454. t_parse = u_ticks_ms() - t_mark;
  5455. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5456. sizeof(page_title));
  5457. t_mark = u_ticks_ms();
  5458. if (load_stylesheets() == FETCH_ABORT)
  5459. return;
  5460. t_css = u_ticks_ms() - t_mark;
  5461. if (pending_action)
  5462. return;
  5463. }
  5464. preload_begin();
  5465. page_loading = 0;
  5466. hist_visit(page_url, page_title);
  5467. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5468. url_in.len = s_len(url_in.text);
  5469. url_in.cursor = url_in.len;
  5470. url_in.scroll = 0;
  5471. ngui_set_focus(&ui, 0);
  5472. /* Paint the parsed page before fetching/running scripts. A slow
  5473. * remote <script src> then does not hide the page behind the loading
  5474. * screen; the fetch helper pumps this UI while it waits. */
  5475. set_status("Loading scripts...", 0, 0);
  5476. t_mark = u_ticks_ms();
  5477. redraw_now();
  5478. t_paint = u_ticks_ms() - t_mark;
  5479. /* Start one image download before the scripts. The other workers
  5480. * fetch the external script bodies in parallel, and the remaining
  5481. * images start as soon as the script phase ends. */
  5482. preload_max_jobs = 1;
  5483. preload_fill_jobs();
  5484. preload_wait = 0;
  5485. t_mark = u_ticks_ms();
  5486. run_page_scripts();
  5487. t_js = u_ticks_ms() - t_mark;
  5488. preload_max_jobs = FETCH_WORKERS;
  5489. if (pending_action)
  5490. return;
  5491. post_status_text[0] = '\0';
  5492. post_status_error = 0;
  5493. post_status_ttl = 0;
  5494. if (js_last_status[0]) {
  5495. s_copy(post_status_text, js_last_status,
  5496. sizeof(post_status_text));
  5497. post_status_error = js_last_error;
  5498. post_status_ttl = 8000;
  5499. } else if (truncated) {
  5500. s_copy(post_status_text, "Page truncated at the buffer limit",
  5501. sizeof(post_status_text));
  5502. post_status_ttl = 6000;
  5503. } else if (doc.truncated) {
  5504. s_copy(post_status_text, "Page truncated by the parser",
  5505. sizeof(post_status_text));
  5506. post_status_ttl = 6000;
  5507. } else if (page_total_ms) {
  5508. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5509. * paint 220, js 1750" -- the phases of this load. */
  5510. unsigned int n = 0;
  5511. static const char *const names[] = {
  5512. ", parse ", ", css ", ", paint ", ", js "
  5513. };
  5514. unsigned int vals[4];
  5515. int k;
  5516. vals[0] = t_parse;
  5517. vals[1] = t_css;
  5518. vals[2] = t_paint;
  5519. vals[3] = t_js;
  5520. (void)page_first_ms;
  5521. if (starts_with(page_url, "https://"))
  5522. s_append(post_status_text, &n,
  5523. "HTTPS (not verified), ",
  5524. sizeof(post_status_text));
  5525. s_append(post_status_text, &n, "Loaded in ",
  5526. sizeof(post_status_text));
  5527. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5528. sizeof(post_status_text));
  5529. s_append(post_status_text, &n, " ms: page ",
  5530. sizeof(post_status_text));
  5531. s_append_dec(post_status_text, &n, t_fetch,
  5532. sizeof(post_status_text));
  5533. s_append(post_status_text, &n, " (headers ",
  5534. sizeof(post_status_text));
  5535. s_append_dec(post_status_text, &n, page_open_ms,
  5536. sizeof(post_status_text));
  5537. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5538. for (k = 0; k < 4; k++) {
  5539. s_append(post_status_text, &n, names[k],
  5540. sizeof(post_status_text));
  5541. s_append_dec(post_status_text, &n, vals[k],
  5542. sizeof(post_status_text));
  5543. }
  5544. post_status_ttl = 12000;
  5545. } else if (starts_with(page_url, "https://")) {
  5546. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5547. sizeof(post_status_text));
  5548. post_status_ttl = 6000;
  5549. }
  5550. set_status(post_status_text, post_status_error, post_status_ttl);
  5551. ngui_invalidate(&ui);
  5552. }
  5553. static void load_home(int push)
  5554. {
  5555. pending_post_len = 0;
  5556. pending_post_is = 0;
  5557. cancel_fetch = 0;
  5558. preload_active = 0;
  5559. preload_pending = 0;
  5560. js_browser_stop();
  5561. js_last_status[0] = '\0';
  5562. js_last_error = 0;
  5563. heap_clear();
  5564. image_reset();
  5565. form_reset_state();
  5566. layout_valid = 0;
  5567. page_scroll.offset = 0;
  5568. page_scroll.dragging = 0;
  5569. page_loading = 1;
  5570. page_is_local = 0;
  5571. s_copy(page_url, "about:home", sizeof(page_url));
  5572. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5573. url_in.len = s_len(url_in.text);
  5574. url_in.cursor = url_in.len;
  5575. url_in.scroll = 0;
  5576. ngui_set_focus(&ui, 0);
  5577. if (push)
  5578. history_push(page_url);
  5579. ngui_invalidate(&ui);
  5580. /* See load_page(): reattach the fonts before the first redraw. */
  5581. if (heap_start() != 0) {
  5582. show_error("Out of memory", "Cannot allocate the browser heap");
  5583. return;
  5584. }
  5585. br_parse_plain(&doc, "", 0);
  5586. ngui_font_attach(&ui);
  5587. redraw_now();
  5588. browser_rules_alloc();
  5589. {
  5590. static const char home[] =
  5591. "<html><head><title>NebOS Browser</title><style>"
  5592. "body { margin: 10px; color: #e4e6f0; }"
  5593. "h1 { color: #7fb0ff; }"
  5594. ".box { background-color: #262b3a; margin: 12px; "
  5595. "padding: 10px; }"
  5596. "a { color: #7fb0ff; }"
  5597. "pre { background-color: #32384a; }"
  5598. "</style></head><body>"
  5599. "<h1>NebOS Browser</h1>"
  5600. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5601. "shared HTTP client and the image library.</p>"
  5602. "<div class=\"box\"><b>Try:</b>"
  5603. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5604. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5605. "<li><a href=\"/floppy1/JS.HTM\">/"
  5606. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5607. "<li><a href=\"http://10.0.2.2:8000/\">"
  5608. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5609. "<li><a href=\"https://example.com/\">"
  5610. "https://example.com/</a> (TLS, not verified)</li>"
  5611. "</ul></div>"
  5612. "<p>Type a URL in the bar above. Esc closes the "
  5613. "window, Ctrl+L focuses the address bar.</p>"
  5614. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5615. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5616. "</body></html>";
  5617. br_set_viewport(ui.w);
  5618. br_parse(&doc, home, sizeof(home) - 1);
  5619. br_parse_inline_css(&doc);
  5620. br_reset_styles(&doc);
  5621. s_copy(page_title, doc.title, sizeof(page_title));
  5622. }
  5623. post_status_text[0] = '\0';
  5624. post_status_error = 0;
  5625. post_status_ttl = 0;
  5626. page_loading = 0;
  5627. set_status("", 0, 0);
  5628. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5629. url_in.len = s_len(url_in.text);
  5630. url_in.cursor = url_in.len;
  5631. url_in.scroll = 0;
  5632. ngui_set_focus(&ui, 0);
  5633. ngui_invalidate(&ui);
  5634. }
  5635. /* Extensions the browser opens from the local filesystem. A dotted input
  5636. * with one of these still resolves relative to the cwd. */
  5637. static int local_file_ext(const char *s)
  5638. {
  5639. static const char *const exts[] = {
  5640. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5641. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5642. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5643. "cfg", "conf", 0
  5644. };
  5645. unsigned int i = 0, start = 0, len = 0, e;
  5646. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5647. s[i] != '#') {
  5648. if (s[i] == '.') {
  5649. start = i + 1;
  5650. len = 0;
  5651. } else if (start) {
  5652. len++;
  5653. }
  5654. i++;
  5655. }
  5656. if (!len)
  5657. return 0;
  5658. for (e = 0; exts[e]; e++) {
  5659. const char *x = exts[e];
  5660. unsigned int xn = s_len(x), k;
  5661. if (xn != len)
  5662. continue;
  5663. for (k = 0; k < len; k++) {
  5664. char a = s[start + k];
  5665. if (a >= 'A' && a <= 'Z')
  5666. a = (char)(a - 'A' + 'a');
  5667. if (a != x[k])
  5668. break;
  5669. }
  5670. if (k == len)
  5671. return 1;
  5672. }
  5673. return 0;
  5674. }
  5675. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5676. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5677. * Enter to the first network request. */
  5678. static int looks_like_host(const char *s)
  5679. {
  5680. unsigned int i = 0;
  5681. int dot = 0;
  5682. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5683. s[i] != ':') {
  5684. char c = s[i];
  5685. if (c == '.') {
  5686. dot = 1;
  5687. } else if (!((c >= 'a' && c <= 'z') ||
  5688. (c >= 'A' && c <= 'Z') ||
  5689. (c >= '0' && c <= '9') ||
  5690. c == '-' || c == '_')) {
  5691. return 0;
  5692. }
  5693. i++;
  5694. }
  5695. return dot && i > 0 && !local_file_ext(s);
  5696. }
  5697. static void load_remote(const char *url, int push)
  5698. {
  5699. char canon[BR_URL_MAX];
  5700. s_copy(canon, url, sizeof(canon));
  5701. origin_cache_apply(canon, sizeof(canon));
  5702. load_page(canon, 0, push);
  5703. }
  5704. static void navigate(const char *input, int push)
  5705. {
  5706. char target[BR_URL_MAX];
  5707. char *t;
  5708. if (!input)
  5709. return;
  5710. s_copy(target, input, sizeof(target));
  5711. t = trim(target);
  5712. if (!t[0])
  5713. return;
  5714. if (s_eq(t, "about:home")) {
  5715. load_home(push);
  5716. return;
  5717. }
  5718. if (starts_with(t, "file://")) {
  5719. make_abs_local(t + 7, target, sizeof(target));
  5720. load_page(target, 1, push);
  5721. return;
  5722. }
  5723. if (is_http(t)) {
  5724. load_remote(t, push);
  5725. return;
  5726. }
  5727. if (t[0] == '/') {
  5728. make_abs_local(t, target, sizeof(target));
  5729. load_page(target, 1, push);
  5730. return;
  5731. }
  5732. if (!looks_like_host(t)) {
  5733. struct sys_stat st;
  5734. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5735. make_abs_local(t, target, sizeof(target));
  5736. load_page(target, 1, push);
  5737. return;
  5738. }
  5739. }
  5740. {
  5741. /* A typed bare host tries https first: nearly every site
  5742. * redirects http -> https anyway, and that hop costs a whole
  5743. * extra connection. load_page() falls back to http when the
  5744. * https connection itself fails. */
  5745. char with_scheme[BR_URL_MAX];
  5746. unsigned int n = 0;
  5747. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5748. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5749. nav_https_upgraded = 1;
  5750. load_remote(with_scheme, push);
  5751. }
  5752. }
  5753. /* ---- layout ---- */
  5754. static struct ufont_face *face_for(unsigned int family, int bold, int italic)
  5755. {
  5756. unsigned int id;
  5757. if (!family || family > BR_MAX_FACES)
  5758. return 0;
  5759. id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
  5760. return id ? font_faces[id - 1] : 0;
  5761. }
  5762. static struct ufont_face *style_face(const struct br_style *st)
  5763. {
  5764. return st ? face_for(st->font_face, st->bold, st->italic) : 0;
  5765. }
  5766. static struct ufont_face *run_face(const struct lay_run *r)
  5767. {
  5768. return face_for(r->font_face, r->bold, r->italic);
  5769. }
  5770. static unsigned int face_text_width(struct ngui *gui,
  5771. const struct br_style *st,
  5772. const char *s, unsigned int n)
  5773. {
  5774. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5775. st->bold, st->italic, st->mono);
  5776. }
  5777. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5778. {
  5779. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5780. st->mono);
  5781. }
  5782. static unsigned int run_text_width(struct ngui *gui,
  5783. const struct lay_run *r,
  5784. const char *s, unsigned int n)
  5785. {
  5786. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5787. r->bold, r->italic, r->mono);
  5788. }
  5789. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5790. {
  5791. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5792. r->mono);
  5793. }
  5794. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5795. {
  5796. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5797. }
  5798. static struct br_style base_style(void)
  5799. {
  5800. struct br_style s = { 0 };
  5801. s.color = ui.theme.text;
  5802. s.bg = ui.theme.bg;
  5803. s.has_bg = 0;
  5804. for (int i = 0; i < 4; i++) {
  5805. s.border_c[i] = 0;
  5806. s.border_w[i] = 0;
  5807. s.border_s[i] = BR_BORDER_SOLID;
  5808. }
  5809. s.font_px = 16;
  5810. s.bold = 0;
  5811. s.italic = 0;
  5812. s.mono = 0;
  5813. s.underline = 0;
  5814. s.strike = 0;
  5815. s.overline = 0;
  5816. s.align = BR_ALIGN_LEFT;
  5817. s.display = BR_DISPLAY_BLOCK;
  5818. s.no_bullet = 0;
  5819. s.list_style = BR_LIST_AUTO;
  5820. s.uppercase = 0;
  5821. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5822. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5823. s.width = s.max_width = s.min_width = 0;
  5824. s.height = s.min_height = s.max_height = 0;
  5825. s.box_sizing = 0;
  5826. s.ml_auto = s.mr_auto = 0;
  5827. s.line_h_pct = 0;
  5828. s.line_h_px = 0;
  5829. s.mt = s.mb = s.ml = s.mr = 0;
  5830. s.pt = s.pb = s.pl = s.pr = 0;
  5831. return s;
  5832. }
  5833. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5834. * a minified page that starts `<!doctype html><html ...>` makes it the
  5835. * <html> element itself, and the layout walks only its children, so its
  5836. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5837. * colour and font there) used to be skipped and the theme defaults showed
  5838. * through. Only inherited properties are taken: the root's box (margins,
  5839. * display, background) is not a container style for its children here. */
  5840. static struct br_style root_style(void)
  5841. {
  5842. struct br_style base = base_style(), st;
  5843. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5844. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5845. return base;
  5846. br_style_for(&doc, doc.root, &base, &st);
  5847. base.color = st.color;
  5848. base.font_px = st.font_px;
  5849. base.bold = st.bold;
  5850. base.italic = st.italic;
  5851. base.mono = st.mono;
  5852. base.font_face = st.font_face;
  5853. base.align = st.align;
  5854. base.line_h_pct = st.line_h_pct;
  5855. base.line_h_px = st.line_h_px;
  5856. base.nowrap = st.nowrap;
  5857. base.uppercase = st.uppercase;
  5858. base.cursor = st.cursor;
  5859. base.vis_hidden = st.vis_hidden;
  5860. base.fill_mode = st.fill_mode;
  5861. base.fill = st.fill;
  5862. base.stroke_mode = st.stroke_mode;
  5863. base.stroke = st.stroke;
  5864. base.stroke_w = st.stroke_w;
  5865. base.fill_evenodd = st.fill_evenodd;
  5866. return base;
  5867. }
  5868. /* Resolve a margin/padding raw value. Percentages use the containing
  5869. * block width for all four sides, as CSS specifies. */
  5870. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5871. {
  5872. if (unit == 1)
  5873. return base * v / 10000;
  5874. if (unit == 2)
  5875. return st->font_px * v / 100;
  5876. if (unit == 3)
  5877. return (int)br_root_font_px() * v / 100;
  5878. if (unit == 4)
  5879. return 0;
  5880. return v;
  5881. }
  5882. static int mp_px(const struct br_style *st, int side, int base)
  5883. {
  5884. int raw;
  5885. switch (side) {
  5886. case 0: raw = st->mt; break;
  5887. case 1: raw = st->mr; break;
  5888. case 2: raw = st->mb; break;
  5889. case 3: raw = st->ml; break;
  5890. case 4: raw = st->pt; break;
  5891. case 5: raw = st->pr; break;
  5892. case 6: raw = st->pb; break;
  5893. default: raw = st->pl; break;
  5894. }
  5895. if (st->mp_unit[side] == 5)
  5896. return base * raw / 100 + st->mp_calc_px[side];
  5897. return css_mp_px(st, raw, st->mp_unit[side], base);
  5898. }
  5899. static int style_width_px(const struct br_style *st, int base)
  5900. {
  5901. if (st->width_kind == 1)
  5902. return st->width;
  5903. if (st->width_kind == 2)
  5904. return base * (int)st->width / 100;
  5905. if (st->width_kind == 3)
  5906. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5907. return 0;
  5908. }
  5909. static int style_height_px(const struct br_style *st, int base)
  5910. {
  5911. if (st->height_kind == 1)
  5912. return st->height;
  5913. if (st->height_kind == 2)
  5914. return base * (int)st->height / 100;
  5915. if (st->height_kind == 3)
  5916. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5917. return 0;
  5918. }
  5919. static int css_size(unsigned char kind, int val, int base)
  5920. {
  5921. if (kind == 1)
  5922. return val;
  5923. if (kind == 2)
  5924. return base * val / 100;
  5925. return -1;
  5926. }
  5927. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5928. int thick, int horizontal, unsigned short color,
  5929. unsigned char style)
  5930. {
  5931. int pos;
  5932. if (len <= 0 || thick <= 0)
  5933. return;
  5934. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5935. if (horizontal)
  5936. ngui_fill_rect(ui, (struct ngui_rect){
  5937. x, y, len, thick}, color);
  5938. else
  5939. ngui_fill_rect(ui, (struct ngui_rect){
  5940. x, y, thick, len}, color);
  5941. return;
  5942. }
  5943. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5944. int seg = len - pos;
  5945. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5946. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5947. if (horizontal)
  5948. ngui_fill_rect(ui, (struct ngui_rect){
  5949. x + pos, y, seg, thick}, color);
  5950. else
  5951. ngui_fill_rect(ui, (struct ngui_rect){
  5952. x, y + pos, thick, seg}, color);
  5953. }
  5954. }
  5955. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5956. const struct br_style *st)
  5957. {
  5958. int top = st->border_w[0], right = st->border_w[1];
  5959. int bottom = st->border_w[2], left = st->border_w[3];
  5960. if (r.w <= 0 || r.h <= 0)
  5961. return;
  5962. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5963. int i;
  5964. for (i = 0; i < 4; i++)
  5965. if (st->border_w[i] && !st->border_t[i]) {
  5966. ngui_fill_rect(ui, r, st->border_c[i]);
  5967. break;
  5968. }
  5969. return;
  5970. }
  5971. if (top && !st->border_t[0])
  5972. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5973. st->border_c[0], st->border_s[0]);
  5974. if (bottom && !st->border_t[2])
  5975. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5976. st->border_c[2], st->border_s[2]);
  5977. if (left && !st->border_t[3])
  5978. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5979. left, 0, st->border_c[3], st->border_s[3]);
  5980. if (right && !st->border_t[1])
  5981. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5982. r.h - top - bottom, right, 0,
  5983. st->border_c[1], st->border_s[1]);
  5984. }
  5985. static void transform_origin(const struct br_style *st, int w, int h,
  5986. int *ox, int *oy)
  5987. {
  5988. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5989. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5990. }
  5991. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5992. unsigned int a)
  5993. {
  5994. unsigned int dr, dg, db, sr, sg, sb;
  5995. if (a >= 255)
  5996. return s;
  5997. dr = (d >> 11) & 31;
  5998. dg = (d >> 5) & 63;
  5999. db = d & 31;
  6000. sr = (s >> 11) & 31;
  6001. sg = (s >> 5) & 63;
  6002. sb = s & 31;
  6003. dr = (dr * (255 - a) + sr * a) / 255;
  6004. dg = (dg * (255 - a) + sg * a) / 255;
  6005. db = (db * (255 - a) + sb * a) / 255;
  6006. return (unsigned short)((dr << 11) | (dg << 5) | db);
  6007. }
  6008. /* Paint a solid box through scale()/rotate() around transform-origin. This
  6009. * transforms the element's own background box; text and descendants keep
  6010. * their layout (documented approximation). */
  6011. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  6012. unsigned short color,
  6013. const struct br_style *st)
  6014. {
  6015. double sx = st->scale_x / 100.0;
  6016. double sy = st->scale_y / 100.0;
  6017. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  6018. double c = cos(th), sn = sin(th);
  6019. int ox, oy, minx, miny, maxx, maxy, x, y;
  6020. double ax, ay;
  6021. double px[4], py[4];
  6022. int cx1, cy1, cx2, cy2, i;
  6023. if (sx == 0)
  6024. sx = 0.01;
  6025. if (sy == 0)
  6026. sy = 0.01;
  6027. transform_origin(st, box.w, box.h, &ox, &oy);
  6028. ax = box.x + ox;
  6029. ay = box.y + oy;
  6030. px[0] = -ox; py[0] = -oy;
  6031. px[1] = box.w - ox; py[1] = -oy;
  6032. px[2] = box.w - ox; py[2] = box.h - oy;
  6033. px[3] = -ox; py[3] = box.h - oy;
  6034. minx = miny = 1000000;
  6035. maxx = maxy = -1000000;
  6036. for (i = 0; i < 4; i++) {
  6037. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  6038. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  6039. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6040. if (dx < minx) minx = dx;
  6041. if (dx > maxx) maxx = dx;
  6042. if (dy < miny) miny = dy;
  6043. if (dy > maxy) maxy = dy;
  6044. }
  6045. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6046. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6047. cx2 = page_rect.x + page_rect.w - 12;
  6048. cy2 = page_rect.y + page_rect.h;
  6049. if (cx2 > gui->w) cx2 = gui->w;
  6050. if (cy2 > gui->h) cy2 = gui->h;
  6051. if (minx < cx1) minx = cx1;
  6052. if (miny < cy1) miny = cy1;
  6053. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6054. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6055. for (y = miny; y <= maxy; y++) {
  6056. for (x = minx; x <= maxx; x++) {
  6057. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  6058. double rx = dx * c + dy * sn;
  6059. double ry = -dx * sn + dy * c;
  6060. double bx = rx / sx + ox;
  6061. double by = ry / sy + oy;
  6062. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  6063. gui->px[y * gui->w + x] = color;
  6064. }
  6065. }
  6066. }
  6067. static void draw_image_transformed(struct ngui *gui,
  6068. const struct img_image *im,
  6069. int x, int y, int w, int h,
  6070. int sx100, int sy100, int rot100,
  6071. int origin_x, int origin_y,
  6072. int origin_x_kind, int origin_y_kind)
  6073. {
  6074. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  6075. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  6076. double c = cos(th), sn = sin(th);
  6077. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  6078. double ax, ay;
  6079. double bx[4], by[4];
  6080. int cx1, cy1, cx2, cy2;
  6081. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  6082. return;
  6083. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  6084. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  6085. ax = x + ox;
  6086. ay = y + oy;
  6087. bx[0] = -ox; by[0] = -oy;
  6088. bx[1] = w - ox; by[1] = -oy;
  6089. bx[2] = w - ox; by[2] = h - oy;
  6090. bx[3] = -ox; by[3] = h - oy;
  6091. minx = miny = 1000000;
  6092. maxx = maxy = -1000000;
  6093. for (i = 0; i < 4; i++) {
  6094. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  6095. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  6096. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  6097. if (dx < minx) minx = dx;
  6098. if (dx > maxx) maxx = dx;
  6099. if (dy < miny) miny = dy;
  6100. if (dy > maxy) maxy = dy;
  6101. }
  6102. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  6103. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  6104. cx2 = page_rect.x + page_rect.w - 12;
  6105. cy2 = page_rect.y + page_rect.h;
  6106. if (cx2 > gui->w) cx2 = gui->w;
  6107. if (cy2 > gui->h) cy2 = gui->h;
  6108. if (minx < cx1) minx = cx1;
  6109. if (miny < cy1) miny = cy1;
  6110. if (maxx > cx2 - 1) maxx = cx2 - 1;
  6111. if (maxy > cy2 - 1) maxy = cy2 - 1;
  6112. for (py = miny; py <= maxy; py++) {
  6113. for (px = minx; px <= maxx; px++) {
  6114. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  6115. double rx = dx * c + dy * sn;
  6116. double ry = -dx * sn + dy * c;
  6117. double fx = rx / sx + ox;
  6118. double fy = ry / sy + oy;
  6119. int ix, iy;
  6120. unsigned int si, a;
  6121. unsigned short src;
  6122. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  6123. continue;
  6124. ix = (int)(fx * (double)im->w / w);
  6125. iy = (int)(fy * (double)im->h / h);
  6126. if (ix < 0 || ix >= (int)im->w ||
  6127. iy < 0 || iy >= (int)im->h)
  6128. continue;
  6129. si = (unsigned int)iy * im->w + (unsigned int)ix;
  6130. src = im->px[si];
  6131. a = im->alpha ? im->alpha[si] : 255;
  6132. gui->px[py * gui->w + px] =
  6133. a >= 255 ? src :
  6134. blend_rgb565(gui->px[py * gui->w + px],
  6135. src, a);
  6136. }
  6137. }
  6138. }
  6139. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6140. unsigned int node, const struct br_style *st);
  6141. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  6142. * first and every pixel outside a corner's arc is restored afterwards. */
  6143. #define BG_ROUND_MAX 64
  6144. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  6145. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  6146. unsigned int node, const struct br_style *st,
  6147. int rtl, int rtr, int rbr, int rbl)
  6148. {
  6149. struct ngui *ui = l->ui;
  6150. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  6151. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  6152. if (ui->nclip > 0)
  6153. clip = ui->clip[ui->nclip - 1];
  6154. for (c = 0; c < 4; c++) {
  6155. if (r[c] > BG_ROUND_MAX)
  6156. r[c] = BG_ROUND_MAX;
  6157. if (r[c] > box.w / 2)
  6158. r[c] = box.w / 2;
  6159. if (r[c] > box.h / 2)
  6160. r[c] = box.h / 2;
  6161. }
  6162. for (c = 0; c < 4; c++) {
  6163. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6164. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6165. for (dy = 0; dy < r[c]; dy++)
  6166. for (dx = 0; dx < r[c]; dx++) {
  6167. int px = ox + dx, py = oy + dy;
  6168. if (px >= clip.x && py >= clip.y &&
  6169. px < clip.x + clip.w && py < clip.y + clip.h)
  6170. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  6171. ui->px[py * ui->w + px];
  6172. }
  6173. }
  6174. draw_bg_image(l, box, node, st);
  6175. for (c = 0; c < 4; c++) {
  6176. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  6177. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  6178. /* arc centre, in corner-square coordinates */
  6179. int cx = (c == 1 || c == 2) ? 0 : r[c];
  6180. int cy = (c >= 2) ? 0 : r[c];
  6181. for (dy = 0; dy < r[c]; dy++)
  6182. for (dx = 0; dx < r[c]; dx++) {
  6183. int px = ox + dx, py = oy + dy;
  6184. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  6185. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  6186. continue;
  6187. if (px >= clip.x && py >= clip.y &&
  6188. px < clip.x + clip.w && py < clip.y + clip.h)
  6189. ui->px[py * ui->w + px] =
  6190. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  6191. }
  6192. }
  6193. }
  6194. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  6195. unsigned int node, const struct br_style *st)
  6196. {
  6197. struct br_image *bi;
  6198. struct img_blit b;
  6199. int tw, th, x, y, rep_x, rep_y, posx, posy;
  6200. unsigned int scale = 65536;
  6201. int legacy, tiles = 0, rows = 0;
  6202. int cx1, cy1, cx2, cy2;
  6203. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  6204. return;
  6205. if (doc.nodes[node].bg_img_index < 0 ||
  6206. doc.nodes[node].bg_img_index >= image_count)
  6207. return;
  6208. bi = &images[doc.nodes[node].bg_img_index];
  6209. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  6210. return;
  6211. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  6212. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  6213. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  6214. if (legacy) {
  6215. scale = ((unsigned int)box.w << 16) / bi->img.w;
  6216. tw = box.w;
  6217. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6218. x = box.x;
  6219. y = box.y;
  6220. rep_x = rep_y = 0;
  6221. } else {
  6222. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  6223. unsigned int sx = ((unsigned int)box.w << 16) /
  6224. bi->img.w;
  6225. unsigned int sy = ((unsigned int)box.h << 16) /
  6226. bi->img.h;
  6227. scale = st->bg_size_kind == 3 ?
  6228. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  6229. } else if (st->bg_size_kind == 1 ||
  6230. st->bg_size_kind == 2) {
  6231. int w = st->bg_size_w;
  6232. int h = st->bg_size_h;
  6233. if (st->bg_size_kind == 2) {
  6234. if (w)
  6235. w = box.w * w / 100;
  6236. if (h)
  6237. h = box.h * h / 100;
  6238. }
  6239. if (w)
  6240. scale = ((unsigned int)w << 16) / bi->img.w;
  6241. else if (h)
  6242. scale = ((unsigned int)h << 16) / bi->img.h;
  6243. }
  6244. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  6245. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  6246. if (tw < 1)
  6247. tw = 1;
  6248. if (th < 1)
  6249. th = 1;
  6250. posx = st->bg_pos_x_kind == 1 ?
  6251. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  6252. posy = st->bg_pos_y_kind == 1 ?
  6253. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  6254. x = box.x + posx;
  6255. y = box.y + posy;
  6256. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  6257. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  6258. if (rep_x) {
  6259. int m = (x - box.x) % tw;
  6260. if (m > 0)
  6261. m -= tw;
  6262. x = box.x + m;
  6263. }
  6264. if (rep_y) {
  6265. int m = (y - box.y) % th;
  6266. if (m > 0)
  6267. m -= th;
  6268. y = box.y + m;
  6269. }
  6270. }
  6271. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  6272. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  6273. cx2 = box.x + box.w;
  6274. cy2 = box.y + box.h;
  6275. if (cx2 > page_rect.x + page_rect.w - 12)
  6276. cx2 = page_rect.x + page_rect.w - 12;
  6277. if (cy2 > page_rect.y + page_rect.h)
  6278. cy2 = page_rect.y + page_rect.h;
  6279. if (cx1 >= cx2 || cy1 >= cy2)
  6280. return;
  6281. b.dst = l->ui->px;
  6282. b.dst_w = l->ui->w;
  6283. b.dst_h = l->ui->h;
  6284. b.clip_x = cx1;
  6285. b.clip_y = cy1;
  6286. b.clip_w = cx2 - cx1;
  6287. b.clip_h = cy2 - cy1;
  6288. b.bg = ui.theme.bg;
  6289. b.bg2 = ui.theme.bg;
  6290. b.dst_a = 0;
  6291. {
  6292. struct img_image *src = image_display_get(bi, tw, th);
  6293. int row_x;
  6294. if (!src)
  6295. src = &bi->img;
  6296. b.scale = ((unsigned int)tw << 16) / src->w;
  6297. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  6298. row_x = x;
  6299. for (;;) {
  6300. for (;;) {
  6301. b.x = x;
  6302. b.y = y;
  6303. img_draw(src, &b);
  6304. if (!rep_x || ++tiles > 512)
  6305. break;
  6306. x += tw;
  6307. if (x >= box.x + box.w)
  6308. break;
  6309. }
  6310. if (!rep_y || ++rows > 64)
  6311. break;
  6312. y += th;
  6313. if (y >= box.y + box.h)
  6314. break;
  6315. x = row_x;
  6316. }
  6317. }
  6318. }
  6319. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  6320. int *out_w, int *out_h);
  6321. static void svg_paint_box(struct ngui *ui, unsigned int node,
  6322. const struct br_style *st, int x, int y, int w,
  6323. int h);
  6324. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  6325. * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
  6326. * ::before/::after box with a background (Infima's menu chevrons). */
  6327. #define RUN_SVG (-3)
  6328. #define RUN_PBOX (-4)
  6329. static int run_width(const struct lay_run *r)
  6330. {
  6331. if (r->img >= 0)
  6332. return r->iw;
  6333. if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
  6334. return r->iw;
  6335. return (int)r->w;
  6336. }
  6337. static void start_line(struct lay *l, const struct br_style *st)
  6338. {
  6339. (void)st;
  6340. if (l->nruns == 0) {
  6341. l->line_y = l->y;
  6342. l->line_h = 0;
  6343. }
  6344. l->line_left = l->left;
  6345. l->line_right = l->right;
  6346. if (l->float_active && l->line_y < l->float_bottom) {
  6347. if (l->float_left > l->line_left)
  6348. l->line_left = l->float_left;
  6349. if (l->float_right < l->line_right)
  6350. l->line_right = l->float_right;
  6351. }
  6352. if (l->line_right < l->line_left + 8)
  6353. l->line_right = l->line_left + 8;
  6354. l->line_x = l->line_left;
  6355. l->run_x = l->line_left;
  6356. }
  6357. static void inline_box_add(const struct lay *l, unsigned int owner, int x,
  6358. int w)
  6359. {
  6360. int y = l->line_y;
  6361. int h = l->line_h ? l->line_h : 16;
  6362. int depth = 0;
  6363. while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
  6364. unsigned int node = owner - 1;
  6365. struct br_layout_box *b = &layout_boxes[node];
  6366. if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
  6367. (inline_box_flush[node] == inline_box_flush_id ||
  6368. inline_box_y[node] < y)) {
  6369. int x1 = b->x + b->w, y1 = b->y + b->h;
  6370. if (x < b->x)
  6371. b->x = x;
  6372. if (y < b->y)
  6373. b->y = y;
  6374. if (x + w > x1)
  6375. x1 = x + w;
  6376. if (y + h > y1)
  6377. y1 = y + h;
  6378. b->w = x1 - b->x;
  6379. b->h = y1 - b->y;
  6380. } else {
  6381. b->x = x;
  6382. b->y = y;
  6383. b->w = w;
  6384. b->h = h;
  6385. b->valid = 1;
  6386. }
  6387. inline_box_pass[node] = inline_box_pass_id;
  6388. inline_box_flush[node] = inline_box_flush_id;
  6389. inline_box_y[node] = y;
  6390. owner = inline_box_parent[node];
  6391. }
  6392. }
  6393. static void flush_line(struct lay *l)
  6394. {
  6395. int total, x, i, vis;
  6396. inline_box_flush_id++;
  6397. if (!l->nruns && l->line_x == l->line_left) {
  6398. l->line_h = 0;
  6399. return;
  6400. }
  6401. total = l->line_x - l->line_left;
  6402. x = l->line_left;
  6403. vis = 1;
  6404. if (l->draw) {
  6405. int lh = l->line_h ? l->line_h : 16;
  6406. vis = l->line_y + lh >= page_rect.y &&
  6407. l->line_y <= page_rect.y + page_rect.h;
  6408. }
  6409. if (l->align == BR_ALIGN_CENTER)
  6410. x += (l->line_right - l->line_left - total) / 2;
  6411. else if (l->align == BR_ALIGN_RIGHT)
  6412. x = l->line_right - total;
  6413. if (x < l->line_left)
  6414. x = l->line_left;
  6415. for (i = 0; i < l->nruns; i++) {
  6416. struct lay_run *r = &l->runs[i];
  6417. int w = run_width(r);
  6418. int ry = l->line_y + r->dy;
  6419. x += r->gap;
  6420. if (l->draw && vis) {
  6421. if (r->form) {
  6422. unsigned int node = r->form - 1;
  6423. struct form_state *fs = form_get(node, 1);
  6424. int hh = r->ih ? r->ih : 20;
  6425. int focused = form_focus == node;
  6426. int disabled = r->form_disabled;
  6427. unsigned short bg = l->ui->theme.panel_alt;
  6428. unsigned short fg = disabled ? 0x8410 : r->color;
  6429. struct ngui_rect box = {x, ry, w, hh};
  6430. if (r->form_kind == FORM_CHECKBOX ||
  6431. r->form_kind == FORM_RADIO) {
  6432. ngui_fill_rect(l->ui, box, bg);
  6433. ngui_frame(l->ui, box,
  6434. focused ? l->ui->theme.accent :
  6435. l->ui->theme.border);
  6436. if (fs && fs->checked) {
  6437. struct ngui_rect dot = {
  6438. x + 4, ry + 4,
  6439. w > 8 ? w - 8 : 1,
  6440. hh > 8 ? hh - 8 : 1
  6441. };
  6442. if (r->form_kind == FORM_RADIO)
  6443. ngui_fill_round_rect(
  6444. l->ui, dot, 4,
  6445. 4, 4, 4,
  6446. l->ui->theme.accent);
  6447. else
  6448. ngui_fill_rect(l->ui,
  6449. dot,
  6450. l->ui->theme.accent);
  6451. }
  6452. } else {
  6453. int editable =
  6454. r->form_kind == FORM_TEXT ||
  6455. r->form_kind == FORM_PASSWORD ||
  6456. r->form_kind == FORM_TEXTAREA;
  6457. int scroll = 0;
  6458. /* Editable fields draw the live value
  6459. * (r->lit is a short copy). */
  6460. static char shown[FORM_VALUE_MAX + 1];
  6461. const char *txt = r->lit;
  6462. unsigned int tl = s_len(r->lit);
  6463. if (editable && fs && fs->len) {
  6464. unsigned int k;
  6465. if (r->form_kind == FORM_PASSWORD) {
  6466. for (k = 0; k < fs->len; k++)
  6467. shown[k] = '*';
  6468. shown[k] = '\0';
  6469. txt = shown;
  6470. } else {
  6471. txt = fs->value;
  6472. }
  6473. tl = fs->len;
  6474. }
  6475. struct br_style fst;
  6476. int author, tx = x + 6, pr = 6;
  6477. style_for_node(node, &fst);
  6478. author = form_author_styled(&fst);
  6479. if (author) {
  6480. /* The page styled the control:
  6481. * its background, border, radius
  6482. * and text colour. */
  6483. form_paint_author(l->ui, box, &fst,
  6484. focused);
  6485. tx = x + fst.border_w[3] +
  6486. mp_px(&fst, 7, w);
  6487. pr = fst.border_w[1] +
  6488. mp_px(&fst, 5, w);
  6489. if (tx < x + 2 && !editable)
  6490. tx = x + 2;
  6491. if (!disabled)
  6492. fg = editable && fs &&
  6493. !fs->len ?
  6494. 0x8410 : fst.color;
  6495. if (!editable) {
  6496. int tw0 = (int)
  6497. run_text_width(l->ui,
  6498. r, txt, tl);
  6499. tx = x + (w - tw0) / 2;
  6500. }
  6501. } else {
  6502. /* The box is drawn in theme colours, so
  6503. * the text is too: the page's CSS colour
  6504. * (dark on a light page) would vanish on
  6505. * the dark field. */
  6506. if (!disabled)
  6507. fg = editable && fs && !fs->len ?
  6508. l->ui->theme.text_dim :
  6509. l->ui->theme.text;
  6510. ngui_fill_rect(l->ui, box, bg);
  6511. ngui_frame(l->ui, box,
  6512. focused ? l->ui->theme.accent :
  6513. l->ui->theme.border);
  6514. }
  6515. /* A value wider than the field shows its
  6516. * tail (where typing happens). */
  6517. if (editable && fs && fs->len &&
  6518. w > (tx - x) + pr) {
  6519. int tw = (int)run_text_width(l->ui,
  6520. r, txt, tl);
  6521. int room = w - (tx - x) - pr;
  6522. if (tw > room)
  6523. scroll = tw - room;
  6524. }
  6525. ngui_push_clip(l->ui, (struct ngui_rect){
  6526. x + 1, ry + 1,
  6527. w > 2 ? w - 2 : 1,
  6528. hh > 2 ? hh - 2 : 1 });
  6529. ngui_text_px_face(l->ui, run_face(r),
  6530. tx - scroll,
  6531. ry + (hh - r->font_px) / 2 - 1,
  6532. txt, tl, fg, r->font_px,
  6533. r->bold, r->italic, r->mono);
  6534. if (focused && fs && editable) {
  6535. int cw = 0;
  6536. if (fs->len && fs->caret)
  6537. cw = (int)run_text_width(
  6538. l->ui, r, txt,
  6539. fs->caret < fs->len ?
  6540. fs->caret : fs->len);
  6541. ngui_fill_rect(l->ui,
  6542. (struct ngui_rect){
  6543. tx + cw - scroll,
  6544. ry + 4, 1,
  6545. hh > 8 ? hh - 8 : 1
  6546. },
  6547. l->ui->theme.accent);
  6548. }
  6549. ngui_pop_clip(l->ui);
  6550. if (r->form_kind == FORM_SELECT) {
  6551. ngui_text_px(l->ui, x + w - 12,
  6552. ry + 2, "v", 1, fg,
  6553. r->font_px, 0, 0, 0);
  6554. }
  6555. }
  6556. } else if (r->img == RUN_PBOX) {
  6557. struct ngui_rect bx = { x, ry, w, r->ih };
  6558. ngui_push_clip(l->ui, bx);
  6559. if (r->pb_has_bg)
  6560. ngui_fill_rect(l->ui, bx, r->pb_bg);
  6561. if (r->pb_img >= 0 && r->pb_img < image_count &&
  6562. images[r->pb_img].state == 1) {
  6563. /* Rotate about the box centre: the
  6564. * image is centred in it here. */
  6565. draw_image_transformed(l->ui,
  6566. &images[r->pb_img].img,
  6567. x + r->pb_x, ry + r->pb_y,
  6568. r->pb_w, r->pb_h,
  6569. r->transform_scale ?
  6570. r->scale_x : 100,
  6571. r->transform_scale ?
  6572. r->scale_y : 100,
  6573. r->transform_scale ?
  6574. r->rotate_x100 : 0,
  6575. 50, 50, 1, 1);
  6576. }
  6577. ngui_pop_clip(l->ui);
  6578. } else if (r->img == RUN_SVG) {
  6579. struct br_style sst;
  6580. style_for_node(r->off, &sst);
  6581. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6582. r->ih);
  6583. } else if (r->img == -2) {
  6584. int hh = r->ih ? r->ih : 20;
  6585. ngui_fill_rect(l->ui,
  6586. (struct ngui_rect){x, ry, w, hh},
  6587. l->ui->theme.panel_alt);
  6588. ngui_frame(l->ui,
  6589. (struct ngui_rect){x, ry, w, hh},
  6590. l->ui->theme.border);
  6591. ngui_text_px_face(l->ui, run_face(r),
  6592. x + 6, ry + 2, r->lit,
  6593. s_len(r->lit), r->color,
  6594. r->font_px, r->bold, r->italic,
  6595. r->mono);
  6596. } else if (r->img >= 0) {
  6597. struct br_image *bi = &images[r->img];
  6598. if (bi->state == 1 && r->transform_scale) {
  6599. draw_image_transformed(l->ui, &bi->img,
  6600. x, ry, r->iw, r->ih,
  6601. r->scale_x, r->scale_y,
  6602. r->rotate_x100, r->origin_x,
  6603. r->origin_y, r->origin_x_kind,
  6604. r->origin_y_kind);
  6605. } else if (bi->state == 1) {
  6606. struct img_image *src =
  6607. image_display_get(bi, r->iw, r->ih);
  6608. struct img_blit b;
  6609. if (!src)
  6610. src = &bi->img;
  6611. b.dst = l->ui->px;
  6612. b.dst_w = l->ui->w;
  6613. b.dst_h = l->ui->h;
  6614. b.clip_x = page_rect.x;
  6615. b.clip_y = page_rect.y;
  6616. b.clip_w = page_rect.w - 12;
  6617. b.clip_h = page_rect.h;
  6618. b.x = x;
  6619. b.y = ry;
  6620. b.scale = ((unsigned int)r->iw << 16) /
  6621. src->w;
  6622. b.bg = ui.theme.bg;
  6623. b.bg2 = ui.theme.bg;
  6624. b.dst_a = 0;
  6625. b.flags = src->alpha ?
  6626. IMG_BLIT_OVER_DST : 0;
  6627. img_draw(src, &b);
  6628. }
  6629. } else {
  6630. const char *s = r->has_lit ? r->lit :
  6631. doc.text + r->off;
  6632. unsigned int n = r->has_lit ? s_len(r->lit) :
  6633. r->len;
  6634. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6635. s, n, r->color, r->font_px,
  6636. r->bold, r->italic, r->mono);
  6637. if (r->underline)
  6638. ngui_fill_rect(l->ui,
  6639. (struct ngui_rect){x,
  6640. ry + run_ascent(l->ui, r) + 2,
  6641. w, 1}, r->color);
  6642. if (r->strike)
  6643. ngui_fill_rect(l->ui,
  6644. (struct ngui_rect){x,
  6645. ry + run_ascent(l->ui, r) -
  6646. (r->font_px > 3 ?
  6647. r->font_px / 3 : 1),
  6648. w, 1}, r->color);
  6649. if (r->overline)
  6650. ngui_fill_rect(l->ui,
  6651. (struct ngui_rect){x, ry,
  6652. w, 1}, r->color);
  6653. }
  6654. if (r->form || r->href) {
  6655. if (nhits < HIT_MAX) {
  6656. struct hit *h = &hits[nhits];
  6657. unsigned int target = r->form ?
  6658. r->form - 1 : r->href;
  6659. int hh = (r->form || r->img >= 0 ||
  6660. r->img == RUN_SVG) ?
  6661. r->ih :
  6662. run_line_height(l->ui, r);
  6663. int merge = nhits > 0 &&
  6664. hits[nhits - 1].node == target &&
  6665. hits[nhits - 1].y == ry &&
  6666. hits[nhits - 1].h == hh &&
  6667. x <= hits[nhits - 1].x +
  6668. hits[nhits - 1].w + 2;
  6669. if (merge) {
  6670. struct hit *p = &hits[nhits - 1];
  6671. int end = x + w;
  6672. if (end > p->x + p->w)
  6673. p->w = end - p->x;
  6674. } else {
  6675. h->x = x;
  6676. h->y = ry;
  6677. h->w = w;
  6678. h->h = hh;
  6679. h->node = (unsigned short)target;
  6680. nhits++;
  6681. }
  6682. }
  6683. }
  6684. }
  6685. if (r->box)
  6686. inline_box_add(l, r->box, x, w);
  6687. x += w;
  6688. }
  6689. l->y += l->line_h + 2;
  6690. if (l->float_active && l->y >= l->float_bottom)
  6691. l->float_active = 0;
  6692. l->nruns = 0;
  6693. l->line_x = l->left;
  6694. l->run_x = l->left;
  6695. l->line_left = l->left;
  6696. l->line_right = l->right;
  6697. l->line_h = 0;
  6698. l->space_pending = 0;
  6699. }
  6700. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6701. const struct br_style *st, unsigned short href,
  6702. const char *lit)
  6703. {
  6704. unsigned int n = lit ? s_len(lit) : len;
  6705. const char *tp = lit ? lit : doc.text + off;
  6706. int w = (int)face_text_width(l->ui, st, tp, n);
  6707. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6708. flush_line(l);
  6709. if (l->nruns == 0) {
  6710. l->line_y = l->y;
  6711. l->line_h = 0;
  6712. start_line(l, st);
  6713. }
  6714. {
  6715. struct lay_run *r = &l->runs[l->nruns++];
  6716. int gap = l->line_x - l->run_x;
  6717. if (gap < 0)
  6718. gap = 0;
  6719. r->box = l->box_owner;
  6720. r->gap = (unsigned short)gap;
  6721. r->off = off;
  6722. r->len = len;
  6723. r->color = st->color;
  6724. r->href = href;
  6725. r->dy = 0;
  6726. r->has_lit = 0;
  6727. r->form = 0;
  6728. r->form_kind = 0;
  6729. r->form_disabled = 0;
  6730. r->lit[0] = '\0';
  6731. if (lit && lit[0]) {
  6732. unsigned int i;
  6733. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6734. r->lit[i] = lit[i];
  6735. r->lit[i] = '\0';
  6736. r->has_lit = 1;
  6737. }
  6738. r->img = -1;
  6739. r->iw = r->ih = 0;
  6740. r->font_px = st->font_px;
  6741. r->bold = st->bold;
  6742. r->italic = st->italic;
  6743. r->mono = st->mono;
  6744. r->font_face = st->font_face;
  6745. /* A control with its own background is a button, not body copy;
  6746. * an inherited link underline would strike through the fill. */
  6747. r->underline = st->underline && !st->has_bg;
  6748. r->strike = st->strike && !st->has_bg;
  6749. r->overline = st->overline && !st->has_bg;
  6750. r->w = (unsigned short)w;
  6751. if (r->has_lit)
  6752. r->w = (unsigned short)run_text_width(
  6753. l->ui, r, r->lit, s_len(r->lit));
  6754. w = r->w;
  6755. }
  6756. l->line_x += w;
  6757. l->run_x = l->line_x;
  6758. {
  6759. int lh = face_line_height(l->ui, st);
  6760. if (st->line_h_px)
  6761. lh = st->line_h_px;
  6762. else if (st->line_h_pct)
  6763. lh = st->font_px * st->line_h_pct / 100;
  6764. if (lh < face_line_height(l->ui, st))
  6765. lh = face_line_height(l->ui, st);
  6766. if (l->line_h < lh)
  6767. l->line_h = lh;
  6768. }
  6769. }
  6770. static void add_image_run(struct lay *l, unsigned int node,
  6771. const struct br_style *st, unsigned short href)
  6772. {
  6773. struct br_image *bi = 0;
  6774. int idx = doc.nodes[node].img_index;
  6775. int dw, dh, maxw;
  6776. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6777. bi = &images[idx];
  6778. if (l->nruns == 0)
  6779. start_line(l, st);
  6780. if (l->space_pending &&
  6781. (l->nruns > 0 || l->line_x > l->line_left)) {
  6782. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6783. if (l->line_x + sp <= l->line_right)
  6784. l->line_x += sp;
  6785. }
  6786. l->space_pending = 0;
  6787. if (!bi) {
  6788. const char *alt = br_alt(&doc, node);
  6789. struct br_style gs = *st;
  6790. char tmp[96];
  6791. unsigned int n = 0;
  6792. int w;
  6793. gs.color = BR_GRAY;
  6794. gs.underline = 0;
  6795. s_append(tmp, &n, "[", sizeof(tmp));
  6796. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6797. s_append(tmp, &n, "]", sizeof(tmp));
  6798. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6799. if (l->line_x + w > l->line_right &&
  6800. (l->nruns > 0 || l->line_x > l->line_left))
  6801. flush_line(l);
  6802. add_run(l, 0, 0, &gs, href, tmp);
  6803. if (!l->draw) {
  6804. int t = l->line_y < 0 ? 0 : l->line_y;
  6805. int hh = face_line_height(l->ui, &gs);
  6806. if (t > 65535)
  6807. t = 65535;
  6808. if (hh > 65535)
  6809. hh = 65535;
  6810. img_top[node] = (unsigned short)t;
  6811. img_h[node] = (unsigned short)hh;
  6812. }
  6813. return;
  6814. }
  6815. maxw = l->line_right - l->line_left;
  6816. if (maxw < 8)
  6817. maxw = 8;
  6818. {
  6819. int iw = bi->native_w, ih = bi->native_h;
  6820. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6821. if (iw <= 0 || ih <= 0) {
  6822. iw = (int)bi->img.w;
  6823. ih = (int)bi->img.h;
  6824. }
  6825. dw = iw;
  6826. dh = ih;
  6827. if (doc.nodes[node].width_attr) {
  6828. int want = doc.nodes[node].width_attr;
  6829. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6830. have_w = 1;
  6831. }
  6832. if (doc.nodes[node].height_attr) {
  6833. int want = doc.nodes[node].height_attr;
  6834. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6835. have_h = 1;
  6836. }
  6837. if (have_w && !have_h)
  6838. dh = ih ? ih * dw / iw : 0;
  6839. if (have_h && !have_w)
  6840. dw = iw ? iw * dh / ih : 0;
  6841. if (st->width_kind) {
  6842. css_w = 1;
  6843. if (st->width_kind == 3)
  6844. dw = maxw * st->width_calc_pct / 100 +
  6845. st->width_calc_px;
  6846. else
  6847. dw = st->width_kind == 2 ?
  6848. maxw * (int)st->width / 100 :
  6849. (int)st->width;
  6850. }
  6851. /* Percentage heights resolve against the containing block's
  6852. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6853. * 2rem }` holding an `img { height: 100% }`), and are auto
  6854. * when it has none; they used to use the width. */
  6855. if (st->height_kind == 1 ||
  6856. ((st->height_kind == 2 || st->height_kind == 3) &&
  6857. l->cb_h > 0)) {
  6858. css_h = 1;
  6859. if (st->height_kind == 3)
  6860. dh = l->cb_h * st->height_calc_pct / 100 +
  6861. st->height_calc_px;
  6862. else
  6863. dh = st->height_kind == 2 ?
  6864. l->cb_h * (int)st->height / 100 :
  6865. (int)st->height;
  6866. }
  6867. if (css_w && !css_h)
  6868. dh = ih ? ih * dw / iw : 0;
  6869. if (css_h && !css_w)
  6870. dw = iw ? iw * dh / ih : 0;
  6871. if (st->max_width_kind) {
  6872. int mw = st->max_width_kind == 3 ?
  6873. maxw * st->max_width_calc_pct / 100 +
  6874. st->max_width_calc_px :
  6875. st->max_width_kind == 2 ?
  6876. maxw * (int)st->max_width / 100 :
  6877. (int)st->max_width;
  6878. if (mw > 0 && dw > mw) {
  6879. dh = iw ? ih * mw / iw : 0;
  6880. dw = mw;
  6881. }
  6882. }
  6883. }
  6884. if (dw < 8)
  6885. dw = 8;
  6886. if (dh < 8)
  6887. dh = 8;
  6888. if (dw > maxw) {
  6889. dh = dw ? dh * maxw / dw : dh;
  6890. dw = maxw;
  6891. }
  6892. if (!l->draw) {
  6893. int t = l->line_y < 0 ? 0 : l->line_y;
  6894. if (t > 65535)
  6895. t = 65535;
  6896. if (dh > 65535)
  6897. dh = 65535;
  6898. img_top[node] = (unsigned short)t;
  6899. img_h[node] = (unsigned short)dh;
  6900. }
  6901. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6902. l->line_x > l->line_left))
  6903. flush_line(l);
  6904. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6905. flush_line(l);
  6906. if (l->nruns == 0) {
  6907. l->line_y = l->y;
  6908. l->line_h = 0;
  6909. start_line(l, st);
  6910. }
  6911. {
  6912. struct lay_run *r = &l->runs[l->nruns++];
  6913. int gap = l->line_x - l->run_x;
  6914. if (gap < 0)
  6915. gap = 0;
  6916. r->box = l->box_owner;
  6917. r->gap = (unsigned short)gap;
  6918. r->off = 0;
  6919. r->len = 0;
  6920. r->color = 0;
  6921. r->href = href;
  6922. r->form = 0;
  6923. r->form_kind = 0;
  6924. r->form_disabled = 0;
  6925. /* Inline replaced elements honour their vertical margins; this
  6926. * is how Bootstrap's negative logo margins centre the wordmark. */
  6927. {
  6928. int idy = mp_px(st, 0, l->right - l->left);
  6929. if (idy < -2048)
  6930. idy = -2048;
  6931. if (idy > 2048)
  6932. idy = 2048;
  6933. r->dy = (signed short)idy;
  6934. }
  6935. r->has_lit = 0;
  6936. r->lit[0] = '\0';
  6937. r->img = (short)idx;
  6938. r->iw = (unsigned short)dw;
  6939. r->ih = (unsigned short)dh;
  6940. r->w = (unsigned short)dw;
  6941. r->font_px = st->font_px;
  6942. r->bold = st->bold;
  6943. r->italic = st->italic;
  6944. r->mono = st->mono;
  6945. r->font_face = st->font_face;
  6946. r->transform_scale = st->transform_scale;
  6947. r->scale_x = st->scale_x;
  6948. r->scale_y = st->scale_y;
  6949. r->rotate_x100 = st->rotate_x100;
  6950. r->origin_x = st->origin_x;
  6951. r->origin_y = st->origin_y;
  6952. r->origin_x_kind = st->origin_x_kind;
  6953. r->origin_y_kind = st->origin_y_kind;
  6954. r->underline = 0;
  6955. }
  6956. if (node < BR_MAX_NODES) {
  6957. layout_boxes[node].x = l->line_x;
  6958. layout_boxes[node].y = l->line_y +
  6959. mp_px(st, 0, l->right - l->left);
  6960. layout_boxes[node].w = dw;
  6961. layout_boxes[node].h = dh;
  6962. layout_boxes[node].valid = 1;
  6963. }
  6964. l->line_x += dw;
  6965. l->run_x = l->line_x;
  6966. if (l->line_h < dh)
  6967. l->line_h = dh;
  6968. }
  6969. /* An inline (or inline-block) <svg> is a replaced element in the text
  6970. * line, like an <img>: comment bubbles and arrows sit next to their label
  6971. * instead of starting a block of their own. */
  6972. static void add_svg_run(struct lay *l, unsigned int node,
  6973. const struct br_style *st, unsigned short href)
  6974. {
  6975. struct lay_run *r;
  6976. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6977. if (lw < 8)
  6978. lw = 8;
  6979. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6980. if (cw < 1)
  6981. cw = 1;
  6982. svg_size(node, st, cw, &dw, &dh);
  6983. if (dw > lw)
  6984. dw = lw;
  6985. ml = mp_px(st, 3, lw);
  6986. mr = mp_px(st, 1, lw);
  6987. if (ml < 0)
  6988. ml = 0;
  6989. if (mr < 0)
  6990. mr = 0;
  6991. if (l->line_x + ml + dw > l->line_right &&
  6992. (l->nruns > 0 || l->line_x > l->line_left))
  6993. flush_line(l);
  6994. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6995. flush_line(l);
  6996. if (l->nruns == 0) {
  6997. l->line_y = l->y;
  6998. l->line_h = 0;
  6999. start_line(l, st);
  7000. }
  7001. l->line_x += ml;
  7002. r = &l->runs[l->nruns++];
  7003. memset(r, 0, sizeof(*r));
  7004. r->box = l->box_owner;
  7005. r->gap = (unsigned short)(l->line_x > l->run_x ?
  7006. l->line_x - l->run_x : 0);
  7007. r->off = node;
  7008. r->color = st->color;
  7009. r->href = href;
  7010. r->img = RUN_SVG;
  7011. r->iw = (unsigned short)dw;
  7012. r->ih = (unsigned short)dh;
  7013. r->w = (unsigned short)dw;
  7014. r->font_px = st->font_px;
  7015. if (node < BR_MAX_NODES) {
  7016. layout_boxes[node].x = l->line_x;
  7017. layout_boxes[node].y = l->line_y;
  7018. layout_boxes[node].w = dw;
  7019. layout_boxes[node].h = dh;
  7020. layout_boxes[node].valid = 1;
  7021. }
  7022. l->line_x += dw + mr;
  7023. l->run_x = l->line_x;
  7024. if (l->line_h < dh)
  7025. l->line_h = dh;
  7026. }
  7027. static int text_width(struct lay *l, const char *s, unsigned int n,
  7028. const struct br_style *st)
  7029. {
  7030. return (int)face_text_width(l->ui, st, s, n);
  7031. }
  7032. /* Longest prefix that fits in maxw, at least one byte. */
  7033. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  7034. const struct br_style *st, int maxw)
  7035. {
  7036. unsigned int take = 0;
  7037. while (take < n) {
  7038. if (text_width(l, s, take + 1, st) > maxw)
  7039. break;
  7040. take++;
  7041. }
  7042. return take ? take : 1;
  7043. }
  7044. static void emit_word(struct lay *l, const char *s, unsigned int start,
  7045. unsigned int n, unsigned int base,
  7046. const struct br_style *st, unsigned short href)
  7047. {
  7048. int avail;
  7049. int w = text_width(l, s + start, n, st);
  7050. unsigned int off = start;
  7051. if (l->nruns == 0)
  7052. start_line(l, st);
  7053. avail = l->line_right - l->line_left;
  7054. if (st->nowrap) {
  7055. if (n)
  7056. add_run(l, base + start,
  7057. (unsigned short)n, st, href, 0);
  7058. return;
  7059. }
  7060. /* A padded/bordered one-word button can be a few pixels wider than
  7061. * the content box; keep it on one line instead of splitting it. */
  7062. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  7063. add_run(l, base + start,
  7064. (unsigned short)n, st, href, 0);
  7065. return;
  7066. }
  7067. if (l->line_x + w > l->line_right &&
  7068. (l->nruns > 0 || l->line_x > l->line_left)) {
  7069. flush_line(l);
  7070. start_line(l, st);
  7071. avail = l->line_right - l->line_left;
  7072. }
  7073. if (w <= avail) {
  7074. if (n)
  7075. add_run(l, base + start,
  7076. (unsigned short)n, st, href, 0);
  7077. return;
  7078. }
  7079. while (n > 0) {
  7080. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  7081. add_run(l, base + off,
  7082. (unsigned short)take, st, href, 0);
  7083. off += take;
  7084. n -= take;
  7085. if (n) {
  7086. flush_line(l);
  7087. start_line(l, st);
  7088. avail = l->line_right - l->line_left;
  7089. }
  7090. }
  7091. }
  7092. static void emit_text(struct lay *l, const char *s, unsigned int len,
  7093. const struct br_style *st, unsigned short href, int pre)
  7094. {
  7095. unsigned int i = 0;
  7096. unsigned int base;
  7097. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  7098. if (!s || !len)
  7099. return;
  7100. if (space_w <= 0)
  7101. space_w = 8;
  7102. if (l->nruns == 0)
  7103. start_line(l, st);
  7104. base = (unsigned int)(s - doc.text);
  7105. if (st->uppercase) {
  7106. char *p = (char *)s;
  7107. unsigned int j;
  7108. for (j = 0; j < len; j++)
  7109. if (p[j] >= 'a' && p[j] <= 'z')
  7110. p[j] = (char)(p[j] - 'a' + 'A');
  7111. }
  7112. if (pre) {
  7113. while (i < len) {
  7114. unsigned int start;
  7115. if (s[i] == '\n') {
  7116. flush_line(l);
  7117. start_line(l, st);
  7118. i++;
  7119. continue;
  7120. }
  7121. if (s[i] == ' ') {
  7122. if (l->line_x + space_w > l->line_right &&
  7123. (l->nruns > 0 || l->line_x > l->line_left)) {
  7124. flush_line(l);
  7125. start_line(l, st);
  7126. } else {
  7127. l->line_x += space_w;
  7128. }
  7129. i++;
  7130. continue;
  7131. }
  7132. start = i;
  7133. while (i < len && s[i] != ' ' && s[i] != '\n')
  7134. i++;
  7135. emit_word(l, s, start, i - start, base, st, href);
  7136. }
  7137. return;
  7138. }
  7139. while (i < len) {
  7140. unsigned int start, n;
  7141. if (s[i] == ' ') {
  7142. l->space_pending = 1;
  7143. i++;
  7144. continue;
  7145. }
  7146. start = i;
  7147. while (i < len && s[i] != ' ')
  7148. i++;
  7149. n = i - start;
  7150. if (l->space_pending &&
  7151. (l->nruns > 0 || l->line_x > l->line_left)) {
  7152. if (st->nowrap ||
  7153. l->line_x + space_w <= l->line_right)
  7154. l->line_x += space_w;
  7155. }
  7156. l->space_pending = 0;
  7157. emit_word(l, s, start, n, base, st, href);
  7158. }
  7159. }
  7160. static int list_index(unsigned int parent, unsigned int node)
  7161. {
  7162. unsigned int n = 0, i;
  7163. for (i = doc.nodes[parent].first; i && i != node;
  7164. i = doc.nodes[i].next)
  7165. if (doc.nodes[i].tag == BR_TAG_LI)
  7166. n++;
  7167. return (int)n + 1;
  7168. }
  7169. static void list_roman(char *m, unsigned int *n, int v, int upper,
  7170. unsigned int cap)
  7171. {
  7172. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  7173. 50, 40, 10, 9, 5, 4, 1 };
  7174. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  7175. "l", "xl", "x", "ix", "v", "iv", "i" };
  7176. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  7177. "L", "XL", "X", "IX", "V", "IV", "I" };
  7178. unsigned int i;
  7179. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  7180. while (v >= val[i] && *n + 1 < cap) {
  7181. const char *s = upper ? up[i] : lo[i];
  7182. while (*s && *n + 1 < cap)
  7183. m[(*n)++] = *s++;
  7184. v -= val[i];
  7185. }
  7186. }
  7187. }
  7188. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  7189. {
  7190. unsigned int n = 0;
  7191. if (style == BR_LIST_DISC) {
  7192. m[n++] = '-';
  7193. } else if (style == BR_LIST_CIRCLE) {
  7194. m[n++] = 'o';
  7195. } else if (style == BR_LIST_SQUARE) {
  7196. m[n++] = '+';
  7197. } else if (style == BR_LIST_LOWER_ALPHA ||
  7198. style == BR_LIST_UPPER_ALPHA) {
  7199. if (idx >= 1 && idx <= 26)
  7200. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  7201. 'A' : 'a') + idx - 1);
  7202. else
  7203. m[n++] = '?';
  7204. m[n++] = '.';
  7205. } else if (style == BR_LIST_LOWER_ROMAN ||
  7206. style == BR_LIST_UPPER_ROMAN) {
  7207. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  7208. if (n + 1 < cap)
  7209. m[n++] = '.';
  7210. } else {
  7211. s_append_dec(m, &n, (unsigned int)idx, cap);
  7212. if (n + 1 < cap)
  7213. m[n++] = '.';
  7214. }
  7215. m[n] = '\0';
  7216. }
  7217. /* A control the page styled itself (background, border or radius in author
  7218. * CSS -- `background:transparent;border:none` counts) is painted with that
  7219. * style, sized from its padding/height and keeps the page's text colour.
  7220. * Unstyled controls keep the ngui theme look. */
  7221. static int form_author_styled(const struct br_style *st)
  7222. {
  7223. int i;
  7224. if (st->bg_set)
  7225. return 1;
  7226. for (i = 0; i < 4; i++)
  7227. if (st->border_w[i] || st->radius[i])
  7228. return 1;
  7229. return 0;
  7230. }
  7231. /* Set by the layout when the control is stretched to its line: a flex item
  7232. * (its box width was assigned by the flex row) or a child of a flex column,
  7233. * whose default align-items: stretch makes inputs full width. */
  7234. static int form_fill_line;
  7235. static void add_form_run(struct lay *l, unsigned int node,
  7236. const struct br_style *st, unsigned short href)
  7237. {
  7238. struct form_state *fs = form_get(node, 1);
  7239. char shown[FORM_VALUE_MAX + 1];
  7240. char opt[64];
  7241. const char *text = "";
  7242. struct lay_run *r;
  7243. int kind = form_kind_of(node);
  7244. int disabled = form_disabled(node);
  7245. int author = form_author_styled(st);
  7246. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  7247. int ml = 0, mr = 0, mt = 0, mb = 0;
  7248. if (!fs)
  7249. return;
  7250. if (l->nruns == 0)
  7251. start_line(l, st);
  7252. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  7253. text = "";
  7254. w = 16;
  7255. h = 16;
  7256. } else if (kind == FORM_SELECT) {
  7257. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  7258. s_copy(opt, "Select", sizeof(opt));
  7259. text = opt;
  7260. w = 120;
  7261. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  7262. kind == FORM_RESET) {
  7263. if (fs->len)
  7264. text = fs->value;
  7265. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  7266. /* A <button>'s label is its content: an empty one
  7267. * (Docusaurus' sidebar caret, drawn by a CSS
  7268. * ::before icon) shows none. Only <input> buttons
  7269. * get the UA's default label. */
  7270. text = "";
  7271. else
  7272. text = kind == FORM_SUBMIT ? "Submit" :
  7273. kind == FORM_RESET ? "Reset" : "Button";
  7274. } else if (kind == FORM_PASSWORD) {
  7275. for (i = 0; i < fs->len; i++)
  7276. shown[i] = '*';
  7277. shown[fs->len] = '\0';
  7278. text = fs->len ? shown : br_placeholder(&doc, node);
  7279. } else {
  7280. if (fs->len)
  7281. text = fs->value;
  7282. else
  7283. text = br_placeholder(&doc, node);
  7284. if (kind == FORM_TEXTAREA) {
  7285. w = 180;
  7286. h = 40;
  7287. }
  7288. }
  7289. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  7290. line_w = l->line_right - l->line_left;
  7291. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  7292. st->border_w[1] + st->border_w[3];
  7293. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  7294. st->border_w[0] + st->border_w[2];
  7295. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  7296. /* Buttons are border-box in every UA stylesheet: an
  7297. * explicit width/height is the whole box. */
  7298. if (author || pad_x) {
  7299. w = tw + pad_x;
  7300. } else {
  7301. w = tw + 18;
  7302. if (w < 64)
  7303. w = 64;
  7304. }
  7305. if (st->width_kind)
  7306. w = style_width_px(st, line_w);
  7307. if (st->min_width_kind == 1 && w < (int)st->min_width)
  7308. w = st->min_width;
  7309. if (st->height_kind == 1)
  7310. h = st->height;
  7311. else if (author)
  7312. h = st->font_px + 6 + pad_y;
  7313. else
  7314. h = 22;
  7315. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  7316. kind == FORM_TEXTAREA) {
  7317. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  7318. st->display == BR_DISPLAY_FLEX;
  7319. int boxed = st->box_sizing ? 0 : pad_x;
  7320. if (st->width_kind)
  7321. w = style_width_px(st, line_w) + boxed;
  7322. else if (fill)
  7323. w = line_w - (l->line_x - l->line_left);
  7324. else
  7325. w = kind == FORM_TEXTAREA ? 180 : 120;
  7326. if (kind == FORM_TEXTAREA) {
  7327. const char *ra = br_find_attr(&doc, node, "rows");
  7328. int rows = 0;
  7329. int lh = st->line_h_px ? st->line_h_px :
  7330. st->font_px * 5 / 4;
  7331. while (ra && *ra >= '0' && *ra <= '9')
  7332. rows = rows * 10 + (*ra++ - '0');
  7333. if (rows < 1 || rows > 40)
  7334. rows = 2;
  7335. h = author ? rows * lh + pad_y : 40;
  7336. } else if (author) {
  7337. h = st->font_px + 8 + pad_y;
  7338. } else if (st->font_px + 8 > h) {
  7339. /* Taller fields for large text (min-height/padding
  7340. * on login pages): keep the box around the glyphs. */
  7341. h = st->font_px + 8;
  7342. }
  7343. if (st->height_kind == 1)
  7344. h = st->height + (st->box_sizing ? 0 : pad_y);
  7345. if (st->min_height_kind == 1 && h < (int)st->min_height)
  7346. h = st->min_height;
  7347. } else if (kind == FORM_SELECT) {
  7348. w = st->width_kind == 1 ? st->width : 120;
  7349. }
  7350. if (author) {
  7351. /* Inline margins (Google's `margin:11px 4px` between its
  7352. * two submit buttons). */
  7353. ml = mp_px(st, 3, line_w);
  7354. mr = mp_px(st, 1, line_w);
  7355. mt = mp_px(st, 0, line_w);
  7356. mb = mp_px(st, 2, line_w);
  7357. if (ml < 0 || ml > 64) ml = 0;
  7358. if (mr < 0 || mr > 64) mr = 0;
  7359. if (mt < 0 || mt > 64) mt = 0;
  7360. if (mb < 0 || mb > 64) mb = 0;
  7361. }
  7362. if (w > line_w - ml - mr)
  7363. w = line_w - ml - mr;
  7364. if (w < 8)
  7365. w = 8;
  7366. if (h > 400)
  7367. h = 400;
  7368. if (l->line_x + ml + w > l->line_right &&
  7369. (l->nruns > 0 || l->line_x > l->line_left))
  7370. flush_line(l);
  7371. if (l->nruns >= 96)
  7372. return;
  7373. if (l->nruns == 0) {
  7374. l->line_y = l->y;
  7375. l->line_h = 0;
  7376. start_line(l, st);
  7377. }
  7378. l->line_x += ml;
  7379. r = &l->runs[l->nruns++];
  7380. r->box = l->box_owner;
  7381. r->gap = (unsigned short)(l->line_x - l->run_x);
  7382. r->off = r->len = 0;
  7383. r->color = st->color;
  7384. r->href = href;
  7385. r->dy = (signed short)mt;
  7386. r->has_lit = 1;
  7387. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  7388. r->lit[i] = text[i];
  7389. r->lit[i] = '\0';
  7390. r->img = -2;
  7391. r->iw = (unsigned short)w;
  7392. r->ih = (unsigned short)h;
  7393. r->w = (unsigned short)w;
  7394. r->font_px = st->font_px;
  7395. r->bold = st->bold;
  7396. r->italic = st->italic;
  7397. r->mono = st->mono;
  7398. r->font_face = st->font_face;
  7399. r->underline = 0;
  7400. r->form = node + 1;
  7401. r->form_kind = (unsigned char)kind;
  7402. r->form_disabled = (unsigned char)disabled;
  7403. if (node < BR_MAX_NODES) {
  7404. layout_boxes[node].x = l->line_x;
  7405. layout_boxes[node].y = l->line_y + mt;
  7406. layout_boxes[node].w = w;
  7407. layout_boxes[node].h = h;
  7408. layout_boxes[node].valid = 1;
  7409. }
  7410. l->line_x += w;
  7411. l->run_x = l->line_x;
  7412. l->line_x += mr;
  7413. if (l->line_h < h + mt + mb)
  7414. l->line_h = h + mt + mb;
  7415. }
  7416. /* Background, border and corner radius of an author-styled control, the
  7417. * same decoration rules as a block box. */
  7418. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  7419. const struct br_style *st, int focused)
  7420. {
  7421. int rtl = css_radius(st, 0, box.w, box.h);
  7422. int rtr = css_radius(st, 1, box.w, box.h);
  7423. int rbr = css_radius(st, 2, box.w, box.h);
  7424. int rbl = css_radius(st, 3, box.w, box.h);
  7425. int bw = st->border_t[0] ? 0 : st->border_w[0];
  7426. (void)focused;
  7427. if (box.w <= 0 || box.h <= 0)
  7428. return;
  7429. if (rtl || rtr || rbr || rbl) {
  7430. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  7431. box.w > bw * 2 && box.h > bw * 2) {
  7432. struct ngui_rect in = { box.x + bw, box.y + bw,
  7433. box.w - bw * 2,
  7434. box.h - bw * 2 };
  7435. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7436. st->border_c[0]);
  7437. ngui_fill_round_rect(ui, in,
  7438. rtl > bw ? rtl - bw : 0,
  7439. rtr > bw ? rtr - bw : 0,
  7440. rbr > bw ? rbr - bw : 0,
  7441. rbl > bw ? rbl - bw : 0, st->bg);
  7442. } else if (st->has_bg) {
  7443. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  7444. st->bg);
  7445. } else if (bw > 0) {
  7446. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  7447. st->border_c[0]);
  7448. }
  7449. return;
  7450. }
  7451. if (st->has_bg)
  7452. ngui_fill_rect(ui, box, st->bg);
  7453. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  7454. st->border_w[3])
  7455. draw_border_box(ui, box, st);
  7456. }
  7457. /* A poster wrapper is absolutely positioned over the media slot; the
  7458. * measured height of its picture is normally added back to the flow. When a
  7459. * loading-skeleton sibling already reserves that slot, adding both doubles
  7460. * the media height and pushes the article text a full screen down. */
  7461. static int has_skeleton_sibling(unsigned int node)
  7462. {
  7463. unsigned int p = doc.nodes[node].parent, c;
  7464. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7465. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7466. continue;
  7467. if (doc.nodes[c].class_off &&
  7468. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7469. "skeleton"))
  7470. return 1;
  7471. }
  7472. return 0;
  7473. }
  7474. static void layout_children(struct lay *l, unsigned int parent,
  7475. const struct br_style *pst, int depth,
  7476. unsigned short link);
  7477. static void layout_flex_children(struct lay *l, unsigned int parent,
  7478. const struct br_style *pst, int depth,
  7479. unsigned short link);
  7480. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  7481. struct br_style *ps, int base);
  7482. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  7483. const struct br_style *ps, unsigned short link);
  7484. static void layout_grid_children(struct lay *l, unsigned int parent,
  7485. const struct br_style *pst, int depth,
  7486. unsigned short link);
  7487. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7488. const struct br_style *pst, int depth,
  7489. unsigned short link);
  7490. static int flex_item_width(struct lay *l, unsigned int n,
  7491. const struct br_style *cs, int avail);
  7492. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7493. const struct br_style *pst, int depth,
  7494. unsigned short link);
  7495. static void layout_table_row(struct lay *l, unsigned int row,
  7496. const struct br_style *pst, int depth,
  7497. unsigned short link);
  7498. static int table_has_rowspan(unsigned int table);
  7499. static void layout_table(struct lay *l, unsigned int table,
  7500. const struct br_style *st, int depth,
  7501. unsigned short link);
  7502. /* A flex container whose items are only inline spans is usually just a
  7503. * heading/icon pair. Our flex row positions such items without emitting
  7504. * their inline text in some deep page contexts; normal inline flow renders
  7505. * the same content correctly. */
  7506. static int layout_out_of_flow(struct lay *l, unsigned int n,
  7507. const struct br_style *cs, int depth,
  7508. unsigned short lk);
  7509. static void layout_flex_column(struct lay *l, unsigned int parent,
  7510. const struct br_style *pst, int depth,
  7511. unsigned short link);
  7512. static void emit_pseudo(struct lay *l, unsigned int node,
  7513. const struct br_style *st, int pe, unsigned short link);
  7514. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7515. {
  7516. unsigned int c;
  7517. int items = 0;
  7518. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7519. struct br_node *nd = &doc.nodes[c];
  7520. struct br_style cs;
  7521. if (nd->type == BR_NODE_TEXT)
  7522. continue;
  7523. br_style_for(&doc, c, pst, &cs);
  7524. if (cs.display == BR_DISPLAY_NONE)
  7525. continue;
  7526. /* `justify-content: space-between` spreads even two plain
  7527. * inline items (a "Password ... Reset password" label row)
  7528. * across the line; inline flow would set them side by side. */
  7529. if (++items >= 2 && pst->justify >= 3)
  7530. return 1;
  7531. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7532. cs.width_kind || cs.has_bg ||
  7533. cs.border_w[0] || cs.border_w[1] ||
  7534. cs.border_w[2] || cs.border_w[3] ||
  7535. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7536. return 1;
  7537. }
  7538. return 0;
  7539. }
  7540. static int css_radius(const struct br_style *st, int corner,
  7541. int w, int h)
  7542. {
  7543. int r = st->radius[corner];
  7544. if (r <= 0)
  7545. return 0;
  7546. if (r > w / 2)
  7547. r = w / 2;
  7548. if (r > h / 2)
  7549. r = h / 2;
  7550. return r;
  7551. }
  7552. /* ---- inline SVG ----
  7553. *
  7554. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7555. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7556. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7557. * opacity and solid paint; a gradient paints the average of its stops) and
  7558. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7559. #define SVG_CACHE_MAX 48
  7560. #define SVG_CACHE_PIXELS (640 * 1024)
  7561. #define SVG_MAX_POINTS 24576
  7562. struct svg_cache_ent {
  7563. unsigned int node;
  7564. int w, h;
  7565. unsigned short *px;
  7566. unsigned char *a;
  7567. unsigned int stamp;
  7568. };
  7569. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7570. static unsigned int svg_cache_pixels, svg_cache_clock;
  7571. static struct svgr svg_geom;
  7572. static void *svg_geom_buf;
  7573. /* Current viewport in user units: percentage lengths resolve against it
  7574. * (the viewBox size, not the device pixels). */
  7575. static double svg_vp_w = 300, svg_vp_h = 150;
  7576. /* The layers live in the page heap: forget them before heap_reset(). */
  7577. static void svg_cache_clear(void)
  7578. {
  7579. memset(svg_cache, 0, sizeof(svg_cache));
  7580. svg_cache_pixels = 0;
  7581. svg_geom_buf = 0;
  7582. }
  7583. static int svg_name_is(const char *a, const char *b)
  7584. {
  7585. while (*a && *b) {
  7586. char x = *a, y = *b;
  7587. if (x >= 'A' && x <= 'Z')
  7588. x = (char)(x - 'A' + 'a');
  7589. if (x != y)
  7590. return 0;
  7591. a++;
  7592. b++;
  7593. }
  7594. return *a == *b;
  7595. }
  7596. static const char *svg_elem_name(unsigned int node)
  7597. {
  7598. const struct br_node *nd = &doc.nodes[node];
  7599. if (nd->name_off)
  7600. return doc.attrs + nd->name_off;
  7601. return br_tag_name(nd->tag);
  7602. }
  7603. /* A numeric attribute; a percentage resolves against `base`. */
  7604. static double svg_attr_num(unsigned int node, const char *name, double def,
  7605. double base)
  7606. {
  7607. const char *v = br_find_attr(&doc, node, name);
  7608. const char *p = v;
  7609. int ok = 0;
  7610. double x;
  7611. if (!v)
  7612. return def;
  7613. x = svgr_num(&p, &ok);
  7614. if (!ok)
  7615. return def;
  7616. if (*p == '%')
  7617. x = x * base / 100.0;
  7618. return x;
  7619. }
  7620. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7621. static int svg_viewbox4(unsigned int node, double vb[4])
  7622. {
  7623. const char *v = br_find_attr(&doc, node, "viewbox");
  7624. const char *p = v;
  7625. int i, ok = 1;
  7626. if (!v)
  7627. return 0;
  7628. for (i = 0; i < 4 && ok; i++)
  7629. vb[i] = svgr_num(&p, &ok);
  7630. return ok && vb[2] > 0 && vb[3] > 0;
  7631. }
  7632. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7633. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7634. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7635. double w, double h, double m[6])
  7636. {
  7637. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7638. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7639. int ax = 1, ay = 1;
  7640. if (par && contains_ci(par, "none")) {
  7641. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7642. m[4] = -vb[0] * sx;
  7643. m[5] = -vb[1] * sy;
  7644. return;
  7645. }
  7646. if (par) {
  7647. if (contains_ci(par, "xmin"))
  7648. ax = 0;
  7649. else if (contains_ci(par, "xmax"))
  7650. ax = 2;
  7651. if (contains_ci(par, "ymin"))
  7652. ay = 0;
  7653. else if (contains_ci(par, "ymax"))
  7654. ay = 2;
  7655. }
  7656. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7657. (sx < sy ? sx : sy);
  7658. tx = (w - vb[2] * s) * ax / 2.0;
  7659. ty = (h - vb[3] * s) * ay / 2.0;
  7660. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7661. m[4] = tx - vb[0] * s;
  7662. m[5] = ty - vb[1] * s;
  7663. }
  7664. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7665. * the paint attribute, then average the gradient's stops. */
  7666. static int svg_url_paint(unsigned int node, const char *attr,
  7667. unsigned short *color, unsigned int *alpha)
  7668. {
  7669. const char *v = 0, *h;
  7670. char id[64];
  7671. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7672. for (k = 0; node && k < 32 && !v; k++) {
  7673. v = br_find_attr(&doc, node, attr);
  7674. if (!v) {
  7675. const char *style = br_find_attr(&doc, node, "style");
  7676. if (style && contains_ci(style, "url(#"))
  7677. v = strstr(style, "url(#");
  7678. }
  7679. if (v && !contains_ci(v, "url("))
  7680. v = 0;
  7681. node = doc.nodes[node].parent;
  7682. }
  7683. if (!v || !(h = strstr(v, "#")))
  7684. return 0;
  7685. h++;
  7686. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7687. id[n++] = *h++;
  7688. id[n] = '\0';
  7689. g = br_find_id(&doc, id);
  7690. /* Follow href chains (a gradient that only references another one's
  7691. * stops), at most a few hops. */
  7692. for (k = 0; g && k < 4; k++) {
  7693. unsigned int gi = g - 1;
  7694. const char *ref;
  7695. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7696. const char *nm, *sc, *so;
  7697. unsigned short col = 0;
  7698. double op = 1;
  7699. if (doc.nodes[c].type != BR_NODE_ELEM)
  7700. continue;
  7701. nm = svg_elem_name(c);
  7702. if (!svg_name_is(nm, "stop"))
  7703. continue;
  7704. sc = br_find_attr(&doc, c, "stop-color");
  7705. so = br_find_attr(&doc, c, "stop-opacity");
  7706. {
  7707. const char *st = br_find_attr(&doc, c, "style");
  7708. const char *q;
  7709. if (st && (q = strstr(st, "stop-color:")) != 0)
  7710. sc = q + 11;
  7711. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7712. so = q + 13;
  7713. }
  7714. if (sc) {
  7715. unsigned int L = 0;
  7716. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7717. L++;
  7718. if (!br_parse_color(sc, L, &col))
  7719. col = 0;
  7720. }
  7721. if (so) {
  7722. const char *p = so;
  7723. int ok = 0;
  7724. double x = svgr_num(&p, &ok);
  7725. if (ok)
  7726. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7727. }
  7728. sr += (col >> 11) & 31;
  7729. sg += (col >> 5) & 63;
  7730. sb += col & 31;
  7731. sa += (unsigned int)(op * 255);
  7732. cnt++;
  7733. }
  7734. if (cnt)
  7735. break;
  7736. ref = br_find_attr(&doc, gi, "href");
  7737. if (!ref)
  7738. ref = br_find_attr(&doc, gi, "xlink:href");
  7739. if (!ref || ref[0] != '#')
  7740. break;
  7741. g = br_find_id(&doc, ref + 1);
  7742. }
  7743. if (!cnt)
  7744. return 0;
  7745. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7746. (sb / cnt));
  7747. *alpha = sa / cnt;
  7748. return 1;
  7749. }
  7750. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7751. unsigned short *color, unsigned int *alpha)
  7752. {
  7753. int mode = fill ? st->fill_mode : st->stroke_mode;
  7754. const char *op = br_find_attr(&doc, node,
  7755. fill ? "fill-opacity" : "stroke-opacity");
  7756. *alpha = 255;
  7757. switch (mode) {
  7758. case BR_PAINT_UNSET:
  7759. if (!fill)
  7760. return 0;
  7761. *color = 0;
  7762. break;
  7763. case BR_PAINT_COLOR:
  7764. *color = fill ? st->fill : st->stroke;
  7765. break;
  7766. case BR_PAINT_CURRENT:
  7767. *color = st->color;
  7768. break;
  7769. case BR_PAINT_URL:
  7770. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7771. alpha))
  7772. return 0;
  7773. break;
  7774. default:
  7775. return 0;
  7776. }
  7777. if (op) {
  7778. const char *p = op;
  7779. int ok = 0;
  7780. double x = svgr_num(&p, &ok);
  7781. if (ok)
  7782. *alpha = (unsigned int)(*alpha *
  7783. (x < 0 ? 0 : x > 1 ? 1 : x));
  7784. }
  7785. return *alpha > 0;
  7786. }
  7787. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7788. const double m[6], const struct br_style *pst,
  7789. unsigned int alpha, int depth);
  7790. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7791. const double m[6], const struct br_style *st,
  7792. unsigned int alpha, int depth)
  7793. {
  7794. unsigned int c;
  7795. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7796. if (doc.nodes[c].type == BR_NODE_ELEM)
  7797. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7798. }
  7799. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7800. const double pm[6], const struct br_style *pst,
  7801. unsigned int alpha, int depth)
  7802. {
  7803. struct br_style st;
  7804. const char *nm = svg_elem_name(node);
  7805. const char *tf;
  7806. double m[6];
  7807. unsigned short color;
  7808. unsigned int pa;
  7809. int shape = 0, fillable = 1;
  7810. if (depth > 24 || !nm)
  7811. return;
  7812. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7813. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7814. svg_name_is(nm, "lineargradient") ||
  7815. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7816. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7817. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7818. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7819. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7820. svg_name_is(nm, "foreignobject"))
  7821. return;
  7822. br_style_for(&doc, node, pst, &st);
  7823. if (st.display == BR_DISPLAY_NONE)
  7824. return;
  7825. memcpy(m, pm, sizeof(m));
  7826. tf = br_find_attr(&doc, node, "transform");
  7827. if (tf)
  7828. svgr_transform(m, tf);
  7829. {
  7830. const char *op = br_find_attr(&doc, node, "opacity");
  7831. if (op) {
  7832. const char *p = op;
  7833. int ok = 0;
  7834. double x = svgr_num(&p, &ok);
  7835. if (ok)
  7836. alpha = (unsigned int)(alpha *
  7837. (x < 0 ? 0 :
  7838. x > 1 ? 1 : x));
  7839. }
  7840. }
  7841. if (!alpha)
  7842. return;
  7843. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7844. svg_name_is(nm, "switch")) {
  7845. svg_draw_children(L, node, m, &st, alpha, depth);
  7846. return;
  7847. }
  7848. if (svg_name_is(nm, "svg")) {
  7849. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7850. y = svg_attr_num(node, "y", 0, 0);
  7851. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7852. t[4] = x;
  7853. t[5] = y;
  7854. svgr_mat_mul(m, m, t);
  7855. double ow = svg_vp_w, oh = svg_vp_h;
  7856. if (svg_viewbox4(node, vb)) {
  7857. double w = svg_attr_num(node, "width", vb[2], ow);
  7858. double h = svg_attr_num(node, "height", vb[3], oh);
  7859. double vm[6];
  7860. svg_viewport_matrix(node, vb, w, h, vm);
  7861. svgr_mat_mul(m, m, vm);
  7862. svg_vp_w = vb[2];
  7863. svg_vp_h = vb[3];
  7864. }
  7865. svg_draw_children(L, node, m, &st, alpha, depth);
  7866. svg_vp_w = ow;
  7867. svg_vp_h = oh;
  7868. return;
  7869. }
  7870. if (svg_name_is(nm, "use")) {
  7871. const char *ref = br_find_attr(&doc, node, "href");
  7872. unsigned int tgt;
  7873. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7874. if (!ref)
  7875. ref = br_find_attr(&doc, node, "xlink:href");
  7876. if (!ref || ref[0] != '#')
  7877. return;
  7878. tgt = br_find_id(&doc, ref + 1);
  7879. if (!tgt || tgt - 1 == node)
  7880. return;
  7881. tgt--;
  7882. t[4] = svg_attr_num(node, "x", 0, 0);
  7883. t[5] = svg_attr_num(node, "y", 0, 0);
  7884. svgr_mat_mul(m, m, t);
  7885. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7886. double vb[4];
  7887. double ow = svg_vp_w, oh = svg_vp_h;
  7888. if (svg_viewbox4(tgt, vb)) {
  7889. /* A <use> without width/height sizes the
  7890. * symbol to 100% of the viewport: Docusaurus'
  7891. * 13.5px external-link icon references a
  7892. * 24-unit symbol and showed only its corner. */
  7893. double w = svg_attr_num(node, "width",
  7894. ow > 0 ? ow : vb[2], ow);
  7895. double h = svg_attr_num(node, "height",
  7896. oh > 0 ? oh : vb[3], oh);
  7897. double vm[6];
  7898. svg_viewport_matrix(tgt, vb, w, h, vm);
  7899. svgr_mat_mul(m, m, vm);
  7900. svg_vp_w = vb[2];
  7901. svg_vp_h = vb[3];
  7902. }
  7903. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7904. svg_vp_w = ow;
  7905. svg_vp_h = oh;
  7906. } else {
  7907. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7908. }
  7909. return;
  7910. }
  7911. svgr_reset(&svg_geom, m);
  7912. if (svg_name_is(nm, "path")) {
  7913. const char *d = br_find_attr(&doc, node, "d");
  7914. if (d) {
  7915. svgr_path(&svg_geom, d);
  7916. shape = 1;
  7917. }
  7918. } else if (svg_name_is(nm, "rect")) {
  7919. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7920. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7921. double rx = svg_attr_num(node, "rx", -1, w);
  7922. double ry = svg_attr_num(node, "ry", -1, h);
  7923. if (rx < 0)
  7924. rx = ry < 0 ? 0 : ry;
  7925. if (ry < 0)
  7926. ry = rx;
  7927. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7928. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7929. shape = 1;
  7930. } else if (svg_name_is(nm, "circle")) {
  7931. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7932. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7933. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7934. shape = 1;
  7935. } else if (svg_name_is(nm, "ellipse")) {
  7936. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7937. svg_attr_num(node, "cy", 0, svg_vp_h),
  7938. svg_attr_num(node, "rx", 0, svg_vp_w),
  7939. svg_attr_num(node, "ry", 0, svg_vp_h));
  7940. shape = 1;
  7941. } else if (svg_name_is(nm, "line")) {
  7942. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7943. svg_attr_num(node, "y1", 0, svg_vp_h));
  7944. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7945. svg_attr_num(node, "y2", 0, svg_vp_h));
  7946. shape = 1;
  7947. fillable = 0;
  7948. } else if (svg_name_is(nm, "polyline") ||
  7949. svg_name_is(nm, "polygon")) {
  7950. const char *pts = br_find_attr(&doc, node, "points");
  7951. if (pts) {
  7952. svgr_points(&svg_geom, pts,
  7953. svg_name_is(nm, "polygon"));
  7954. shape = 1;
  7955. }
  7956. }
  7957. if (!shape)
  7958. return;
  7959. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7960. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7961. st.fill_evenodd);
  7962. if (svg_paint(node, &st, 0, &color, &pa)) {
  7963. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7964. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7965. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7966. }
  7967. }
  7968. /* <text> elements: drawn straight onto the page every frame (the glyph
  7969. * renderer targets the ngui canvas, not a layer). x/y map through the
  7970. * accumulated transform; the font size scales with it. */
  7971. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7972. const double pm[6], const struct br_style *pst,
  7973. int ox, int oy, int depth)
  7974. {
  7975. unsigned int c;
  7976. if (depth > 24)
  7977. return;
  7978. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7979. struct br_style st;
  7980. const char *nm, *tf;
  7981. double m[6];
  7982. if (doc.nodes[c].type != BR_NODE_ELEM)
  7983. continue;
  7984. nm = svg_elem_name(c);
  7985. if (!nm || svg_name_is(nm, "defs") ||
  7986. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7987. svg_name_is(nm, "clippath"))
  7988. continue;
  7989. br_style_for(&doc, c, pst, &st);
  7990. if (st.display == BR_DISPLAY_NONE)
  7991. continue;
  7992. memcpy(m, pm, sizeof(m));
  7993. tf = br_find_attr(&doc, c, "transform");
  7994. if (tf)
  7995. svgr_transform(m, tf);
  7996. if (svg_name_is(nm, "text")) {
  7997. unsigned int t = doc.nodes[c].first;
  7998. const char *s;
  7999. unsigned int n, tw;
  8000. double x = svg_attr_num(c, "x", 0, 0),
  8001. y = svg_attr_num(c, "y", 0, 0);
  8002. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  8003. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  8004. int tx, ty, anchor;
  8005. unsigned short col;
  8006. unsigned int pa;
  8007. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  8008. continue;
  8009. if (px < 6)
  8010. px = 6;
  8011. if (px > 72)
  8012. px = 72;
  8013. if (!svg_paint(c, &st, 1, &col, &pa))
  8014. continue;
  8015. s = doc.text + doc.nodes[t].text_off;
  8016. n = doc.nodes[t].text_len;
  8017. st.font_px = (unsigned char)px;
  8018. tw = face_text_width(ui, &st, s, n);
  8019. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  8020. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  8021. ngui_text_ascent_face(ui, style_face(&st), px,
  8022. st.mono);
  8023. anchor = st.align;
  8024. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  8025. anchor = BR_ALIGN_CENTER;
  8026. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  8027. anchor = BR_ALIGN_RIGHT;
  8028. if (anchor == BR_ALIGN_CENTER)
  8029. tx -= (int)tw / 2;
  8030. else if (anchor == BR_ALIGN_RIGHT)
  8031. tx -= (int)tw;
  8032. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  8033. col, px, st.bold, st.italic,
  8034. st.mono);
  8035. } else {
  8036. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  8037. }
  8038. }
  8039. }
  8040. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  8041. {
  8042. double vb[4];
  8043. if (svg_viewbox4(node, vb)) {
  8044. svg_viewport_matrix(node, vb, w, h, m);
  8045. } else {
  8046. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  8047. }
  8048. }
  8049. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  8050. const struct br_style *st)
  8051. {
  8052. struct svg_cache_ent *e = 0;
  8053. struct svgr_layer L;
  8054. double m[6];
  8055. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  8056. svg_cache_clock++;
  8057. for (i = 0; i < SVG_CACHE_MAX; i++)
  8058. if (svg_cache[i].px && svg_cache[i].node == node &&
  8059. svg_cache[i].w == w && svg_cache[i].h == h) {
  8060. svg_cache[i].stamp = svg_cache_clock;
  8061. return &svg_cache[i];
  8062. }
  8063. if (need > SVG_CACHE_PIXELS)
  8064. return 0;
  8065. /* Evict least recently used layers until this one fits. */
  8066. for (;;) {
  8067. struct svg_cache_ent *lru = 0, *free_slot = 0;
  8068. for (i = 0; i < SVG_CACHE_MAX; i++) {
  8069. if (!svg_cache[i].px) {
  8070. if (!free_slot)
  8071. free_slot = &svg_cache[i];
  8072. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  8073. lru = &svg_cache[i];
  8074. }
  8075. }
  8076. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  8077. e = free_slot;
  8078. break;
  8079. }
  8080. if (!lru)
  8081. return 0;
  8082. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  8083. free(lru->px);
  8084. free(lru->a);
  8085. memset(lru, 0, sizeof(*lru));
  8086. }
  8087. if (!svg_geom_buf) {
  8088. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8089. if (!svg_geom_buf)
  8090. return 0;
  8091. }
  8092. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8093. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8094. e->a = (unsigned char *)calloc(need, 1);
  8095. if (!e->px || !e->a) {
  8096. free(e->px);
  8097. free(e->a);
  8098. memset(e, 0, sizeof(*e));
  8099. return 0;
  8100. }
  8101. e->node = node;
  8102. e->w = w;
  8103. e->h = h;
  8104. e->stamp = svg_cache_clock;
  8105. svg_cache_pixels += need;
  8106. L.px = e->px;
  8107. L.a = e->a;
  8108. L.w = w;
  8109. L.h = h;
  8110. svg_root_matrix(node, w, h, m);
  8111. {
  8112. double vb[4];
  8113. if (svg_viewbox4(node, vb)) {
  8114. svg_vp_w = vb[2];
  8115. svg_vp_h = vb[3];
  8116. } else {
  8117. svg_vp_w = w;
  8118. svg_vp_h = h;
  8119. }
  8120. }
  8121. svg_draw_children(&L, node, m, st, 255, 0);
  8122. return e;
  8123. }
  8124. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  8125. *
  8126. * The markup is parsed into a detached subtree of the page document and
  8127. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  8128. * bitmap, which then behaves like any decoded image. currentColor is
  8129. * black (an image has no inherited text colour); <text> is not drawn. */
  8130. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  8131. {
  8132. unsigned int i = 0;
  8133. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  8134. i = 3;
  8135. while (i < len) {
  8136. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  8137. d[i] == '\r' || d[i] == '\n'))
  8138. i++;
  8139. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  8140. return 1;
  8141. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  8142. i += 4;
  8143. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  8144. i++;
  8145. i += 3;
  8146. continue;
  8147. }
  8148. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  8149. while (i < len && d[i] != '>')
  8150. i++;
  8151. i++;
  8152. continue;
  8153. }
  8154. return 0;
  8155. }
  8156. return 0;
  8157. }
  8158. static int svg_len_attr(unsigned int node, const char *name)
  8159. {
  8160. const char *v = br_find_attr(&doc, node, name);
  8161. int n = 0, any = 0;
  8162. if (!v)
  8163. return 0;
  8164. while (*v == ' ')
  8165. v++;
  8166. while (*v >= '0' && *v <= '9') {
  8167. n = n * 10 + (*v++ - '0');
  8168. any = 1;
  8169. }
  8170. if (*v == '.')
  8171. while (*++v >= '0' && *v <= '9')
  8172. ;
  8173. if (!any || *v == '%')
  8174. return 0;
  8175. return n;
  8176. }
  8177. static int svg_decode_image(const unsigned char *data, unsigned int len,
  8178. struct br_image *bi, int box_w, int box_h)
  8179. {
  8180. unsigned int holder, svg = 0, c, need, i;
  8181. struct br_style base = base_style(), st;
  8182. struct svgr_layer L;
  8183. double vb[4], m[6];
  8184. int w, h, have_vb, nat_w, nat_h;
  8185. holder = br_create_element(&doc, "div", 3);
  8186. if (!holder) {
  8187. s_copy(bi->err, "page is full", sizeof(bi->err));
  8188. return -1;
  8189. }
  8190. holder--;
  8191. br_set_inner_html(&doc, holder, (const char *)data, len);
  8192. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  8193. if (doc.nodes[c].type == BR_NODE_ELEM &&
  8194. doc.nodes[c].tag == BR_TAG_SVG) {
  8195. svg = c;
  8196. break;
  8197. }
  8198. if (!svg) {
  8199. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  8200. return -1;
  8201. }
  8202. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  8203. w = svg_len_attr(svg, "width");
  8204. h = svg_len_attr(svg, "height");
  8205. if (box_w > 0 && box_h > 0) {
  8206. w = box_w;
  8207. h = box_h;
  8208. } else if (!w && !h) {
  8209. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  8210. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  8211. } else if (!w) {
  8212. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  8213. } else if (!h) {
  8214. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  8215. }
  8216. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  8217. * so CSS scaling stays crisp. */
  8218. nat_w = w;
  8219. nat_h = h;
  8220. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  8221. w *= 2;
  8222. h *= 2;
  8223. }
  8224. if (w > BR_IMG_LAYOUT_W) {
  8225. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  8226. w = BR_IMG_LAYOUT_W;
  8227. }
  8228. if (h > 2048)
  8229. h = 2048;
  8230. if (w < 1)
  8231. w = 1;
  8232. if (h < 1)
  8233. h = 1;
  8234. need = (unsigned int)w * (unsigned int)h;
  8235. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  8236. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  8237. return -1;
  8238. }
  8239. if (!svg_geom_buf) {
  8240. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  8241. if (!svg_geom_buf) {
  8242. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8243. return -1;
  8244. }
  8245. }
  8246. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  8247. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  8248. L.a = (unsigned char *)calloc(need, 1);
  8249. if (!L.px || !L.a) {
  8250. free(L.px);
  8251. free(L.a);
  8252. s_copy(bi->err, "out of memory", sizeof(bi->err));
  8253. return -1;
  8254. }
  8255. for (i = 0; i < need; i++)
  8256. L.px[i] = 0xFFFF;
  8257. L.w = w;
  8258. L.h = h;
  8259. base.color = 0x0000;
  8260. br_style_for(&doc, svg, &base, &st);
  8261. svg_root_matrix(svg, w, h, m);
  8262. if (!have_vb && nat_w > 0 && nat_h > 0) {
  8263. /* No viewBox: user units are CSS pixels of the natural size,
  8264. * so the up-to-4x raster (and a box size) must scale them.
  8265. * A 40x20 icon used to fill only the top-left quarter of its
  8266. * 160x80 bitmap and was drawn at a quarter of its size. */
  8267. m[0] = (double)w / nat_w;
  8268. m[3] = (double)h / nat_h;
  8269. }
  8270. svg_vp_w = have_vb ? vb[2] : nat_w;
  8271. svg_vp_h = have_vb ? vb[3] : nat_h;
  8272. svg_draw_children(&L, svg, m, &st, 255, 0);
  8273. bi->native_w = nat_w;
  8274. bi->native_h = nat_h;
  8275. bi->img.format = 0;
  8276. bi->img.w = (unsigned int)w;
  8277. bi->img.h = (unsigned int)h;
  8278. bi->img.px = L.px;
  8279. bi->img.alpha = L.a;
  8280. bi->img.flags = 0;
  8281. bi->state = 1;
  8282. image_pixels += need;
  8283. return 0;
  8284. }
  8285. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  8286. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  8287. int *out_w, int *out_h)
  8288. {
  8289. double vb[4];
  8290. int has_vb = svg_viewbox4(node, vb);
  8291. double aw = svg_attr_num(node, "width", -1, cw);
  8292. double ah = svg_attr_num(node, "height", -1, 0);
  8293. int w, h;
  8294. if (st->width_kind)
  8295. w = cw;
  8296. else if (aw > 0)
  8297. w = (int)(aw + 0.5);
  8298. else if (st->height_kind == 1 && has_vb)
  8299. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  8300. else if (ah > 0 && has_vb)
  8301. w = (int)(ah * vb[2] / vb[3] + 0.5);
  8302. else if (has_vb)
  8303. w = cw;
  8304. else
  8305. w = 300;
  8306. if (st->max_width_kind == 1 && w > st->max_width)
  8307. w = st->max_width;
  8308. if (w > cw && cw > 0 && !(aw > 0))
  8309. w = cw;
  8310. if (w < 1)
  8311. w = 1;
  8312. if (w > 2000)
  8313. w = 2000;
  8314. if (st->height_kind == 1)
  8315. h = st->height;
  8316. else if (ah > 0)
  8317. h = (int)(ah + 0.5);
  8318. else if (has_vb)
  8319. h = (int)(w * vb[3] / vb[2] + 0.5);
  8320. else
  8321. h = 150;
  8322. if (h < 1)
  8323. h = 1;
  8324. if (h > 1400)
  8325. h = 1400;
  8326. *out_w = w;
  8327. *out_h = h;
  8328. }
  8329. static void svg_paint_box(struct ngui *ui, unsigned int node,
  8330. const struct br_style *st, int x, int y, int w, int h)
  8331. {
  8332. struct svg_cache_ent *e;
  8333. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  8334. int cx0, cy0, cx1, cy1, px, py;
  8335. double m[6];
  8336. if (ui->nclip > 0)
  8337. clip = ui->clip[ui->nclip - 1];
  8338. cx0 = r.x > clip.x ? r.x : clip.x;
  8339. cy0 = r.y > clip.y ? r.y : clip.y;
  8340. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  8341. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  8342. if (cx0 >= cx1 || cy0 >= cy1)
  8343. return;
  8344. e = svg_layer(node, w, h, st);
  8345. if (e) {
  8346. for (py = cy0; py < cy1; py++) {
  8347. unsigned int srow = (unsigned int)(py - y) *
  8348. (unsigned int)w;
  8349. unsigned short *dst = ui->px + py * ui->w;
  8350. for (px = cx0; px < cx1; px++) {
  8351. unsigned int si = srow + (unsigned int)(px - x);
  8352. unsigned int a = e->a[si];
  8353. if (!a)
  8354. continue;
  8355. dst[px] = a >= 255 ? e->px[si] :
  8356. blend_rgb565(dst[px], e->px[si], a);
  8357. }
  8358. }
  8359. }
  8360. svg_root_matrix(node, w, h, m);
  8361. ngui_push_clip(ui, r);
  8362. svg_draw_text(ui, node, m, st, x, y, 0);
  8363. ngui_pop_clip(ui);
  8364. }
  8365. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  8366. * keep using add_image_run(); this covers the CSS `position:absolute;
  8367. * width:100%` poster pattern used by news sites. */
  8368. static void image_block_size(unsigned int node, const struct br_style *st,
  8369. int cbw, int *out_w, int *out_h)
  8370. {
  8371. struct br_node *nd = &doc.nodes[node];
  8372. int idx = nd->img_index;
  8373. int iw = 0, ih = 0, w, h, aw, ah;
  8374. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8375. iw = (int)images[idx].img.w;
  8376. ih = (int)images[idx].img.h;
  8377. if (iw <= 0 || ih <= 0) {
  8378. iw = (int)images[idx].native_w;
  8379. ih = (int)images[idx].native_h;
  8380. }
  8381. }
  8382. if (st->width_kind)
  8383. w = style_width_px(st, cbw);
  8384. else if (nd->width_attr)
  8385. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  8386. (int)nd->width_attr;
  8387. else if (nd->height_attr && !nd->height_pct && iw && ih)
  8388. w = iw * (int)nd->height_attr / ih;
  8389. else if (iw)
  8390. w = iw;
  8391. else
  8392. w = 64;
  8393. /* max-width/min-width against the containing block: Tailwind's
  8394. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  8395. * 300x300 thumbnail to its 75 px avatar box. */
  8396. if (st->max_width_kind) {
  8397. int mw = st->max_width_kind == 3 ?
  8398. cbw * st->max_width_calc_pct / 100 +
  8399. st->max_width_calc_px :
  8400. st->max_width_kind == 2 ?
  8401. cbw * (int)st->max_width / 100 : (int)st->max_width;
  8402. if (mw > 0 && w > mw)
  8403. w = mw;
  8404. }
  8405. if (st->min_width_kind) {
  8406. int mn = st->min_width_kind == 3 ?
  8407. cbw * st->min_width_calc_pct / 100 +
  8408. st->min_width_calc_px :
  8409. st->min_width_kind == 2 ?
  8410. cbw * (int)st->min_width / 100 : (int)st->min_width;
  8411. if (mn > w)
  8412. w = mn;
  8413. }
  8414. if (w < 8)
  8415. w = 8;
  8416. if (cbw > 0 && w > cbw)
  8417. w = cbw;
  8418. /* Without a CSS height the attributes (or the bitmap) only give the
  8419. * aspect ratio: a width clamped by max-width scales the height too,
  8420. * instead of letterboxing the image into its attribute height. */
  8421. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  8422. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  8423. if (st->height_kind)
  8424. h = style_height_px(st, cbw);
  8425. else if (aw > 0 && ah > 0)
  8426. h = w * ah / aw;
  8427. else if (nd->height_attr)
  8428. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  8429. (int)nd->height_attr;
  8430. else
  8431. h = 64;
  8432. if (h < 8)
  8433. h = 8;
  8434. *out_w = w;
  8435. *out_h = h;
  8436. }
  8437. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  8438. int dw, int dh)
  8439. {
  8440. int idx = doc.nodes[node].img_index;
  8441. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  8442. struct img_image *src = image_display_get(&images[idx], dw, dh);
  8443. struct img_blit b;
  8444. if (!src)
  8445. src = &images[idx].img;
  8446. b.dst = l->ui->px;
  8447. b.dst_w = l->ui->w;
  8448. b.dst_h = l->ui->h;
  8449. b.clip_x = page_rect.x;
  8450. b.clip_y = page_rect.y;
  8451. b.clip_w = page_rect.w - 12;
  8452. b.clip_h = page_rect.h;
  8453. b.x = x;
  8454. b.y = y;
  8455. b.scale = ((unsigned int)dw << 16) / src->w;
  8456. b.bg = ui.theme.bg;
  8457. b.bg2 = ui.theme.bg;
  8458. b.dst_a = 0;
  8459. /* OVER_DST is only needed for an alpha source; an opaque one can
  8460. * take img_draw's 1:1 copy path. */
  8461. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  8462. img_draw(src, &b);
  8463. } else if (l->draw) {
  8464. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  8465. 0xD69A);
  8466. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  8467. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  8468. }
  8469. }
  8470. static void layout_block(struct lay *l, unsigned int node,
  8471. const struct br_style *st, int depth,
  8472. unsigned short link)
  8473. {
  8474. int old_left = l->left, old_right = l->right, old_align = l->align;
  8475. int parent_cb_h = l->cb_h;
  8476. int saved_parent_top = l->parent_top;
  8477. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  8478. int saved_cb_top = l->cb_top;
  8479. int top, l0, r0;
  8480. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  8481. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  8482. int deco_w, deco_h, content_w, content_h, box_h;
  8483. int img_dh = 0;
  8484. int definite_w = 0;
  8485. int normal_top = 0;
  8486. int rel_dx = 0, rel_dy = 0;
  8487. int clip_pushed = 0;
  8488. struct ngui_rect clip_rect;
  8489. /* A DOM level costs about two depth units (layout_block ->
  8490. * layout_children), so 48 covers a ~24-level page. Real news pages
  8491. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8492. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8493. return;
  8494. flow_y = l->y;
  8495. flow_left = l->left;
  8496. flow_right = l->right;
  8497. positioned = st->pos == 1 || st->pos == 2;
  8498. relative = st->pos == 3;
  8499. sticky = st->pos == 4;
  8500. shifted = relative || sticky || st->transform_set;
  8501. if (positioned) {
  8502. int def_w = st->width_kind == 1 ? st->width : -1;
  8503. if (st->pos == 2) {
  8504. int avail_w = page_rect.w - 12;
  8505. if (st->right_set && def_w >= 0)
  8506. l->left = page_rect.x + avail_w - st->right -
  8507. def_w;
  8508. else if (!st->left_set && !st->right_set)
  8509. l->left = flow_left; /* static position */
  8510. else
  8511. l->left = page_rect.x +
  8512. (st->left_set ? st->left : 0);
  8513. l->right = def_w >= 0 ? l->left + def_w :
  8514. st->width_kind == 2 ?
  8515. l->left + avail_w * (int)st->width / 100 :
  8516. page_rect.x + avail_w;
  8517. /* Placed by `bottom` (a page footer): an auto
  8518. * height is the measured one. */
  8519. if (st->bottom_set && st->height_kind)
  8520. l->y = page_rect.y + page_rect.h -
  8521. st->bottom -
  8522. style_height_px(st, page_rect.w);
  8523. else if (st->bottom_set && !st->top_set &&
  8524. block_h[node])
  8525. l->y = page_rect.y + page_rect.h -
  8526. st->bottom - (int)block_h[node] -
  8527. mp_px(st, 0, avail_w) -
  8528. mp_px(st, 2, avail_w);
  8529. else
  8530. l->y = page_rect.y +
  8531. (st->top_set ? st->top : 0);
  8532. } else {
  8533. int left = flow_left + (st->left_set ? st->left : 0);
  8534. unsigned int parent = doc.nodes[node].parent;
  8535. if (st->right_set && def_w >= 0)
  8536. left = flow_right - st->right - def_w;
  8537. l->left = left;
  8538. l->right = def_w >= 0 ? left + def_w :
  8539. flow_right +
  8540. (st->left_set ? st->left : 0);
  8541. l->y = flow_y + (st->top_set ? st->top : 0);
  8542. if (st->bottom_set && st->height_kind &&
  8543. parent < BR_MAX_NODES && block_h[parent] > 0)
  8544. l->y = flow_y + block_h[parent] - st->bottom -
  8545. style_height_px(st, old_right - old_left);
  8546. else if (st->bottom_set && !st->top_set &&
  8547. parent < BR_MAX_NODES && block_h[parent] > 0 &&
  8548. block_h[node] > 0)
  8549. l->y = flow_y + block_h[parent] - st->bottom -
  8550. (int)block_h[node] -
  8551. mp_px(st, 0, old_right - old_left) -
  8552. mp_px(st, 2, old_right - old_left);
  8553. }
  8554. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8555. * content" link) past the containing block's right edge
  8556. * until it is focused. An auto width then has no room: it
  8557. * used to collapse to 8 px and wrap one word per line into a
  8558. * tall column painted over the page. Lay it out at the
  8559. * containing block's width so it stays one line and
  8560. * overflows (off-screen) like in a real browser. */
  8561. if (def_w < 0 && l->right - l->left < 8) {
  8562. int avail = st->pos == 2 ? page_rect.w - 12 :
  8563. flow_right - flow_left;
  8564. l->right = l->left + (avail > 8 ? avail : 8);
  8565. }
  8566. old_left = l->left;
  8567. old_right = l->right;
  8568. } else if (relative) {
  8569. rel_dx = st->left_set ? st->left :
  8570. (st->right_set ? -st->right : 0);
  8571. rel_dy = st->top_set ? st->top :
  8572. (st->bottom_set ? -st->bottom : 0);
  8573. }
  8574. if (st->transform_set) {
  8575. rel_dx += st->tx;
  8576. rel_dy += st->ty;
  8577. }
  8578. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8579. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8580. doc.nodes[node].tag == BR_TAG_SELECT ||
  8581. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8582. !button_has_elements(node)) {
  8583. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8584. s_eq(br_type(&doc, node), "hidden"))
  8585. return;
  8586. /* Reached as a block-level box (a flex item): the control
  8587. * fills the box the caller assigned, and its line is flushed
  8588. * here; flex layout resets the run list for the next item, so
  8589. * a queued run would never be drawn. */
  8590. form_fill_line = 1;
  8591. add_form_run(l, node, st, link);
  8592. form_fill_line = 0;
  8593. flush_line(l);
  8594. return;
  8595. }
  8596. flush_line(l);
  8597. cbw = old_right - old_left;
  8598. if (cbw < 8)
  8599. cbw = 8;
  8600. l->y += mp_px(st, 0, cbw);
  8601. top = l->y;
  8602. ml = mp_px(st, 3, cbw);
  8603. mr = mp_px(st, 1, cbw);
  8604. bl = st->border_w[3];
  8605. br = st->border_w[1];
  8606. pl = mp_px(st, 7, cbw);
  8607. pr = mp_px(st, 5, cbw);
  8608. bt = st->border_w[0];
  8609. bb = st->border_w[2];
  8610. pt = mp_px(st, 4, cbw);
  8611. pb = mp_px(st, 6, cbw);
  8612. deco_w = bl + br + pl + pr;
  8613. deco_h = bt + bb + pt + pb;
  8614. if (st->width_kind) {
  8615. int w;
  8616. if (st->width_kind == 3)
  8617. w = cbw * st->width_calc_pct / 100 +
  8618. st->width_calc_px;
  8619. else
  8620. w = css_size(st->width_kind, st->width, cbw);
  8621. if (w < 0)
  8622. w = 0;
  8623. content_w = st->box_sizing ? w - deco_w : w;
  8624. definite_w = 1;
  8625. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8626. doc.nodes[node].tag == BR_TAG_TD ||
  8627. doc.nodes[node].tag == BR_TAG_TH) &&
  8628. doc.nodes[node].width_attr) {
  8629. /* Legacy table/cell width attributes: percentages resolve
  8630. * against the containing block, bare numbers are pixels. */
  8631. int w = doc.nodes[node].width_pct ?
  8632. cbw * doc.nodes[node].width_attr / 100 :
  8633. doc.nodes[node].width_attr;
  8634. if (w < 0)
  8635. w = 0;
  8636. content_w = st->box_sizing ? w - deco_w : w;
  8637. definite_w = 1;
  8638. } else {
  8639. content_w = cbw - ml - mr - deco_w;
  8640. }
  8641. if (content_w < 0)
  8642. content_w = 0;
  8643. if (st->max_width_kind) {
  8644. int mw = st->max_width_kind == 3 ?
  8645. cbw * st->max_width_calc_pct / 100 +
  8646. st->max_width_calc_px :
  8647. css_size(st->max_width_kind, st->max_width, cbw);
  8648. int max_box = st->box_sizing ? mw : mw + deco_w;
  8649. /* A clamped auto width is used as the width, so auto
  8650. * margins share the rest (Google's 688 px search box). */
  8651. if (content_w + deco_w > max_box) {
  8652. content_w = max_box - deco_w;
  8653. definite_w = 1;
  8654. }
  8655. }
  8656. if (st->min_width_kind) {
  8657. int mw = st->min_width_kind == 3 ?
  8658. cbw * st->min_width_calc_pct / 100 +
  8659. st->min_width_calc_px :
  8660. css_size(st->min_width_kind, st->min_width, cbw);
  8661. int min_box = st->box_sizing ? mw : mw + deco_w;
  8662. if (content_w + deco_w < min_box) {
  8663. content_w = min_box - deco_w;
  8664. definite_w = 1;
  8665. }
  8666. }
  8667. if (content_w < 8)
  8668. content_w = 8;
  8669. if (definite_w) {
  8670. int free_w = cbw - ml - mr - deco_w - content_w;
  8671. if (free_w < 0)
  8672. free_w = 0;
  8673. if (st->ml_auto && st->mr_auto) {
  8674. ml = free_w / 2;
  8675. mr = free_w - ml;
  8676. } else if (st->ml_auto) {
  8677. ml = free_w;
  8678. } else if (st->mr_auto) {
  8679. mr = free_w;
  8680. }
  8681. }
  8682. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8683. int iw, ih;
  8684. image_block_size(node, st, cbw, &iw, &ih);
  8685. content_w = iw;
  8686. img_dh = ih;
  8687. }
  8688. l0 = old_left + ml;
  8689. r0 = l0 + deco_w + content_w;
  8690. if (r0 < l0 + 8)
  8691. r0 = l0 + 8;
  8692. normal_top = top;
  8693. if (sticky) {
  8694. if (st->top_set) {
  8695. int stick = page_rect.y + st->top;
  8696. if (normal_top < stick)
  8697. rel_dy += stick - normal_top;
  8698. } else if (st->bottom_set && block_h[node]) {
  8699. int stick = page_rect.y + page_rect.h - st->bottom -
  8700. block_h[node];
  8701. if (normal_top > stick)
  8702. rel_dy += stick - normal_top;
  8703. }
  8704. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8705. block_h[doc.nodes[node].parent]) {
  8706. unsigned int p = doc.nodes[node].parent;
  8707. int ptop = l->parent_top;
  8708. int pbottom = ptop + block_h[p];
  8709. int eh = block_h[node];
  8710. int moved_top = normal_top + rel_dy;
  8711. int moved_bottom = moved_top + eh;
  8712. if (moved_bottom > pbottom)
  8713. rel_dy -= moved_bottom - pbottom;
  8714. moved_top = normal_top + rel_dy;
  8715. if (moved_top < ptop)
  8716. rel_dy += ptop - moved_top;
  8717. }
  8718. }
  8719. if (shifted && l->draw) {
  8720. top += rel_dy;
  8721. l0 += rel_dx;
  8722. r0 += rel_dx;
  8723. }
  8724. l->parent_top = top;
  8725. if (st->pos != 0) {
  8726. /* Positioned boxes establish the containing block for their
  8727. * absolutely positioned descendants. */
  8728. l->cb_left = l0;
  8729. l->cb_right = r0;
  8730. l->cb_top = top;
  8731. }
  8732. if (l->draw && block_h[node] &&
  8733. top < page_rect.y + page_rect.h &&
  8734. top + block_h[node] > page_rect.y) {
  8735. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8736. int rtl = css_radius(st, 0, box.w, box.h);
  8737. int rtr = css_radius(st, 1, box.w, box.h);
  8738. int rbr = css_radius(st, 2, box.w, box.h);
  8739. int rbl = css_radius(st, 3, box.w, box.h);
  8740. if (st->transform_scale) {
  8741. if (st->has_bg)
  8742. fill_transformed_rect(l->ui, box, st->bg, st);
  8743. } else if (rtl || rtr || rbr || rbl) {
  8744. if (st->has_bg) {
  8745. int bw = st->border_w[0];
  8746. if (bw > 0 && !st->border_t[0] &&
  8747. st->border_c[0] != st->bg &&
  8748. box.w > bw * 2 && box.h > bw * 2) {
  8749. struct ngui_rect inner = {
  8750. box.x + bw, box.y + bw,
  8751. box.w - bw * 2, box.h - bw * 2
  8752. };
  8753. int itl = rtl > bw ? rtl - bw : 0;
  8754. int itr = rtr > bw ? rtr - bw : 0;
  8755. int ibr = rbr > bw ? rbr - bw : 0;
  8756. int ibl = rbl > bw ? rbl - bw : 0;
  8757. ngui_fill_round_rect(l->ui, box, rtl,
  8758. rtr, rbr, rbl,
  8759. st->border_c[0]);
  8760. ngui_fill_round_rect(l->ui, inner,
  8761. itl, itr, ibr,
  8762. ibl, st->bg);
  8763. } else {
  8764. ngui_fill_round_rect(l->ui, box, rtl,
  8765. rtr, rbr, rbl,
  8766. st->bg);
  8767. }
  8768. } else if (st->border_w[0] && !st->border_t[0]) {
  8769. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8770. rbl, st->border_w[0],
  8771. st->border_c[0]);
  8772. }
  8773. /* Rounded boxes paint their background image too
  8774. * (app icons are rounded squares), kept inside the
  8775. * corner arcs. */
  8776. if (st->bg_image)
  8777. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8778. rbr, rbl);
  8779. } else {
  8780. if (st->has_bg)
  8781. ngui_fill_rect(l->ui, box, st->bg);
  8782. if (st->bg_image)
  8783. draw_bg_image(l, box, node, st);
  8784. if (st->border_w[0] || st->border_w[1] ||
  8785. st->border_w[2] || st->border_w[3])
  8786. draw_border_box(l->ui, box, st);
  8787. }
  8788. }
  8789. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8790. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8791. content_w, img_dh);
  8792. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8793. l->ui && l->ui->nclip < 4) {
  8794. clip_rect.x = l0 + bl;
  8795. clip_rect.y = top + bt;
  8796. clip_rect.w = (r0 - l0) - bl - br;
  8797. clip_rect.h = (int)block_h[node] - bt - bb;
  8798. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8799. ngui_push_clip(l->ui, clip_rect);
  8800. clip_pushed = 1;
  8801. }
  8802. }
  8803. l->left = l0 + bl + pl;
  8804. l->right = l->left + content_w;
  8805. if (l->right < l->left + 8)
  8806. l->right = l->left + 8;
  8807. l->align = st->align;
  8808. l->line_left = l->left;
  8809. l->line_right = l->right;
  8810. l->y = top + bt + pt;
  8811. if (doc.nodes[node].tag == BR_TAG_HR) {
  8812. if (l->draw)
  8813. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8814. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8815. l->y += 8;
  8816. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8817. int vw = l->right - l->left;
  8818. int vh;
  8819. if (doc.nodes[node].width_pct)
  8820. vw = vw * doc.nodes[node].width_attr / 100;
  8821. else if (doc.nodes[node].width_attr)
  8822. vw = doc.nodes[node].width_attr;
  8823. if (vw > l->right - l->left)
  8824. vw = l->right - l->left;
  8825. if (vw < 8)
  8826. vw = 8;
  8827. vh = vw * 9 / 16;
  8828. if (vh > 240)
  8829. vh = 240;
  8830. if (vh < 80)
  8831. vh = 80;
  8832. if (l->draw) {
  8833. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8834. vw, vh}, 0xD69A);
  8835. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8836. vw, vh}, 0x8410);
  8837. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8838. 0x4208);
  8839. }
  8840. l->y += vh + 4;
  8841. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8842. int dw, dh, cw = l->right - l->left;
  8843. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8844. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8845. l->y + dh > page_rect.y)
  8846. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8847. l->y += dh;
  8848. } else {
  8849. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8850. !st->no_bullet) {
  8851. char *m = li_marker[node];
  8852. if (!m[0]) {
  8853. unsigned int parent = doc.nodes[node].parent;
  8854. int style = st->list_style;
  8855. int idx = parent ? list_index(parent, node) : 1;
  8856. if (style == BR_LIST_AUTO)
  8857. style = (parent &&
  8858. doc.nodes[parent].tag ==
  8859. BR_TAG_OL) ?
  8860. BR_LIST_DECIMAL : BR_LIST_DISC;
  8861. list_marker_text(m, sizeof(li_marker[node]),
  8862. style, idx);
  8863. }
  8864. if (l->draw && m[0]) {
  8865. int mw = (int)ngui_text_width_ui(l->ui, m);
  8866. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8867. st->color);
  8868. }
  8869. }
  8870. /* This box's definite content height, for its children's
  8871. * percentage heights. */
  8872. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8873. doc.nodes[node].tag == BR_TAG_BODY)
  8874. l->cb_h = layout_view_h;
  8875. else if (st->height_kind == 1)
  8876. l->cb_h = (int)st->height -
  8877. (st->box_sizing ? deco_h : 0);
  8878. else if (st->height_kind == 2 && parent_cb_h > 0)
  8879. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8880. (st->box_sizing ? deco_h : 0);
  8881. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8882. l->cb_h = content_w * (int)st->aspect_h /
  8883. (int)st->aspect_w;
  8884. else if (!st->height_kind && node < BR_MAX_NODES &&
  8885. flex_stretch_h[node] > deco_h)
  8886. l->cb_h = flex_stretch_h[node] - deco_h;
  8887. else
  8888. l->cb_h = 0;
  8889. if (l->cb_h < 0)
  8890. l->cb_h = 0;
  8891. if (doc.nodes[node].tag == BR_TAG_TR)
  8892. layout_table_row(l, node, st, depth + 1, link);
  8893. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8894. table_has_rowspan(node))
  8895. layout_table(l, node, st, depth + 1, link);
  8896. else if (st->grid_auto)
  8897. layout_grid_auto(l, node, st, depth + 1, link);
  8898. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8899. st->grid_gap > 0)
  8900. layout_grid_children(l, node, st, depth + 1, link);
  8901. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8902. flex_wants_row(node, st))
  8903. layout_flex_children(l, node, st, depth + 1, link);
  8904. else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
  8905. layout_flex_column(l, node, st, depth + 1, link);
  8906. else
  8907. layout_children(l, node, st, depth + 1, link);
  8908. l->cb_h = parent_cb_h;
  8909. }
  8910. flush_line(l);
  8911. if (clip_pushed)
  8912. ngui_pop_clip(l->ui);
  8913. if (l->float_active) {
  8914. if (l->y < l->float_bottom)
  8915. l->y = l->float_bottom;
  8916. l->float_active = 0;
  8917. }
  8918. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8919. content_h = img_dh;
  8920. } else if (st->height_kind == 2 &&
  8921. doc.nodes[node].tag != BR_TAG_HTML &&
  8922. doc.nodes[node].tag != BR_TAG_BODY) {
  8923. /* A percentage of the containing block's definite height, or
  8924. * auto when it has none (it used to resolve against the
  8925. * width). The result is a minimum: without scrollable inner
  8926. * boxes, an app shell's height:100%; overflow:hidden column
  8927. * would otherwise clip everything past the first screen. */
  8928. int auto_h = l->y - (top + bt + pt);
  8929. content_h = parent_cb_h > 0 ?
  8930. parent_cb_h * (int)st->height / 100 -
  8931. (st->box_sizing ? deco_h : 0) : 0;
  8932. if (content_h < auto_h)
  8933. content_h = auto_h;
  8934. } else if (st->height_kind &&
  8935. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8936. doc.nodes[node].tag == BR_TAG_BODY) &&
  8937. st->height_kind == 2)) {
  8938. content_h = style_height_px(st, cbw);
  8939. if (st->box_sizing)
  8940. content_h -= deco_h;
  8941. } else {
  8942. /* Percentage heights on html/body resolve against the
  8943. * viewport, but their content still defines the document
  8944. * scroll height. Treating them as auto avoids collapsing
  8945. * the measured page to the containing block width. */
  8946. content_h = l->y - (top + bt + pt);
  8947. /* aspect-ratio: the preferred height of an auto-height box
  8948. * (Tailwind aspect-video image frames); content can still
  8949. * make it taller, as with min-height: auto. */
  8950. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8951. int ah = content_w * (int)st->aspect_h /
  8952. (int)st->aspect_w;
  8953. if (content_h < ah)
  8954. content_h = ah;
  8955. }
  8956. }
  8957. if (content_h < 0)
  8958. content_h = 0;
  8959. if (!st->height_kind && node < BR_MAX_NODES &&
  8960. content_h + deco_h < flex_stretch_h[node])
  8961. content_h = flex_stretch_h[node] - deco_h;
  8962. if (st->max_height_kind) {
  8963. int mh = st->max_height_kind == 3 ?
  8964. cbw * st->max_height_calc_pct / 100 +
  8965. st->max_height_calc_px :
  8966. css_size(st->max_height_kind, st->max_height, cbw);
  8967. int max_box = st->box_sizing ? mh : mh + deco_h;
  8968. if (content_h + deco_h > max_box)
  8969. content_h = max_box - deco_h;
  8970. }
  8971. if (st->min_height_kind &&
  8972. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8973. doc.nodes[node].tag == BR_TAG_BODY) &&
  8974. st->min_height_kind == 2)) {
  8975. int mh = st->min_height_kind == 3 ?
  8976. cbw * st->min_height_calc_pct / 100 +
  8977. st->min_height_calc_px :
  8978. css_size(st->min_height_kind, st->min_height, cbw);
  8979. int min_box = st->box_sizing ? mh : mh + deco_h;
  8980. if (content_h + deco_h < min_box)
  8981. content_h = min_box - deco_h;
  8982. }
  8983. if (content_h < 0)
  8984. content_h = 0;
  8985. box_h = deco_h + content_h;
  8986. if (box_h < 0)
  8987. box_h = 0;
  8988. l->y = (shifted ? normal_top : top) + box_h;
  8989. if (node < BR_MAX_NODES) {
  8990. layout_boxes[node].x = l0;
  8991. layout_boxes[node].y = top;
  8992. layout_boxes[node].w = r0 - l0;
  8993. layout_boxes[node].h = box_h;
  8994. layout_boxes[node].valid = r0 > l0;
  8995. }
  8996. l->left = old_left;
  8997. l->right = old_right;
  8998. l->align = old_align;
  8999. l->y += mp_px(st, 2, cbw);
  9000. if (!l->draw) {
  9001. if (box_h > 65535)
  9002. box_h = 65535;
  9003. block_h[node] = (unsigned short)box_h;
  9004. block_top[node] = (unsigned short)(top < 0 ? 0 :
  9005. top > 65535 ? 65535 : top);
  9006. }
  9007. if (positioned) {
  9008. l->y = flow_y;
  9009. l->left = flow_left;
  9010. l->right = flow_right;
  9011. }
  9012. l->parent_top = saved_parent_top;
  9013. l->cb_left = saved_cb_left;
  9014. l->cb_right = saved_cb_right;
  9015. l->cb_top = saved_cb_top;
  9016. }
  9017. static int text_node_blank(const struct br_node *nd)
  9018. {
  9019. const char *t = doc.text + nd->text_off;
  9020. unsigned int i;
  9021. for (i = 0; i < nd->text_len; i++)
  9022. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  9023. t[i] != '\r')
  9024. return 0;
  9025. return 1;
  9026. }
  9027. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  9028. * text/image widths in the subtree, plus padding and margins. This keeps
  9029. * Bootstrap's floated nav items on one line instead of giving each the whole
  9030. * row. */
  9031. static int text_space(char c)
  9032. {
  9033. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  9034. }
  9035. static int intrinsic_width(struct ngui *ui, unsigned int node,
  9036. const struct br_style *pst, int depth, int base)
  9037. {
  9038. unsigned int c;
  9039. int line_w = 0, max_w = 0;
  9040. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  9041. if (depth > 32)
  9042. return 0;
  9043. if (doc.npe_rules) {
  9044. struct br_style ps;
  9045. /* Icon boxes (::before/::after with a size) are inline
  9046. * content of the element. */
  9047. line_w += pseudo_box_w(node, pst, 1, &ps, base) +
  9048. pseudo_box_w(node, pst, 2, &ps, base);
  9049. }
  9050. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9051. struct br_node *nd = &doc.nodes[c];
  9052. struct br_style cs;
  9053. if (nd->type == BR_NODE_TEXT) {
  9054. const char *t = doc.text + nd->text_off;
  9055. unsigned int tn = nd->text_len;
  9056. if (doc.nodes[node].tag == BR_TAG_PRE) {
  9057. line_w += (int)face_text_width(ui, pst, t, tn);
  9058. } else {
  9059. unsigned int ti = 0;
  9060. int first = 1;
  9061. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  9062. int sp = (int)face_text_width(ui, pst, " ", 1);
  9063. while (ti < tn) {
  9064. unsigned int ts;
  9065. while (ti < tn && text_space(t[ti]))
  9066. ti++;
  9067. ts = ti;
  9068. while (ti < tn && !text_space(t[ti]))
  9069. ti++;
  9070. if (ti == ts)
  9071. break;
  9072. if (!first || lead)
  9073. line_w += sp;
  9074. lead = 0;
  9075. line_w += (int)face_text_width(ui, pst,
  9076. t + ts, ti - ts);
  9077. first = 0;
  9078. }
  9079. }
  9080. continue;
  9081. }
  9082. br_style_for(&doc, c, pst, &cs);
  9083. if (cs.display == BR_DISPLAY_NONE)
  9084. continue;
  9085. if (nd->tag == BR_TAG_BR) {
  9086. if (line_w > max_w)
  9087. max_w = line_w;
  9088. line_w = 0;
  9089. continue;
  9090. }
  9091. if (nd->tag == BR_TAG_IMG) {
  9092. /* Measure the image as layout will draw it: a CSS or
  9093. * attribute height keeps the intrinsic aspect ratio, and
  9094. * a CSS width overrides the native pixel width. Bootstrap
  9095. * sizes the Cloudron logo with height:40px only. */
  9096. int idx = nd->img_index;
  9097. int iw = 0, ih = 0;
  9098. if (idx >= 0 && idx < image_count &&
  9099. images[idx].state == 1) {
  9100. iw = (int)images[idx].native_w;
  9101. ih = (int)images[idx].native_h;
  9102. if (iw <= 0 || ih <= 0) {
  9103. iw = (int)images[idx].img.w;
  9104. ih = (int)images[idx].img.h;
  9105. }
  9106. }
  9107. if (cs.width_kind) {
  9108. int ww = style_width_px(&cs, base);
  9109. line_w += ww > 0 ? ww : 64;
  9110. } else if (nd->width_attr) {
  9111. line_w += nd->width_attr;
  9112. } else if (nd->height_attr && iw && ih) {
  9113. line_w += iw * (int)nd->height_attr / ih;
  9114. } else if (cs.height_kind && iw && ih) {
  9115. /* A percentage height needs the parent's
  9116. * definite height (the logo's 2rem box), as in
  9117. * add_image_run(); otherwise it is auto. */
  9118. int hh = cs.height_kind == 1 ?
  9119. style_height_px(&cs, base) :
  9120. cs.height_kind == 2 &&
  9121. pst->height_kind == 1 ?
  9122. (int)pst->height * (int)cs.height / 100 :
  9123. 0;
  9124. line_w += hh > 0 ? iw * hh / ih : iw;
  9125. } else if (iw) {
  9126. line_w += iw;
  9127. } else {
  9128. line_w += 64;
  9129. }
  9130. continue;
  9131. }
  9132. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9133. nd->tag == BR_TAG_TEXTAREA) &&
  9134. !s_eq(br_type(&doc, c), "hidden")) {
  9135. /* Form controls are replaced: CSS width applies even
  9136. * when they are inline (add_form_run's sizes). */
  9137. int fw = cs.width_kind ? style_width_px(&cs, base) :
  9138. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  9139. if (s_eq(br_type(&doc, c), "checkbox") ||
  9140. s_eq(br_type(&doc, c), "radio"))
  9141. fw = 16;
  9142. line_w += (fw > 0 ? fw : 120) +
  9143. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  9144. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  9145. continue;
  9146. }
  9147. if (nd->tag == BR_TAG_SVG) {
  9148. /* A replaced element: its own size, like add_svg_run()
  9149. * (its path children have no width). */
  9150. int sw, sh, sb = cs.width_kind ?
  9151. style_width_px(&cs, base) : base;
  9152. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  9153. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9154. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  9155. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9156. line_w += sw;
  9157. } else {
  9158. if (line_w > max_w)
  9159. max_w = line_w;
  9160. line_w = 0;
  9161. if (sw > max_w)
  9162. max_w = sw;
  9163. }
  9164. continue;
  9165. }
  9166. {
  9167. int cw = mp_px(&cs, 7, base) +
  9168. mp_px(&cs, 5, base) +
  9169. mp_px(&cs, 3, base) +
  9170. mp_px(&cs, 1, base) +
  9171. cs.border_w[1] + cs.border_w[3];
  9172. /* width/height do not apply to non-replaced inline
  9173. * boxes. The tagesschau home label is an inline span
  9174. * with width:1px for the mobile icon-only header; using
  9175. * that width made the whole subnav collapse to a
  9176. * one-character column. */
  9177. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  9178. cw += cs.width_kind == 1 ? cs.width :
  9179. style_width_px(&cs, base);
  9180. else
  9181. cw += intrinsic_width(ui, c, &cs, depth + 1,
  9182. base);
  9183. if (flex_row || cs.float_left ||
  9184. cs.display == BR_DISPLAY_INLINE ||
  9185. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9186. line_w += cw;
  9187. } else {
  9188. if (line_w > max_w)
  9189. max_w = line_w;
  9190. line_w = 0;
  9191. if (cw > max_w)
  9192. max_w = cw;
  9193. }
  9194. }
  9195. if (line_w > 4096 || max_w > 4096)
  9196. break;
  9197. }
  9198. return line_w > max_w ? line_w : max_w;
  9199. }
  9200. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  9201. * the main user: .row > .col-md-* with float:left and a percentage width.
  9202. * Each column is laid out with its own left/right edge and the row advances
  9203. * to the tallest column. Returns the first child not consumed. */
  9204. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  9205. const struct br_style *pst, int depth,
  9206. unsigned short link)
  9207. {
  9208. unsigned int n = first;
  9209. int row_left = l->left, row_right = l->right;
  9210. int row_top, row_bottom, xl, xr, any = 0;
  9211. int fl_left = row_left, fl_right = row_right, fl_bottom;
  9212. flush_line(l);
  9213. row_top = l->y;
  9214. row_bottom = l->y;
  9215. fl_bottom = row_top;
  9216. xl = row_left;
  9217. xr = row_right;
  9218. while (n) {
  9219. struct br_node *nd = &doc.nodes[n];
  9220. struct br_style cs;
  9221. unsigned short lk = link;
  9222. int colw, right;
  9223. if (nd->type == BR_NODE_TEXT) {
  9224. if (text_node_blank(nd)) {
  9225. n = nd->next;
  9226. continue;
  9227. }
  9228. break;
  9229. }
  9230. br_style_for(&doc, n, pst, &cs);
  9231. if (cs.display == BR_DISPLAY_NONE) {
  9232. n = nd->next;
  9233. continue;
  9234. }
  9235. /* A float blockifies its box: Bootstrap floats inline
  9236. * anchors too (the navbar brand and its text links), and
  9237. * their padding must be honoured. */
  9238. if (!cs.float_left)
  9239. break;
  9240. if (nd->tag == BR_TAG_A && nd->href_off)
  9241. lk = (unsigned short)n;
  9242. right = cs.float_left == 2;
  9243. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  9244. cs.width_kind == 3) {
  9245. /* The column is the margin box: `width` is the
  9246. * content (or, with border-box, the border) box,
  9247. * and layout_block() takes margins, padding and
  9248. * borders back out of the column. A 200px float
  9249. * with margin-right:20px used to get 180px of
  9250. * content. */
  9251. int base = row_right - row_left;
  9252. colw = cs.width_kind == 1 ? (int)cs.width :
  9253. style_width_px(&cs, base);
  9254. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  9255. if (!cs.box_sizing)
  9256. colw += mp_px(&cs, 7, base) +
  9257. mp_px(&cs, 5, base) +
  9258. cs.border_w[1] + cs.border_w[3];
  9259. } else {
  9260. int base = row_right - row_left;
  9261. /* Shrink-to-fit outer width: borders too (Google's
  9262. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  9263. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  9264. mp_px(&cs, 7, base) +
  9265. mp_px(&cs, 5, base) +
  9266. mp_px(&cs, 3, base) +
  9267. mp_px(&cs, 1, base) +
  9268. cs.border_w[1] + cs.border_w[3];
  9269. if (colw < 8)
  9270. colw = 8;
  9271. }
  9272. if (colw < 8)
  9273. colw = 8;
  9274. if (colw > row_right - row_left)
  9275. colw = row_right - row_left;
  9276. /* The float column width is already resolved. */
  9277. cs.width_kind = 0;
  9278. cs.max_width_kind = 0;
  9279. if (right) {
  9280. if (any && xr - colw < xl) {
  9281. row_top = row_bottom;
  9282. row_bottom = row_top;
  9283. xl = row_left;
  9284. xr = row_right;
  9285. }
  9286. if (xr - colw < xl)
  9287. colw = xr - xl;
  9288. if (colw < 8)
  9289. colw = 8;
  9290. l->left = xr - colw;
  9291. if (l->left < row_left)
  9292. l->left = row_left;
  9293. l->right = xr;
  9294. xr = l->left;
  9295. if (xr < fl_right)
  9296. fl_right = xr;
  9297. } else {
  9298. if (any && xl + colw > xr) {
  9299. row_top = row_bottom;
  9300. row_bottom = row_top;
  9301. xl = row_left;
  9302. xr = row_right;
  9303. }
  9304. l->left = xl;
  9305. l->right = xl + colw;
  9306. xl += colw;
  9307. if (xl > fl_left)
  9308. fl_left = xl;
  9309. }
  9310. if (l->right < l->left + 8)
  9311. l->right = l->left + 8;
  9312. l->y = row_top;
  9313. l->line_left = l->line_x = l->left;
  9314. l->run_x = l->left;
  9315. l->line_y = l->y;
  9316. l->line_h = 0;
  9317. l->nruns = 0;
  9318. l->space_pending = 0;
  9319. l->align = cs.align;
  9320. layout_block(l, n, &cs, depth + 1, lk);
  9321. if (l->y > row_bottom)
  9322. row_bottom = l->y;
  9323. if (l->y > fl_bottom)
  9324. fl_bottom = l->y;
  9325. any = 1;
  9326. n = nd->next;
  9327. }
  9328. l->left = row_left;
  9329. l->right = row_right;
  9330. if (n && any) {
  9331. struct br_node *nd = &doc.nodes[n];
  9332. int inline_next = 0;
  9333. if (nd->type == BR_NODE_TEXT) {
  9334. inline_next = 1;
  9335. } else if (nd->type == BR_NODE_ELEM) {
  9336. struct br_style cs;
  9337. br_style_for(&doc, n, pst, &cs);
  9338. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  9339. cs.display != BR_DISPLAY_NONE &&
  9340. !br_tag_is_block(nd->tag);
  9341. }
  9342. if (inline_next) {
  9343. if (l->float_active) {
  9344. if (l->float_left > fl_left)
  9345. fl_left = l->float_left;
  9346. if (l->float_right < fl_right)
  9347. fl_right = l->float_right;
  9348. if (l->float_bottom > fl_bottom)
  9349. fl_bottom = l->float_bottom;
  9350. }
  9351. l->float_active = 1;
  9352. l->float_left = fl_left;
  9353. l->float_right = fl_right;
  9354. l->float_bottom = fl_bottom;
  9355. l->y = row_top;
  9356. } else {
  9357. l->float_active = 0;
  9358. l->y = row_bottom;
  9359. }
  9360. } else {
  9361. l->float_active = 0;
  9362. l->y = row_bottom;
  9363. }
  9364. l->line_x = l->left;
  9365. l->run_x = l->left;
  9366. l->line_left = l->left;
  9367. l->line_right = l->right;
  9368. l->line_y = l->y;
  9369. l->line_h = 0;
  9370. l->nruns = 0;
  9371. l->space_pending = 0;
  9372. return n;
  9373. }
  9374. static int flex_item_width(struct lay *l, unsigned int n,
  9375. const struct br_style *cs, int avail)
  9376. {
  9377. struct br_node *nd = &doc.nodes[n];
  9378. (void)l;
  9379. int w;
  9380. if (cs->width_kind == 2 || cs->width_kind == 3)
  9381. w = style_width_px(cs, avail);
  9382. else if (cs->width_kind == 1)
  9383. w = (int)cs->width;
  9384. else if (nd->tag == BR_TAG_IMG) {
  9385. int idx = nd->img_index;
  9386. if (idx >= 0 && idx < image_count &&
  9387. images[idx].state == 1)
  9388. w = (int)images[idx].img.w;
  9389. else if (nd->width_attr)
  9390. w = (int)nd->width_attr;
  9391. else
  9392. w = 64;
  9393. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  9394. nd->tag == BR_TAG_TEXTAREA) {
  9395. /* A control has no content to measure: its default size
  9396. * (a search field in a filter bar). */
  9397. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  9398. } else {
  9399. w = intrinsic_width(l->ui, n, cs, 0, avail);
  9400. }
  9401. /* Explicit widths are content-box sizes; the flex item's outer width
  9402. * must include padding, borders and margins. */
  9403. w += mp_px(cs, 7, avail);
  9404. w += mp_px(cs, 5, avail);
  9405. w += mp_px(cs, 3, avail);
  9406. w += mp_px(cs, 1, avail);
  9407. w += cs->border_w[1] + cs->border_w[3];
  9408. if (w < 24)
  9409. w = 24;
  9410. if (w > avail)
  9411. w = avail;
  9412. return w;
  9413. }
  9414. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9415. int depth);
  9416. /* An inline child of a text-only inline-block: the same test minus the
  9417. * display check (an inline <span> may have padding/background in CSS, but
  9418. * the inline path paints those for spans anyway). */
  9419. static int inline_block_flows_inline(unsigned int node,
  9420. const struct br_style *cs, int depth)
  9421. {
  9422. unsigned int c;
  9423. if (depth > 3 || cs->pos)
  9424. return 0;
  9425. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9426. const struct br_node *nd = &doc.nodes[c];
  9427. struct br_style ch;
  9428. if (nd->type != BR_NODE_ELEM)
  9429. continue;
  9430. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  9431. br_tag_is_block(nd->tag))
  9432. return 0;
  9433. br_style_for(&doc, c, cs, &ch);
  9434. if (ch.display == BR_DISPLAY_NONE)
  9435. continue;
  9436. if (ch.display != BR_DISPLAY_INLINE ||
  9437. !inline_block_flows_inline(c, &ch, depth + 1))
  9438. return 0;
  9439. }
  9440. return 1;
  9441. }
  9442. /* An inline-block that is only text in a line (a <time> in a byline, a
  9443. * label) with no box of its own -- no size, background, border or padding
  9444. * -- lays out exactly like an inline element, so it stays in the text line
  9445. * instead of ending it. Boxes with any of those keep the row path. */
  9446. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  9447. int depth)
  9448. {
  9449. unsigned int c;
  9450. int i;
  9451. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  9452. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  9453. cs->pos || depth > 3)
  9454. return 0;
  9455. for (i = 0; i < 4; i++)
  9456. if (cs->border_w[i])
  9457. return 0;
  9458. for (i = 4; i < 8; i++)
  9459. if (mp_px(cs, i, 0) > 0)
  9460. return 0;
  9461. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  9462. const struct br_node *nd = &doc.nodes[c];
  9463. struct br_style ch;
  9464. if (nd->type != BR_NODE_ELEM)
  9465. continue;
  9466. if (nd->tag == BR_TAG_SVG) {
  9467. /* An icon box (Docusaurus' admonition heading:
  9468. * `<span inline-block><svg/></span>Note`): the SVG
  9469. * is an inline replaced run, so the box can stay in
  9470. * the text line. */
  9471. br_style_for(&doc, c, cs, &ch);
  9472. if (ch.display == BR_DISPLAY_NONE ||
  9473. ch.display == BR_DISPLAY_INLINE ||
  9474. ch.display == BR_DISPLAY_INLINE_BLOCK)
  9475. continue;
  9476. return 0;
  9477. }
  9478. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  9479. return 0;
  9480. br_style_for(&doc, c, cs, &ch);
  9481. if (ch.display == BR_DISPLAY_NONE)
  9482. continue;
  9483. if (ch.display != BR_DISPLAY_INLINE ||
  9484. !inline_block_flows_inline(c, &ch, depth + 1))
  9485. return 0;
  9486. }
  9487. return 1;
  9488. }
  9489. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  9490. * on one line, not one full-width block each. Place intrinsic widths from
  9491. * left to right and wrap when the row is full. */
  9492. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  9493. const struct br_style *pst, int depth,
  9494. unsigned short link)
  9495. {
  9496. unsigned int n = first;
  9497. int row_left = l->left, row_right = l->right;
  9498. int avail = row_right - row_left;
  9499. int x = row_left, y = l->y, row_h = 0, any = 0;
  9500. /* Each box sets l->align from its own style; the text after the row
  9501. * must keep the container's (a centred .fa-fw icon centred the menu
  9502. * label that followed it). */
  9503. unsigned char row_align = l->align;
  9504. flush_line(l);
  9505. y = l->y;
  9506. while (n) {
  9507. struct br_node *nd = &doc.nodes[n];
  9508. struct br_style cs;
  9509. unsigned short lk = link;
  9510. int colw, h;
  9511. if (nd->type == BR_NODE_TEXT) {
  9512. if (!text_node_blank(nd))
  9513. break;
  9514. if (any)
  9515. x += 4;
  9516. n = nd->next;
  9517. continue;
  9518. }
  9519. br_style_for(&doc, n, pst, &cs);
  9520. if (cs.display == BR_DISPLAY_NONE) {
  9521. n = nd->next;
  9522. continue;
  9523. }
  9524. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9525. break;
  9526. if (nd->tag == BR_TAG_A && nd->href_off)
  9527. lk = (unsigned short)n;
  9528. colw = flex_item_width(l, n, &cs, avail);
  9529. /* A few pixels of slack keep a single long token (boot.S)
  9530. * from wrapping at the exact content width. */
  9531. colw += 8;
  9532. if (colw > avail)
  9533. colw = avail;
  9534. cs.width_kind = 0;
  9535. cs.max_width_kind = 0;
  9536. if (any && x + colw > row_right) {
  9537. y += row_h + 2;
  9538. x = row_left;
  9539. row_h = 0;
  9540. any = 0;
  9541. }
  9542. if (any && x > row_left)
  9543. x += 4;
  9544. l->left = x;
  9545. l->right = x + colw;
  9546. if (l->right < l->left + 8)
  9547. l->right = l->left + 8;
  9548. l->y = y;
  9549. l->line_left = l->line_x = l->left;
  9550. l->run_x = l->left;
  9551. l->line_y = l->y;
  9552. l->line_h = 0;
  9553. l->nruns = 0;
  9554. l->space_pending = 0;
  9555. l->align = cs.align;
  9556. layout_block(l, n, &cs, depth + 1, lk);
  9557. h = l->y - y;
  9558. if (h > row_h)
  9559. row_h = h;
  9560. x += colw;
  9561. any = 1;
  9562. n = nd->next;
  9563. }
  9564. if (any)
  9565. y += row_h;
  9566. l->left = row_left;
  9567. l->right = row_right;
  9568. l->align = row_align;
  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. return n;
  9577. }
  9578. struct flex_item {
  9579. unsigned int node;
  9580. unsigned short link;
  9581. int w;
  9582. };
  9583. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9584. * row, or -1 when unset. Percentages and calc() resolve against the
  9585. * container width. */
  9586. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9587. {
  9588. unsigned char kind = which_max ? cs->max_width_kind :
  9589. cs->min_width_kind;
  9590. int w;
  9591. if (kind == 3)
  9592. w = which_max ?
  9593. avail * cs->max_width_calc_pct / 100 +
  9594. cs->max_width_calc_px :
  9595. avail * cs->min_width_calc_pct / 100 +
  9596. cs->min_width_calc_px;
  9597. else
  9598. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9599. avail);
  9600. if (w < 0)
  9601. return -1;
  9602. if (!cs->box_sizing)
  9603. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9604. cs->border_w[1] + cs->border_w[3];
  9605. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9606. }
  9607. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9608. {
  9609. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9610. if (mx >= 0 && w > mx)
  9611. w = mx;
  9612. if (mn >= 0 && w < mn)
  9613. w = mn;
  9614. return w;
  9615. }
  9616. /* Does a flex row stretch this item to the line height? Only items with
  9617. * no height of their own and align-self/align-items stretch; replaced
  9618. * content (images, icons) keeps its aspect ratio. */
  9619. static int flex_item_stretches(unsigned int node, const struct br_style *cs,
  9620. const struct br_style *pst)
  9621. {
  9622. int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
  9623. unsigned char tag = doc.nodes[node].tag;
  9624. return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
  9625. tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
  9626. tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
  9627. tag != BR_TAG_BUTTON;
  9628. }
  9629. static void flex_set_stretch(unsigned int node, const struct br_style *cs,
  9630. int line_h, int cbw)
  9631. {
  9632. int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
  9633. if (node >= BR_MAX_NODES || h <= 0)
  9634. return;
  9635. if (h > 65535)
  9636. h = 65535;
  9637. flex_stretch_h[node] = (unsigned short)h;
  9638. if (block_h[node] < h)
  9639. block_h[node] = (unsigned short)h;
  9640. }
  9641. static void layout_flex_children(struct lay *l, unsigned int parent,
  9642. const struct br_style *pst, int depth,
  9643. unsigned short link)
  9644. {
  9645. struct flex_item it[32];
  9646. unsigned int c;
  9647. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9648. int grow_need = 0; /* growing items at their content width */
  9649. int row_left = l->left, row_right = l->right;
  9650. int avail = row_right - row_left;
  9651. int idx, row_top;
  9652. unsigned char row_align = l->align;
  9653. int box_left = l->left, box_right = l->right, row_top0 = l->y;
  9654. int bw = 0, aw = 0, first_h = -1;
  9655. int cont_h = l->cb_h; /* the container's definite content height */
  9656. struct br_style bps, aps;
  9657. if (avail < 8 || depth > 48) {
  9658. layout_children(l, parent, pst, depth, link);
  9659. return;
  9660. }
  9661. /* If direct text is not just whitespace, normal block flow handles it
  9662. * better than pretending it is a flex item. */
  9663. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9664. struct br_node *nd = &doc.nodes[c];
  9665. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9666. layout_children(l, parent, pst, depth, link);
  9667. return;
  9668. }
  9669. }
  9670. /* ::before/::after icon boxes are the row's first and last items
  9671. * (Docusaurus' sidebar chevron): reserve their columns. */
  9672. if (doc.npe_rules) {
  9673. bw = pseudo_box_w(parent, pst, 1, &bps, avail);
  9674. aw = pseudo_box_w(parent, pst, 2, &aps, avail);
  9675. if (bw + aw > avail - 8) {
  9676. bw = 0;
  9677. aw = 0;
  9678. }
  9679. row_left += bw;
  9680. row_right -= aw;
  9681. avail = row_right - row_left;
  9682. }
  9683. for (c = doc.nodes[parent].first;
  9684. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9685. c = doc.nodes[c].next) {
  9686. struct br_node *nd = &doc.nodes[c];
  9687. struct br_style cs;
  9688. if (nd->type == BR_NODE_TEXT)
  9689. continue;
  9690. br_style_for(&doc, c, pst, &cs);
  9691. if (cs.display == BR_DISPLAY_NONE)
  9692. continue;
  9693. if ((cs.pos == 1 || cs.pos == 2) &&
  9694. layout_out_of_flow(l, c, &cs, depth,
  9695. (nd->tag == BR_TAG_A && nd->href_off) ?
  9696. (unsigned short)c : link))
  9697. continue; /* absolutely positioned: not an item */
  9698. it[nitem].node = c;
  9699. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9700. (unsigned short)c : link;
  9701. it[nitem].w = 0;
  9702. if (cs.flex_grow && !cs.width_kind) {
  9703. grow_count++;
  9704. grow_need += flex_item_width(l, c, &cs, avail);
  9705. } else
  9706. fixed += flex_clamp_w(&cs,
  9707. flex_item_width(l, c, &cs, avail),
  9708. avail);
  9709. nitem++;
  9710. }
  9711. /* A narrow container (an icon row sized to its content, Google's
  9712. * mic + lens buttons) is still a row when its items fit; only a
  9713. * narrow one that would overflow or squeeze growing items falls
  9714. * back to block flow. */
  9715. if (avail < 160 && fixed + grow_need > avail) {
  9716. layout_children(l, parent, pst, depth, link);
  9717. return;
  9718. }
  9719. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9720. /* A growing item capped by max-width (Docusaurus' doc column,
  9721. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9722. * keeps its cap and leaves the rest of the free space to the other
  9723. * growing items. */
  9724. if (grow_count) {
  9725. int pass, capped[32] = { 0 };
  9726. for (pass = 0; pass < nitem; pass++) {
  9727. int changed = 0;
  9728. for (idx = 0; idx < nitem; idx++) {
  9729. struct br_style cs;
  9730. int lim;
  9731. if (capped[idx])
  9732. continue;
  9733. br_style_for(&doc, it[idx].node, pst, &cs);
  9734. if (!cs.flex_grow || cs.width_kind)
  9735. continue;
  9736. lim = flex_clamp_w(&cs, grow_w, avail);
  9737. if (lim == grow_w)
  9738. continue;
  9739. capped[idx] = lim + 1;
  9740. fixed += lim;
  9741. grow_count--;
  9742. changed = 1;
  9743. }
  9744. if (!changed || !grow_count)
  9745. break;
  9746. grow_w = (avail - fixed) / grow_count;
  9747. }
  9748. for (idx = 0; idx < nitem; idx++)
  9749. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9750. }
  9751. if (grow_w < 96 && avail >= 160)
  9752. grow_w = 96;
  9753. for (idx = 0; idx < nitem; idx++) {
  9754. struct br_style cs;
  9755. if (it[idx].w)
  9756. continue; /* capped growing item */
  9757. br_style_for(&doc, it[idx].node, pst, &cs);
  9758. if (cs.flex_grow && !cs.width_kind)
  9759. it[idx].w = grow_w;
  9760. else
  9761. it[idx].w = flex_clamp_w(&cs,
  9762. flex_item_width(l,
  9763. it[idx].node,
  9764. &cs, avail),
  9765. avail);
  9766. if (it[idx].w > avail)
  9767. it[idx].w = avail;
  9768. if (it[idx].w < 8)
  9769. it[idx].w = 8;
  9770. }
  9771. row_top = l->y;
  9772. idx = 0;
  9773. while (idx < nitem) {
  9774. int start = idx, count = 0, row_w = 0;
  9775. int free_w, x, extra = 0, row_h = 0, k;
  9776. while (idx < nitem) {
  9777. int add = it[idx].w + (count ? gap : 0);
  9778. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9779. * starts a new row. */
  9780. if (count && pst->flex_wrap == 1 &&
  9781. row_w + add > avail)
  9782. break;
  9783. row_w += add;
  9784. count++;
  9785. idx++;
  9786. }
  9787. if (!count) {
  9788. count = 1;
  9789. row_w = it[start].w;
  9790. idx = start + 1;
  9791. }
  9792. free_w = avail - row_w;
  9793. if (free_w < 0)
  9794. free_w = 0;
  9795. x = row_left;
  9796. if (pst->justify == 1) {
  9797. x += free_w / 2;
  9798. } else if (pst->justify == 2) {
  9799. x += free_w;
  9800. } else if (pst->justify == 3) {
  9801. extra = count > 1 ? free_w / (count - 1) : 0;
  9802. } else if (pst->justify == 4) {
  9803. extra = count ? free_w / count : 0;
  9804. x += extra / 2;
  9805. } else if (pst->justify == 5) {
  9806. extra = count ? free_w / (count + 1) : 0;
  9807. x += extra;
  9808. }
  9809. for (k = 0; k < count; k++) {
  9810. int node = (int)it[start + k].node;
  9811. int h = block_h[node];
  9812. if (h > row_h)
  9813. row_h = h;
  9814. }
  9815. /* A single line fills a definite container height (an app
  9816. * shell's `height: 100%` sidebar + content row). */
  9817. if (pst->flex_wrap != 1 && cont_h > row_h)
  9818. row_h = cont_h;
  9819. else if (pst->height_kind == 1 && (int)pst->height > row_h)
  9820. row_h = pst->height;
  9821. for (k = 0; k < count; k++) {
  9822. struct br_style cs;
  9823. int node = (int)it[start + k].node;
  9824. int yoff = 0;
  9825. br_style_for(&doc, node, pst, &cs);
  9826. cs.width_kind = 0;
  9827. cs.max_width_kind = 0;
  9828. /* align-items: stretch. With a definite line height
  9829. * the item is laid out at it, so its own children see
  9830. * a definite height; otherwise the measure pass
  9831. * stretches it once the line is known (below). */
  9832. if (!l->draw && row_h > 0 && flex_item_stretches(node,
  9833. &cs, pst))
  9834. flex_set_stretch(node, &cs, row_h, avail);
  9835. {
  9836. int ai = cs.align_self ? cs.align_self - 1 :
  9837. pst->align_items;
  9838. if (l->draw && ai && row_h > block_h[node]) {
  9839. if (ai == 1)
  9840. yoff = (row_h -
  9841. block_h[node]) / 2;
  9842. else if (ai == 2)
  9843. yoff = row_h - block_h[node];
  9844. }
  9845. }
  9846. l->left = x;
  9847. l->right = x + it[start + k].w;
  9848. if (l->right < l->left + 8)
  9849. l->right = l->left + 8;
  9850. l->y = row_top + yoff;
  9851. /* line_left too: a stale one from the previous item
  9852. * made flush_line() see a non-empty line and push
  9853. * every later item down by an empty line's height. */
  9854. l->line_left = l->line_x = l->run_x = l->left;
  9855. l->line_right = l->right;
  9856. l->line_y = l->y;
  9857. l->line_h = 0;
  9858. l->nruns = 0;
  9859. l->space_pending = 0;
  9860. l->align = cs.align;
  9861. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9862. {
  9863. /* Both passes: a form control item has no
  9864. * block_h of its own, so the draw pass would
  9865. * otherwise end a row of only an <input> at
  9866. * height 0 and pull the content below up. */
  9867. int h = l->y - row_top;
  9868. if (h > row_h)
  9869. row_h = h;
  9870. }
  9871. x += it[start + k].w;
  9872. if (k + 1 < count)
  9873. x += gap + extra;
  9874. }
  9875. if (!l->draw) {
  9876. for (k = 0; k < count; k++) {
  9877. struct br_style cs;
  9878. int node = (int)it[start + k].node;
  9879. br_style_for(&doc, node, pst, &cs);
  9880. if (!flex_item_stretches(node, &cs, pst))
  9881. continue;
  9882. /* To the line's bottom edge from where the
  9883. * item really starts (its top margin, or a
  9884. * line box above it). */
  9885. if (layout_boxes[node].valid)
  9886. flex_set_stretch(node, &cs,
  9887. row_top + row_h -
  9888. layout_boxes[node].y +
  9889. mp_px(&cs, 0, avail), avail);
  9890. else
  9891. flex_set_stretch(node, &cs, row_h, avail);
  9892. }
  9893. }
  9894. if (first_h < 0)
  9895. first_h = row_h;
  9896. row_top += row_h;
  9897. }
  9898. if (bw || aw) {
  9899. int pass;
  9900. for (pass = 0; pass < 2; pass++) {
  9901. const struct br_style *ps = pass ? &aps : &bps;
  9902. int a = pass ? row_right : box_left;
  9903. int b = pass ? box_right : row_left;
  9904. int h = ps->height_kind ?
  9905. style_height_px(ps, box_right - box_left) : 0;
  9906. if (!(pass ? aw : bw))
  9907. continue;
  9908. l->left = l->line_left = l->line_x = l->run_x = a;
  9909. l->right = l->line_right = b;
  9910. l->y = row_top0;
  9911. if (pst->align_items == 1 && first_h > h)
  9912. l->y += (first_h - h) / 2;
  9913. l->line_y = l->y;
  9914. l->line_h = 0;
  9915. l->nruns = 0;
  9916. l->space_pending = 0;
  9917. emit_pseudo_box(l, pst, ps, link);
  9918. flush_line(l);
  9919. /* The box sits inside the first row; it only makes
  9920. * the row taller when it is taller itself. */
  9921. if (row_top0 + h > row_top)
  9922. row_top = row_top0 + h;
  9923. }
  9924. }
  9925. l->left = box_left;
  9926. l->right = box_right;
  9927. l->align = row_align;
  9928. l->y = row_top;
  9929. l->line_left = l->line_x = l->run_x = l->left;
  9930. l->line_right = l->right;
  9931. l->line_y = l->y;
  9932. l->line_h = 0;
  9933. l->nruns = 0;
  9934. l->space_pending = 0;
  9935. }
  9936. /* flex-direction: column. Items stack in order with the gap and never
  9937. * collapse margins. In the draw pass justify-content shares out the free
  9938. * height of the container's measured box (a definite or min-height, or a
  9939. * row stretch), and align-items places each item: stretch (the default)
  9940. * fills the line, start/center/end shrink an item to its content width
  9941. * (a login form's "Log in" button, a centred logo and name). */
  9942. static void layout_flex_column(struct lay *l, unsigned int parent,
  9943. const struct br_style *pst, int depth,
  9944. unsigned short link)
  9945. {
  9946. unsigned int c;
  9947. int box_left = l->left, box_right = l->right;
  9948. int avail = box_right - box_left;
  9949. int gap = pst->grid_gap, y0 = l->y;
  9950. int n = 0, k = 0, total = 0, lead = 0, extra = 0;
  9951. unsigned char row_align = l->align;
  9952. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9953. struct br_node *nd = &doc.nodes[c];
  9954. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
  9955. break;
  9956. }
  9957. if (c || avail < 8 || depth > 48) {
  9958. /* Loose text: block flow, with centred lines standing in
  9959. * for align-items: center. */
  9960. struct br_style cst = *pst;
  9961. if (pst->align_items == 1) {
  9962. cst.align = BR_ALIGN_CENTER;
  9963. l->align = BR_ALIGN_CENTER;
  9964. }
  9965. layout_children(l, parent, &cst, depth, link);
  9966. return;
  9967. }
  9968. emit_pseudo(l, parent, pst, 1, link);
  9969. flush_line(l);
  9970. y0 = l->y;
  9971. if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
  9972. int inner = (int)block_h[parent] - pst->border_w[0] -
  9973. pst->border_w[2] - mp_px(pst, 4, avail) -
  9974. mp_px(pst, 6, avail) - (y0 - l->parent_top -
  9975. pst->border_w[0] - mp_px(pst, 4, avail));
  9976. int free_h;
  9977. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9978. struct br_style cs;
  9979. if (doc.nodes[c].type != BR_NODE_ELEM)
  9980. continue;
  9981. br_style_for(&doc, c, pst, &cs);
  9982. if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
  9983. cs.pos == 2)
  9984. continue;
  9985. total += block_h[c] + mp_px(&cs, 0, avail) +
  9986. mp_px(&cs, 2, avail);
  9987. n++;
  9988. }
  9989. if (n > 1)
  9990. total += gap * (n - 1);
  9991. free_h = inner - total;
  9992. if (n && free_h > 0) {
  9993. if (pst->justify == 1) {
  9994. lead = free_h / 2;
  9995. } else if (pst->justify == 2) {
  9996. lead = free_h;
  9997. } else if (pst->justify == 3) {
  9998. extra = n > 1 ? free_h / (n - 1) : 0;
  9999. } else if (pst->justify == 4) {
  10000. extra = free_h / n;
  10001. lead = extra / 2;
  10002. } else if (pst->justify == 5) {
  10003. extra = free_h / (n + 1);
  10004. lead = extra;
  10005. }
  10006. }
  10007. }
  10008. l->y = y0 + lead;
  10009. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10010. struct br_node *nd = &doc.nodes[c];
  10011. unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
  10012. (unsigned short)c : link;
  10013. struct br_style cs;
  10014. int ai, left = box_left, right = box_right;
  10015. if (nd->type != BR_NODE_ELEM)
  10016. continue;
  10017. br_style_for(&doc, c, pst, &cs);
  10018. if (cs.display == BR_DISPLAY_NONE)
  10019. continue;
  10020. if ((cs.pos == 1 || cs.pos == 2) &&
  10021. layout_out_of_flow(l, c, &cs, depth, lk))
  10022. continue;
  10023. if (k++)
  10024. l->y += gap + extra;
  10025. ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
  10026. if (ai) {
  10027. int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
  10028. avail),
  10029. avail);
  10030. if (ai == 1)
  10031. left += (avail - w) / 2;
  10032. else if (ai == 2)
  10033. left += avail - w;
  10034. right = left + w;
  10035. cs.width_kind = 0;
  10036. cs.max_width_kind = 0;
  10037. }
  10038. l->left = l->line_left = l->line_x = l->run_x = left;
  10039. l->right = l->line_right = right;
  10040. l->line_y = l->y;
  10041. l->line_h = 0;
  10042. l->nruns = 0;
  10043. l->space_pending = 0;
  10044. l->align = cs.align;
  10045. layout_block(l, c, &cs, depth + 1, lk);
  10046. }
  10047. l->left = l->line_left = l->line_x = l->run_x = box_left;
  10048. l->right = l->line_right = box_right;
  10049. l->align = row_align;
  10050. l->line_y = l->y;
  10051. l->line_h = 0;
  10052. l->nruns = 0;
  10053. l->space_pending = 0;
  10054. emit_pseudo(l, parent, pst, 2, link);
  10055. }
  10056. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  10057. * plus the grid-area hints used by site shells (site notice/footer full
  10058. * width, column-start left, page-content right). Anything more elaborate
  10059. * falls back to normal block flow. */
  10060. static int grid_track_width(unsigned char kind, unsigned short val,
  10061. int avail, int other)
  10062. {
  10063. if (kind == 2)
  10064. return avail * (int)val / 100;
  10065. if (kind == 1)
  10066. return val;
  10067. return other;
  10068. }
  10069. static void layout_grid_children(struct lay *l, unsigned int parent,
  10070. const struct br_style *pst, int depth,
  10071. unsigned short link)
  10072. {
  10073. unsigned int n;
  10074. int row_left = l->left, row_right = l->right;
  10075. int avail = row_right - row_left;
  10076. int gap = pst->grid_gap;
  10077. int track_total = avail - gap;
  10078. int col0, col1, x0, x1;
  10079. int row_y, row_bottom, have_left = 0, have_right = 0;
  10080. unsigned int c;
  10081. if (avail < 32 || depth > 48)
  10082. return;
  10083. if (track_total < 16)
  10084. track_total = 16;
  10085. col0 = grid_track_width((unsigned char)(pst->width_kind),
  10086. pst->width, track_total, 0);
  10087. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  10088. pst->max_width, track_total, 0);
  10089. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  10090. int w0 = pst->width ? pst->width : 1;
  10091. int w1 = pst->max_width ? pst->max_width : 1;
  10092. col0 = track_total * w0 / (w0 + w1);
  10093. col1 = track_total - col0;
  10094. } else if (pst->width_kind == 3) {
  10095. col0 = track_total - col1;
  10096. if (col0 < 24)
  10097. col0 = 24;
  10098. } else if (pst->max_width_kind == 3) {
  10099. col1 = track_total - col0;
  10100. if (col1 < 24)
  10101. col1 = 24;
  10102. }
  10103. if (col0 < 24)
  10104. col0 = 24;
  10105. if (col1 < 24)
  10106. col1 = 24;
  10107. if (col0 + col1 > track_total) {
  10108. col1 = track_total - col0;
  10109. if (col1 < 24)
  10110. col1 = 24;
  10111. }
  10112. x0 = row_left;
  10113. x1 = row_left + col0 + gap;
  10114. /* Direct text makes a grid ambiguous; use block flow instead. */
  10115. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10116. struct br_node *nd = &doc.nodes[c];
  10117. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10118. layout_children(l, parent, pst, depth, link);
  10119. return;
  10120. }
  10121. }
  10122. row_y = row_bottom = l->y;
  10123. n = doc.nodes[parent].first;
  10124. while (n) {
  10125. struct br_node *nd = &doc.nodes[n];
  10126. struct br_style cs;
  10127. unsigned short lk = link;
  10128. int slot, x, w;
  10129. if (nd->type == BR_NODE_TEXT) {
  10130. n = nd->next;
  10131. continue;
  10132. }
  10133. br_style_for(&doc, n, pst, &cs);
  10134. if (cs.display == BR_DISPLAY_NONE) {
  10135. n = nd->next;
  10136. continue;
  10137. }
  10138. if (nd->tag == BR_TAG_A && nd->href_off)
  10139. lk = (unsigned short)n;
  10140. slot = cs.grid_slot;
  10141. if (!slot) {
  10142. if (!have_left)
  10143. slot = 2;
  10144. else if (!have_right)
  10145. slot = 3;
  10146. else
  10147. slot = 2;
  10148. }
  10149. if (slot == 1) {
  10150. if (have_left || have_right) {
  10151. row_y = row_bottom;
  10152. have_left = have_right = 0;
  10153. }
  10154. x = row_left;
  10155. w = avail;
  10156. } else if (slot == 2) {
  10157. if (have_left) {
  10158. row_y = row_bottom;
  10159. have_left = have_right = 0;
  10160. }
  10161. x = x0;
  10162. w = col0;
  10163. have_left = 1;
  10164. } else {
  10165. if (have_right) {
  10166. row_y = row_bottom;
  10167. have_left = have_right = 0;
  10168. }
  10169. x = x1;
  10170. w = col1;
  10171. have_right = 1;
  10172. }
  10173. cs.width_kind = 0;
  10174. cs.max_width_kind = 0;
  10175. l->left = x;
  10176. l->right = x + w;
  10177. if (l->right < l->left + 8)
  10178. l->right = l->left + 8;
  10179. l->y = row_y;
  10180. l->line_left = l->line_x = l->left;
  10181. l->run_x = l->left;
  10182. l->line_y = l->y;
  10183. l->line_h = 0;
  10184. l->nruns = 0;
  10185. l->space_pending = 0;
  10186. l->align = cs.align;
  10187. layout_block(l, n, &cs, depth + 1, lk);
  10188. if (l->y > row_bottom)
  10189. row_bottom = l->y;
  10190. n = nd->next;
  10191. }
  10192. l->left = row_left;
  10193. l->right = row_right;
  10194. l->y = row_bottom;
  10195. l->line_left = l->line_x = l->left;
  10196. l->run_x = l->left;
  10197. l->line_y = l->y;
  10198. l->line_h = 0;
  10199. l->nruns = 0;
  10200. l->space_pending = 0;
  10201. }
  10202. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  10203. * capped at four. Used by the project docs' card grids. A fixed
  10204. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  10205. static void layout_grid_auto(struct lay *l, unsigned int parent,
  10206. const struct br_style *pst, int depth,
  10207. unsigned short link)
  10208. {
  10209. unsigned int n, c;
  10210. int row_left = l->left, row_right = l->right;
  10211. int avail = row_right - row_left;
  10212. int gap = pst->grid_gap;
  10213. int minw = pst->width_kind == 1 ? pst->width : 200;
  10214. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  10215. if (avail < 32 || depth > 48) {
  10216. layout_children(l, parent, pst, depth, link);
  10217. return;
  10218. }
  10219. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  10220. struct br_node *nd = &doc.nodes[c];
  10221. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  10222. layout_children(l, parent, pst, depth, link);
  10223. return;
  10224. }
  10225. }
  10226. if (minw < 80)
  10227. minw = 80;
  10228. ncols = (avail + gap) / (minw + gap);
  10229. if (ncols < 1)
  10230. ncols = 1;
  10231. if (ncols > 4)
  10232. ncols = 4;
  10233. if (pst->grid_auto > BR_GRID_FIXED) {
  10234. /* grid-template-columns: repeat(N, 1fr) */
  10235. ncols = pst->grid_auto - BR_GRID_FIXED;
  10236. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  10237. ncols--;
  10238. }
  10239. colw = (avail - gap * (ncols - 1)) / ncols;
  10240. if (colw < 24)
  10241. colw = 24;
  10242. x = row_left;
  10243. n = doc.nodes[parent].first;
  10244. while (n) {
  10245. struct br_node *nd = &doc.nodes[n];
  10246. struct br_style cs;
  10247. unsigned short lk = link;
  10248. int h;
  10249. if (nd->type == BR_NODE_TEXT) {
  10250. n = nd->next;
  10251. continue;
  10252. }
  10253. br_style_for(&doc, n, pst, &cs);
  10254. if (cs.display == BR_DISPLAY_NONE) {
  10255. n = nd->next;
  10256. continue;
  10257. }
  10258. if (nd->tag == BR_TAG_A && nd->href_off)
  10259. lk = (unsigned short)n;
  10260. cs.width_kind = 0;
  10261. cs.max_width_kind = 0;
  10262. l->left = x;
  10263. l->right = x + colw;
  10264. if (l->right < l->left + 8)
  10265. l->right = l->left + 8;
  10266. l->y = y;
  10267. l->line_left = l->line_x = l->left;
  10268. l->run_x = l->left;
  10269. l->line_y = l->y;
  10270. l->line_h = 0;
  10271. l->nruns = 0;
  10272. l->space_pending = 0;
  10273. l->align = cs.align;
  10274. layout_block(l, n, &cs, depth + 1, lk);
  10275. h = l->y - y;
  10276. if (h > row_h)
  10277. row_h = h;
  10278. col++;
  10279. n = nd->next;
  10280. if (col == ncols) {
  10281. y += row_h + gap;
  10282. x = row_left;
  10283. row_h = 0;
  10284. col = 0;
  10285. } else {
  10286. x += colw + gap;
  10287. }
  10288. }
  10289. if (col)
  10290. y += row_h;
  10291. else if (y > start_y)
  10292. y -= gap;
  10293. l->left = row_left;
  10294. l->right = row_right;
  10295. l->y = y;
  10296. l->line_left = l->line_x = l->left;
  10297. l->run_x = l->left;
  10298. l->line_y = l->y;
  10299. l->line_h = 0;
  10300. l->nruns = 0;
  10301. l->space_pending = 0;
  10302. }
  10303. /* Column widths are the widest cell in each column across every row, so all
  10304. * rows line up. The table model is still deliberately basic: no colspan,
  10305. * border-collapse or percentage columns. */
  10306. static void table_columns(struct lay *l, unsigned int table,
  10307. const struct br_style *pst, int avail,
  10308. int *raw, int maxcols, int *out_cols,
  10309. int *out_total)
  10310. {
  10311. unsigned int r, c;
  10312. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  10313. int fixed[12];
  10314. for (c = 0; c < (unsigned int)maxcols; c++) {
  10315. raw[c] = 0;
  10316. fixed[c] = 0;
  10317. }
  10318. /* Intrinsic widths of single-column cells. */
  10319. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10320. struct br_node *rn = &doc.nodes[r];
  10321. int col = 0;
  10322. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10323. continue;
  10324. for (c = rn->first; c; c = doc.nodes[c].next) {
  10325. struct br_node *cn = &doc.nodes[c];
  10326. struct br_style cs;
  10327. int w, span;
  10328. if (cn->type != BR_NODE_ELEM ||
  10329. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10330. continue;
  10331. span = cn->colspan ? cn->colspan : 1;
  10332. br_style_for(&doc, c, pst, &cs);
  10333. if (cs.display == BR_DISPLAY_NONE)
  10334. continue;
  10335. if (col + span > maxcols)
  10336. span = maxcols - col;
  10337. if (span < 1)
  10338. break;
  10339. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  10340. mp_px(&cs, 7, avail) +
  10341. mp_px(&cs, 5, avail) +
  10342. mp_px(&cs, 3, avail) +
  10343. mp_px(&cs, 1, avail) +
  10344. cs.border_w[0] + cs.border_w[1] +
  10345. cs.border_w[2] + cs.border_w[3];
  10346. if (w < 24)
  10347. w = 24;
  10348. if (span == 1) {
  10349. if (w > raw[col])
  10350. raw[col] = w;
  10351. }
  10352. if (col + span > cols)
  10353. cols = col + span;
  10354. col += span;
  10355. }
  10356. }
  10357. /* A colspan cell only has to be as wide as the sum of its columns. */
  10358. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10359. struct br_node *rn = &doc.nodes[r];
  10360. int col = 0;
  10361. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10362. continue;
  10363. for (c = rn->first; c; c = doc.nodes[c].next) {
  10364. struct br_node *cn = &doc.nodes[c];
  10365. struct br_style cs;
  10366. int span, w, sum, i;
  10367. if (cn->type != BR_NODE_ELEM ||
  10368. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10369. continue;
  10370. span = cn->colspan ? cn->colspan : 1;
  10371. if (col + span > maxcols)
  10372. span = maxcols - col;
  10373. if (span < 1)
  10374. break;
  10375. if (span > 1) {
  10376. br_style_for(&doc, c, pst, &cs);
  10377. if (cs.display != BR_DISPLAY_NONE) {
  10378. w = intrinsic_width(l->ui, c, &cs,
  10379. 0, avail) +
  10380. mp_px(&cs, 7, avail) +
  10381. mp_px(&cs, 5, avail) +
  10382. mp_px(&cs, 3, avail) +
  10383. mp_px(&cs, 1, avail) +
  10384. cs.border_w[0] + cs.border_w[1] +
  10385. cs.border_w[2] + cs.border_w[3];
  10386. sum = 0;
  10387. for (i = 0; i < span; i++)
  10388. sum += raw[col + i];
  10389. if (w > sum)
  10390. raw[col + span - 1] += w - sum;
  10391. }
  10392. }
  10393. col += span;
  10394. }
  10395. }
  10396. /* Explicit and percentage widths override intrinsic widths. */
  10397. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10398. struct br_node *rn = &doc.nodes[r];
  10399. int col = 0;
  10400. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10401. continue;
  10402. for (c = rn->first; c; c = doc.nodes[c].next) {
  10403. struct br_node *cn = &doc.nodes[c];
  10404. struct br_style cs;
  10405. int span;
  10406. if (cn->type != BR_NODE_ELEM ||
  10407. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  10408. continue;
  10409. span = cn->colspan ? cn->colspan : 1;
  10410. if (col + span > maxcols)
  10411. span = maxcols - col;
  10412. if (span < 1)
  10413. break;
  10414. if (span == 1) {
  10415. br_style_for(&doc, c, pst, &cs);
  10416. if (cs.display != BR_DISPLAY_NONE) {
  10417. if (cs.width_kind == 1) {
  10418. raw[col] = cs.width;
  10419. fixed[col] = 1;
  10420. } else if (cs.width_kind == 2 ||
  10421. cs.width_kind == 3) {
  10422. raw[col] = style_width_px(&cs,
  10423. avail);
  10424. fixed[col] = 1;
  10425. }
  10426. }
  10427. }
  10428. col += span;
  10429. }
  10430. }
  10431. for (c = 0; c < (unsigned int)cols; c++) {
  10432. if (raw[c] < 8)
  10433. raw[c] = 8;
  10434. total += raw[c];
  10435. if (fixed[c])
  10436. fixed_sum += raw[c];
  10437. else {
  10438. free_raw += raw[c];
  10439. free_cols++;
  10440. }
  10441. }
  10442. if (fixed_sum > 0 && fixed_sum < avail) {
  10443. int free_avail = avail - fixed_sum;
  10444. int i;
  10445. if (free_raw > 0) {
  10446. for (i = 0; i < cols; i++)
  10447. if (!fixed[i])
  10448. raw[i] = free_avail * raw[i] /
  10449. free_raw;
  10450. } else if (free_cols > 0) {
  10451. for (i = 0; i < cols; i++)
  10452. if (!fixed[i])
  10453. raw[i] = free_avail / free_cols;
  10454. }
  10455. total = 0;
  10456. for (i = 0; i < cols; i++)
  10457. total += raw[i];
  10458. } else if (total < avail && total > 0) {
  10459. int i;
  10460. for (i = 0; i < cols; i++)
  10461. raw[i] = raw[i] * avail / total;
  10462. total = 0;
  10463. for (i = 0; i < cols; i++)
  10464. total += raw[i];
  10465. }
  10466. *out_cols = cols;
  10467. *out_total = total;
  10468. }
  10469. static void layout_table_row(struct lay *l, unsigned int row,
  10470. const struct br_style *pst, int depth,
  10471. unsigned short link)
  10472. {
  10473. unsigned int n, cell[12];
  10474. int raw[12], colstart[12], colspan[12];
  10475. int prefix[13];
  10476. int ncell = 0, total = 0, cols = 0, col = 0;
  10477. int row_left = l->left, row_right = l->right;
  10478. int avail = row_right - row_left;
  10479. int y = l->y, bottom = l->y;
  10480. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  10481. struct br_node *nd = &doc.nodes[n];
  10482. struct br_style cs;
  10483. int span;
  10484. if (nd->type == BR_NODE_TEXT) {
  10485. if (text_node_blank(nd))
  10486. continue;
  10487. layout_children(l, row, pst, depth, link);
  10488. return;
  10489. }
  10490. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  10491. layout_children(l, row, pst, depth, link);
  10492. return;
  10493. }
  10494. br_style_for(&doc, n, pst, &cs);
  10495. if (cs.display == BR_DISPLAY_NONE)
  10496. continue;
  10497. if (ncell >= 12) {
  10498. layout_children(l, row, pst, depth, link);
  10499. return;
  10500. }
  10501. span = nd->colspan ? nd->colspan : 1;
  10502. if (span > 12 - col)
  10503. span = 12 - col;
  10504. if (span < 1)
  10505. continue;
  10506. cell[ncell] = n;
  10507. colstart[ncell] = col;
  10508. colspan[ncell] = span;
  10509. col += span;
  10510. ncell++;
  10511. }
  10512. if (ncell < 1 || avail < 32) {
  10513. layout_children(l, row, pst, depth, link);
  10514. return;
  10515. }
  10516. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  10517. &total);
  10518. if (cols < 2 || total <= 0) {
  10519. int c;
  10520. total = 0;
  10521. for (c = 0; c < ncell; c++) {
  10522. struct br_style cs;
  10523. br_style_for(&doc, cell[c], pst, &cs);
  10524. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  10525. avail) +
  10526. mp_px(&cs, 7, avail) +
  10527. mp_px(&cs, 5, avail) +
  10528. mp_px(&cs, 3, avail) +
  10529. mp_px(&cs, 1, avail);
  10530. if (raw[c] < 24)
  10531. raw[c] = 24;
  10532. total += raw[c];
  10533. }
  10534. /* A one-column table still has to fill its own width; the
  10535. * intrinsic fallback above otherwise leaves the cell at its
  10536. * text width (HN's outer table and nested story table). */
  10537. if (total > 0 && total < avail) {
  10538. int c;
  10539. for (c = 0; c < ncell; c++)
  10540. raw[c] = raw[c] * avail / total;
  10541. total = avail;
  10542. }
  10543. }
  10544. prefix[0] = row_left;
  10545. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  10546. prefix[n + 1] = prefix[n] + raw[n];
  10547. for (n = 0; n < (unsigned int)ncell; n++) {
  10548. struct br_style cs;
  10549. int start = colstart[n];
  10550. int end = start + colspan[n];
  10551. int w;
  10552. if (end > cols)
  10553. end = cols;
  10554. if (start >= cols)
  10555. continue;
  10556. w = prefix[end] - prefix[start];
  10557. br_style_for(&doc, cell[n], pst, &cs);
  10558. /* The column width already reflects the cell's width property. */
  10559. cs.width_kind = 0;
  10560. cs.max_width_kind = 0;
  10561. if (w < 24)
  10562. w = 24;
  10563. if (w < 8)
  10564. w = 8;
  10565. l->left = prefix[start];
  10566. l->right = l->left + w;
  10567. l->y = y;
  10568. l->line_left = l->line_x = l->left;
  10569. l->run_x = l->left;
  10570. l->line_y = l->y;
  10571. l->line_h = 0;
  10572. l->nruns = 0;
  10573. l->space_pending = 0;
  10574. l->align = cs.align;
  10575. layout_block(l, cell[n], &cs, depth + 1, link);
  10576. if (l->y > bottom)
  10577. bottom = l->y;
  10578. }
  10579. l->left = row_left;
  10580. l->right = row_right;
  10581. l->y = bottom;
  10582. l->line_left = l->line_x = l->left;
  10583. l->run_x = l->left;
  10584. l->line_y = l->y;
  10585. l->line_h = 0;
  10586. l->nruns = 0;
  10587. l->space_pending = 0;
  10588. }
  10589. #define TBL_MAX_ROWS 32
  10590. #define TBL_MAX_COLS 12
  10591. #define TBL_MAX_CELLS 128
  10592. struct tbl_cell {
  10593. unsigned int node;
  10594. unsigned char row, col, rowspan, colspan;
  10595. int height;
  10596. };
  10597. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  10598. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  10599. static int table_active;
  10600. static int table_has_rowspan(unsigned int table)
  10601. {
  10602. unsigned int r, c;
  10603. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  10604. struct br_node *rn = &doc.nodes[r];
  10605. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  10606. continue;
  10607. for (c = rn->first; c; c = doc.nodes[c].next) {
  10608. struct br_node *cn = &doc.nodes[c];
  10609. if (cn->type == BR_NODE_ELEM &&
  10610. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  10611. cn->rowspan > 1)
  10612. return 1;
  10613. }
  10614. }
  10615. return 0;
  10616. }
  10617. static void table_cell_style(unsigned int row, unsigned int cell,
  10618. const struct br_style *st, struct br_style *out)
  10619. {
  10620. struct br_style trs;
  10621. br_style_for(&doc, row, st, &trs);
  10622. br_style_for(&doc, cell, &trs, out);
  10623. }
  10624. /* Tables that use rowspan need row heights before anything is painted. This
  10625. * path builds a small occupancy grid, measures the natural cell heights, then
  10626. * lays every cell out at its row/column position. Tables without rowspan
  10627. * keep the lighter per-row path in layout_table_row(). */
  10628. static void layout_table(struct lay *l, unsigned int table,
  10629. const struct br_style *st, int depth,
  10630. unsigned short link)
  10631. {
  10632. unsigned int rows[TBL_MAX_ROWS];
  10633. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  10634. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  10635. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  10636. int free_raw = 0, free_cols = 0;
  10637. int table_left = l->left, table_right = l->right;
  10638. int top = l->y, avail = table_right - table_left;
  10639. unsigned int r, c;
  10640. int i, rr, cc;
  10641. if (depth > 48 || table_active) {
  10642. layout_children(l, table, st, depth, link);
  10643. return;
  10644. }
  10645. table_active = 1;
  10646. for (r = doc.nodes[table].first;
  10647. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  10648. struct br_node *rn = &doc.nodes[r];
  10649. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  10650. rows[nrows++] = r;
  10651. }
  10652. if (!nrows) {
  10653. table_active = 0;
  10654. layout_children(l, table, st, depth, link);
  10655. return;
  10656. }
  10657. for (rr = 0; rr < nrows; rr++)
  10658. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  10659. tbl_at[rr][cc] = 0;
  10660. for (rr = 0; rr < nrows; rr++) {
  10661. int col = 0;
  10662. for (c = doc.nodes[rows[rr]].first; c;
  10663. c = doc.nodes[c].next) {
  10664. struct br_node *cn = &doc.nodes[c];
  10665. struct br_style cs;
  10666. int rs, csn;
  10667. if (cn->type != BR_NODE_ELEM ||
  10668. (cn->tag != BR_TAG_TD &&
  10669. cn->tag != BR_TAG_TH))
  10670. continue;
  10671. table_cell_style(rows[rr], c, st, &cs);
  10672. if (cs.display == BR_DISPLAY_NONE)
  10673. continue;
  10674. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  10675. col++;
  10676. if (col >= TBL_MAX_COLS)
  10677. break;
  10678. rs = cn->rowspan ? cn->rowspan : 1;
  10679. csn = cn->colspan ? cn->colspan : 1;
  10680. if (rr + rs > nrows)
  10681. rs = nrows - rr;
  10682. if (col + csn > TBL_MAX_COLS)
  10683. csn = TBL_MAX_COLS - col;
  10684. if (rs < 1 || csn < 1)
  10685. continue;
  10686. if (ncells >= TBL_MAX_CELLS)
  10687. break;
  10688. tbl_cells[ncells].node = c;
  10689. tbl_cells[ncells].row = (unsigned char)rr;
  10690. tbl_cells[ncells].col = (unsigned char)col;
  10691. tbl_cells[ncells].rowspan = (unsigned char)rs;
  10692. tbl_cells[ncells].colspan = (unsigned char)csn;
  10693. tbl_cells[ncells].height = 0;
  10694. for (i = rr; i < rr + rs; i++)
  10695. for (int j = col; j < col + csn; j++)
  10696. tbl_at[i][j] =
  10697. (unsigned short)(ncells + 1);
  10698. ncells++;
  10699. col += csn;
  10700. if (col > cols)
  10701. cols = col;
  10702. }
  10703. }
  10704. if (!ncells || cols < 1) {
  10705. table_active = 0;
  10706. layout_children(l, table, st, depth, link);
  10707. return;
  10708. }
  10709. for (i = 0; i < cols; i++) {
  10710. raw[i] = 0;
  10711. fixed[i] = 0;
  10712. }
  10713. /* Intrinsic widths of single-column cells. */
  10714. for (i = 0; i < ncells; i++) {
  10715. struct br_style cs;
  10716. int w;
  10717. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10718. st, &cs);
  10719. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10720. mp_px(&cs, 7, avail) +
  10721. mp_px(&cs, 5, avail) +
  10722. mp_px(&cs, 3, avail) +
  10723. mp_px(&cs, 1, avail) +
  10724. cs.border_w[0] + cs.border_w[1] +
  10725. cs.border_w[2] + cs.border_w[3];
  10726. if (w < 24)
  10727. w = 24;
  10728. if (tbl_cells[i].colspan == 1) {
  10729. int col = tbl_cells[i].col;
  10730. if (w > raw[col])
  10731. raw[col] = w;
  10732. }
  10733. }
  10734. /* A spanning cell only needs the sum of its columns to be large
  10735. * enough; put the deficit in the last column. */
  10736. for (i = 0; i < ncells; i++) {
  10737. struct br_style cs;
  10738. int w, sum, col, span;
  10739. if (tbl_cells[i].colspan < 2)
  10740. continue;
  10741. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10742. st, &cs);
  10743. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10744. mp_px(&cs, 7, avail) +
  10745. mp_px(&cs, 5, avail) +
  10746. mp_px(&cs, 3, avail) +
  10747. mp_px(&cs, 1, avail) +
  10748. cs.border_w[0] + cs.border_w[1] +
  10749. cs.border_w[2] + cs.border_w[3];
  10750. col = tbl_cells[i].col;
  10751. span = tbl_cells[i].colspan;
  10752. sum = 0;
  10753. for (int j = 0; j < span; j++)
  10754. sum += raw[col + j];
  10755. if (w > sum)
  10756. raw[col + span - 1] += w - sum;
  10757. }
  10758. /* Explicit/percentage widths, as in table_columns(). */
  10759. for (i = 0; i < ncells; i++) {
  10760. struct br_style cs;
  10761. int col;
  10762. if (tbl_cells[i].colspan != 1)
  10763. continue;
  10764. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10765. st, &cs);
  10766. col = tbl_cells[i].col;
  10767. if (cs.width_kind == 1) {
  10768. raw[col] = cs.width;
  10769. fixed[col] = 1;
  10770. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10771. raw[col] = style_width_px(&cs, avail);
  10772. fixed[col] = 1;
  10773. }
  10774. }
  10775. for (i = 0; i < cols; i++) {
  10776. if (raw[i] < 8)
  10777. raw[i] = 8;
  10778. total += raw[i];
  10779. if (fixed[i])
  10780. fixed_sum += raw[i];
  10781. else {
  10782. free_raw += raw[i];
  10783. free_cols++;
  10784. }
  10785. }
  10786. if (fixed_sum > 0 && fixed_sum < avail) {
  10787. int free_avail = avail - fixed_sum;
  10788. if (free_raw > 0) {
  10789. for (i = 0; i < cols; i++)
  10790. if (!fixed[i])
  10791. raw[i] = free_avail * raw[i] /
  10792. free_raw;
  10793. } else if (free_cols > 0) {
  10794. for (i = 0; i < cols; i++)
  10795. if (!fixed[i])
  10796. raw[i] = free_avail / free_cols;
  10797. }
  10798. } else if (total < avail && total > 0) {
  10799. for (i = 0; i < cols; i++)
  10800. raw[i] = raw[i] * avail / total;
  10801. }
  10802. prefix[0] = table_left;
  10803. for (i = 0; i < cols; i++)
  10804. prefix[i + 1] = prefix[i] + raw[i];
  10805. /* Measure natural cell heights with the column widths. */
  10806. for (i = 0; i < ncells; i++) {
  10807. struct br_style cs;
  10808. int col = tbl_cells[i].col;
  10809. int span = tbl_cells[i].colspan;
  10810. int w = prefix[col + span] - prefix[col];
  10811. int sl = l->left, sr = l->right, sy = l->y;
  10812. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10813. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10814. int sal = l->align, sdraw = l->draw;
  10815. struct ngui *sui = l->ui;
  10816. if (w < 8)
  10817. w = 8;
  10818. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10819. st, &cs);
  10820. cs.width_kind = 0;
  10821. cs.max_width_kind = 0;
  10822. l->draw = 0;
  10823. l->ui = 0;
  10824. l->left = prefix[col];
  10825. l->right = l->left + w;
  10826. l->y = 0;
  10827. l->line_left = l->line_x = l->left;
  10828. l->run_x = l->left;
  10829. l->line_y = 0;
  10830. l->line_h = 0;
  10831. l->nruns = 0;
  10832. l->space_pending = 0;
  10833. l->align = cs.align;
  10834. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10835. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10836. l->left = sl;
  10837. l->right = sr;
  10838. l->y = sy;
  10839. l->line_x = slx;
  10840. l->run_x = srx;
  10841. l->line_y = sly;
  10842. l->line_h = slh;
  10843. l->nruns = snr;
  10844. l->space_pending = ssp;
  10845. l->align = sal;
  10846. l->draw = sdraw;
  10847. l->ui = sui;
  10848. }
  10849. for (i = 0; i < nrows; i++)
  10850. rowh[i] = 0;
  10851. for (i = 0; i < ncells; i++) {
  10852. int row = tbl_cells[i].row;
  10853. if (tbl_cells[i].rowspan == 1) {
  10854. if (tbl_cells[i].height > rowh[row])
  10855. rowh[row] = tbl_cells[i].height;
  10856. }
  10857. }
  10858. for (i = 0; i < ncells; i++) {
  10859. int row = tbl_cells[i].row;
  10860. int span = tbl_cells[i].rowspan;
  10861. int sum = 0;
  10862. if (span < 2)
  10863. continue;
  10864. for (int j = 0; j < span; j++)
  10865. sum += rowh[row + j];
  10866. if (sum < tbl_cells[i].height)
  10867. rowh[row + span - 1] +=
  10868. tbl_cells[i].height - sum;
  10869. }
  10870. for (i = 0; i < nrows; i++)
  10871. if (rowh[i] < 8)
  10872. rowh[i] = 8;
  10873. rowy[0] = top;
  10874. for (i = 1; i < nrows; i++)
  10875. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10876. if (!l->draw) {
  10877. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10878. table_active = 0;
  10879. return;
  10880. }
  10881. for (i = 0; i < ncells; i++) {
  10882. struct br_style cs;
  10883. int col = tbl_cells[i].col;
  10884. int span = tbl_cells[i].colspan;
  10885. int row = tbl_cells[i].row;
  10886. int rspan = tbl_cells[i].rowspan;
  10887. int w = prefix[col + span] - prefix[col];
  10888. int h = 0;
  10889. int sl = l->left, sr = l->right, sy = l->y;
  10890. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10891. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10892. int sal = l->align;
  10893. int deco;
  10894. for (int j = 0; j < rspan; j++)
  10895. h += rowh[row + j];
  10896. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10897. cs.width_kind = 0;
  10898. cs.max_width_kind = 0;
  10899. cs.box_sizing = 0;
  10900. deco = mp_px(&cs, 4, avail) +
  10901. mp_px(&cs, 6, avail) +
  10902. cs.border_w[0] + cs.border_w[2];
  10903. cs.height_kind = 1;
  10904. cs.height = h > deco ? h - deco : 0;
  10905. /* The block painter reads block_h[] from the measure pass; make
  10906. * the table cell fill its row/rowspan, not just its content. */
  10907. if (h > 0 && h < 65536)
  10908. block_h[tbl_cells[i].node] = (unsigned short)h;
  10909. l->left = prefix[col];
  10910. l->right = l->left + w;
  10911. l->y = rowy[row];
  10912. l->line_left = l->line_x = l->left;
  10913. l->run_x = l->left;
  10914. l->line_y = l->y;
  10915. l->line_h = 0;
  10916. l->nruns = 0;
  10917. l->space_pending = 0;
  10918. l->align = cs.align;
  10919. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10920. l->left = sl;
  10921. l->right = sr;
  10922. l->y = sy;
  10923. l->line_x = slx;
  10924. l->run_x = srx;
  10925. l->line_y = sly;
  10926. l->line_h = slh;
  10927. l->nruns = snr;
  10928. l->space_pending = ssp;
  10929. l->align = sal;
  10930. }
  10931. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10932. table_active = 0;
  10933. }
  10934. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10935. * flow so they sit above it, like CSS painting order. Their flow origin is
  10936. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10937. struct br_deferred {
  10938. unsigned int node;
  10939. int flow_y, flow_left, flow_right;
  10940. int parent_top; /* the parent box top, for sticky clamping */
  10941. unsigned short link;
  10942. signed short z_index;
  10943. unsigned char z_set;
  10944. unsigned int order;
  10945. };
  10946. /* Positioned boxes painted after the flow. News front pages have one or two
  10947. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10948. * old 16 entries the rest fell back into the flow, so a hero image landed
  10949. * below its padding-top aspect box instead of on top of it. */
  10950. #define BR_MAX_DEFERRED 256
  10951. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10952. static int ndeferred;
  10953. /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
  10954. * box, 0 when it has none; *ps receives the pseudo-element's style. */
  10955. static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
  10956. struct br_style *ps, int base)
  10957. {
  10958. char buf[8];
  10959. int w, h;
  10960. if (!doc.npe_rules ||
  10961. br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
  10962. ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
  10963. return 0;
  10964. w = ps->width_kind ? style_width_px(ps, base) : 0;
  10965. h = ps->height_kind ? style_height_px(ps, base) : 0;
  10966. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10967. w = (int)ps->min_width;
  10968. if (w <= 0)
  10969. w = h;
  10970. if (w <= 0 || w > 512)
  10971. return 0;
  10972. return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
  10973. }
  10974. /* An empty ::before/::after with a size and a background: one run the
  10975. * size of the box. Only data: background images are drawn (decoded at
  10976. * the background-size); `margin-left: auto` inside a flex parent pushes
  10977. * the box to the line's right edge like the flex row would. */
  10978. static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
  10979. const struct br_style *ps, unsigned short link)
  10980. {
  10981. struct lay_run *r;
  10982. int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
  10983. const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
  10984. if (lw < 8)
  10985. lw = 8;
  10986. w = ps->width_kind ? style_width_px(ps, lw) : 0;
  10987. h = ps->height_kind ? style_height_px(ps, lw) : 0;
  10988. if (ps->min_width_kind == 1 && w < (int)ps->min_width)
  10989. w = (int)ps->min_width;
  10990. if (w <= 0)
  10991. w = h;
  10992. if (h <= 0)
  10993. h = w;
  10994. if (w <= 0 || w > 512 || h > 512)
  10995. return;
  10996. ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
  10997. mr = mp_px(ps, 1, lw);
  10998. if (ml < 0)
  10999. ml = 0;
  11000. if (mr < 0)
  11001. mr = 0;
  11002. if (l->line_x + ml + w > l->line_right &&
  11003. (l->nruns > 0 || l->line_x > l->line_left))
  11004. flush_line(l);
  11005. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  11006. flush_line(l);
  11007. if (l->nruns == 0) {
  11008. l->line_y = l->y;
  11009. l->line_h = 0;
  11010. start_line(l, ps);
  11011. }
  11012. if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
  11013. l->line_right - w - mr > l->line_x)
  11014. l->line_x = l->line_right - w - mr;
  11015. else
  11016. l->line_x += ml;
  11017. r = &l->runs[l->nruns++];
  11018. memset(r, 0, sizeof(*r));
  11019. r->box = l->box_owner;
  11020. r->gap = (unsigned short)(l->line_x > l->run_x ?
  11021. l->line_x - l->run_x : 0);
  11022. r->img = RUN_PBOX;
  11023. r->href = link;
  11024. r->iw = (unsigned short)w;
  11025. r->ih = (unsigned short)h;
  11026. r->w = (unsigned short)w;
  11027. r->font_px = ps->font_px;
  11028. r->pb_has_bg = ps->has_bg;
  11029. r->pb_bg = ps->bg;
  11030. r->pb_img = -1;
  11031. if (ps->transform_set) {
  11032. r->transform_scale = 1;
  11033. r->scale_x = ps->scale_x;
  11034. r->scale_y = ps->scale_y;
  11035. r->rotate_x100 = ps->rotate_x100;
  11036. }
  11037. /* Background size and position, as draw_bg_image() resolves them. */
  11038. tw = w;
  11039. th = h;
  11040. if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
  11041. int bw = ps->bg_size_w, bh = ps->bg_size_h;
  11042. if (ps->bg_size_kind == 2) {
  11043. bw = bw ? w * bw / 100 : 0;
  11044. bh = bh ? h * bh / 100 : 0;
  11045. }
  11046. tw = bw ? bw : (bh ? bh : w);
  11047. th = bh ? bh : tw;
  11048. }
  11049. if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
  11050. r->pb_img = (short)data_url_image(url, tw, th);
  11051. r->pb_w = (short)tw;
  11052. r->pb_h = (short)th;
  11053. r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
  11054. (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
  11055. r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
  11056. (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
  11057. l->line_x += w + mr;
  11058. l->run_x = l->line_x;
  11059. if (l->line_h < h)
  11060. l->line_h = h;
  11061. }
  11062. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  11063. * element's line. A block-level pseudo-element gets its own line; its box
  11064. * (margins, padding, background) is not drawn. */
  11065. static void emit_pseudo(struct lay *l, unsigned int node,
  11066. const struct br_style *st, int pe, unsigned short link)
  11067. {
  11068. char buf[160];
  11069. struct br_style ps;
  11070. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  11071. unsigned int i = 0;
  11072. int block, space_w;
  11073. if (!n && ps.content == BR_CONTENT_EMPTY &&
  11074. ps.display != BR_DISPLAY_NONE) {
  11075. emit_pseudo_box(l, st, &ps, link);
  11076. return;
  11077. }
  11078. if (!n)
  11079. return;
  11080. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  11081. if (block)
  11082. flush_line(l);
  11083. if (ps.uppercase)
  11084. for (i = 0; i < n; i++)
  11085. if (buf[i] >= 'a' && buf[i] <= 'z')
  11086. buf[i] = (char)(buf[i] - 'a' + 'A');
  11087. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  11088. if (space_w <= 0)
  11089. space_w = 8;
  11090. i = 0;
  11091. while (i < n) {
  11092. char word[28];
  11093. unsigned int k = 0;
  11094. int w;
  11095. if (buf[i] == ' ') {
  11096. l->space_pending = 1;
  11097. i++;
  11098. continue;
  11099. }
  11100. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  11101. word[k++] = buf[i++];
  11102. word[k] = '\0';
  11103. if (l->space_pending &&
  11104. (l->nruns > 0 || l->line_x > l->line_left) &&
  11105. l->line_x + space_w <= l->line_right)
  11106. l->line_x += space_w;
  11107. l->space_pending = 0;
  11108. w = (int)face_text_width(l->ui, &ps, word, k);
  11109. if (l->line_x + w > l->line_right &&
  11110. (l->nruns > 0 || l->line_x > l->line_left))
  11111. flush_line(l);
  11112. add_run(l, 0, 0, &ps, link, word);
  11113. }
  11114. if (block)
  11115. flush_line(l);
  11116. }
  11117. /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
  11118. * z-index): measured in place, painted from the deferred stacked pass
  11119. * against its containing block. Shared by block and flex layout, so an
  11120. * absolute icon inside a flex row (a password field's reveal button) is
  11121. * not laid out as one of the row's items. Returns 1 when it handled n. */
  11122. static int layout_out_of_flow(struct lay *l, unsigned int n,
  11123. const struct br_style *cs, int depth,
  11124. unsigned short lk)
  11125. {
  11126. if (!(cs->pos == 1 || cs->pos == 2 ||
  11127. ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
  11128. return 0;
  11129. if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
  11130. ndeferred < BR_MAX_DEFERRED) {
  11131. /* Relative or sticky z-index (a sticky site
  11132. * header): measure and advance the flow without
  11133. * painting, then paint it in the deferred
  11134. * (stacked) pass, above the content after it. */
  11135. int fy = l->y, fl = l->left, fr = l->right;
  11136. int save_draw = l->draw;
  11137. l->draw = 0;
  11138. layout_block(l, n, cs, depth + 1, lk);
  11139. l->draw = save_draw;
  11140. deferred[ndeferred].node = n;
  11141. deferred[ndeferred].parent_top = l->parent_top;
  11142. deferred[ndeferred].flow_y = fy;
  11143. deferred[ndeferred].flow_left = fl;
  11144. deferred[ndeferred].flow_right = fr;
  11145. deferred[ndeferred].link = lk;
  11146. deferred[ndeferred].z_index = cs->z_index;
  11147. deferred[ndeferred].z_set = cs->z_set;
  11148. deferred[ndeferred].order = (unsigned int)ndeferred;
  11149. ndeferred++;
  11150. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  11151. deferred[ndeferred].node = n;
  11152. deferred[ndeferred].parent_top = l->parent_top;
  11153. deferred[ndeferred].flow_y =
  11154. cs->pos == 1 ? l->cb_top : l->y;
  11155. deferred[ndeferred].flow_left =
  11156. cs->pos == 1 ? l->cb_left : l->left;
  11157. deferred[ndeferred].flow_right =
  11158. cs->pos == 1 ? l->cb_right : l->right;
  11159. deferred[ndeferred].link = lk;
  11160. deferred[ndeferred].z_index = cs->z_index;
  11161. deferred[ndeferred].z_set = cs->z_set;
  11162. deferred[ndeferred].order = (unsigned int)ndeferred;
  11163. ndeferred++;
  11164. } else if (l->draw && cs->pos == 1) {
  11165. /* Deferred list full: paint in place, but still
  11166. * against the containing block, not the flow. */
  11167. int fy = l->y, fl = l->left, fr = l->right;
  11168. l->y = l->cb_top;
  11169. l->left = l->cb_left;
  11170. l->right = l->cb_right;
  11171. layout_block(l, n, cs, depth + 1, lk);
  11172. l->y = fy;
  11173. l->left = fl;
  11174. l->right = fr;
  11175. } else {
  11176. layout_block(l, n, cs, depth + 1, lk);
  11177. }
  11178. if (cs->pos == 1 && block_h[n] &&
  11179. doc.nodes[n].class_off) {
  11180. const char *cl = doc.attrs +
  11181. doc.nodes[n].class_off;
  11182. if ((contains_ci(cl, "poster-wrapper") ||
  11183. contains_ci(cl, "ts-picture")) &&
  11184. !has_skeleton_sibling(n))
  11185. l->y += block_h[n];
  11186. }
  11187. return 1;
  11188. }
  11189. /* An element laid out in the text line (an inline span, or an inline-block
  11190. * that flows like one): its runs are tagged with it, so flush_line() can
  11191. * record its box for getBoundingClientRect() and click targeting. */
  11192. static void layout_inline_box(struct lay *l, unsigned int node,
  11193. const struct br_style *cs, int depth,
  11194. unsigned short link)
  11195. {
  11196. unsigned short saved = l->box_owner;
  11197. if (node < BR_MAX_NODES) {
  11198. inline_box_parent[node] = saved;
  11199. l->box_owner = (unsigned short)(node + 1);
  11200. }
  11201. layout_children(l, node, cs, depth + 1, link);
  11202. l->box_owner = saved;
  11203. }
  11204. static void layout_children(struct lay *l, unsigned int parent,
  11205. const struct br_style *pst, int depth,
  11206. unsigned short link)
  11207. {
  11208. unsigned int n;
  11209. if (depth > 48)
  11210. return;
  11211. emit_pseudo(l, parent, pst, 1, link);
  11212. n = doc.nodes[parent].first;
  11213. while (n) {
  11214. struct br_node *nd = &doc.nodes[n];
  11215. struct br_style cs;
  11216. unsigned short lk = link;
  11217. if (nd->type == BR_NODE_TEXT) {
  11218. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  11219. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  11220. n = nd->next;
  11221. continue;
  11222. }
  11223. br_style_for(&doc, n, pst, &cs);
  11224. if (cs.display == BR_DISPLAY_NONE) {
  11225. n = nd->next;
  11226. continue;
  11227. }
  11228. if (cs.clear && l->float_active) {
  11229. flush_line(l);
  11230. if (l->y < l->float_bottom)
  11231. l->y = l->float_bottom;
  11232. l->float_active = 0;
  11233. l->line_x = l->left;
  11234. l->run_x = l->left;
  11235. l->line_left = l->left;
  11236. l->line_right = l->right;
  11237. l->line_y = l->y;
  11238. l->line_h = 0;
  11239. l->nruns = 0;
  11240. l->space_pending = 0;
  11241. }
  11242. if (nd->tag == BR_TAG_A && nd->href_off)
  11243. lk = (unsigned short)n;
  11244. if (layout_out_of_flow(l, n, &cs, depth, lk)) {
  11245. n = nd->next;
  11246. continue;
  11247. }
  11248. if (nd->tag == BR_TAG_BR) {
  11249. flush_line(l);
  11250. n = nd->next;
  11251. continue;
  11252. }
  11253. if (nd->tag == BR_TAG_HR) {
  11254. flush_line(l);
  11255. if (l->draw)
  11256. ngui_fill_rect(l->ui,
  11257. (struct ngui_rect){l->left, l->y + 2,
  11258. l->right - l->left, 1}, BR_GRAY);
  11259. l->y += 8;
  11260. n = nd->next;
  11261. continue;
  11262. }
  11263. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  11264. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  11265. !button_has_elements(n)) {
  11266. if (!(nd->tag == BR_TAG_INPUT &&
  11267. s_eq(br_type(&doc, n), "hidden"))) {
  11268. form_fill_line = pst->display ==
  11269. BR_DISPLAY_FLEX &&
  11270. pst->flex_col;
  11271. add_form_run(l, n, &cs, lk);
  11272. form_fill_line = 0;
  11273. }
  11274. n = nd->next;
  11275. continue;
  11276. }
  11277. if (nd->tag == BR_TAG_IMG) {
  11278. add_image_run(l, n, &cs, lk);
  11279. n = nd->next;
  11280. continue;
  11281. }
  11282. if (nd->tag == BR_TAG_SVG &&
  11283. (cs.display == BR_DISPLAY_INLINE ||
  11284. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  11285. !cs.float_left) {
  11286. add_svg_run(l, n, &cs, lk);
  11287. n = nd->next;
  11288. continue;
  11289. }
  11290. if (nd->tag == BR_TAG_VIDEO) {
  11291. layout_block(l, n, &cs, depth + 1, lk);
  11292. n = nd->next;
  11293. continue;
  11294. }
  11295. if (cs.float_left) {
  11296. n = layout_float_group(l, n, pst, depth, lk);
  11297. continue;
  11298. }
  11299. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  11300. inline_block_flows(n, &cs, 0)) {
  11301. layout_inline_box(l, n, &cs, depth, lk);
  11302. n = nd->next;
  11303. continue;
  11304. }
  11305. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  11306. n = layout_inline_blocks(l, n, pst, depth, link);
  11307. continue;
  11308. }
  11309. /* A flex container is block-level like any block box even when
  11310. * the element is an inline tag such as <a> (a link card with
  11311. * display:flex is common on news sites). Without the block box
  11312. * its children were laid out in the parent flow with a 0x0 box
  11313. * of their own. */
  11314. /* inline-flex around inline content only ("| mehr" link
  11315. * tails, icon+label pills) stays in the text line. */
  11316. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  11317. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  11318. !flex_wants_row(n, &cs)) {
  11319. layout_children(l, n, &cs, depth + 1, lk);
  11320. } else if (cs.display == BR_DISPLAY_BLOCK ||
  11321. cs.display == BR_DISPLAY_FLEX ||
  11322. br_tag_is_block(nd->tag))
  11323. layout_block(l, n, &cs, depth + 1, lk);
  11324. else if (cs.display == BR_DISPLAY_INLINE &&
  11325. nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
  11326. layout_inline_box(l, n, &cs, depth, lk);
  11327. else {
  11328. layout_children(l, n, &cs, depth + 1, lk);
  11329. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  11330. l->space_pending = 1;
  11331. }
  11332. n = nd->next;
  11333. }
  11334. emit_pseudo(l, parent, pst, 2, link);
  11335. }
  11336. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  11337. * runs and a recursive page can otherwise overflow the stack. */
  11338. static struct lay layout_state;
  11339. static int measure_page(int left, int right)
  11340. {
  11341. struct lay *l = &layout_state;
  11342. struct br_style base = base_style();
  11343. unsigned int i;
  11344. for (i = 0; i < BR_MAX_NODES; i++) {
  11345. block_h[i] = 0;
  11346. flex_stretch_h[i] = 0;
  11347. img_top[i] = 0;
  11348. block_top[i] = 0;
  11349. img_h[i] = 0;
  11350. layout_boxes[i].valid = 0;
  11351. }
  11352. memset(li_marker, 0, sizeof(li_marker));
  11353. inline_box_pass_id++;
  11354. l->box_owner = 0;
  11355. l->draw = 0;
  11356. l->ui = &ui;
  11357. l->left = left;
  11358. l->right = right;
  11359. l->y = 0;
  11360. l->line_x = left;
  11361. l->run_x = left;
  11362. l->line_left = left;
  11363. l->line_right = right;
  11364. l->line_y = 0;
  11365. l->line_h = 0;
  11366. l->align = BR_ALIGN_LEFT;
  11367. l->cb_h = layout_view_h;
  11368. l->float_active = 0;
  11369. l->parent_top = 0;
  11370. l->cb_left = left;
  11371. l->cb_right = right;
  11372. l->cb_top = 0;
  11373. l->depth = 0;
  11374. l->nruns = 0;
  11375. l->space_pending = 0;
  11376. base = root_style();
  11377. layout_children(l, doc.root, &base, 0, 0);
  11378. return l->y + 8;
  11379. }
  11380. static int deferred_cmp(const struct br_deferred *a,
  11381. const struct br_deferred *b)
  11382. {
  11383. int az = a->z_set ? a->z_index : 0;
  11384. int bz = b->z_set ? b->z_index : 0;
  11385. if (az != bz)
  11386. return az < bz ? -1 : 1;
  11387. if (a->order != b->order)
  11388. return a->order < b->order ? -1 : 1;
  11389. return 0;
  11390. }
  11391. static void sort_deferred(void)
  11392. {
  11393. int i;
  11394. for (i = 1; i < ndeferred; i++) {
  11395. struct br_deferred key = deferred[i];
  11396. int j = i;
  11397. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  11398. deferred[j] = deferred[j - 1];
  11399. j--;
  11400. }
  11401. deferred[j] = key;
  11402. }
  11403. }
  11404. static void render_page(int left, int right, int y0)
  11405. {
  11406. struct lay *l = &layout_state;
  11407. struct br_style base = base_style();
  11408. inline_box_pass_id++;
  11409. l->box_owner = 0;
  11410. l->draw = 1;
  11411. l->ui = &ui;
  11412. l->left = left;
  11413. l->right = right;
  11414. l->y = y0;
  11415. l->line_x = left;
  11416. l->run_x = left;
  11417. l->line_left = left;
  11418. l->line_right = right;
  11419. l->line_y = y0;
  11420. l->line_h = 0;
  11421. l->align = BR_ALIGN_LEFT;
  11422. l->cb_h = layout_view_h;
  11423. l->float_active = 0;
  11424. l->parent_top = 0;
  11425. l->cb_left = left;
  11426. l->cb_right = right;
  11427. l->cb_top = y0;
  11428. l->depth = 0;
  11429. l->nruns = 0;
  11430. l->space_pending = 0;
  11431. nhits = 0;
  11432. ndeferred = 0;
  11433. base = root_style();
  11434. layout_children(l, doc.root, &base, 0, 0);
  11435. sort_deferred();
  11436. {
  11437. int i;
  11438. for (i = 0; i < ndeferred; i++) {
  11439. struct br_style st;
  11440. br_style_for(&doc, deferred[i].node, &base, &st);
  11441. if (st.display == BR_DISPLAY_NONE)
  11442. continue;
  11443. l->draw = 1;
  11444. l->left = deferred[i].flow_left;
  11445. l->right = deferred[i].flow_right;
  11446. l->y = deferred[i].flow_y;
  11447. l->parent_top = deferred[i].parent_top;
  11448. l->line_left = l->line_x = l->left;
  11449. l->run_x = l->left;
  11450. l->line_y = l->y;
  11451. l->line_h = 0;
  11452. l->nruns = 0;
  11453. l->space_pending = 0;
  11454. l->align = st.align;
  11455. if (st.pos == 2 && block_h[deferred[i].node]) {
  11456. struct ngui_rect clip;
  11457. int ch = block_h[deferred[i].node] + 24;
  11458. int pr = page_rect.x + page_rect.w - 12;
  11459. int x0 = page_rect.x, x1 = pr;
  11460. int y0 = page_rect.y;
  11461. /* A box placed by `bottom` (a page footer) is
  11462. * clipped and filled where layout_block puts
  11463. * it, against the bottom edge. */
  11464. if (st.bottom_set && !st.top_set) {
  11465. ch = block_h[deferred[i].node] +
  11466. mp_px(&st, 0, pr - page_rect.x) +
  11467. mp_px(&st, 2, pr - page_rect.x);
  11468. y0 = page_rect.y + page_rect.h -
  11469. st.bottom - ch;
  11470. }
  11471. /* The background pre-fill spans the box's own
  11472. * columns, not the whole page: Docusaurus parks
  11473. * a white "Skip to main content" link at
  11474. * `left: 100%` with a z-index above the navbar,
  11475. * and a full-width fill painted over the bar. */
  11476. if (st.left_set)
  11477. x0 = page_rect.x + st.left;
  11478. else if (!st.right_set)
  11479. x0 = deferred[i].flow_left;
  11480. if (st.width_kind == 1) {
  11481. if (st.right_set && !st.left_set)
  11482. x0 = pr - st.right - st.width;
  11483. x1 = x0 + st.width;
  11484. } else if (st.right_set) {
  11485. x1 = pr - st.right;
  11486. }
  11487. if (x0 >= pr || x1 <= page_rect.x)
  11488. continue; /* entirely off-screen */
  11489. if (x0 < page_rect.x)
  11490. x0 = page_rect.x;
  11491. if (x1 > pr)
  11492. x1 = pr;
  11493. if (y0 < page_rect.y) {
  11494. ch -= page_rect.y - y0;
  11495. y0 = page_rect.y;
  11496. }
  11497. clip.x = x0;
  11498. clip.y = y0;
  11499. clip.w = x1 - x0;
  11500. if (ch > page_rect.h)
  11501. ch = page_rect.h;
  11502. if (ch <= 0)
  11503. continue;
  11504. clip.h = ch;
  11505. ngui_push_clip(&ui, clip);
  11506. if (st.has_bg)
  11507. ngui_fill_rect(&ui, clip, st.bg);
  11508. layout_block(l, deferred[i].node, &st, 0,
  11509. deferred[i].link);
  11510. ngui_pop_clip(&ui);
  11511. } else {
  11512. layout_block(l, deferred[i].node, &st, 0,
  11513. deferred[i].link);
  11514. }
  11515. }
  11516. }
  11517. }
  11518. /* ---- UI ---- */
  11519. static int find_hit(int x, int y)
  11520. {
  11521. int i;
  11522. for (i = nhits - 1; i >= 0; i--) {
  11523. struct hit *h = &hits[i];
  11524. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  11525. y < h->y + h->h)
  11526. return (int)h->node;
  11527. }
  11528. return 0;
  11529. }
  11530. /* ---- URL-bar autocomplete ----
  11531. *
  11532. * While the address bar has the focus a dropdown lists up to SUG_MAX
  11533. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  11534. * visited/recent sites; typing ranks prefix matches of the URL (with or
  11535. * without the scheme and "www.") above substring matches of the URL, then
  11536. * of the title, and adds visit count and recency. Typing at the end of the
  11537. * text also completes inline to the next '/' of the best prefix match
  11538. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  11539. * keystroke replaces it; Enter on that text opens the history URL it came
  11540. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  11541. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  11542. * bar), and a click on a row opens it. */
  11543. #define SUG_MAX 6
  11544. #define SUG_ROW_H 36
  11545. static int sug_idx[SUG_MAX];
  11546. static int sug_n, sug_sel = -1, sug_open;
  11547. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  11548. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  11549. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  11550. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  11551. static struct ngui_rect url_rect, sug_rect;
  11552. static int url_had_focus;
  11553. static char lc(char c)
  11554. {
  11555. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  11556. }
  11557. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  11558. {
  11559. for (; *p; s++, p++)
  11560. if (lc(*s) != *p)
  11561. return 0;
  11562. return 1;
  11563. }
  11564. static unsigned int url_scheme_len(const char *url)
  11565. {
  11566. if (starts_with(url, "https://"))
  11567. return 8;
  11568. if (starts_with(url, "http://"))
  11569. return 7;
  11570. return 0;
  11571. }
  11572. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  11573. * whole URL, the URL without its scheme, or without scheme and "www.". */
  11574. static int hist_prefix_at(const char *url, const char *t)
  11575. {
  11576. unsigned int s = url_scheme_len(url);
  11577. if (prefix_ci(url, t))
  11578. return 0;
  11579. if (s && prefix_ci(url + s, t))
  11580. return (int)s;
  11581. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  11582. return (int)s + 4;
  11583. return -1;
  11584. }
  11585. static int hist_score(const struct hist_ent *e, const char *t,
  11586. unsigned int next)
  11587. {
  11588. unsigned int age = next - e->stamp;
  11589. int sc, at;
  11590. if (!t[0]) {
  11591. sc = 0;
  11592. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  11593. /* Shorter rests first: "cloudron.io/" before its subpages. */
  11594. int rest = (int)s_len(e->url + at);
  11595. sc = 4000 - (rest > 400 ? 400 : rest);
  11596. } else if (contains_ci(e->url, t)) {
  11597. sc = 1000;
  11598. } else if (contains_ci(e->title, t)) {
  11599. sc = 600;
  11600. } else {
  11601. return -1;
  11602. }
  11603. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  11604. sc += age >= 500 ? 0 : (int)(500 - age);
  11605. return sc;
  11606. }
  11607. static void sug_lower(char *t, unsigned int cap)
  11608. {
  11609. unsigned int k;
  11610. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  11611. t[k] = lc(sug_typed[k]);
  11612. t[k] = '\0';
  11613. }
  11614. static void sug_refresh(void)
  11615. {
  11616. char t[NGUI_INPUT_MAX];
  11617. int sc[SUG_MAX], i, j;
  11618. unsigned int next = hist_next_stamp();
  11619. sug_lower(t, sizeof(t));
  11620. sug_n = 0;
  11621. for (i = 0; i < hist_n; i++) {
  11622. int s = hist_score(&hist_tab[i], t, next);
  11623. if (s < 0)
  11624. continue;
  11625. j = sug_n;
  11626. if (j == SUG_MAX) {
  11627. if (sc[SUG_MAX - 1] >= s)
  11628. continue;
  11629. j = SUG_MAX - 1;
  11630. }
  11631. while (j > 0 && sc[j - 1] < s) {
  11632. sc[j] = sc[j - 1];
  11633. sug_idx[j] = sug_idx[j - 1];
  11634. j--;
  11635. }
  11636. sc[j] = s;
  11637. sug_idx[j] = i;
  11638. if (sug_n < SUG_MAX)
  11639. sug_n++;
  11640. }
  11641. if (sug_sel >= sug_n)
  11642. sug_sel = -1;
  11643. }
  11644. /* Complete the typed text inline to the next '/' of the best prefix match. */
  11645. static void sug_inline(void)
  11646. {
  11647. char t[NGUI_INPUT_MAX];
  11648. const char *url, *rest;
  11649. unsigned int L, start, end, hs, tn, n = 0;
  11650. unsigned int next = hist_next_stamp();
  11651. int i, best = -1, best_sc = -1, at = 0;
  11652. sug_lower(t, sizeof(t));
  11653. L = s_len(t);
  11654. if (!L)
  11655. return;
  11656. for (i = 0; i < hist_n; i++) {
  11657. int a = hist_prefix_at(hist_tab[i].url, t), s;
  11658. if (a < 0)
  11659. continue;
  11660. s = hist_score(&hist_tab[i], t, next);
  11661. if (s > best_sc) {
  11662. best_sc = s;
  11663. best = i;
  11664. at = a;
  11665. }
  11666. }
  11667. if (best < 0)
  11668. return;
  11669. url = hist_tab[best].url;
  11670. rest = url + at;
  11671. /* Typing the scheme ("htt") completes past "https://", not to it. */
  11672. hs = at == 0 ? url_scheme_len(url) : 0;
  11673. start = L > hs ? L : hs;
  11674. end = start;
  11675. while (rest[end] && rest[end] != '/')
  11676. end++;
  11677. if (rest[end] == '/')
  11678. end++;
  11679. tn = s_len(sug_typed);
  11680. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  11681. return;
  11682. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  11683. for (; L < end && n + 1 < sizeof(ac_text); L++)
  11684. ac_text[n++] = rest[L];
  11685. ac_text[n] = '\0';
  11686. s_copy(ac_url, url, (unsigned int)at + end + 1);
  11687. ngui_input_set(&url_in, ac_text);
  11688. url_in.anchor = tn; /* select the completed part */
  11689. }
  11690. static void sug_close(void)
  11691. {
  11692. sug_open = 0;
  11693. sug_sel = -1;
  11694. ac_text[0] = '\0';
  11695. }
  11696. static int sug_visible(void)
  11697. {
  11698. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  11699. }
  11700. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  11701. * start page) lists the top sites until something is typed. */
  11702. static int sug_focus_check(void)
  11703. {
  11704. int focused = ngui_focus(&ui) == ID_URL;
  11705. if (focused && !url_had_focus) {
  11706. sug_typed[0] = '\0';
  11707. sug_close();
  11708. sug_open = 1;
  11709. sug_refresh();
  11710. }
  11711. url_had_focus = focused;
  11712. return focused;
  11713. }
  11714. static void url_submit(unsigned int *action)
  11715. {
  11716. if (ac_text[0] && s_eq(url_in.text, ac_text))
  11717. s_copy(click_url, ac_url, sizeof(click_url));
  11718. *action |= ACT_NAV;
  11719. sug_close();
  11720. }
  11721. /* The bar text changed through typing or editing. */
  11722. static void sug_changed(void)
  11723. {
  11724. unsigned int pl = s_len(sug_typed);
  11725. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  11726. !memcmp(url_in.text, sug_typed, pl);
  11727. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  11728. ac_text[0] = '\0';
  11729. sug_sel = -1;
  11730. sug_open = 1;
  11731. sug_refresh();
  11732. if (grew)
  11733. sug_inline();
  11734. }
  11735. /* Keys for the list, taken off the queue before the text field sees them.
  11736. * Only a leading run is handled; the rest goes to the field. */
  11737. static void sug_keys(void)
  11738. {
  11739. int k;
  11740. while ((k = ngui_key_peek(&ui)) != 0) {
  11741. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  11742. ngui_key(&ui);
  11743. if (!sug_open) {
  11744. sug_open = 1;
  11745. continue;
  11746. }
  11747. if (sug_sel < 0)
  11748. s_copy(sug_restore, url_in.text,
  11749. sizeof(sug_restore));
  11750. if (k == NGUI_KEY_DOWN)
  11751. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  11752. else
  11753. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  11754. ngui_input_set(&url_in, sug_sel >= 0 ?
  11755. hist_tab[sug_idx[sug_sel]].url :
  11756. sug_restore);
  11757. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  11758. ngui_key(&ui);
  11759. if (sug_sel >= 0)
  11760. ngui_input_set(&url_in, sug_restore);
  11761. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  11762. ngui_input_set(&url_in, sug_typed);
  11763. sug_close();
  11764. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  11765. sug_sel >= 0) {
  11766. ngui_key(&ui);
  11767. hist_forget(sug_idx[sug_sel]);
  11768. ngui_input_set(&url_in, sug_restore);
  11769. sug_sel = -1;
  11770. sug_refresh();
  11771. } else {
  11772. break;
  11773. }
  11774. }
  11775. }
  11776. /* A press on a row of last frame's list opens it; any press on the list is
  11777. * swallowed so the page underneath does not see it. */
  11778. static void sug_click(unsigned int *action)
  11779. {
  11780. int row;
  11781. if (!(ui.pressed & 1) || !sug_rect.w ||
  11782. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  11783. return;
  11784. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  11785. if (row >= 0 && row < sug_n) {
  11786. s_copy(click_url, hist_tab[sug_idx[row]].url,
  11787. sizeof(click_url));
  11788. *action |= ACT_NAV;
  11789. sug_close();
  11790. }
  11791. ui.pressed = 0;
  11792. }
  11793. static void draw_suggest(struct ngui_rect page)
  11794. {
  11795. struct ngui_rect r;
  11796. int i, rows = sug_n, hover = -1;
  11797. r.x = url_rect.x;
  11798. r.y = url_rect.y + url_rect.h + 1;
  11799. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  11800. if (r.x + r.w > ui.w - 2)
  11801. r.w = ui.w - 2 - r.x;
  11802. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  11803. rows--;
  11804. if (rows <= 0 || r.w < 60) {
  11805. sug_rect.w = 0;
  11806. return;
  11807. }
  11808. r.h = rows * SUG_ROW_H + 2;
  11809. sug_rect = r;
  11810. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  11811. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  11812. ngui_set_cursor(&ui, CURSOR_POINTER);
  11813. }
  11814. ngui_fill_rect(&ui, r, ui.theme.border);
  11815. for (i = 0; i < rows; i++) {
  11816. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  11817. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  11818. r.w - 2, SUG_ROW_H};
  11819. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  11820. unsigned short bg = i == sug_sel ? ui.theme.selection :
  11821. i == hover ? ui.theme.panel_alt :
  11822. ui.theme.panel;
  11823. ngui_fill_rect(&ui, rr, bg);
  11824. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  11825. e->title[0] ? e->title : e->url,
  11826. ui.theme.text);
  11827. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  11828. i == sug_sel ? ui.theme.text :
  11829. ui.theme.text_dim);
  11830. }
  11831. }
  11832. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  11833. {
  11834. int x = r.x + 4, y = r.y + 4, h = 22;
  11835. int compact = r.w < 560;
  11836. int go_w = r.w < 420 ? 32 : 42;
  11837. int in_x, in_w, res;
  11838. ngui_fill_rect(&ui, r, ui.theme.panel);
  11839. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  11840. ui.theme.border);
  11841. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  11842. NGUI_ICON_CHEVRON_LEFT))
  11843. *action |= ACT_BACK;
  11844. x += 32;
  11845. if (!compact) {
  11846. if (ngui_icon_button(&ui, ID_FORWARD,
  11847. (struct ngui_rect){x, y, 28, h},
  11848. NGUI_ICON_CHEVRON_RIGHT))
  11849. *action |= ACT_FORWARD;
  11850. x += 32;
  11851. }
  11852. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  11853. NGUI_ICON_REFRESH))
  11854. *action |= ACT_RELOAD;
  11855. x += 32;
  11856. if (!compact) {
  11857. if (ngui_icon_button(&ui, ID_HOME,
  11858. (struct ngui_rect){x, y, 28, h},
  11859. NGUI_ICON_HOME))
  11860. *action |= ACT_HOME;
  11861. x += 32;
  11862. }
  11863. in_x = x + 2;
  11864. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  11865. if (in_w < 60)
  11866. in_w = 60;
  11867. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  11868. if (sug_focus_check())
  11869. sug_keys();
  11870. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  11871. sug_focus_check(); /* a click into the bar focuses it here */
  11872. if (res & NGUI_INPUT_CHANGED)
  11873. sug_changed();
  11874. if (res & NGUI_INPUT_SUBMIT)
  11875. url_submit(action);
  11876. if (res & NGUI_INPUT_CANCEL)
  11877. ngui_set_focus(&ui, 0);
  11878. if (ngui_button(&ui, ID_GO,
  11879. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  11880. "Go"))
  11881. url_submit(action);
  11882. if (!sug_focus_check())
  11883. sug_close();
  11884. }
  11885. static int page_hover_node(void)
  11886. {
  11887. if (!ui.inside)
  11888. return 0;
  11889. if (ui.mouse_x < page_rect.x ||
  11890. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  11891. ui.mouse_y < page_rect.y ||
  11892. ui.mouse_y >= page_rect.y + page_rect.h)
  11893. return 0;
  11894. return find_hit(ui.mouse_x, ui.mouse_y);
  11895. }
  11896. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  11897. {
  11898. int x, y, w = page.w, h = page.h;
  11899. if (!src || w <= 0 || h <= 0)
  11900. return;
  11901. for (y = 0; y < h; y++) {
  11902. unsigned short *s = src + (page.y + y) * sw + page.x;
  11903. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  11904. for (x = 0; x + 1 < w; x += 2) {
  11905. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  11906. }
  11907. if (x < w)
  11908. d[x] = s[x];
  11909. }
  11910. }
  11911. static void draw_page(struct ngui_rect page)
  11912. {
  11913. int left, right, ch;
  11914. int old_panel, old_dim;
  11915. unsigned short *saved_px;
  11916. unsigned short page_bg = ui.theme.bg;
  11917. int saved_w, saved_h, use_buf;
  11918. unsigned int t0 = u_ticks_ms();
  11919. page_rect = page;
  11920. {
  11921. unsigned int root = doc.nnode > 1 ?
  11922. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11923. unsigned int body = doc.nnode > 1 ?
  11924. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11925. struct br_style bs;
  11926. int bg_found = 0;
  11927. if (root) {
  11928. style_for_node(root - 1, &bs);
  11929. if (bs.has_bg) {
  11930. page_bg = bs.bg;
  11931. bg_found = 1;
  11932. }
  11933. }
  11934. if (body) {
  11935. style_for_node(body - 1, &bs);
  11936. if (bs.has_bg) {
  11937. page_bg = bs.bg;
  11938. bg_found = 1;
  11939. }
  11940. }
  11941. /* No canvas colour, but the author made the text dark
  11942. * (Infima's light theme: `--ifm-background-color:
  11943. * transparent` on html, #1c1e21 text): the page expects the
  11944. * white canvas of a normal browser, and dark text on the
  11945. * dark default canvas is unreadable. */
  11946. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11947. unsigned int c = bs.color;
  11948. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11949. ((c >> 5) & 63) * 4 * 587 +
  11950. (c & 31) * 8 * 114;
  11951. if (lum < 100 * 1000)
  11952. page_bg = 0xFFFF;
  11953. }
  11954. }
  11955. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11956. page_cache_valid && layout_valid &&
  11957. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11958. !(ui.scroll_y &&
  11959. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11960. page_scroll.offset == page_cache_scroll &&
  11961. page_cache_nnode == doc.nnode &&
  11962. page_cache_x == page.x && page_cache_y == page.y &&
  11963. page_cache_w == page.w && page_cache_h == page.h) {
  11964. blit_page(page, page_backbuf, pagebuf_w);
  11965. if (img_stat_n)
  11966. img_stat_paint += u_ticks_ms() - t0;
  11967. return;
  11968. }
  11969. ngui_fill_rect(&ui, page, page_bg);
  11970. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11971. const char *s = page_loading ? "Loading..." : "No page";
  11972. int w = (int)ngui_text_width_ui(&ui, s);
  11973. ngui_text(&ui, page.x + (page.w - w) / 2,
  11974. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11975. page_scroll.content_h = 0;
  11976. page_scroll.view_h = page.h;
  11977. page_cache_valid = 0;
  11978. return;
  11979. }
  11980. if (page.w < 40 || page.h < 40) {
  11981. page_cache_valid = 0;
  11982. return;
  11983. }
  11984. saved_px = ui.px;
  11985. saved_w = ui.w;
  11986. saved_h = ui.h;
  11987. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11988. if (use_buf) {
  11989. ui.px = page_backbuf;
  11990. ui.w = pagebuf_w;
  11991. ui.h = pagebuf_h;
  11992. ngui_fill_rect(&ui, page, page_bg);
  11993. }
  11994. /* No gutter of our own: the body's UA margin provides it. The
  11995. * right 12 px stay clear for the scrollbar, like every viewport
  11996. * width below (page_rect.w - 12). */
  11997. left = page.x;
  11998. right = page.x + page.w - 12;
  11999. if (!layout_valid || left != layout_left || right != layout_right ||
  12000. layout_nnode != doc.nnode) {
  12001. unsigned int tm = u_ticks_ms();
  12002. layout_view_h = page.h;
  12003. layout_content_h = measure_page(left, right);
  12004. if (img_stat_n)
  12005. img_stat_reflow += u_ticks_ms() - tm;
  12006. layout_valid = 1;
  12007. layout_left = left;
  12008. layout_right = right;
  12009. layout_nnode = doc.nnode;
  12010. /* Scripts that measured before any layout (offsetWidth on
  12011. * mount) get a resize event once real boxes exist, and again
  12012. * whenever the page width changes. */
  12013. if (js_browser_active() && right - left != resize_sent_w)
  12014. resize_pending = 1;
  12015. }
  12016. ch = layout_content_h;
  12017. page_scroll.content_h = ch;
  12018. page_scroll.view_h = page.h;
  12019. t0 = u_ticks_ms();
  12020. ngui_scroll_begin(&ui, page, &page_scroll);
  12021. ngui_scroll_wheel(&ui, page, &page_scroll);
  12022. render_page(left, right, page.y - page_scroll.offset);
  12023. old_panel = ui.theme.panel_alt;
  12024. old_dim = ui.theme.text_dim;
  12025. ui.theme.panel_alt = 0xC618;
  12026. ui.theme.text_dim = 0x8410;
  12027. ngui_scroll_end(&ui, page, &page_scroll);
  12028. ui.theme.panel_alt = old_panel;
  12029. ui.theme.text_dim = old_dim;
  12030. if (use_buf) {
  12031. ui.px = saved_px;
  12032. ui.w = saved_w;
  12033. ui.h = saved_h;
  12034. blit_page(page, page_backbuf, pagebuf_w);
  12035. page_cache_valid = 1;
  12036. page_cache_scroll = page_scroll.offset;
  12037. page_cache_nnode = doc.nnode;
  12038. page_cache_x = page.x;
  12039. page_cache_y = page.y;
  12040. page_cache_w = page.w;
  12041. page_cache_h = page.h;
  12042. } else {
  12043. page_cache_valid = 0;
  12044. }
  12045. if (img_stat_n)
  12046. img_stat_paint += u_ticks_ms() - t0;
  12047. }
  12048. static void draw_status(struct ngui_rect r)
  12049. {
  12050. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  12051. unsigned int n = 0;
  12052. int hover = page_hover_node();
  12053. unsigned short color;
  12054. const char *kind;
  12055. ngui_fill_rect(&ui, r, ui.theme.panel);
  12056. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  12057. ui.theme.border);
  12058. /* Only a real link target is shown: a form control, or an element
  12059. * that is merely clickable through a script listener (google.com's
  12060. * jsaction wrapper around its search field), is not a link. */
  12061. if (hover && !br_href(&doc, (unsigned int)hover))
  12062. hover = 0;
  12063. if (hover) {
  12064. const char *href = br_href(&doc, (unsigned int)hover);
  12065. char url[BR_URL_MAX];
  12066. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  12067. s_append(msg, &n, "Link: ", sizeof(msg));
  12068. s_append(msg, &n, url, sizeof(msg));
  12069. } else {
  12070. s_copy(msg, "Link", sizeof(msg));
  12071. }
  12072. color = ui.theme.accent;
  12073. } else if (status_text[0]) {
  12074. s_copy(msg, status_text, sizeof(msg));
  12075. color = status_error ? ui.theme.error : ui.theme.text;
  12076. } else if (page_title[0]) {
  12077. s_copy(msg, page_title, sizeof(msg));
  12078. color = ui.theme.text;
  12079. } else {
  12080. s_copy(msg, "Ready", sizeof(msg));
  12081. color = ui.theme.text_dim;
  12082. }
  12083. kind = s_eq(page_url, "about:home") ? "HOME" :
  12084. page_is_local ? "FILE" :
  12085. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  12086. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  12087. {
  12088. int kw = (int)ngui_text_width_ui(&ui, kind);
  12089. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  12090. ui.theme.text_dim);
  12091. }
  12092. }
  12093. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  12094. * for `auto`, a hand over links, the I-beam over text fields, and the
  12095. * progress arrow anywhere on the page while it is still loading. The
  12096. * toolbar's URL field sets its own I-beam through ngui. */
  12097. static void page_cursor(void)
  12098. {
  12099. int hover = page_hover_node();
  12100. struct br_style st;
  12101. if (!hover) {
  12102. if (page_loading && ui.inside &&
  12103. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  12104. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12105. return;
  12106. }
  12107. style_for_node((unsigned int)hover, &st);
  12108. if (st.cursor != BR_CURSOR_AUTO) {
  12109. ngui_set_cursor(&ui, (int)st.cursor - 1);
  12110. return;
  12111. }
  12112. if (br_href(&doc, (unsigned int)hover)) {
  12113. ngui_set_cursor(&ui, CURSOR_POINTER);
  12114. return;
  12115. }
  12116. if (form_is_control((unsigned int)hover)) {
  12117. int k = form_kind_of((unsigned int)hover);
  12118. if (form_disabled((unsigned int)hover))
  12119. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  12120. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  12121. k == FORM_TEXTAREA)
  12122. ngui_set_cursor(&ui, CURSOR_TEXT);
  12123. return;
  12124. }
  12125. if (page_loading)
  12126. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  12127. }
  12128. static void draw(unsigned int *action)
  12129. {
  12130. struct ngui_rect r = {0, 0, ui.w, ui.h};
  12131. struct ngui_rect toolbar, status, page;
  12132. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  12133. status = ngui_cut_bottom(&r, BR_STATUS_H);
  12134. page = r;
  12135. if (sug_visible())
  12136. sug_click(action);
  12137. draw_toolbar(toolbar, action);
  12138. draw_page(page);
  12139. draw_status(status);
  12140. page_cursor();
  12141. if (sug_visible())
  12142. draw_suggest(page);
  12143. else
  12144. sug_rect.w = 0;
  12145. }
  12146. static void redraw_now(void)
  12147. {
  12148. unsigned int action = 0;
  12149. ngui_begin(&ui);
  12150. draw(&action);
  12151. ngui_end(&ui);
  12152. }
  12153. static void handle_keys(unsigned int *action)
  12154. {
  12155. int k, scrolled = 0;
  12156. if (form_focus >= doc.nnode)
  12157. form_focus = 0;
  12158. if (form_focus && !ngui_focus(&ui)) {
  12159. while ((k = ngui_key(&ui)) != 0)
  12160. form_key(k);
  12161. return;
  12162. }
  12163. /* Batch queued page keys: a slow full-page render must not make a
  12164. * held Page Down advance only once every few frames. */
  12165. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  12166. scrolled++;
  12167. if (scrolled)
  12168. ngui_invalidate(&ui);
  12169. if (ngui_focus(&ui))
  12170. return;
  12171. while ((k = ngui_key(&ui)) != 0) {
  12172. switch (k) {
  12173. case NGUI_KEY_ESC:
  12174. *action |= ACT_CLOSE;
  12175. break;
  12176. case NGUI_KEY_TAB:
  12177. case 0x0C: /* Ctrl+L */
  12178. ngui_set_focus(&ui, ID_URL);
  12179. break;
  12180. case 0x12: /* Ctrl+R */
  12181. *action |= ACT_RELOAD;
  12182. break;
  12183. case NGUI_KEY_BACKSPACE:
  12184. *action |= ACT_BACK;
  12185. break;
  12186. case NGUI_KEY_UP:
  12187. ngui_scroll_to(&page_scroll,
  12188. page_scroll.offset - 24);
  12189. ngui_invalidate(&ui);
  12190. break;
  12191. case NGUI_KEY_DOWN:
  12192. ngui_scroll_to(&page_scroll,
  12193. page_scroll.offset + 24);
  12194. ngui_invalidate(&ui);
  12195. break;
  12196. case NGUI_KEY_HOME:
  12197. ngui_scroll_to(&page_scroll, 0);
  12198. ngui_invalidate(&ui);
  12199. break;
  12200. case NGUI_KEY_END:
  12201. ngui_scroll_to(&page_scroll,
  12202. page_scroll.content_h -
  12203. page_scroll.view_h);
  12204. ngui_invalidate(&ui);
  12205. break;
  12206. default:
  12207. break;
  12208. }
  12209. }
  12210. }
  12211. static unsigned int form_ancestor(unsigned int node)
  12212. {
  12213. unsigned int p = node;
  12214. while (p && p < doc.nnode) {
  12215. if (doc.nodes[p].tag == BR_TAG_FORM &&
  12216. doc.nodes[p].type == BR_NODE_ELEM)
  12217. return p;
  12218. p = doc.nodes[p].parent;
  12219. }
  12220. return 0;
  12221. }
  12222. static int form_descendant(unsigned int node, unsigned int form)
  12223. {
  12224. unsigned int p = node;
  12225. while (p && p < doc.nnode) {
  12226. if (p == form)
  12227. return 1;
  12228. p = doc.nodes[p].parent;
  12229. }
  12230. return 0;
  12231. }
  12232. static void form_reset_form(unsigned int form)
  12233. {
  12234. unsigned int i;
  12235. for (i = 0; i < FORM_MAX; i++)
  12236. if (form_states[i].used &&
  12237. form_descendant(form_states[i].node, form))
  12238. form_states[i].used = 0;
  12239. form_focus = 0;
  12240. }
  12241. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  12242. const char *s)
  12243. {
  12244. static const char hex[] = "0123456789ABCDEF";
  12245. while (s && *s && *n + 1 < cap) {
  12246. unsigned char c = (unsigned char)*s++;
  12247. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  12248. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  12249. c == '.' || c == '~') {
  12250. dst[(*n)++] = (char)c;
  12251. } else if (c == ' ') {
  12252. dst[(*n)++] = '+';
  12253. } else if (*n + 3 < cap) {
  12254. dst[(*n)++] = '%';
  12255. dst[(*n)++] = hex[c >> 4];
  12256. dst[(*n)++] = hex[c & 15];
  12257. }
  12258. }
  12259. dst[*n] = '\0';
  12260. }
  12261. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  12262. const char *name, const char *value, int *first)
  12263. {
  12264. if (!name || !name[0])
  12265. return;
  12266. if (!*first && *n + 1 < cap)
  12267. dst[(*n)++] = '&';
  12268. *first = 0;
  12269. form_url_append(dst, n, cap, name);
  12270. if (*n + 1 < cap)
  12271. dst[(*n)++] = '=';
  12272. form_url_append(dst, n, cap, value ? value : "");
  12273. dst[*n] = '\0';
  12274. }
  12275. static int form_submit_form(unsigned int node, int fire_event)
  12276. {
  12277. unsigned int form = form_ancestor(node);
  12278. char action[BR_URL_MAX], query[2048];
  12279. unsigned int qn = 0, i;
  12280. int first = 1, is_post = 0;
  12281. const char *a, *method;
  12282. if (!form)
  12283. return 0;
  12284. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  12285. return 0;
  12286. method = br_find_attr(&doc, form, "method");
  12287. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  12288. is_post = 1;
  12289. a = br_find_attr(&doc, form, "action");
  12290. if (a && a[0]) {
  12291. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  12292. return 0;
  12293. } else {
  12294. s_copy(action, page_url, sizeof(action));
  12295. }
  12296. query[0] = '\0';
  12297. for (i = 0; i < doc.nnode; i++) {
  12298. struct br_node *nd = &doc.nodes[i];
  12299. struct form_state *fs;
  12300. const char *name;
  12301. const char *value = "";
  12302. if (nd->type != BR_NODE_ELEM || i == form ||
  12303. !form_descendant(i, form))
  12304. continue;
  12305. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  12306. nd->tag != BR_TAG_SELECT)
  12307. continue;
  12308. if (form_disabled(i))
  12309. continue;
  12310. name = br_find_attr(&doc, i, "name");
  12311. if (!name || !name[0])
  12312. continue;
  12313. fs = form_get(i, 1);
  12314. if (!fs)
  12315. continue;
  12316. if (nd->tag == BR_TAG_SELECT) {
  12317. char opt[64];
  12318. if (!form_option_text(i, fs->selected, opt,
  12319. sizeof(opt)))
  12320. s_copy(opt, "", sizeof(opt));
  12321. value = opt;
  12322. {
  12323. unsigned int c, oi = 0;
  12324. for (c = nd->first; c;
  12325. c = doc.nodes[c].next) {
  12326. if (doc.nodes[c].type != BR_NODE_ELEM ||
  12327. doc.nodes[c].tag != BR_TAG_OPTION)
  12328. continue;
  12329. if (oi == fs->selected) {
  12330. const char *v =
  12331. br_value(&doc, c);
  12332. if (v && v[0])
  12333. value = v;
  12334. break;
  12335. }
  12336. oi++;
  12337. }
  12338. }
  12339. } else if (nd->tag == BR_TAG_INPUT) {
  12340. int kind = form_kind_of(i);
  12341. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12342. if (!fs->checked)
  12343. continue;
  12344. value = br_value(&doc, i);
  12345. if (!value || !value[0])
  12346. value = "on";
  12347. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  12348. kind == FORM_BUTTON) {
  12349. if (i != node)
  12350. continue;
  12351. value = fs->value;
  12352. } else {
  12353. value = fs->value;
  12354. }
  12355. } else {
  12356. value = fs->value;
  12357. }
  12358. form_add_param(query, &qn, sizeof(query), name, value, &first);
  12359. }
  12360. if (is_post) {
  12361. if (action[0] == '/') {
  12362. set_status("POST forms need an HTTP action URL", 1, 4000);
  12363. ngui_invalidate(&ui);
  12364. return 0;
  12365. }
  12366. if (qn >= sizeof(pending_post))
  12367. qn = sizeof(pending_post) - 1;
  12368. if (qn)
  12369. memcpy(pending_post, query, qn);
  12370. pending_post[qn] = '\0';
  12371. pending_post_len = qn;
  12372. pending_post_is = 1;
  12373. } else {
  12374. pending_post_len = 0;
  12375. pending_post_is = 0;
  12376. if (qn) {
  12377. unsigned int an = s_len(action);
  12378. if (an + qn + 2 < sizeof(action)) {
  12379. action[an++] = strchr(action, '?') ? '&' : '?';
  12380. action[an] = '\0';
  12381. s_copy(action + an, query,
  12382. sizeof(action) - an);
  12383. }
  12384. }
  12385. }
  12386. s_copy(pending_url, action, sizeof(pending_url));
  12387. pending_action |= ACT_NAV;
  12388. cancel_fetch = 1;
  12389. ngui_invalidate(&ui);
  12390. return 1;
  12391. }
  12392. static void form_reset_event(unsigned int form)
  12393. {
  12394. if (form && !js_browser_event(form, "reset", 1, 1))
  12395. return;
  12396. if (form)
  12397. form_reset_form(form);
  12398. else
  12399. form_reset_state();
  12400. form_dirty = 0;
  12401. layout_valid = 0;
  12402. ngui_invalidate(&ui);
  12403. }
  12404. static void form_blur(void)
  12405. {
  12406. unsigned int node = form_focus;
  12407. form_focus = 0;
  12408. if (node && form_dirty) {
  12409. form_dirty = 0;
  12410. js_browser_event(node, "change", 1, 0);
  12411. }
  12412. }
  12413. static void form_click(unsigned int node)
  12414. {
  12415. struct form_state *fs;
  12416. int kind, changed = 0;
  12417. if (!form_is_control(node) || form_disabled(node))
  12418. return;
  12419. if (form_focus != node)
  12420. form_blur();
  12421. fs = form_get(node, 1);
  12422. if (!fs)
  12423. return;
  12424. kind = form_kind_of(node);
  12425. /* Focus moves on the press, before `click` is dispatched: a page
  12426. * that cancels the click (a framework's root listener) suppresses
  12427. * the activation behaviour below, never the focus (as in other
  12428. * browsers, where focus follows mousedown). */
  12429. form_focus = node;
  12430. form_dirty = 0;
  12431. if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  12432. kind == FORM_TEXTAREA)
  12433. fs->caret = fs->len;
  12434. layout_valid = 0;
  12435. ngui_invalidate(&ui);
  12436. if (!js_browser_event(node, "click", 1, 1))
  12437. return;
  12438. fs = form_get(node, 0); /* the handler may have changed the DOM */
  12439. if (!fs)
  12440. return;
  12441. if (kind == FORM_CHECKBOX) {
  12442. fs->checked = !fs->checked;
  12443. changed = 1;
  12444. } else if (kind == FORM_RADIO) {
  12445. const char *name = br_find_attr(&doc, node, "name");
  12446. unsigned int i;
  12447. fs->checked = 1;
  12448. changed = 1;
  12449. if (name) {
  12450. for (i = 0; i < FORM_MAX; i++) {
  12451. struct form_state *o = &form_states[i];
  12452. if (!o->used || o->node == node)
  12453. continue;
  12454. if (form_kind_of(o->node) == FORM_RADIO) {
  12455. const char *on = br_find_attr(&doc,
  12456. o->node,
  12457. "name");
  12458. if (on && s_eq(on, name))
  12459. o->checked = 0;
  12460. }
  12461. }
  12462. }
  12463. } else if (kind == FORM_SELECT) {
  12464. unsigned int n = form_option_count(node);
  12465. if (n) {
  12466. fs->selected = (unsigned char)
  12467. ((fs->selected + 1) % n);
  12468. changed = 1;
  12469. }
  12470. } else if (kind == FORM_SUBMIT) {
  12471. form_submit_form(node, 1);
  12472. return;
  12473. } else if (kind == FORM_RESET) {
  12474. form_reset_event(form_ancestor(node));
  12475. return;
  12476. }
  12477. if (changed) {
  12478. js_browser_event(node, "input", 1, 0);
  12479. js_browser_event(node, "change", 1, 0);
  12480. }
  12481. layout_valid = 0;
  12482. ngui_invalidate(&ui);
  12483. }
  12484. static void form_focus_next(void)
  12485. {
  12486. unsigned int start = form_focus ? form_focus + 1 : 0;
  12487. unsigned int i;
  12488. form_blur();
  12489. for (i = start; i < doc.nnode; i++) {
  12490. if (form_is_control(i) && !form_disabled(i) &&
  12491. !s_eq(br_type(&doc, i), "hidden")) {
  12492. form_focus = i;
  12493. layout_valid = 0;
  12494. ngui_invalidate(&ui);
  12495. return;
  12496. }
  12497. }
  12498. form_focus = 0;
  12499. layout_valid = 0;
  12500. ngui_invalidate(&ui);
  12501. }
  12502. static void form_key(int k)
  12503. {
  12504. struct form_state *fs;
  12505. int kind;
  12506. if (!form_focus || form_focus >= doc.nnode) {
  12507. form_focus = 0;
  12508. return;
  12509. }
  12510. fs = form_get(form_focus, 1);
  12511. if (!fs || form_disabled(form_focus))
  12512. return;
  12513. kind = form_kind_of(form_focus);
  12514. if (kind == FORM_SELECT) {
  12515. unsigned int n = form_option_count(form_focus);
  12516. int changed = 0;
  12517. if (k == NGUI_KEY_UP && n) {
  12518. fs->selected = (unsigned char)
  12519. ((fs->selected + n - 1) % n);
  12520. changed = 1;
  12521. } else if (k == NGUI_KEY_DOWN && n) {
  12522. fs->selected = (unsigned char)
  12523. ((fs->selected + 1) % n);
  12524. changed = 1;
  12525. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12526. form_blur();
  12527. layout_valid = 0;
  12528. ngui_invalidate(&ui);
  12529. return;
  12530. } else {
  12531. return;
  12532. }
  12533. if (changed) {
  12534. js_browser_event(form_focus, "input", 1, 0);
  12535. js_browser_event(form_focus, "change", 1, 0);
  12536. }
  12537. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  12538. if (k == ' ') {
  12539. form_click(form_focus);
  12540. return;
  12541. }
  12542. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  12543. form_blur();
  12544. layout_valid = 0;
  12545. ngui_invalidate(&ui);
  12546. }
  12547. return;
  12548. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  12549. kind == FORM_RESET) {
  12550. if (k == NGUI_KEY_ESC) {
  12551. form_blur();
  12552. layout_valid = 0;
  12553. ngui_invalidate(&ui);
  12554. } else if (k == '\r' || k == '\n' || k == ' ') {
  12555. form_click(form_focus);
  12556. }
  12557. return;
  12558. } else if (k == NGUI_KEY_TAB) {
  12559. form_focus_next();
  12560. return;
  12561. } else if (k == NGUI_KEY_ESC) {
  12562. form_blur();
  12563. layout_valid = 0;
  12564. ngui_invalidate(&ui);
  12565. return;
  12566. } else if (k == '\r' || k == '\n') {
  12567. unsigned int node = form_focus;
  12568. form_blur();
  12569. if (form_ancestor(node))
  12570. form_submit_form(node, 1);
  12571. layout_valid = 0;
  12572. ngui_invalidate(&ui);
  12573. return;
  12574. } else if (k == NGUI_KEY_BACKSPACE) {
  12575. if (fs->caret) {
  12576. unsigned int i = --fs->caret;
  12577. for (; i < fs->len; i++)
  12578. fs->value[i] = fs->value[i + 1];
  12579. if (fs->len)
  12580. fs->len--;
  12581. form_dirty = 1;
  12582. js_browser_event(form_focus, "input", 1, 0);
  12583. }
  12584. } else if (k == NGUI_KEY_DELETE) {
  12585. if (fs->caret < fs->len) {
  12586. unsigned int i;
  12587. for (i = fs->caret; i < fs->len; i++)
  12588. fs->value[i] = fs->value[i + 1];
  12589. fs->len--;
  12590. form_dirty = 1;
  12591. js_browser_event(form_focus, "input", 1, 0);
  12592. }
  12593. } else if (k == NGUI_KEY_LEFT) {
  12594. if (fs->caret)
  12595. fs->caret--;
  12596. } else if (k == NGUI_KEY_RIGHT) {
  12597. if (fs->caret < fs->len)
  12598. fs->caret++;
  12599. } else if (k == NGUI_KEY_HOME) {
  12600. fs->caret = 0;
  12601. } else if (k == NGUI_KEY_END) {
  12602. fs->caret = fs->len;
  12603. } else if (k >= 32 && k < 127) {
  12604. if (fs->len < FORM_VALUE_MAX) {
  12605. unsigned int i;
  12606. for (i = fs->len; i > fs->caret; i--)
  12607. fs->value[i] = fs->value[i - 1];
  12608. fs->value[fs->caret++] = (char)k;
  12609. fs->len++;
  12610. form_dirty = 1;
  12611. js_browser_event(form_focus, "input", 1, 0);
  12612. }
  12613. } else {
  12614. return;
  12615. }
  12616. fs->value[fs->len] = '\0';
  12617. layout_valid = 0;
  12618. ngui_invalidate(&ui);
  12619. }
  12620. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  12621. * a same-document navigation: update the URL and fire hashchange. Returns
  12622. * 1 when handled. */
  12623. static int link_fragment_nav(unsigned int node)
  12624. {
  12625. const char *href = br_href(&doc, node);
  12626. char url[BR_URL_MAX];
  12627. unsigned int n = 0;
  12628. if (!href || !href[0] || !js_browser_active())
  12629. return 0;
  12630. if (href[0] == '#') {
  12631. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  12632. url[n] = page_url[n];
  12633. n++;
  12634. }
  12635. url[n] = '\0';
  12636. s_append(url, &n, href, sizeof(url));
  12637. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  12638. return 0;
  12639. }
  12640. if (!same_doc_fragment(url))
  12641. return href[0] == '#';
  12642. page_set_fragment(url, 1);
  12643. js_browser_hashchange();
  12644. return 1;
  12645. }
  12646. /* The innermost laid-out box under a screen point: the smallest valid box
  12647. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  12648. * Used to deliver clicks to elements that are neither links nor controls
  12649. * (a Vue <div role="button">, a card with a click listener). */
  12650. static unsigned int find_box_hit(int x, int y)
  12651. {
  12652. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  12653. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  12654. const struct br_layout_box *b = &layout_boxes[i];
  12655. unsigned int area;
  12656. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  12657. x < b->x || y < b->y || x >= b->x + b->w ||
  12658. y >= b->y + b->h)
  12659. continue;
  12660. area = (unsigned int)b->w * (unsigned int)b->h;
  12661. if (area <= best_area) {
  12662. best = i;
  12663. best_area = area;
  12664. }
  12665. }
  12666. return best;
  12667. }
  12668. static void handle_page_click(unsigned int *action)
  12669. {
  12670. int node;
  12671. char url[BR_URL_MAX];
  12672. if (!ui.pressed)
  12673. return;
  12674. if (ui.press_x < page_rect.x ||
  12675. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  12676. ui.press_y < page_rect.y ||
  12677. ui.press_y >= page_rect.y + page_rect.h)
  12678. return;
  12679. node = find_hit(ui.press_x, ui.press_y);
  12680. if (!node) {
  12681. unsigned int box;
  12682. if (!js_browser_active())
  12683. return;
  12684. box = find_box_hit(ui.press_x, ui.press_y);
  12685. if (box) {
  12686. form_blur();
  12687. js_browser_event(box, "click", 1, 1);
  12688. }
  12689. return;
  12690. }
  12691. if (form_is_control((unsigned int)node)) {
  12692. form_click((unsigned int)node);
  12693. return;
  12694. }
  12695. form_blur();
  12696. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  12697. return;
  12698. if (link_fragment_nav((unsigned int)node))
  12699. return;
  12700. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  12701. sizeof(url)) != 0)
  12702. return;
  12703. s_copy(click_url, url, sizeof(click_url));
  12704. *action |= ACT_NAV;
  12705. }
  12706. void _start(const char *arg)
  12707. {
  12708. struct win_info wi;
  12709. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  12710. u_win_create(960, 640, "Browser", &wi) != 0 &&
  12711. u_win_create(780, 540, "Browser", &wi) != 0) {
  12712. u_puts("browser: no graphics window\n");
  12713. u_exit(1);
  12714. }
  12715. ufont_set_arena_bytes(BR_FONT_ARENA);
  12716. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  12717. url_in.placeholder = "http://...";
  12718. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  12719. ui.theme.accent);
  12720. br_set_viewport(wi.width);
  12721. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  12722. s_copy(cwd, "/", sizeof(cwd));
  12723. heap_clear();
  12724. origin_cache_load();
  12725. css_cache_init();
  12726. script_cache_init();
  12727. font_cache_init();
  12728. persist_restore();
  12729. hist_load();
  12730. page_scroll.offset = 0;
  12731. page_scroll.content_h = 0;
  12732. if (arg && arg[0]) {
  12733. navigate(arg, 1);
  12734. } else {
  12735. load_home(1);
  12736. /* Start ready to type: keep the home page, but leave the address
  12737. * bar empty instead of showing "about:home". */
  12738. ngui_input_set(&url_in, "");
  12739. ngui_set_focus(&ui, ID_URL);
  12740. }
  12741. for (;;) {
  12742. unsigned int action = 0;
  12743. unsigned int now;
  12744. click_url[0] = '\0';
  12745. if (pending_action) {
  12746. action |= pending_action & ACT_WAIT_NAV;
  12747. if (pending_url[0])
  12748. s_copy(click_url, pending_url, sizeof(click_url));
  12749. pending_action = 0;
  12750. pending_url[0] = '\0';
  12751. cancel_fetch = 0;
  12752. } else if (preload_active) {
  12753. if (preload_wait)
  12754. preload_wait = 0;
  12755. else
  12756. preload_step();
  12757. } else if ((preload_pending &&
  12758. page_scroll.offset != preload_scroll) ||
  12759. (preload_rescan && layout_valid)) {
  12760. preload_scroll = page_scroll.offset;
  12761. preload_rescan = 0;
  12762. preload_pending = 0;
  12763. preload_node = 0;
  12764. preload_active = 1;
  12765. }
  12766. js_browser_tick();
  12767. if (resize_pending && !pending_action) {
  12768. resize_pending = 0;
  12769. resize_sent_w = layout_right - layout_left;
  12770. js_browser_window_event("resize");
  12771. }
  12772. persist_tick();
  12773. if (pending_action)
  12774. continue;
  12775. now = u_ticks_ms();
  12776. if (status_until && (int)(now - status_until) >= 0) {
  12777. status_text[0] = '\0';
  12778. status_until = 0;
  12779. status_error = 0;
  12780. ngui_invalidate(&ui);
  12781. }
  12782. if (!ngui_begin(&ui)) {
  12783. /* A queued navigation (e.g. Enter in the URL bar during
  12784. * a slow fetch) must be handled even when this frame
  12785. * needs no redraw. */
  12786. if (!action) {
  12787. fetch_workers_stop_if_unfocused();
  12788. u_sleep_ms(10);
  12789. continue;
  12790. }
  12791. } else {
  12792. draw(&action);
  12793. handle_keys(&action);
  12794. handle_page_click(&action);
  12795. ngui_end(&ui);
  12796. }
  12797. if (action & ACT_NAV) {
  12798. if (click_url[0]) {
  12799. navigate(click_url, 1);
  12800. click_url[0] = '\0';
  12801. } else {
  12802. navigate(url_in.text, 1);
  12803. }
  12804. }
  12805. if (action & ACT_BACK) {
  12806. if (hist_pos > 0) {
  12807. hist_pos--;
  12808. if (same_doc_fragment(history[hist_pos])) {
  12809. page_set_fragment(history[hist_pos], 0);
  12810. js_browser_hashchange();
  12811. } else {
  12812. navigate(history[hist_pos], 0);
  12813. }
  12814. }
  12815. }
  12816. if (action & ACT_FORWARD) {
  12817. if (hist_pos + 1 < hist_len) {
  12818. hist_pos++;
  12819. if (same_doc_fragment(history[hist_pos])) {
  12820. page_set_fragment(history[hist_pos], 0);
  12821. js_browser_hashchange();
  12822. } else {
  12823. navigate(history[hist_pos], 0);
  12824. }
  12825. }
  12826. }
  12827. if (action & ACT_RELOAD) {
  12828. if (s_eq(page_url, "about:home"))
  12829. load_home(0);
  12830. else
  12831. navigate(page_url, 0);
  12832. }
  12833. if (action & ACT_HOME)
  12834. load_home(1);
  12835. if (action & ACT_CLOSE)
  12836. quit = 1;
  12837. if (quit)
  12838. break;
  12839. if (pending_action)
  12840. continue;
  12841. fetch_workers_stop_if_unfocused();
  12842. u_sleep_ms(10);
  12843. }
  12844. fetch_workers_stop_all();
  12845. u_win_close();
  12846. u_exit(0);
  12847. }