| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894128951289612897128981289912900129011290212903129041290512906129071290812909129101291112912129131291412915129161291712918129191292012921129221292312924129251292612927129281292912930129311293212933129341293512936129371293812939129401294112942129431294412945129461294712948129491295012951129521295312954129551295612957129581295912960129611296212963129641296512966129671296812969129701297112972129731297412975129761297712978129791298012981129821298312984129851298612987129881298912990129911299212993129941299512996129971299812999130001300113002130031300413005130061300713008130091301013011130121301313014130151301613017130181301913020130211302213023130241302513026130271302813029130301303113032130331303413035130361303713038130391304013041130421304313044130451304613047130481304913050130511305213053130541305513056130571305813059130601306113062130631306413065130661306713068130691307013071130721307313074130751307613077130781307913080130811308213083130841308513086130871308813089130901309113092130931309413095130961309713098130991310013101131021310313104131051310613107131081310913110131111311213113131141311513116131171311813119131201312113122131231312413125131261312713128131291313013131131321313313134131351313613137131381313913140131411314213143131441314513146131471314813149131501315113152131531315413155131561315713158131591316013161131621316313164131651316613167131681316913170131711317213173131741317513176131771317813179131801318113182131831318413185131861318713188131891319013191131921319313194131951319613197131981319913200132011320213203132041320513206132071320813209132101321113212132131321413215132161321713218132191322013221132221322313224132251322613227132281322913230132311323213233132341323513236132371323813239132401324113242132431324413245132461324713248132491325013251132521325313254132551325613257132581325913260132611326213263132641326513266132671326813269132701327113272132731327413275132761327713278132791328013281132821328313284132851328613287132881328913290132911329213293132941329513296132971329813299133001330113302133031330413305133061330713308133091331013311133121331313314133151331613317133181331913320133211332213323133241332513326133271332813329133301333113332133331333413335133361333713338133391334013341133421334313344133451334613347133481334913350133511335213353133541335513356133571335813359133601336113362133631336413365133661336713368133691337013371133721337313374133751337613377133781337913380133811338213383133841338513386133871338813389133901339113392133931339413395133961339713398133991340013401134021340313404134051340613407134081340913410134111341213413134141341513416134171341813419134201342113422134231342413425134261342713428134291343013431134321343313434134351343613437134381343913440134411344213443134441344513446134471344813449134501345113452134531345413455134561345713458134591346013461134621346313464134651346613467134681346913470134711347213473134741347513476134771347813479134801348113482134831348413485134861348713488134891349013491134921349313494134951349613497134981349913500135011350213503135041350513506135071350813509135101351113512135131351413515135161351713518135191352013521135221352313524135251352613527135281352913530135311353213533135341353513536135371353813539135401354113542135431354413545135461354713548135491355013551135521355313554135551355613557135581355913560135611356213563135641356513566135671356813569135701357113572135731357413575135761357713578135791358013581135821358313584135851358613587135881358913590135911359213593135941359513596135971359813599136001360113602136031360413605136061360713608136091361013611136121361313614136151361613617136181361913620136211362213623136241362513626136271362813629136301363113632136331363413635136361363713638136391364013641136421364313644136451364613647136481364913650136511365213653136541365513656136571365813659136601366113662136631366413665136661366713668136691367013671136721367313674136751367613677136781367913680136811368213683136841368513686136871368813689136901369113692136931369413695136961369713698136991370013701137021370313704137051370613707137081370913710137111371213713137141371513716137171371813719137201372113722137231372413725137261372713728137291373013731137321373313734137351373613737137381373913740137411374213743137441374513746137471374813749137501375113752137531375413755137561375713758137591376013761137621376313764137651376613767137681376913770137711377213773137741377513776137771377813779137801378113782137831378413785137861378713788137891379013791137921379313794137951379613797137981379913800138011380213803138041380513806138071380813809138101381113812138131381413815138161381713818138191382013821138221382313824138251382613827138281382913830138311383213833138341383513836138371383813839138401384113842138431384413845138461384713848138491385013851138521385313854138551385613857138581385913860138611386213863138641386513866138671386813869138701387113872138731387413875138761387713878138791388013881138821388313884138851388613887 |
- /* browser: a small HTML/CSS browser built on ngui, the image library and the
- * shared uhttp client.
- *
- * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
- * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
- * decoded with img.c and drawn inline. Page-scoped buffers (page body,
- * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
- * exact-size decode arena that is freed as soon as the scaled bitmap exists.
- * The DOM and the image/CSS I/O scratch use fixed static arenas.
- */
- #include <stdlib.h>
- #include <stdio.h>
- #include <string.h>
- #include <math.h>
- #include <ucmd_heap.h>
- #include "ucmd_lib.h"
- #include "ngui.h"
- #include "browser_html.h"
- #include "js_browser.h"
- #include "uhttp.h"
- #include "uhttp_cookie.h"
- #include "img.h"
- #include "inflate.h"
- #include "ufont.h"
- #include "svg_raster.h"
- static void svg_cache_clear(void);
- static unsigned char *decode_arena; /* see decode_arena_get() */
- static unsigned int decode_arena_size;
- /* Start wide enough for the desktop nav; smaller screens fall back to
- * 960x640 and 780x540, which still fit a 1024x768 panel. */
- #define BR_W 1100
- #define BR_H 700
- #define BR_TOOLBAR_H 30
- #define BR_STATUS_H 18
- #define BR_PAGE_MAX (2u * 1024u * 1024u)
- #define BR_IMG_FILE_MAX (1024u * 1024u)
- #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
- #define BR_MAX_IMAGES 256
- /* Decoded display bitmaps share the page heap: cap their total pixels
- * (RGB565 plus an optional alpha plane) instead of their count. */
- #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
- #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
- #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
- #define BR_IMG_LAYOUT_W 1000
- /* Decode completed image jobs for at most this long per main-loop pass, then
- * return to input/painting. One image per pass plus a 10 ms sleep made a
- * page of small icons trickle in. */
- #define BR_IMG_DECODE_BUDGET_MS 40u
- /* Coalesce image-driven repaints: each decode invalidates the page, and a
- * full repaint per image made loading superlinear on image-heavy pages. */
- #define BR_IMG_REPAINT_MS 100u
- #define BR_IMG_STAT_LOG 3584
- /* An image job may hold a fetch helper this long. The page/script
- * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
- * must not starve the other images of all four helpers that long. */
- #define BR_IMG_JOB_TIMEOUT_MS 30000u
- #define BR_CSS_MAX (832u * 1024u)
- #define BR_CSS_COMP_MAX (192u * 1024u)
- /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
- * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
- #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
- #define FETCH_ABORT (-2)
- /* Session cache for remote stylesheets (per launch; cleared at startup). */
- #define CSS_CACHE_MAX 16
- #define CSS_CACHE_FILE_MAX (256u * 1024u)
- #define CSS_CACHE_PREFIX "bcss-"
- #define SCRIPT_CACHE_MAX 24
- #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
- #define SCRIPT_CACHE_PREFIX "bjs-"
- /* Web fonts cached for the boot; /share holds 64 entries / 16 MB in all. */
- #define FONT_CACHE_MAX 8
- #define FONT_CACHE_PREFIX "bfont-"
- /* The ufont arena (built-in faces, @font-face files and glyph masks); the
- * 512 KB default holds the built-in set but not a page's web fonts. */
- #define BR_FONT_ARENA (3u * 1024u * 1024u)
- #define BR_MAX_SHEETS 6
- #define BR_HISTORY 16
- #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
- #define BR_STATUS_MAX 200
- #define BR_IMG_RGB565(r, g, b) \
- ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
- #define BR_GRAY 0x8410
- enum {
- ID_URL = 1,
- ID_GO,
- ID_BACK,
- ID_FORWARD,
- ID_RELOAD,
- ID_HOME
- };
- #define ACT_NAV (1u << 0)
- #define ACT_BACK (1u << 1)
- #define ACT_FORWARD (1u << 2)
- #define ACT_RELOAD (1u << 3)
- #define ACT_HOME (1u << 4)
- #define ACT_CLOSE (1u << 5)
- #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
- ACT_HOME | ACT_CLOSE)
- struct br_image {
- int state; /* 0 empty, 1 ready */
- struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
- int native_w, native_h;
- unsigned int url_hash; /* <img> source, 0 = not shareable */
- char err[32];
- /* Display-size cache: the box an image is actually painted in. The
- * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
- * window resize can re-scale it; the cached copy is exactly dw x dh,
- * so every repaint is a 1:1 blit instead of a per-pixel resample. */
- struct img_image disp;
- unsigned int disp_pixels;
- unsigned int disp_last;
- };
- static struct ngui ui;
- static struct ngui_input url_in;
- static struct ngui_scroll page_scroll;
- static struct br_doc doc;
- static struct br_image images[BR_MAX_IMAGES];
- static int image_count;
- static unsigned int image_pixels;
- static unsigned int image_disp_pixels;
- static unsigned int image_disp_clock;
- /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
- * numbers are what decides whether the next work is network, decode or
- * display; keep them cheap (one tick read per phase). */
- static unsigned int img_stat_start;
- static unsigned int img_stat_wall;
- static unsigned int img_stat_net;
- static unsigned int img_stat_open;
- static unsigned int img_stat_first;
- static unsigned int img_stat_io;
- static unsigned int img_stat_dec;
- static unsigned int img_stat_scale;
- static unsigned int img_stat_paint;
- static unsigned int img_stat_reflow;
- static unsigned int img_stat_bytes;
- static int img_stat_n;
- static unsigned int img_last_dec_ms;
- static unsigned int img_last_scale_ms;
- static char img_stat_log[BR_IMG_STAT_LOG];
- static unsigned int img_stat_log_len;
- static unsigned int img_repaint_ms;
- static int img_repaint_pending;
- /* Painted border boxes, in page/screen coordinates (layout starts at
- * page_rect.y - scroll). getBoundingClientRect() subtracts page_rect. */
- struct br_layout_box {
- int x, y;
- int w, h;
- unsigned char valid;
- };
- static struct br_layout_box layout_boxes[BR_MAX_NODES];
- /* Inline boxes are built from their line runs in flush_line(): a box is
- * replaced when a new layout pass (or a re-layout at the same or an
- * earlier line) reaches it, and grown when its runs continue on the same
- * or a later line of the same pass. inline_box_parent[] is the enclosing
- * inline box (node + 1), so nested spans grow their ancestors too. */
- static unsigned int inline_box_pass_id;
- static unsigned int inline_box_flush_id;
- static unsigned int inline_box_pass[BR_MAX_NODES];
- static unsigned int inline_box_flush[BR_MAX_NODES];
- static int inline_box_y[BR_MAX_NODES];
- static unsigned short inline_box_parent[BR_MAX_NODES];
- /* Images are loaded one per main-loop iteration so the parsed page stays
- * interactive while a slow network/TLS fetch or 4K decode is in progress. */
- static int preload_active;
- static int preload_max_jobs;
- static int preload_pending;
- static int preload_wait;
- static unsigned int preload_node;
- static int preload_loaded;
- static int preload_scroll;
- static int preload_rescan;
- static char post_status_text[BR_STATUS_MAX];
- static int post_status_error;
- static unsigned int post_status_ttl;
- /* Content-relative position/height of each <img>, recorded by the measure
- * pass so image loading can be deferred until it is near the viewport. */
- static unsigned short img_top[BR_MAX_NODES];
- static unsigned short img_h[BR_MAX_NODES];
- /* One reusable I/O buffer: the two halves double as the gzip input scratch
- * for page/CSS fetches, where the heap has no room for another multi-megabyte
- * body. Decode arenas are allocated per image instead of living here. */
- static unsigned char *image_io_buf;
- static struct ufont_face *font_faces[BR_MAX_FACES];
- /* [family id - 1][bold * 2 + italic] -> 1-based face id, 0 = built-in. */
- static unsigned char font_pick[BR_MAX_FACES][4];
- #define image_file_buf (image_io_buf)
- #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
- #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
- static struct inflate image_inflate_ws;
- #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
- #error "CSS scratch must fit in image_io_buf"
- #endif
- static char page_url[BR_URL_MAX];
- static char page_title[BR_TITLE_MAX];
- static char cwd[64];
- static int page_is_local;
- static int page_loading;
- static char status_text[BR_STATUS_MAX];
- static unsigned int status_until;
- static int status_error;
- static char history[BR_HISTORY][BR_URL_MAX];
- static int hist_len, hist_pos;
- static char click_url[BR_URL_MAX];
- static char pending_url[BR_URL_MAX];
- #define BR_POST_MAX 4096
- static char pending_post[BR_POST_MAX];
- static unsigned int pending_post_len;
- /* The pending navigation is a POST even when its body is empty (a form
- * without fields, e.g. the OIDC consent auto-submit). */
- static int pending_post_is;
- /* window "resize" bookkeeping: the page width the last event was for. */
- static int resize_sent_w = -1;
- static int resize_pending;
- static unsigned int pending_action;
- static int cancel_fetch;
- static int quit;
- static struct ngui_rect page_rect;
- static unsigned short *page_backbuf;
- static int pagebuf_w, pagebuf_h;
- static int page_cache_valid;
- static int page_cache_scroll;
- static unsigned int page_cache_nnode;
- static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
- static int layout_valid, layout_left, layout_right;
- /* Height of the page viewport: what html/body height:100% resolves to. */
- static int layout_view_h;
- static unsigned int layout_nnode;
- static int layout_content_h;
- /* layout output */
- struct lay_run {
- unsigned int off;
- unsigned short len;
- unsigned short gap;
- unsigned short color;
- unsigned short href;
- char lit[28];
- short img;
- signed short dy; /* inline image vertical offset */
- unsigned short iw, ih;
- unsigned short w;
- unsigned char font_px, bold, italic, mono, underline, strike;
- unsigned char overline, font_face;
- unsigned char transform_scale;
- unsigned char origin_x_kind, origin_y_kind;
- signed short scale_x, scale_y, rotate_x100;
- signed short origin_x, origin_y;
- unsigned char has_lit;
- unsigned int form; /* node + 1, 0 = not a control */
- unsigned char form_kind;
- unsigned char form_disabled;
- /* RUN_PBOX: background colour, background image and its placement
- * inside the iw x ih box (relative offsets, drawn size). */
- unsigned char pb_has_bg;
- unsigned short pb_bg;
- short pb_img;
- short pb_x, pb_y, pb_w, pb_h;
- /* Innermost inline element (node + 1) whose box this run belongs
- * to, 0 = none; flush_line() unions the placed runs into
- * layout_boxes[] so getBoundingClientRect() sees inline boxes. */
- unsigned short box;
- };
- struct lay {
- int draw;
- struct ngui *ui;
- int left, right;
- int y;
- int line_x, line_y, line_h;
- int line_left, line_right;
- int parent_top;
- int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
- int cb_h; /* definite content height of the containing block for
- * percentage heights; 0 = indefinite (auto) */
- int run_x;
- int align;
- int depth;
- int space_pending;
- unsigned char float_active;
- int float_left, float_right, float_bottom;
- struct lay_run runs[96];
- int nruns;
- unsigned short box_owner; /* node + 1 of the open inline box */
- };
- struct hit {
- int x, y, w, h;
- unsigned short node;
- };
- /* Live form state; the DOM attributes stay the initial/default value. */
- #define FORM_MAX 64
- #define FORM_VALUE_MAX 63
- enum {
- FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
- FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
- };
- struct form_state {
- unsigned int node;
- char value[FORM_VALUE_MAX + 1];
- unsigned char len, caret, checked, selected, used;
- };
- static struct form_state form_states[FORM_MAX];
- static unsigned int form_focus;
- static unsigned int form_dirty;
- static int form_descendant(unsigned int node, unsigned int form);
- static int form_submit_form(unsigned int node, int fire_event);
- static int link_fragment_nav(unsigned int node);
- static void history_push(const char *url);
- static void form_reset_event(unsigned int form);
- static unsigned int s_len(const char *s);
- static int s_eq(const char *a, const char *b);
- static void form_key(int k);
- static void form_click(unsigned int node);
- static void style_for_node(unsigned int node, struct br_style *out);
- static int form_author_styled(const struct br_style *st);
- static int css_radius(const struct br_style *st, int corner, int w, int h);
- static void form_paint_author(struct ngui *ui, struct ngui_rect box,
- const struct br_style *st, int focused);
- static int form_disabled(unsigned int node)
- {
- struct br_node *n = &doc.nodes[node];
- if (n->attr_flags & BR_ATTR_DISABLED)
- return 1;
- return br_find_attr(&doc, node, "disabled") != 0;
- }
- static int form_kind_of(unsigned int node)
- {
- const char *type = br_type(&doc, node);
- if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
- return FORM_TEXTAREA;
- if (doc.nodes[node].tag == BR_TAG_SELECT)
- return FORM_SELECT;
- if (doc.nodes[node].tag == BR_TAG_BUTTON) {
- if (s_eq(type, "reset"))
- return FORM_RESET;
- if (s_eq(type, "button"))
- return FORM_BUTTON;
- return FORM_SUBMIT;
- }
- if (s_eq(type, "password"))
- return FORM_PASSWORD;
- if (s_eq(type, "checkbox"))
- return FORM_CHECKBOX;
- if (s_eq(type, "radio"))
- return FORM_RADIO;
- if (s_eq(type, "submit"))
- return FORM_SUBMIT;
- if (s_eq(type, "reset"))
- return FORM_RESET;
- if (s_eq(type, "button"))
- return FORM_BUTTON;
- return FORM_TEXT;
- }
- static unsigned int form_option_count(unsigned int node)
- {
- unsigned int c, n = 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
- if (doc.nodes[c].type == BR_NODE_ELEM &&
- doc.nodes[c].tag == BR_TAG_OPTION)
- n++;
- return n;
- }
- static unsigned int form_option_selected(unsigned int node)
- {
- unsigned int c, i = 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- if (doc.nodes[c].type != BR_NODE_ELEM ||
- doc.nodes[c].tag != BR_TAG_OPTION)
- continue;
- if (br_find_attr(&doc, c, "selected"))
- return i;
- i++;
- }
- return 0;
- }
- static unsigned int form_option_text(unsigned int node, unsigned int idx,
- char *out, unsigned int cap)
- {
- unsigned int c, i = 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- if (doc.nodes[c].type != BR_NODE_ELEM ||
- doc.nodes[c].tag != BR_TAG_OPTION)
- continue;
- if (i == idx)
- return br_text_content(&doc, c, out, cap);
- i++;
- }
- return 0;
- }
- static int form_is_control(unsigned int node);
- static struct form_state *form_get(unsigned int node, int create)
- {
- struct form_state *slot = 0;
- unsigned int i;
- for (i = 0; i < FORM_MAX; i++) {
- if (form_states[i].used) {
- if (form_states[i].node == node)
- return &form_states[i];
- } else if (!slot) {
- slot = &form_states[i];
- }
- }
- if (create && !slot) {
- /* Full: a client-side router (Docusaurus' React Router)
- * replaces page content without a navigation, so slots of
- * controls that left the document pile up until no new
- * control can be drawn or focused.
- * Reuse those first, then slots of nodes that are no longer
- * controls. */
- for (i = 0; i < FORM_MAX && !slot; i++)
- if (form_states[i].node != form_focus &&
- br_node_detached(&doc, form_states[i].node))
- slot = &form_states[i];
- for (i = 0; i < FORM_MAX && !slot; i++)
- if (form_states[i].node != form_focus &&
- !form_is_control(form_states[i].node))
- slot = &form_states[i];
- }
- if (!create || !slot)
- return 0;
- slot->node = node;
- slot->len = 0;
- slot->caret = 0;
- slot->checked = br_find_attr(&doc, node, "checked") != 0;
- slot->selected = form_option_selected(node);
- slot->used = 1;
- {
- unsigned int n = 0;
- if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
- n = br_text_content(&doc, node, slot->value,
- FORM_VALUE_MAX + 1);
- } else {
- const char *v = br_value(&doc, node);
- if (v) {
- n = s_len(v);
- if (n > FORM_VALUE_MAX)
- n = FORM_VALUE_MAX;
- for (unsigned int j = 0; j < n; j++)
- slot->value[j] = v[j];
- }
- if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
- n = br_text_content(&doc, node, slot->value,
- FORM_VALUE_MAX + 1);
- }
- if (n > FORM_VALUE_MAX)
- n = FORM_VALUE_MAX;
- slot->value[n] = '\0';
- slot->len = (unsigned char)n;
- slot->caret = (unsigned char)n;
- }
- return slot;
- }
- static void form_reset_state(void)
- {
- unsigned int i;
- for (i = 0; i < FORM_MAX; i++)
- form_states[i].used = 0;
- form_focus = 0;
- }
- /* A <button> with element content (an icon <svg>/<img>, a <span> label)
- * is laid out like a normal element so that content shows; only a text or
- * empty button is drawn as a native control. Clicks still reach it
- * through the box hit test. */
- static int button_has_elements(unsigned int node)
- {
- unsigned int c;
- if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
- return 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
- if (doc.nodes[c].type == BR_NODE_ELEM)
- return 1;
- /* An empty button whose icon is a ::before/::after box (Docusaurus'
- * sidebar caret) is laid out as an element so the box is drawn. */
- if (!doc.nodes[node].first && doc.npe_rules) {
- struct br_style st, ps;
- char buf[8];
- int pe;
- style_for_node(node, &st);
- for (pe = 1; pe <= 2; pe++)
- if (!br_pseudo(&doc, node, pe, &st, &ps, buf,
- sizeof(buf)) &&
- ps.content == BR_CONTENT_EMPTY &&
- ps.display != BR_DISPLAY_NONE)
- return 1;
- }
- return 0;
- }
- static int form_is_control(unsigned int node)
- {
- unsigned int tag;
- if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
- return 0;
- tag = doc.nodes[node].tag;
- return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
- tag == BR_TAG_SELECT ||
- (tag == BR_TAG_BUTTON && !button_has_elements(node));
- }
- #define HIT_MAX 96
- static struct hit hits[HIT_MAX];
- static int nhits;
- static unsigned short block_h[BR_MAX_NODES];
- /* Border-box height a flex container stretches an item to (align-items:
- * stretch in a row with a taller line or a definite height), 0 = none.
- * Written by the measure pass, read by both. */
- static unsigned short flex_stretch_h[BR_MAX_NODES];
- /* Measure-pass top of each block, in the same document coordinates as
- * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
- * paint, so it cannot drive the lazy background loader). */
- static unsigned short block_top[BR_MAX_NODES];
- static char li_marker[BR_MAX_NODES][12];
- /* one connection object; the browser fetches one resource at a time */
- /* ---- tiny strings ---- */
- static unsigned int s_len(const char *s)
- {
- unsigned int n = 0;
- while (s && s[n])
- n++;
- return n;
- }
- static void s_copy(char *d, const char *s, unsigned int cap)
- {
- unsigned int i = 0;
- if (!cap)
- return;
- while (s && s[i] && i + 1 < cap) {
- d[i] = s[i];
- i++;
- }
- d[i] = '\0';
- }
- static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
- {
- while (s && *s && *n + 1 < cap)
- d[(*n)++] = *s++;
- d[*n] = '\0';
- }
- static void s_append_dec(char *d, unsigned int *n, unsigned int v,
- unsigned int cap)
- {
- char tmp[12];
- unsigned int i = 0, j;
- do {
- tmp[i++] = (char)('0' + v % 10);
- v /= 10;
- } while (v && i < sizeof(tmp));
- for (j = 0; j < i && *n + 1 < cap; j++)
- d[(*n)++] = tmp[i - 1 - j];
- d[*n] = '\0';
- }
- static int s_eq(const char *a, const char *b)
- {
- while (*a && *b) {
- if (*a != *b)
- return 0;
- a++;
- b++;
- }
- return *a == *b;
- }
- static int starts_with(const char *s, const char *p)
- {
- unsigned int i = 0;
- while (p[i]) {
- if (s[i] != p[i])
- return 0;
- i++;
- }
- return 1;
- }
- static int contains_ci(const char *s, const char *p)
- {
- unsigned int i, j;
- for (i = 0; s[i]; i++) {
- for (j = 0; p[j]; j++) {
- char a = s[i + j];
- if (a >= 'A' && a <= 'Z')
- a = (char)(a - 'A' + 'a');
- if (a != p[j])
- break;
- }
- if (!p[j])
- return 1;
- }
- return 0;
- }
- static char *trim(char *s)
- {
- unsigned int n;
- while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
- s++;
- n = s_len(s);
- while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
- s[n - 1] == '\r' || s[n - 1] == '\n'))
- s[--n] = '\0';
- return s;
- }
- /* ---- per-process heap ---- */
- static int heap_start(void)
- {
- image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
- if (!image_io_buf)
- return -1;
- page_backbuf = (unsigned short *)malloc(
- (unsigned int)ui.w * (unsigned int)ui.h * 2u);
- pagebuf_w = page_backbuf ? ui.w : 0;
- pagebuf_h = page_backbuf ? ui.h : 0;
- page_cache_valid = 0;
- return 0;
- }
- static void heap_clear(void)
- {
- memset(font_faces, 0, sizeof(font_faces));
- memset(font_pick, 0, sizeof(font_pick));
- ngui_font_detach(&ui);
- svg_cache_clear();
- decode_arena = 0; /* lives in the page heap too */
- decode_arena_size = 0;
- heap_reset();
- /* The document arenas live in that heap; drop the stale pointers so
- * the next br_parse_plain() allocates fresh ones. */
- doc.nodes = 0;
- doc.text = 0;
- doc.attrs = 0;
- image_io_buf = 0;
- page_backbuf = 0;
- pagebuf_w = pagebuf_h = 0;
- page_cache_valid = 0;
- }
- static void browser_rules_alloc(void)
- {
- struct br_rule *rules;
- rules = (struct br_rule *)malloc(
- (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
- br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
- }
- /* ---- status ---- */
- static void set_status(const char *s, int err, unsigned int ttl_ms)
- {
- s_copy(status_text, s, sizeof(status_text));
- status_error = err;
- status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
- ngui_invalidate(&ui);
- }
- /* Update the status text without forcing a frame; the throttled image
- * repaint picks it up. Starting one helper per image used to invalidate the
- * whole page before every decode. */
- static void set_status_quiet(const char *s)
- {
- s_copy(status_text, s, sizeof(status_text));
- status_error = 0;
- status_until = 0;
- }
- /* ---- JavaScript ---- */
- static int resolve_link(const char *base, const char *href, char *out,
- unsigned int cap);
- static char js_last_status[BR_STATUS_MAX];
- static int js_last_error;
- static void js_host_status(const char *msg, int error)
- {
- s_copy(js_last_status, msg, sizeof(js_last_status));
- js_last_error = error;
- set_status(msg, error, 6000);
- }
- static void js_host_report(const char *msg)
- {
- u_puts("[js] ");
- u_puts(msg);
- u_putc('\n');
- s_copy(js_last_status, msg, sizeof(js_last_status));
- js_last_error = 1;
- set_status(msg, 1, 8000);
- }
- static void js_host_navigate(const char *url)
- {
- char resolved[BR_URL_MAX];
- if (!url || !url[0])
- return;
- if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
- return;
- s_copy(pending_url, resolved, sizeof(pending_url));
- pending_action |= ACT_NAV;
- cancel_fetch = 1;
- }
- /* Same-document fragment change (location.hash, an <a href="#/x"> click,
- * back/forward between fragments): the page URL, address bar and history
- * follow, nothing is reloaded. `push` adds a history entry. */
- static int page_set_fragment(const char *url, int push)
- {
- if (!url || !url[0] || s_len(url) >= sizeof(page_url))
- return -1;
- s_copy(page_url, url, sizeof(page_url));
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- if (push)
- history_push(page_url);
- ngui_invalidate(&ui);
- return 0;
- }
- static int js_host_set_hash(const char *url)
- {
- return page_set_fragment(url, 1);
- }
- /* 1 when `url` is this page with a different #fragment (and JavaScript runs
- * the page, so a hash router can react). */
- static int same_doc_fragment(const char *url)
- {
- unsigned int a = 0, b = 0;
- if (!js_browser_active() || !url)
- return 0;
- while (url[a] && url[a] != '#')
- a++;
- while (page_url[b] && page_url[b] != '#')
- b++;
- return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
- !s_eq(url, page_url);
- }
- static void js_host_changed(void)
- {
- /* Class/style/attribute mutations change computed styles, not just the
- * text: drop the per-node style cache before the next layout. */
- br_reset_styles(&doc);
- layout_valid = 0;
- /* Script-built content (Angular's ng-repeat cards) brings new images
- * and inline background styles: rescan once the main loop is idle. */
- preload_rescan = 1;
- ngui_invalidate(&ui);
- }
- static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
- {
- if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
- return 0;
- *x = layout_boxes[node].x - page_rect.x;
- *y = layout_boxes[node].y - page_rect.y;
- *w = layout_boxes[node].w;
- *h = layout_boxes[node].h;
- return 1;
- }
- static void form_copy_out(const char *s, char *buf, int cap)
- {
- int i = 0;
- if (!buf || cap <= 0)
- return;
- while (s && s[i] && i + 1 < cap) {
- buf[i] = s[i];
- i++;
- }
- buf[i] = '\0';
- }
- static int js_host_form_value(unsigned int node, char *buf, int cap)
- {
- struct form_state *fs;
- int kind;
- if (!form_is_control(node))
- return 0;
- kind = form_kind_of(node);
- if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
- return 0;
- if (kind == FORM_SELECT) {
- char opt[64] = "";
- unsigned int c, i = 0;
- fs = form_get(node, 1);
- if (!fs)
- return 0;
- form_option_text(node, fs->selected, opt, sizeof(opt));
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- if (doc.nodes[c].type != BR_NODE_ELEM ||
- doc.nodes[c].tag != BR_TAG_OPTION)
- continue;
- if (i == fs->selected) {
- const char *v = br_value(&doc, c);
- if (v && v[0])
- form_copy_out(v, buf, cap);
- else
- form_copy_out(opt, buf, cap);
- return 1;
- }
- i++;
- }
- form_copy_out(opt, buf, cap);
- return 1;
- }
- fs = form_get(node, 1);
- if (!fs)
- return 0;
- form_copy_out(fs->value, buf, cap);
- return 1;
- }
- static int js_host_form_checked(unsigned int node)
- {
- struct form_state *fs;
- int kind;
- if (!form_is_control(node))
- return -1;
- kind = form_kind_of(node);
- if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
- return -1;
- fs = form_get(node, 1);
- return fs ? fs->checked : 0;
- }
- static int js_host_form_selected(unsigned int node)
- {
- struct form_state *fs;
- if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
- return -1;
- fs = form_get(node, 1);
- return fs ? fs->selected : 0;
- }
- static int js_host_form_set_value(unsigned int node, const char *value)
- {
- struct form_state *fs;
- unsigned int n;
- if (!form_is_control(node))
- return 0;
- fs = form_get(node, 1);
- if (!fs)
- return 0;
- n = s_len(value ? value : "");
- if (n > FORM_VALUE_MAX)
- n = FORM_VALUE_MAX;
- for (unsigned int i = 0; i < n; i++)
- fs->value[i] = value[i];
- fs->value[n] = '\0';
- fs->len = (unsigned char)n;
- fs->caret = (unsigned char)n;
- layout_valid = 0;
- ngui_invalidate(&ui);
- return 1;
- }
- static int js_host_form_set_checked(unsigned int node, int checked)
- {
- struct form_state *fs;
- int kind;
- if (!form_is_control(node))
- return 0;
- kind = form_kind_of(node);
- if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
- return 0;
- fs = form_get(node, 1);
- if (!fs)
- return 0;
- fs->checked = (unsigned char)(checked != 0);
- layout_valid = 0;
- ngui_invalidate(&ui);
- return 1;
- }
- static int js_host_form_set_selected(unsigned int node, int index)
- {
- struct form_state *fs;
- unsigned int n;
- if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
- return 0;
- fs = form_get(node, 1);
- if (!fs)
- return 0;
- n = form_option_count(node);
- if (index < 0)
- index = 0;
- if (n && (unsigned int)index >= n)
- index = (int)n - 1;
- fs->selected = (unsigned char)index;
- layout_valid = 0;
- ngui_invalidate(&ui);
- return 1;
- }
- static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
- {
- unsigned int i;
- int n = 0;
- if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
- doc.nodes[form].tag != BR_TAG_FORM)
- return 0;
- for (i = 0; i < doc.nnode && n < cap; i++) {
- struct br_node *nd = &doc.nodes[i];
- if (i == form || nd->type != BR_NODE_ELEM)
- continue;
- if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
- nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
- continue;
- if (!form_descendant(i, form))
- continue;
- out[n++] = i;
- }
- return n;
- }
- static int js_host_form_submit(unsigned int form)
- {
- form_submit_form(form, 0);
- return 1;
- }
- static int js_host_form_reset(unsigned int form)
- {
- form_reset_event(form);
- return 1;
- }
- static void css_computed_name(const char *p, char *out, int cap)
- {
- int n = 0;
- for (; p && *p && n + 2 < cap; p++) {
- char c = *p;
- if (c >= 'A' && c <= 'Z') {
- out[n++] = '-';
- c = (char)(c - 'A' + 'a');
- } else if (c == '_') {
- c = '-';
- } else if (c >= 'a' && c <= 'z') {
- /* keep */
- }
- out[n++] = c;
- }
- out[n] = '\0';
- if (!strcmp(out, "css-float"))
- strcpy(out, "float");
- }
- static void css_rgb(unsigned short c, char *buf, int cap)
- {
- int r = ((c >> 11) & 31) * 255 / 31;
- int g = ((c >> 5) & 63) * 255 / 63;
- int b = (c & 31) * 255 / 31;
- snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
- }
- static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
- int font_px)
- {
- if (unit == 4) {
- snprintf(buf, cap, "auto");
- } else if (unit == 0) {
- snprintf(buf, cap, "%dpx", raw);
- } else if (unit == 1) {
- snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
- } else if (unit == 2) {
- /* Chrome's getComputedStyle() reports used pixel values. */
- snprintf(buf, cap, "%dpx", font_px * raw / 100);
- } else if (unit == 3) {
- snprintf(buf, cap, "%dpx",
- (int)br_root_font_px() * raw / 100);
- } else {
- snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
- raw / 100, raw % 100, px);
- }
- }
- static int js_host_computed(unsigned int node, const char *property,
- char *buf, int cap)
- {
- struct br_style st;
- char name[40];
- /* Node 0 is a real element when the page starts with <html>. */
- if (!buf || cap <= 0 || node >= doc.nnode ||
- (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
- return 0;
- buf[0] = '\0';
- css_computed_name(property, name, sizeof(name));
- style_for_node(node, &st);
- if (!strcmp(name, "display")) {
- const char *v = "inline";
- if (st.display == BR_DISPLAY_BLOCK)
- v = "block";
- else if (st.display == BR_DISPLAY_NONE)
- v = "none";
- else if (st.display == BR_DISPLAY_FLEX)
- v = "flex";
- else if (st.display == BR_DISPLAY_GRID)
- v = "grid";
- else if (st.display == BR_DISPLAY_INLINE_BLOCK)
- v = "inline-block";
- snprintf(buf, cap, "%s", v);
- } else if (!strcmp(name, "position")) {
- static const char *pos[] = {
- "static", "absolute", "fixed", "relative", "sticky"
- };
- snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
- } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
- int is_w = name[0] == 'w';
- int kind = is_w ? st.width_kind : st.height_kind;
- int val = is_w ? st.width : st.height;
- if (kind == 3) {
- if (is_w)
- snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
- st.width_calc_pct / 100,
- st.width_calc_pct % 100,
- st.width_calc_px);
- else
- snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
- st.height_calc_pct / 100,
- st.height_calc_pct % 100,
- st.height_calc_px);
- } else if (kind == 1) {
- snprintf(buf, cap, "%dpx", val);
- } else if (kind == 2) {
- snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
- } else {
- snprintf(buf, cap, "auto");
- }
- } else if (!strcmp(name, "color") ||
- !strcmp(name, "background-color")) {
- if (!strcmp(name, "background-color") && !st.has_bg)
- snprintf(buf, cap, "rgba(0, 0, 0, 0)");
- else
- css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
- } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
- int is_fill = name[0] == 'f';
- int mode = is_fill ? st.fill_mode : st.stroke_mode;
- if (mode == BR_PAINT_COLOR)
- css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
- else if (mode == BR_PAINT_CURRENT)
- css_rgb(st.color, buf, cap);
- else if (mode == BR_PAINT_UNSET && is_fill)
- snprintf(buf, cap, "rgb(0, 0, 0)");
- else if (mode == BR_PAINT_URL)
- snprintf(buf, cap, "url()");
- else
- snprintf(buf, cap, "none");
- } else if (!strcmp(name, "font-size")) {
- snprintf(buf, cap, "%dpx", st.font_px);
- } else if (!strcmp(name, "font-weight")) {
- snprintf(buf, cap, "%s", st.bold ? "700" : "400");
- } else if (!strcmp(name, "font-style")) {
- snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
- } else if (!strcmp(name, "font-family")) {
- if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
- br_font_face_family(st.font_face)[0])
- snprintf(buf, cap, "%s",
- br_font_face_family(st.font_face));
- else
- snprintf(buf, cap, "%s",
- st.mono ? "monospace" : "sans-serif");
- } else if (!strcmp(name, "text-align")) {
- static const char *al[] = { "left", "center", "right", "justify" };
- snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
- } else if (!strcmp(name, "float")) {
- snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
- st.float_left == 2 ? "right" : "none");
- } else if (!strcmp(name, "clear")) {
- static const char *cl[] = { "none", "left", "right", "both" };
- snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
- } else if (!strcmp(name, "opacity")) {
- snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
- } else if (!strcmp(name, "visibility")) {
- snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
- } else if (!strcmp(name, "overflow")) {
- snprintf(buf, cap, "%s",
- st.overflow_hidden ? "hidden" : "visible");
- } else if (!strcmp(name, "white-space")) {
- snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
- } else if (!strcmp(name, "text-transform")) {
- snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
- } else if (!strcmp(name, "box-sizing")) {
- snprintf(buf, cap, "%s",
- st.box_sizing ? "border-box" : "content-box");
- } else if (!strcmp(name, "line-height")) {
- if (st.line_h_px)
- snprintf(buf, cap, "%dpx", st.line_h_px);
- else if (st.line_h_pct)
- snprintf(buf, cap, "%d%%", st.line_h_pct);
- else
- snprintf(buf, cap, "normal");
- } else if (!strcmp(name, "z-index")) {
- if (st.z_set)
- snprintf(buf, cap, "%d", st.z_index);
- else
- snprintf(buf, cap, "auto");
- } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
- !strcmp(name, "right") || !strcmp(name, "bottom")) {
- int set = name[0] == 't' ? st.top_set :
- name[0] == 'l' ? st.left_set :
- name[0] == 'r' ? st.right_set : st.bottom_set;
- int v = name[0] == 't' ? st.top :
- name[0] == 'l' ? st.left :
- name[0] == 'r' ? st.right : st.bottom;
- if (set)
- snprintf(buf, cap, "%dpx", v);
- else
- snprintf(buf, cap, "auto");
- } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
- !strcmp(name, "margin-bottom") ||
- !strcmp(name, "margin-left") ||
- !strcmp(name, "padding-top") ||
- !strcmp(name, "padding-right") ||
- !strcmp(name, "padding-bottom") ||
- !strcmp(name, "padding-left")) {
- int is_pad = name[0] == 'p';
- int side = name[strlen(name) - 1] == 'p' ? 0 :
- name[strlen(name) - 1] == 't' ? 1 :
- name[strlen(name) - 1] == 'm' ? 2 : 3;
- /* last letter: top p, right t, bottom m, left t (ambiguity). */
- if (!strcmp(name, "margin-right") ||
- !strcmp(name, "padding-right"))
- side = 1;
- else if (!strcmp(name, "margin-bottom") ||
- !strcmp(name, "padding-bottom"))
- side = 2;
- else if (!strcmp(name, "margin-left") ||
- !strcmp(name, "padding-left"))
- side = 3;
- else
- side = 0;
- side += is_pad ? 4 : 0;
- css_mp_value(buf, cap,
- side == 0 ? st.mt : side == 1 ? st.mr :
- side == 2 ? st.mb : side == 3 ? st.ml :
- side == 4 ? st.pt : side == 5 ? st.pr :
- side == 6 ? st.pb : st.pl,
- st.mp_unit[side], st.mp_calc_px[side],
- st.font_px);
- } else if (!strcmp(name, "border-top-width") ||
- !strcmp(name, "border-right-width") ||
- !strcmp(name, "border-bottom-width") ||
- !strcmp(name, "border-left-width")) {
- int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
- name[7] == 'b' ? 2 : 3;
- snprintf(buf, cap, "%dpx", st.border_w[side]);
- } else if (!strcmp(name, "border-top-color") ||
- !strcmp(name, "border-right-color") ||
- !strcmp(name, "border-bottom-color") ||
- !strcmp(name, "border-left-color")) {
- int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
- name[7] == 'b' ? 2 : 3;
- if (st.border_w[side] && !st.border_t[side])
- css_rgb(st.border_c[side], buf, cap);
- else
- snprintf(buf, cap, "rgba(0, 0, 0, 0)");
- } else if (!strcmp(name, "background-image")) {
- if (st.bg_image)
- snprintf(buf, cap, "url(\"%s\")",
- br_bg_image_url(st.bg_image - 1));
- else
- snprintf(buf, cap, "none");
- } else if (!strcmp(name, "background-repeat")) {
- static const char *rp[] = {
- "repeat", "no-repeat", "repeat-x", "repeat-y"
- };
- snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
- st.bg_repeat : 0]);
- } else if (!strcmp(name, "background-position")) {
- if (st.bg_pos_x_kind == 1)
- snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
- st.bg_pos_y);
- else
- snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
- st.bg_pos_y);
- } else if (!strcmp(name, "background-size")) {
- if (st.bg_size_kind == 3)
- snprintf(buf, cap, "cover");
- else if (st.bg_size_kind == 4)
- snprintf(buf, cap, "contain");
- else if (st.bg_size_kind == 1)
- snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
- st.bg_size_h);
- else if (st.bg_size_kind == 2)
- snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
- st.bg_size_h);
- else
- snprintf(buf, cap, "auto");
- } else if (!strcmp(name, "transform")) {
- char tmp[128];
- unsigned int n = 0;
- if (!st.transform_set) {
- snprintf(buf, cap, "none");
- } else {
- tmp[0] = '\0';
- if (st.tx || st.ty) {
- snprintf(tmp + n, sizeof(tmp) - n,
- "translate(%dpx, %dpx)", st.tx, st.ty);
- n = (unsigned int)strlen(tmp);
- }
- if (st.transform_scale) {
- snprintf(tmp + n, sizeof(tmp) - n,
- "%sscale(%d.%02d, %d.%02d)",
- n ? " " : "", st.scale_x / 100,
- st.scale_x % 100, st.scale_y / 100,
- st.scale_y % 100);
- n = (unsigned int)strlen(tmp);
- if (st.rotate_x100) {
- snprintf(tmp + n, sizeof(tmp) - n,
- " rotate(%d.%02ddeg)",
- st.rotate_x100 / 100,
- st.rotate_x100 % 100);
- }
- } else if (st.rotate_x100) {
- snprintf(tmp + n, sizeof(tmp) - n,
- "%srotate(%d.%02ddeg)",
- n ? " " : "", st.rotate_x100 / 100,
- st.rotate_x100 % 100);
- }
- snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
- }
- } else {
- return 0;
- }
- return buf[0] != '\0';
- }
- static int js_host_click(unsigned int node)
- {
- char url[BR_URL_MAX];
- const char *href;
- if (node >= doc.nnode)
- return 0;
- if (form_is_control(node)) {
- form_click(node); /* dispatches its own click event */
- return 1;
- }
- /* element.click() fires a bubbling, cancelable click before the
- * default action, like a real click (delegated list handlers). */
- if (!js_browser_event(node, "click", 1, 1))
- return 1;
- if (link_fragment_nav(node))
- return 1;
- href = br_href(&doc, node);
- if (resolve_link(page_url, href, url, sizeof(url)) != 0)
- return 0;
- s_copy(pending_url, url, sizeof(pending_url));
- pending_action |= ACT_NAV;
- cancel_fetch = 1;
- ngui_invalidate(&ui);
- return 1;
- }
- static int fetch_script_text(const char *url, unsigned char **out,
- unsigned int *outlen, char *err,
- unsigned int errcap);
- struct fetch_worker;
- static struct fetch_worker *fetch_worker_alloc(void);
- static void fetch_worker_release(struct fetch_worker *w);
- static int fetch_worker_submit(struct fetch_worker *w, const char *url,
- unsigned int cap, const char *post,
- unsigned int post_len, unsigned int node,
- int bg, char *err, unsigned int errcap);
- static int fetch_worker_wait(struct fetch_worker *w, char *err,
- unsigned int errcap);
- static int fetch_worker_read_body(struct fetch_worker *w,
- unsigned char *plain,
- unsigned int plaincap,
- unsigned char *comp,
- unsigned int compcap,
- int *truncated, char *err,
- unsigned int errcap);
- static void fetch_workers_stop_all(void);
- static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
- unsigned int cap, const char *method,
- const char *ctype, const char *post,
- unsigned int post_len, unsigned int node,
- int bg, unsigned int dec_w,
- unsigned int dec_h, char *err,
- unsigned int errcap);
- static int script_cache_has(const char *url);
- static void script_cache_put(const char *url, const unsigned char *data,
- unsigned int len);
- static unsigned int script_cache_hash(const char *s);
- static int fetch_worker_poll(struct fetch_worker *w, char *err,
- unsigned int errcap);
- static void fetch_workers_cancel_busy(void);
- static void worker_wait_ui(void);
- static int fetch_worker_status(const struct fetch_worker *w);
- /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
- * module load: the wait must not pump input, or a click would dispatch DOM
- * events into the middle of the running script. */
- static int fetch_wait_passive;
- static void script_error(const char *what, const char *url, const char *why)
- {
- char msg[192];
- unsigned int n = 0;
- s_append(msg, &n, what, sizeof(msg));
- if (url && url[0]) {
- s_append(msg, &n, " ", sizeof(msg));
- s_append(msg, &n, url, sizeof(msg));
- }
- if (why && why[0]) {
- s_append(msg, &n, ": ", sizeof(msg));
- s_append(msg, &n, why, sizeof(msg));
- }
- js_host_report(msg);
- }
- /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
- /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
- * body (FETCH_POST_MAX in ucmd_curl.c). */
- #define JS_HTTP_MAX (2u * 1024u * 1024u)
- #define JS_HTTP_POST_MAX (16u * 1024u)
- /* struct fetch_meta / fetch_worker internals come later in the file. */
- static int js_worker_http(const char *method, const char *url,
- const char *ctype, const char *body,
- unsigned int body_len, struct js_http_resp *r,
- char *err, int errcap);
- static int js_host_http(const char *method, const char *url,
- const char *ctype, const char *body,
- unsigned int body_len, struct js_http_resp *r,
- char *err, int errcap)
- {
- if (pending_action) {
- s_copy(err, "page is navigating", (unsigned int)errcap);
- return -1;
- }
- if (url[0] == '/') {
- /* Local file: GET only. */
- unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
- int rv;
- if (!buf) {
- s_copy(err, "out of memory", (unsigned int)errcap);
- return -1;
- }
- rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
- (int)JS_HTTP_MAX);
- r->status = rv < 0 ? 404 : 200;
- r->len = rv < 0 ? 0 : (unsigned int)rv;
- buf[r->len] = '\0';
- r->body = (char *)buf;
- s_copy(r->url, url, sizeof(r->url));
- if (contains_ci(url, ".json"))
- s_copy(r->ctype, "application/json", sizeof(r->ctype));
- return 0;
- }
- if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
- s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
- return -1;
- }
- if (body_len > JS_HTTP_POST_MAX) {
- s_copy(err, "request body too large", (unsigned int)errcap);
- return -1;
- }
- return js_worker_http(method, url, ctype, body, body_len, r, err,
- errcap);
- }
- /* Module source for the engine's loader: the boot script cache first, then
- * one blocking fetch with input pumping disabled (the loader runs inside
- * JavaScript). */
- static char *js_host_load_script(const char *url, unsigned int *len)
- {
- unsigned char *data = 0;
- char err[64];
- int rv;
- fetch_wait_passive++;
- set_status("Loading module...", 0, 0);
- rv = fetch_script_text(url, &data, len, err, sizeof(err));
- fetch_wait_passive--;
- if (rv != 0) {
- script_error("Cannot load module", url,
- rv == FETCH_ABORT ? "navigation" : err);
- return 0;
- }
- return (char *)data;
- }
- /* Web Storage lives in /share, outside the page heap that every navigation
- * resets: localStorage per origin for the boot, sessionStorage per origin
- * and browser window. */
- #define JS_ORIGIN_MAX 160
- /* scheme://host[:port] of the page (a local page's whole path). */
- static void js_page_origin(char *origin, unsigned int cap)
- {
- unsigned int i = 0, slashes = 0;
- while (page_url[i] && i + 1 < cap) {
- if (page_url[i] == '/' && ++slashes == 3)
- break;
- origin[i] = page_url[i];
- i++;
- }
- origin[i] = '\0';
- }
- static void js_origin_path(const char *origin, char *out, unsigned int cap)
- {
- unsigned int n = 0;
- s_append(out, &n, "/share/bls", cap);
- s_append_dec(out, &n, script_cache_hash(origin), cap);
- }
- static void js_storage_path(int kind, char *out, unsigned int cap)
- {
- char origin[JS_ORIGIN_MAX];
- unsigned int n = 0;
- js_page_origin(origin, sizeof(origin));
- if (!kind) {
- js_origin_path(origin, out, cap);
- return;
- }
- s_append(out, &n, "/share/bss", cap);
- if (kind) {
- s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
- s_append(out, &n, "-", cap);
- }
- s_append_dec(out, &n, script_cache_hash(origin), cap);
- }
- static void persist_mark_origin(const char *origin);
- static int persist_store_lookup(const char *origin, char *out, int cap);
- static int js_host_storage(int kind, const char *set, char *out, int cap)
- {
- char path[48], origin[JS_ORIGIN_MAX];
- int rv;
- js_storage_path(kind, path, sizeof(path));
- if (set) {
- if (kind) {
- if (!set[0] || !strcmp(set, "{}")) {
- u_syscall1(SYS_UNLINK, (int)path);
- return 0;
- }
- } else {
- /* localStorage keeps an explicit "{}" rather than no
- * file: a missing /share file means "not loaded from
- * /data yet", and a cleared store must not come back
- * from the disk copy before it is flushed. */
- if (!set[0])
- set = "{}";
- js_page_origin(origin, sizeof(origin));
- persist_mark_origin(origin);
- }
- return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
- (int)strlen(set)) < 0 ? -1 : 0;
- }
- rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
- if (rv < 0 && !kind) {
- /* First use this boot: the persistent copy on /data. */
- js_page_origin(origin, sizeof(origin));
- rv = persist_store_lookup(origin, out, cap);
- if (rv >= 0)
- u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
- }
- if (rv < 0)
- return -1;
- out[rv] = '\0';
- return rv;
- }
- /* ---- persistence on /data ----
- *
- * /share is the working copy (RAM, shared by every helper and window); the
- * installed disk's /data volume keeps the cookie jar and localStorage
- * across reboots when it is mounted. The browser owns the disk copies: at
- * start it restores the jar into /share, and its main loop writes back
- * whatever changed at most every PERSIST_MS, so a burst of cookie or
- * setItem updates costs one FAT write. The helpers only touch /share (they
- * are killed on focus loss, so they cannot be trusted to flush). Without a
- * /data mount every disk access simply fails. Both files are plaintext
- * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
- #define PERSIST_MS 3000u
- #define SHARE_COOKIES "/share/bcookies"
- #define DATA_COOKIES "/data/BCOOKIES.BIN"
- #define DATA_STORE "/data/BSTORE.DAT"
- #define DATA_STORE_MAGIC "NBLS1\n"
- #define DATA_STORE_MAX (192u * 1024u)
- #define PERSIST_DIRTY_MAX 8
- static unsigned int persist_due;
- static unsigned int cookie_sum_saved;
- static int cookie_sum_valid;
- static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
- static int persist_ndirty;
- static unsigned int persist_sum(const unsigned char *p, unsigned int n)
- {
- unsigned int h = 2166136261u, i;
- for (i = 0; i < n; i++)
- h = (h ^ p[i]) * 16777619u;
- return h;
- }
- /* Called once at startup, before any helper runs. */
- static void persist_restore(void)
- {
- unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
- int n;
- if (!jar)
- return;
- n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
- (int)sizeof(struct uhttp_jar));
- if (n != (int)sizeof(struct uhttp_jar)) {
- n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
- (int)sizeof(struct uhttp_jar));
- if (n == (int)sizeof(struct uhttp_jar)) {
- u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
- (int)jar, n);
- cookie_sum_saved = persist_sum(jar, (unsigned int)n);
- cookie_sum_valid = 1;
- }
- }
- free(jar);
- persist_due = u_ticks_ms() + PERSIST_MS;
- }
- static void persist_mark_origin(const char *origin)
- {
- int i;
- for (i = 0; i < persist_ndirty; i++)
- if (s_eq(persist_dirty[i], origin))
- return;
- if (persist_ndirty < PERSIST_DIRTY_MAX)
- s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
- }
- /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
- * Walk it; returns 1 with the record's fields, 0 at the end. */
- static int store_next(const char *buf, unsigned int len, unsigned int *pos,
- unsigned int *o_off, unsigned int *o_len,
- unsigned int *d_off, unsigned int *d_len,
- unsigned int *rec_end)
- {
- unsigned int p = *pos, v = 0;
- if (p >= len)
- return 0;
- *o_off = p;
- while (p < len && buf[p] != '\n')
- p++;
- if (p >= len)
- return 0;
- *o_len = p - *o_off;
- p++;
- while (p < len && buf[p] >= '0' && buf[p] <= '9')
- v = v * 10 + (unsigned int)(buf[p++] - '0');
- if (p >= len || buf[p] != '\n')
- return 0;
- p++;
- if (v > len - p)
- return 0;
- *d_off = p;
- *d_len = v;
- p += v;
- if (p < len && buf[p] == '\n')
- p++;
- *rec_end = p;
- *pos = p;
- return 1;
- }
- static int store_load(char **out)
- {
- char *buf = (char *)malloc(DATA_STORE_MAX + 1);
- int n;
- *out = buf;
- if (!buf)
- return -1;
- n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
- (int)DATA_STORE_MAX);
- if (n < (int)s_len(DATA_STORE_MAGIC) ||
- !starts_with(buf, DATA_STORE_MAGIC))
- return 0;
- return n;
- }
- static int persist_store_lookup(const char *origin, char *out, int cap)
- {
- char *buf;
- unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
- unsigned int olen = s_len(origin);
- int n = store_load(&buf), rv = -1;
- while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
- &dl, &e)) {
- if (ol == olen && !memcmp(buf + oo, origin, olen)) {
- if ((int)dl < cap) {
- memcpy(out, buf + d, dl);
- out[dl] = '\0';
- rv = (int)dl;
- }
- break;
- }
- }
- free(buf);
- return rv;
- }
- /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
- static void persist_store_flush(void)
- {
- char *old, *nb, path[48];
- unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
- int n = store_load(&old), i, w;
- nb = (char *)malloc(DATA_STORE_MAX + 1);
- if (n < 0 || !nb) {
- free(old);
- free(nb);
- return;
- }
- s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
- /* Untouched origins first, in their old order. */
- while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
- &dl, &e)) {
- int dirty = 0;
- for (i = 0; i < persist_ndirty; i++)
- if (s_len(persist_dirty[i]) == ol &&
- !memcmp(persist_dirty[i], old + oo, ol))
- dirty = 1;
- if (dirty || nn + (e - oo) > DATA_STORE_MAX)
- continue;
- memcpy(nb + nn, old + oo, e - oo);
- nn += e - oo;
- }
- /* Then the changed ones (an emptied store is dropped). */
- for (i = 0; i < persist_ndirty; i++) {
- char num[12];
- unsigned int k = 0;
- js_origin_path(persist_dirty[i], path, sizeof(path));
- w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
- (int)DATA_STORE_MAX);
- if (w <= 2) /* missing or "{}" */
- continue;
- s_append_dec(num, &k, (unsigned int)w, sizeof(num));
- if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
- DATA_STORE_MAX) {
- set_status("Saved site data is full; a site's "
- "localStorage was not saved", 1, 6000);
- continue;
- }
- s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
- nb[nn++] = '\n';
- s_append(nb, &nn, num, DATA_STORE_MAX);
- nb[nn++] = '\n';
- memcpy(nb + nn, old, (unsigned int)w);
- nn += (unsigned int)w;
- nb[nn++] = '\n';
- }
- u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
- persist_ndirty = 0;
- free(old);
- free(nb);
- }
- static void persist_cookies_flush(void)
- {
- unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
- unsigned int sum;
- int n;
- if (!jar)
- return;
- n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
- (int)sizeof(struct uhttp_jar));
- if (n == (int)sizeof(struct uhttp_jar)) {
- sum = persist_sum(jar, (unsigned int)n);
- if (!cookie_sum_valid || sum != cookie_sum_saved) {
- if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
- (int)jar, n) >= 0) {
- cookie_sum_saved = sum;
- cookie_sum_valid = 1;
- }
- }
- }
- free(jar);
- }
- /* ---- visit history (URL-bar autocomplete) ----
- *
- * Every page that finishes loading is recorded with its title, a visit
- * count and a stamp: a counter that only grows and travels with the file,
- * so it orders visits across windows and boots without a wall clock. The
- * table lives in BSS, because the page heap is reset on every navigation.
- * The boot's browser windows share it through /share/bhist (rewritten on
- * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
- * at most every PERSIST_MS, like the cookie jar. A save re-reads
- * /share/bhist and merges it first, so two windows add to one history
- * instead of overwriting each other. File format: "NBHIST1\n", then
- * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
- * other browser state on /data. */
- #define HIST_MAX 128
- #define HIST_URL_MAX 512
- #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
- #define HIST_MAGIC "NBHIST1\n"
- #define SHARE_HIST "/share/bhist"
- #define DATA_HIST "/data/BHIST.DAT"
- #define HIST_FORGET_MAX 16
- struct hist_ent {
- unsigned int visits;
- unsigned int stamp;
- char url[HIST_URL_MAX];
- char title[BR_TITLE_MAX];
- };
- static struct hist_ent hist_tab[HIST_MAX];
- static int hist_n;
- static int hist_share_dirty, hist_data_dirty;
- /* URLs removed in this process: a merge must not bring them back. */
- static unsigned int hist_forgot[HIST_FORGET_MAX];
- static int hist_nforgot;
- static unsigned int hist_hash(const char *s)
- {
- return persist_sum((const unsigned char *)s, s_len(s));
- }
- static int hist_is_forgotten(const char *url)
- {
- unsigned int h = hist_hash(url);
- int i;
- for (i = 0; i < hist_nforgot; i++)
- if (hist_forgot[i] == h)
- return 1;
- return 0;
- }
- static int hist_find(const char *url)
- {
- int i;
- for (i = 0; i < hist_n; i++)
- if (s_eq(hist_tab[i].url, url))
- return i;
- return -1;
- }
- static unsigned int hist_next_stamp(void)
- {
- unsigned int m = 0;
- int i;
- for (i = 0; i < hist_n; i++)
- if (hist_tab[i].stamp > m)
- m = hist_tab[i].stamp;
- return m + 1;
- }
- /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
- static void hist_copy_title(char *d, const char *s, unsigned int n)
- {
- unsigned int i;
- for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
- d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
- d[i] = '\0';
- }
- /* Insert or update an entry; the newer stamp wins the title, the larger
- * visit count is kept. A full table evicts the least recent entry, unless
- * the new one is older still. Returns NULL when nothing was stored. */
- static struct hist_ent *hist_put(const char *url, const char *title,
- unsigned int visits, unsigned int stamp)
- {
- struct hist_ent *e;
- int i = hist_find(url);
- if (i < 0) {
- if (hist_n < HIST_MAX) {
- i = hist_n++;
- } else {
- int j;
- i = 0;
- for (j = 1; j < hist_n; j++)
- if (hist_tab[j].stamp < hist_tab[i].stamp)
- i = j;
- if (hist_tab[i].stamp >= stamp)
- return 0;
- }
- e = &hist_tab[i];
- e->visits = 0;
- e->stamp = 0;
- e->title[0] = '\0';
- s_copy(e->url, url, sizeof(e->url));
- }
- e = &hist_tab[i];
- if (visits > e->visits)
- e->visits = visits;
- if (stamp >= e->stamp) {
- e->stamp = stamp;
- if (title && title[0])
- hist_copy_title(e->title, title, BR_TITLE_MAX);
- } else if (!e->title[0] && title) {
- hist_copy_title(e->title, title, BR_TITLE_MAX);
- }
- return e;
- }
- static unsigned int hist_parse_dec(const char *b, int n, int *pos)
- {
- unsigned int v = 0;
- while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
- v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
- return v;
- }
- static void hist_merge_buf(const char *b, int n)
- {
- int pos = (int)s_len(HIST_MAGIC);
- char url[HIST_URL_MAX], title[BR_TITLE_MAX];
- if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
- return;
- while (pos < n) {
- unsigned int visits, stamp, ul = 0;
- int t0, t1;
- visits = hist_parse_dec(b, n, &pos);
- if (pos < n && b[pos] == ' ')
- pos++;
- stamp = hist_parse_dec(b, n, &pos);
- if (pos < n && b[pos] == ' ')
- pos++;
- while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
- if (ul + 1 < sizeof(url))
- url[ul++] = b[pos];
- pos++;
- }
- url[ul] = '\0';
- t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
- while (t1 < n && b[t1] != '\n')
- t1++;
- pos = t1 + 1;
- hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
- if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
- hist_put(url, title, visits, stamp);
- }
- }
- static int hist_serialize(char *b, unsigned int cap)
- {
- unsigned int n = 0;
- int i;
- s_append(b, &n, HIST_MAGIC, cap);
- for (i = 0; i < hist_n; i++) {
- struct hist_ent *e = &hist_tab[i];
- if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
- break;
- s_append_dec(b, &n, e->visits, cap);
- b[n++] = ' ';
- s_append_dec(b, &n, e->stamp, cap);
- b[n++] = ' ';
- s_append(b, &n, e->url, cap);
- b[n++] = '\t';
- s_append(b, &n, e->title, cap);
- b[n++] = '\n';
- }
- return (int)n;
- }
- /* Merge /share/bhist, then write it back (and /data when asked). */
- static void hist_sync(int to_data)
- {
- char *b = (char *)malloc(HIST_FILE_MAX + 1);
- int n;
- if (!b)
- return;
- n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
- (int)HIST_FILE_MAX);
- if (n > 0)
- hist_merge_buf(b, n);
- n = hist_serialize(b, HIST_FILE_MAX);
- u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
- hist_share_dirty = 0;
- if (to_data) {
- /* No /data mount: the write fails, and there is nothing to
- * retry until the next visit. */
- u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
- hist_data_dirty = 0;
- }
- free(b);
- }
- /* Startup: the boot's shared copy, else the saved one from /data. */
- static void hist_load(void)
- {
- char *b = (char *)malloc(HIST_FILE_MAX + 1);
- int n;
- if (!b)
- return;
- n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
- (int)HIST_FILE_MAX);
- if (n <= 0) {
- n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
- (int)HIST_FILE_MAX);
- if (n > 0)
- u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
- }
- if (n > 0)
- hist_merge_buf(b, n);
- free(b);
- }
- static void hist_visit(const char *url, const char *title)
- {
- struct hist_ent *e;
- unsigned int i;
- if (!url[0] || starts_with(url, "about:") ||
- s_len(url) >= HIST_URL_MAX)
- return;
- for (i = 0; url[i]; i++)
- if ((unsigned char)url[i] < 0x20)
- return;
- e = hist_put(url, title, 0, hist_next_stamp());
- if (!e)
- return;
- e->visits++;
- hist_data_dirty = 1;
- hist_sync(0);
- }
- static void hist_forget(int i)
- {
- if (i < 0 || i >= hist_n)
- return;
- if (hist_nforgot < HIST_FORGET_MAX)
- hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
- hist_n--;
- for (; i < hist_n; i++)
- hist_tab[i] = hist_tab[i + 1];
- hist_data_dirty = 1;
- hist_sync(0);
- }
- static void hist_tick(void)
- {
- if (hist_share_dirty || hist_data_dirty)
- hist_sync(hist_data_dirty);
- }
- /* Main-loop hook: write back to /data at most every PERSIST_MS. */
- static void persist_tick(void)
- {
- unsigned int now = u_ticks_ms();
- if ((int)(now - persist_due) < 0)
- return;
- persist_due = now + PERSIST_MS;
- persist_cookies_flush();
- if (persist_ndirty)
- persist_store_flush();
- hist_tick();
- }
- /* <link rel="modulepreload">: download the page's module graph on all
- * helpers at once into the boot script cache, before any script runs. The
- * engine's module loader is sequential (one blocking fetch per import), so
- * without this a Vite app with a dozen chunks pays every round trip in a
- * row. Failures are ignored; the loader fetches what is missing. */
- #define MODULE_PRELOAD_MAX 24
- static void prefetch_module_preloads(void)
- {
- static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
- struct fetch_worker *slot[MODULE_PRELOAD_MAX];
- unsigned int count = 0, next = 0, done = 0, i;
- char err[64];
- for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
- struct br_node *nd = &doc.nodes[i];
- const char *rel, *href;
- if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
- continue;
- rel = br_rel(&doc, i);
- href = br_href(&doc, i);
- if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
- continue;
- if (resolve_link(page_url, href, urls[count],
- sizeof(urls[count])) != 0 ||
- urls[count][0] == '/' || script_cache_has(urls[count]))
- continue;
- slot[count++] = 0;
- }
- if (!count)
- return;
- set_status("Loading modules...", 0, 0);
- while (done < count) {
- struct fetch_worker *w;
- while (next < count && (w = fetch_worker_alloc()) != 0) {
- if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
- 0, 0, 0, err,
- sizeof(err)) != 0) {
- fetch_worker_release(w);
- done++;
- } else {
- slot[next] = w;
- }
- next++;
- }
- worker_wait_ui();
- if (cancel_fetch || pending_action) {
- fetch_workers_cancel_busy();
- return;
- }
- for (i = 0; i < next; i++) {
- unsigned char *body;
- int rv, tr = 0;
- if (!slot[i])
- continue;
- rv = fetch_worker_poll(slot[i], err, sizeof(err));
- if (rv == 0)
- continue;
- body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
- (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
- if (body) {
- rv = fetch_worker_read_body(slot[i], body,
- BR_SCRIPT_MAX, image_io_buf,
- BR_PAGE_COMP_MAX, &tr, err,
- sizeof(err));
- if (rv > 0 && !tr)
- script_cache_put(urls[i], body,
- (unsigned int)rv);
- free(body);
- }
- fetch_worker_release(slot[i]);
- slot[i] = 0;
- done++;
- }
- u_sleep_ms(10);
- }
- }
- /* Script prefetch state: one entry per <script> block. Remote bodies are
- * submitted to helper workers ahead of time, but scripts still execute in
- * document order. */
- #define SCRIPT_INLINE 0
- #define SCRIPT_LOCAL 1
- #define SCRIPT_REMOTE 2
- #define SCRIPT_ERROR 3
- static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
- static unsigned char script_kind[BR_MAX_SCRIPTS];
- static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
- static void script_submit_window(unsigned int *next, char *err,
- unsigned int errcap)
- {
- while (*next < doc.nscripts) {
- struct fetch_worker *w;
- if (script_kind[*next] != SCRIPT_REMOTE) {
- (*next)++;
- continue;
- }
- w = fetch_worker_alloc();
- if (!w)
- return;
- if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
- 0, 0, 0, 0, err, errcap) != 0) {
- fetch_worker_release(w);
- script_kind[*next] = SCRIPT_ERROR;
- (*next)++;
- continue;
- }
- script_slot[*next] = w;
- (*next)++;
- }
- }
- /* Run the page's scripts in document order. External bodies are prefetched
- * in parallel so downloading script N+1 overlaps executing script N; inline
- * bodies are copied because the engine needs NUL-terminated text. */
- static void run_page_scripts(void)
- {
- struct js_browser_host host;
- unsigned int i, next = 0;
- char err[64], ferr[64];
- if (!doc.nscripts)
- return;
- host.status = js_host_status;
- host.report = js_host_report;
- host.navigate = js_host_navigate;
- host.changed = js_host_changed;
- host.rect = js_host_rect;
- host.form_value = js_host_form_value;
- host.form_checked = js_host_form_checked;
- host.form_selected = js_host_form_selected;
- host.form_set_value = js_host_form_set_value;
- host.form_set_checked = js_host_form_set_checked;
- host.form_set_selected = js_host_form_set_selected;
- host.form_elements = js_host_form_elements;
- host.form_submit = js_host_form_submit;
- host.form_reset = js_host_form_reset;
- host.click = js_host_click;
- host.computed = js_host_computed;
- host.http = js_host_http;
- host.load_script = js_host_load_script;
- host.storage = js_host_storage;
- host.set_hash = js_host_set_hash;
- host.page_url = page_url;
- host.width = ui.w;
- host.height = ui.h;
- if (js_browser_start(&doc, &host) != 0) {
- js_host_status("JavaScript: out of memory", 1);
- return;
- }
- resize_sent_w = -1;
- resize_pending = 0;
- prefetch_module_preloads();
- for (i = 0; i < doc.nscripts; i++) {
- struct br_script *script = &doc.scripts[i];
- const char *src_attr = script->src_off ?
- doc.attrs + script->src_off : "";
- script_slot[i] = 0;
- if (!script->src_off) {
- script_kind[i] = SCRIPT_INLINE;
- continue;
- }
- if (!src_attr[0] ||
- resolve_link(page_url, src_attr, script_urls[i],
- sizeof(script_urls[i])) != 0) {
- script_urls[i][0] = '\0';
- script_kind[i] = SCRIPT_ERROR;
- continue;
- }
- if (script_urls[i][0] == '/' ||
- script_cache_has(script_urls[i]))
- script_kind[i] = SCRIPT_LOCAL;
- else
- script_kind[i] = SCRIPT_REMOTE;
- }
- script_submit_window(&next, ferr, sizeof(ferr));
- for (i = 0; i < doc.nscripts; i++) {
- struct br_script *script = &doc.scripts[i];
- /* document.currentScript for classic scripts (null for modules) */
- js_browser_set_current_script(script->module ? 0 : script->node);
- if (script_kind[i] == SCRIPT_INLINE) {
- unsigned int off = script->off;
- unsigned int len = script->len;
- unsigned int k;
- char *src = (char *)malloc(len + 1);
- if (!src) {
- js_host_status("JavaScript: out of memory", 1);
- break;
- }
- for (k = 0; k < len; k++)
- src[k] = doc.script_src[off + k];
- src[len] = '\0';
- if (script->module) {
- /* A distinct module name per inline module
- * (QuickJS registers modules by name); the
- * fragment keeps relative imports resolving
- * against the page. */
- char mname[BR_URL_MAX + 16];
- unsigned int mn = 0;
- s_append(mname, &mn, page_url, sizeof(mname));
- s_append(mname, &mn, "#module", sizeof(mname));
- s_append_dec(mname, &mn, i, sizeof(mname));
- js_browser_run_module(src, mname);
- } else {
- js_browser_run(src, page_url);
- }
- free(src);
- } else if (script->src_off) {
- const char *src_attr = doc.attrs + script->src_off;
- if (script_kind[i] == SCRIPT_ERROR) {
- script_error("Cannot load script", src_attr,
- script_urls[i][0] ?
- "network busy" :
- "unsupported URL");
- continue;
- }
- if (script_kind[i] == SCRIPT_LOCAL) {
- unsigned char *data = 0;
- unsigned int len = 0;
- int rv;
- set_status("Loading script...", 0, 0);
- rv = fetch_script_text(script_urls[i], &data,
- &len, err, sizeof(err));
- if (rv == FETCH_ABORT)
- break;
- if (rv != 0) {
- script_error("Cannot load script",
- script_urls[i], err);
- continue;
- }
- if (script->module)
- js_browser_run_module(
- (const char *)data,
- script_urls[i]);
- else
- js_browser_run((const char *)data,
- script_urls[i]);
- free(data);
- } else {
- struct fetch_worker *w = script_slot[i];
- unsigned char *body = 0;
- int tr = 0, rv;
- if (!w) {
- w = fetch_worker_alloc();
- if (!w)
- continue;
- if (fetch_worker_submit(w,
- script_urls[i],
- BR_SCRIPT_MAX,
- 0, 0, 0, 0, err,
- sizeof(err)) != 0) {
- fetch_worker_release(w);
- script_kind[i] = SCRIPT_ERROR;
- if (i == next)
- next++;
- continue;
- }
- script_slot[i] = w;
- if (i == next)
- next++;
- }
- set_status("Loading script...", 0, 0);
- rv = fetch_worker_wait(w, err, sizeof(err));
- if (rv == FETCH_ABORT) {
- fetch_workers_stop_all();
- break;
- }
- /* The body gets its own buffer (scripts are up
- * to 2 MB); image_io_buf takes the gzip
- * stream. */
- body = rv == 0 ? (unsigned char *)malloc(
- BR_SCRIPT_MAX + 1) : 0;
- if (body)
- rv = fetch_worker_read_body(w, body,
- BR_SCRIPT_MAX, image_io_buf,
- BR_PAGE_COMP_MAX, &tr, err,
- sizeof(err));
- else {
- if (rv == 0)
- s_copy(err, "out of memory",
- sizeof(err));
- rv = -1;
- }
- fetch_worker_release(w);
- script_slot[i] = 0;
- script_submit_window(&next, ferr, sizeof(ferr));
- if (rv <= 0)
- script_error("Cannot load script",
- script_urls[i], err);
- else if (tr || (unsigned int)rv >=
- BR_SCRIPT_MAX)
- script_error("Cannot load script",
- script_urls[i],
- "script is too large");
- else {
- body[rv] = '\0';
- script_cache_put(script_urls[i], body,
- (unsigned int)rv);
- if (script->module)
- js_browser_run_module(
- (const char *)body,
- script_urls[i]);
- else
- js_browser_run(
- (const char *)body,
- script_urls[i]);
- }
- free(body);
- }
- }
- if (pending_action)
- break;
- }
- js_browser_set_current_script(0);
- /* Keep the state alive for setTimeout/ready callbacks; load_page() and
- * load_home() stop it before the next navigation. */
- if (doc.scripts_truncated && !js_last_error)
- js_host_status("Page has more than 32 scripts; extra scripts skipped",
- 1);
- }
- /* ---- images ---- */
- /* data: images that failed to decode (key = data_img_key()), so a layout
- * pass does not retry them on every frame. */
- #define DATA_IMG_FAIL_MAX 32
- static unsigned int data_img_fail[DATA_IMG_FAIL_MAX];
- static int data_img_nfail;
- static void image_reset(void)
- {
- int i;
- for (i = 0; i < BR_MAX_IMAGES; i++) {
- images[i].state = 0;
- images[i].native_w = images[i].native_h = 0;
- images[i].err[0] = '\0';
- /* heap_clear() ran before us, so these pointers are stale: drop
- * them without calling free(). */
- memset(&images[i].disp, 0, sizeof(images[i].disp));
- images[i].disp_pixels = 0;
- images[i].disp_last = 0;
- }
- image_count = 0;
- data_img_nfail = 0;
- image_pixels = 0;
- image_disp_pixels = 0;
- image_disp_clock = 0;
- memset(img_stat_log, 0, sizeof(img_stat_log));
- img_stat_log_len = 0;
- img_stat_start = 0;
- img_stat_wall = 0;
- img_stat_net = img_stat_open = img_stat_first = 0;
- img_stat_io = img_stat_dec = img_stat_scale = 0;
- img_stat_paint = img_stat_reflow = 0;
- img_stat_bytes = 0;
- img_stat_n = 0;
- img_last_dec_ms = img_last_scale_ms = 0;
- img_repaint_ms = 0;
- img_repaint_pending = 0;
- preload_active = 0;
- preload_pending = 0;
- preload_wait = 0;
- preload_node = 0;
- preload_loaded = 0;
- }
- /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
- * are arriving. The main loop draws once per dirty frame; without this a
- * page of N images did N full layout+paint passes. */
- static void image_repaint(void)
- {
- unsigned int now = u_ticks_ms();
- if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
- img_repaint_ms = now;
- img_repaint_pending = 0;
- ngui_invalidate(&ui);
- } else {
- img_repaint_pending = 1;
- }
- }
- static void image_disp_drop(struct br_image *bi)
- {
- if (bi->disp.px)
- free(bi->disp.px);
- if (bi->disp.alpha)
- free(bi->disp.alpha);
- memset(&bi->disp, 0, sizeof(bi->disp));
- if (bi->disp_pixels) {
- if (image_disp_pixels >= bi->disp_pixels)
- image_disp_pixels -= bi->disp_pixels;
- bi->disp_pixels = 0;
- }
- }
- /* Free the least recently used display caches until need pixels fit. The
- * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
- static int image_disp_room(unsigned int need)
- {
- while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
- unsigned int oldest = ~0u;
- int i, victim = -1;
- for (i = 0; i < image_count; i++) {
- if (!images[i].disp.px)
- continue;
- if (images[i].disp_last < oldest) {
- oldest = images[i].disp_last;
- victim = i;
- }
- }
- if (victim < 0)
- return -1;
- image_disp_drop(&images[victim]);
- }
- return 0;
- }
- /* Return a bitmap at exactly dw x dh, building it once from the capped source
- * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
- static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
- {
- struct img_blit b;
- unsigned int px;
- if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
- return 0;
- if (dw == (int)bi->img.w && dh == (int)bi->img.h)
- return &bi->img;
- if (dw > 4096 || dh > 4096)
- return &bi->img;
- if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
- bi->disp.h == (unsigned int)dh) {
- bi->disp_last = ++image_disp_clock;
- return &bi->disp;
- }
- px = (unsigned int)dw * (unsigned int)dh;
- if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
- return &bi->img;
- image_disp_drop(bi);
- bi->disp.px = (unsigned short *)malloc(px * 2u);
- if (!bi->disp.px)
- return &bi->img;
- if (bi->img.alpha) {
- bi->disp.alpha = (unsigned char *)malloc(px);
- if (!bi->disp.alpha) {
- free(bi->disp.px);
- bi->disp.px = 0;
- return &bi->img;
- }
- }
- bi->disp.w = (unsigned int)dw;
- bi->disp.h = (unsigned int)dh;
- bi->disp.format = bi->img.format;
- bi->disp.flags = 0;
- memset(&b, 0, sizeof(b));
- b.dst = bi->disp.px;
- b.dst_w = dw;
- b.dst_h = dh;
- b.clip_w = dw;
- b.clip_h = dh;
- b.scale = ((unsigned int)dw << 16) / bi->img.w;
- b.dst_a = bi->disp.alpha;
- b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
- img_draw(&bi->img, &b);
- bi->disp_pixels = px;
- image_disp_pixels += px;
- bi->disp_last = ++image_disp_clock;
- return &bi->disp;
- }
- /* Decode into the shared arena, then copy/scale the result into a display
- * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
- * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
- * pixels. Transparent edges are composited over white. */
- /* One decode scratch arena per page, reused across images. Allocating and
- * freeing a multi-megabyte arena per image fragmented the first-fit heap:
- * each small display bitmap landed in the hole the previous arena left, so
- * the next arena no longer fit and the heap ratcheted up until an app
- * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
- * still released right after their one image. */
- #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
- static unsigned char *decode_arena_get(unsigned int bytes)
- {
- if (decode_arena && decode_arena_size >= bytes)
- return decode_arena;
- free(decode_arena);
- decode_arena = (unsigned char *)malloc(bytes);
- decode_arena_size = decode_arena ? bytes : 0;
- return decode_arena;
- }
- static void decode_arena_put(void)
- {
- if (decode_arena_size > DECODE_ARENA_KEEP) {
- free(decode_arena);
- decode_arena = 0;
- decode_arena_size = 0;
- }
- }
- /* box_w/box_h: the laid-out box a background image paints, or 0. The
- * bitmap then only needs to cover that box (an app-store icon is 48 px), not
- * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
- static int svg_text_sniff(const unsigned char *d, unsigned int len);
- static int svg_decode_image(const unsigned char *data, unsigned int len,
- struct br_image *bi, int box_w, int box_h);
- static int decode_image_data(const unsigned char *data, unsigned int len,
- struct br_image *bi, int box_w, int box_h,
- int fit_w, int fit_h)
- {
- struct img_info info;
- struct img_options opt;
- struct img_mem mem;
- struct img_image decoded;
- unsigned char *arena;
- unsigned int est, bytes, i;
- unsigned int t0;
- unsigned short *px;
- unsigned char *alpha = 0;
- int dw, dh, r;
- bi->url_hash = 0;
- img_last_dec_ms = 0;
- img_last_scale_ms = 0;
- if (img_sniff(data, len, &info) != 0) {
- if (svg_text_sniff(data, len))
- return svg_decode_image(data, len, bi,
- box_w > 0 && box_h > 0 ? box_w : fit_w,
- box_w > 0 && box_h > 0 ? box_h : fit_h);
- s_copy(bi->err, "unknown image format", sizeof(bi->err));
- return -1;
- }
- est = img_estimate(&info);
- if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
- s_copy(bi->err, "image too large", sizeof(bi->err));
- return -1;
- }
- arena = decode_arena_get(est);
- if (!arena) {
- s_copy(bi->err, "out of memory", sizeof(bi->err));
- return -1;
- }
- img_mem_init(&mem, arena, est);
- opt.max_pixels = BR_IMG_PIX_MAX;
- opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
- (box_w > 0 ? (unsigned int)box_w : 0);
- opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
- (box_h > 0 ? (unsigned int)box_h : 0);
- t0 = u_ticks_ms();
- r = img_decode(data, len, &opt, &mem, &decoded);
- img_last_dec_ms = u_ticks_ms() - t0;
- if (r != 0) {
- s_copy(bi->err, img_error_string(r), sizeof(bi->err));
- goto fail;
- }
- if (decoded.w == 0 || decoded.h == 0) {
- s_copy(bi->err, "empty image", sizeof(bi->err));
- goto fail;
- }
- /* The JPEG decoder may have reduced the IDCT output; the layout still
- * needs the intrinsic dimensions from the header. */
- bi->native_w = info.width ? (int)info.width : (int)decoded.w;
- bi->native_h = info.height ? (int)info.height : (int)decoded.h;
- dw = (int)decoded.w;
- dh = (int)decoded.h;
- /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
- * decoding 1200x800 and then box-filtering it to 1000x666, only to
- * paint it at 400x267, doubled the decode-time scaling work. cap both
- * axes with one scale so the aspect ratio is preserved. */
- if (fit_w > 0 || fit_h > 0) {
- unsigned int scw = fit_w > 0 ?
- ((unsigned int)fit_w << 16) / decoded.w : ~0u;
- unsigned int sch = fit_h > 0 ?
- ((unsigned int)fit_h << 16) / decoded.h : ~0u;
- unsigned int sc = scw < sch ? scw : sch;
- if (sc < 0x10000u) {
- dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
- dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
- if (dw < 1)
- dw = 1;
- if (dh < 1)
- dh = 1;
- }
- }
- if (box_w > 0 && box_h > 0) {
- /* cover: scale so both box sides are filled, never up */
- unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
- unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
- unsigned int sc = sw > sh ? sw : sh;
- if (sc < 0x10000u) {
- dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
- dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
- }
- }
- if (dw > BR_IMG_LAYOUT_W) {
- dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
- dw = BR_IMG_LAYOUT_W;
- }
- if (dh < 1)
- dh = 1;
- if (dw < 1)
- dw = 1;
- if (image_pixels + (unsigned int)dw * (unsigned int)dh >
- BR_IMG_PIXEL_BUDGET) {
- s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
- goto fail;
- }
- bytes = (unsigned int)dw * (unsigned int)dh * 2u;
- px = (unsigned short *)malloc(bytes);
- if (!px) {
- s_copy(bi->err, "out of memory", sizeof(bi->err));
- goto fail;
- }
- /* Keep the alpha plane for the scaled image so transparent logos and
- * icons composite over the page instead of the browser's dark theme
- * background. Very large alpha images stay flattened to bound the
- * heap use. */
- if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
- alpha = (unsigned char *)malloc((unsigned int)dw *
- (unsigned int)dh);
- if (alpha) {
- for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
- alpha[i] = 255;
- }
- }
- /* With an alpha plane the colour under transparent pixels only shows
- * through partially covered edge pixels of the downscale: use white,
- * as documented above, not the dark browser theme (which left a dark
- * fringe around scaled app icons). */
- for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
- px[i] = alpha ? 0xFFFF : ui.theme.bg;
- {
- struct img_blit b;
- b.dst = px;
- b.dst_w = dw;
- b.dst_h = dh;
- b.clip_x = 0;
- b.clip_y = 0;
- b.clip_w = dw;
- b.clip_h = dh;
- b.x = 0;
- b.y = 0;
- b.scale = ((unsigned int)dw << 16) / decoded.w;
- b.bg = alpha ? 0xFFFF : ui.theme.bg;
- b.bg2 = b.bg;
- b.dst_a = alpha;
- b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
- t0 = u_ticks_ms();
- img_draw(&decoded, &b);
- img_last_scale_ms = u_ticks_ms() - t0;
- }
- bi->img.format = decoded.format;
- bi->img.w = (unsigned int)dw;
- bi->img.h = (unsigned int)dh;
- bi->img.px = px;
- bi->img.alpha = alpha;
- bi->img.flags = 0;
- bi->state = 1;
- image_pixels += (unsigned int)dw * (unsigned int)dh;
- decode_arena_put();
- return 0;
- fail:
- decode_arena_put();
- return -1;
- }
- /* ---- URL / local path handling ---- */
- static int is_http(const char *s)
- {
- return starts_with(s, "http://") || starts_with(s, "https://");
- }
- /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
- static int normalize_abs(const char *in, char *out, unsigned int cap)
- {
- char seg[64];
- unsigned int i = 0, o = 1;
- int depth = 0;
- int trailing;
- if (!in || in[0] != '/' || cap < 2)
- return -1;
- trailing = 0;
- {
- unsigned int n = s_len(in);
- if (n > 1 && in[n - 1] == '/')
- trailing = 1;
- }
- out[0] = '/';
- while (in[i]) {
- unsigned int n = 0;
- while (in[i] == '/')
- i++;
- while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
- if (n + 1 < sizeof(seg))
- seg[n++] = in[i];
- i++;
- }
- seg[n] = '\0';
- if (n == 0)
- break;
- if (s_eq(seg, "."))
- continue;
- if (s_eq(seg, "..")) {
- if (depth > 0) {
- while (o > 1 && out[o - 1] != '/')
- o--;
- if (o > 1)
- o--;
- depth--;
- }
- continue;
- }
- if (o > 1) {
- if (o + 1 >= cap)
- return -1;
- out[o++] = '/';
- }
- if (o + n + 1 >= cap)
- return -1;
- {
- unsigned int j;
- for (j = 0; j < n; j++)
- out[o++] = seg[j];
- }
- depth++;
- }
- if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
- if (o + 1 >= cap)
- return -1;
- out[o++] = '/';
- }
- /* Keep the query/fragment suffix for form GET and in-page anchors. */
- if (in[i] == '?' || in[i] == '#') {
- while (in[i]) {
- if (o + 1 >= cap)
- return -1;
- out[o++] = in[i++];
- }
- }
- out[o] = '\0';
- return 0;
- }
- static void make_abs_local(const char *in, char *out, unsigned int cap)
- {
- char joined[BR_URL_MAX];
- if (!in || !in[0]) {
- s_copy(out, cwd[0] ? cwd : "/", cap);
- return;
- }
- if (in[0] == '/') {
- if (normalize_abs(in, out, cap) != 0)
- s_copy(out, in, cap);
- return;
- }
- {
- unsigned int n = 0;
- s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
- s_append(joined, &n, "/", sizeof(joined));
- s_append(joined, &n, in, sizeof(joined));
- }
- if (normalize_abs(joined, out, cap) != 0)
- s_copy(out, joined, cap);
- }
- /* ---- canonical origin cache ---- *
- *
- * Sites commonly redirect http://host to https://host and then to
- * https://www.host. Remember the final scheme/host of the last navigation so
- * a bare domain typed again goes straight there instead of paying for two
- * more connections and TLS handshakes. Only default-port requests are
- * rewritten; explicit ports are left alone. */
- #define ORIGIN_CACHE_MAX 8
- #define ORIGIN_FILE "/share/borigins"
- #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
- UHTTP_HOST_MAX + 2))
- struct origin_cache_entry {
- char host[UHTTP_HOST_MAX];
- char origin[UHTTP_HOST_MAX + 16];
- };
- static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
- static int origin_count;
- static char origin_buf[ORIGIN_BUF_SIZE];
- static int default_port(const struct uhttp_url *u)
- {
- return u->secure ? u->port == 443 : u->port == 80;
- }
- static void url_origin(const struct uhttp_url *u, char *out,
- unsigned int cap)
- {
- unsigned int n = 0;
- s_append(out, &n, u->secure ? "https://" : "http://", cap);
- s_append(out, &n, u->host, cap);
- if (!default_port(u)) {
- s_append(out, &n, ":", cap);
- s_append_dec(out, &n, u->port, cap);
- }
- }
- static void origin_cache_apply(char *url, unsigned int cap)
- {
- struct uhttp_url u;
- char out[BR_URL_MAX];
- unsigned int n = 0;
- int i;
- if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
- return;
- for (i = 0; i < origin_count; i++) {
- if (!s_eq(u.host, origins[i].host))
- continue;
- s_append(out, &n, origins[i].origin, sizeof(out));
- s_append(out, &n, u.path, sizeof(out));
- s_copy(url, out, cap);
- return;
- }
- }
- static void origin_cache_save(void)
- {
- unsigned int n = 0;
- int i;
- for (i = 0; i < origin_count; i++) {
- s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
- s_append(origin_buf, &n, " ", sizeof(origin_buf));
- s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
- s_append(origin_buf, &n, "\n", sizeof(origin_buf));
- }
- if (n)
- u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
- (int)origin_buf, (int)n);
- }
- static void origin_cache_load(void)
- {
- char *p;
- int rn;
- rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
- (int)(sizeof(origin_buf) - 1));
- if (rn <= 0)
- return;
- origin_buf[rn] = '\0';
- p = origin_buf;
- while (*p && origin_count < ORIGIN_CACHE_MAX) {
- char *line = p, *origin;
- while (*p && *p != '\n')
- p++;
- if (*p)
- *p++ = '\0';
- if (!line[0])
- continue;
- origin = line;
- while (*origin && *origin != ' ')
- origin++;
- if (!*origin)
- continue;
- *origin++ = '\0';
- if (!line[0] || !is_http(origin))
- continue;
- {
- struct uhttp_url uo;
- if (uhttp_parse_url(origin, &uo) != 0 ||
- !s_eq(uo.path, "/"))
- continue;
- }
- s_copy(origins[origin_count].host, line,
- sizeof(origins[origin_count].host));
- s_copy(origins[origin_count].origin, origin,
- sizeof(origins[origin_count].origin));
- origin_count++;
- }
- }
- static int host_is_www_of(const char *host, const char *base)
- {
- return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
- host[3] == '.' && s_eq(host + 4, base);
- }
- static void origin_cache_learn(const char *requested, const char *final)
- {
- struct uhttp_url from, to;
- char origin[UHTTP_HOST_MAX + 16];
- int i;
- if (!is_http(requested) || !is_http(final))
- return;
- if (uhttp_parse_url(requested, &from) != 0 ||
- uhttp_parse_url(final, &to) != 0)
- return;
- if (!default_port(&from))
- return;
- if (s_eq(from.host, to.host) && from.secure == to.secure &&
- from.port == to.port)
- return;
- /* Only remember origin-level canonicalisation: the same path, and
- * either the same host or its www./apex sibling. A path- or
- * host-specific redirect (a shortener, a login page) must not poison
- * every request to the typed host. */
- if (!s_eq(from.path, to.path))
- return;
- if (!s_eq(from.host, to.host) &&
- !host_is_www_of(to.host, from.host) &&
- !host_is_www_of(from.host, to.host))
- return;
- url_origin(&to, origin, sizeof(origin));
- for (i = 0; i < origin_count; i++) {
- if (s_eq(origins[i].host, from.host)) {
- if (!s_eq(origins[i].origin, origin)) {
- s_copy(origins[i].origin, origin,
- sizeof(origins[i].origin));
- origin_cache_save();
- }
- return;
- }
- }
- i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
- s_copy(origins[i].host, from.host, sizeof(origins[i].host));
- s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
- origin_cache_save();
- }
- static int path_dir(const char *path, char *out, unsigned int cap)
- {
- unsigned int i, last = 0;
- for (i = 0; path[i]; i++)
- if (path[i] == '/')
- last = i;
- if (last == 0) {
- if (cap < 2)
- return -1;
- out[0] = '/';
- out[1] = '\0';
- return 0;
- }
- if (last + 1 >= cap)
- return -1;
- {
- unsigned int j;
- for (j = 0; j < last; j++)
- out[j] = path[j];
- out[last] = '\0';
- }
- return 0;
- }
- /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
- static int resolve_link(const char *base, const char *href, char *out,
- unsigned int cap)
- {
- static char joined[BR_URL_MAX]; /* leaf: off the stack */
- if (!href || !href[0] || href[0] == '#')
- return -1;
- if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
- starts_with(href, "data:") || starts_with(href, "tel:"))
- return -1;
- if (starts_with(href, "about:")) {
- s_copy(out, href, cap);
- return 0;
- }
- if (is_http(href)) {
- s_copy(out, href, cap);
- return 0;
- }
- if (starts_with(href, "//")) {
- if (is_http(base)) {
- unsigned int n = 0;
- s_append(out, &n, starts_with(base, "https:") ?
- "https:" : "http:", cap);
- s_append(out, &n, href, cap);
- return 0;
- }
- return -1;
- }
- if (is_http(base)) {
- return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
- }
- /* local page */
- if (href[0] == '/') {
- if (normalize_abs(href, out, cap) != 0)
- return -1;
- return 0;
- }
- {
- static char dir[BR_URL_MAX];
- unsigned int n = 0;
- if (s_eq(base, "about:home"))
- s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
- else if (path_dir(base, dir, sizeof(dir)) != 0)
- s_copy(dir, "/", sizeof(dir));
- s_append(joined, &n, dir, sizeof(joined));
- if (n == 0 || joined[n - 1] != '/')
- s_append(joined, &n, "/", sizeof(joined));
- s_append(joined, &n, href, sizeof(joined));
- }
- return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
- }
- /* Best-effort decompression: keep the first `cap` bytes and discard the
- * rest instead of failing when a page or stylesheet is larger than the
- * buffer. The stream is still walked to the end, so a normal page is
- * verified; a truncated compressed input still returns whatever was decoded
- * so far. */
- struct trunc_buf {
- unsigned char *dst;
- unsigned int cap, pos;
- int full;
- };
- static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
- {
- struct trunc_buf *m = (struct trunc_buf *)ctx;
- if (len > m->cap - m->pos) {
- unsigned int room = m->cap - m->pos;
- if (room) {
- unsigned int i;
- for (i = 0; i < room; i++)
- m->dst[m->pos + i] = data[i];
- m->pos += room;
- }
- m->full = 1;
- return 0;
- }
- {
- unsigned int i;
- for (i = 0; i < len; i++)
- m->dst[m->pos + i] = data[i];
- }
- m->pos += len;
- return 0;
- }
- static void worker_wait_ui(void);
- static void inflate_ui_pump(void *ctx)
- {
- static unsigned int last;
- unsigned int now = u_ticks_ms();
- (void)ctx;
- if ((int)(now - last) >= 50) {
- last = now;
- worker_wait_ui();
- }
- }
- static int inflate_trunc(const unsigned char *src, unsigned int len,
- unsigned char *dst, unsigned int cap,
- unsigned int *outlen, int gzip, int *truncated)
- {
- struct inflate_src in;
- struct inflate_sink sink;
- struct trunc_buf m;
- unsigned int got = 0;
- int r;
- in.p = src;
- in.len = len;
- in.more = 0;
- in.ctx = 0;
- m.dst = dst;
- m.cap = cap;
- m.pos = 0;
- m.full = 0;
- sink.write = trunc_write;
- sink.ctx = &m;
- inflate_init(&image_inflate_ws, &in, &sink);
- image_inflate_ws.progress = inflate_ui_pump;
- image_inflate_ws.progress_ctx = 0;
- r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
- inflate_zlib(&image_inflate_ws, &got);
- *outlen = m.pos;
- *truncated = m.full || r != 0;
- if (r != 0 && m.pos == 0)
- return -1;
- return 0;
- }
- /* ---- headless fetch workers ------------------------------------------ *
- *
- * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
- * writes the raw response, a small metadata file and a done marker under
- * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
- * or a multi-megabyte body never freezes the UI and images download in
- * parallel.
- */
- struct fetch_meta {
- int status;
- int error;
- int trunc;
- unsigned int len;
- unsigned int open_ms;
- unsigned int first_ms;
- unsigned int total_ms;
- /* Optional decoded bitmap produced by the helper (image jobs). */
- unsigned int dw, dh, nw, nh;
- unsigned int alpha;
- unsigned int px_len;
- unsigned int dec_ms;
- int dec_err;
- char encoding[16];
- char ctype[64];
- char final[BR_URL_MAX];
- };
- static void draw(unsigned int *action);
- static void handle_keys(unsigned int *action);
- static void handle_page_click(unsigned int *action);
- #define FETCH_WORKERS 4
- #define FETCH_PATH_MAX 32
- /* One long-lived curl __serve helper per worker. Each worker has its own
- * request/body/meta/done files under /share so several downloads can be in
- * flight at once; the keep-alive connection stays in the helper process, so
- * tls.c's per-process state remains valid. */
- struct fetch_worker {
- int pid;
- int slot;
- int busy;
- int ready;
- int image_job;
- unsigned int seq;
- unsigned int deadline;
- int retried;
- unsigned int dec_w, dec_h;
- int dec_retried;
- char req[FETCH_PATH_MAX];
- char body[FETCH_PATH_MAX];
- char meta[FETCH_PATH_MAX];
- char done[FETCH_PATH_MAX];
- char post[FETCH_PATH_MAX];
- char px[FETCH_PATH_MAX];
- /* Optional preload job attached to this worker. */
- unsigned int node;
- int bg;
- char url[BR_URL_MAX];
- struct fetch_meta m;
- };
- static struct fetch_worker fetch_workers[FETCH_WORKERS];
- static int fetch_tty = -2;
- static void fetch_tty_drain(void);
- static unsigned int fetch_session;
- static unsigned int fetch_seq;
- static struct fetch_meta fetch_meta;
- /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
- * an HTTP-level error (helper died, timeout in the browser, ...). */
- static int fetch_last_error;
- static unsigned int meta_uint(char **pp)
- {
- char *p = *pp;
- unsigned int v = 0;
- while (*p >= '0' && *p <= '9') {
- v = v * 10 + (unsigned int)(*p - '0');
- p++;
- }
- while (*p && *p != '\n')
- p++;
- if (*p == '\n')
- p++;
- *pp = p;
- return v;
- }
- static void meta_str(char **pp, char *out, unsigned int cap)
- {
- char *p = *pp;
- unsigned int n = 0;
- while (*p && *p != '\n' && n + 1 < cap)
- out[n++] = *p++;
- out[n] = '\0';
- while (*p && *p != '\n')
- p++;
- if (*p == '\n')
- p++;
- *pp = p;
- }
- static void worker_wait_ui(void)
- {
- unsigned int action = 0;
- if (!ngui_begin(&ui))
- return;
- draw(&action);
- handle_keys(&action);
- handle_page_click(&action);
- if (action & ACT_WAIT_NAV) {
- pending_action |= action & ACT_WAIT_NAV;
- if ((action & ACT_NAV) && click_url[0])
- s_copy(pending_url, click_url, sizeof(pending_url));
- click_url[0] = '\0';
- cancel_fetch = 1;
- }
- if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
- ngui_invalidate(&ui);
- ngui_end(&ui);
- }
- static void fetch_path(char *out, unsigned int cap, const char *kind,
- unsigned int session, int slot)
- {
- unsigned int n = 0;
- s_append(out, &n, "/share/bf", cap);
- s_append_dec(out, &n, session, cap);
- s_append(out, &n, "_", cap);
- s_append_dec(out, &n, (unsigned int)slot, cap);
- s_append(out, &n, kind, cap);
- }
- static void fetch_pool_init(void)
- {
- static int ready;
- int i;
- if (ready)
- return;
- ready = 1;
- fetch_session = ((unsigned int)u_getpid() << 16) ^
- (u_ticks_ms() & 0xFFFFu);
- if (!fetch_session)
- fetch_session = 1;
- for (i = 0; i < FETCH_WORKERS; i++) {
- struct fetch_worker *w = &fetch_workers[i];
- w->pid = -1;
- w->slot = i;
- fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
- fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
- fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
- fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
- fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
- fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
- }
- }
- static void fetch_worker_stop(struct fetch_worker *w)
- {
- int i;
- /* An abandoned image job leaves its node loadable again. */
- if (w->busy && w->image_job && w->node < doc.nnode) {
- if (w->bg && doc.nodes[w->node].bg_img_index == -3)
- doc.nodes[w->node].bg_img_index = -1;
- else if (!w->bg && doc.nodes[w->node].img_index == -3)
- doc.nodes[w->node].img_index = -1;
- }
- if (w->pid > 0) {
- u_kill((unsigned int)w->pid);
- for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
- u_sleep_ms(5);
- /* Let the reaper close the socket before we reuse the slot. */
- u_sleep_ms(10);
- }
- w->pid = -1;
- w->busy = 0;
- w->ready = 0;
- w->image_job = 0;
- if (w->req[0]) {
- u_syscall1(SYS_UNLINK, (int)w->done);
- u_syscall1(SYS_UNLINK, (int)w->meta);
- u_syscall1(SYS_UNLINK, (int)w->body);
- u_syscall1(SYS_UNLINK, (int)w->post);
- u_syscall1(SYS_UNLINK, (int)w->req);
- }
- }
- static void fetch_workers_stop_all(void)
- {
- int i;
- for (i = 0; i < FETCH_WORKERS; i++)
- fetch_worker_stop(&fetch_workers[i]);
- }
- /* Abandon the transfers of the current page but keep idle helpers and their
- * TCP/TLS connections warm for the next navigation. A busy helper is killed
- * because its response would otherwise land in a reused /share slot. */
- static void fetch_workers_cancel_busy(void)
- {
- int i;
- for (i = 0; i < FETCH_WORKERS; i++)
- if (fetch_workers[i].busy)
- fetch_worker_stop(&fetch_workers[i]);
- }
- static void fetch_workers_prepare_nav(const char *url)
- {
- int i;
- (void)url;
- for (i = 0; i < FETCH_WORKERS; i++) {
- struct fetch_worker *w = &fetch_workers[i];
- if (w->pid <= 0)
- continue;
- /* Only an in-flight transfer must be aborted. Idle helpers
- * stay warm across origins: there are just FETCH_WORKERS of
- * them, and uhttp_open drops the old connection when the
- * next job is for another host. Killing and respawning all
- * four on every navigation churned processes and sockets
- * while images were still loading. */
- if (w->busy)
- fetch_worker_stop(w);
- }
- }
- /* The browser is no longer the active window and no fetch is running: give
- * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
- static void fetch_workers_stop_if_unfocused(void)
- {
- int i;
- fetch_tty_drain();
- if (ui.focused || page_loading || preload_active)
- return;
- for (i = 0; i < FETCH_WORKERS; i++)
- if (fetch_workers[i].pid > 0) {
- fetch_workers_stop_all();
- return;
- }
- }
- /* The helpers (and this process, since u_tty_create() rebinds our own
- * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
- * it, and a full 4 KB tty ring blocks its writers: after a page that opened
- * a dozen TLS connections every helper hung in its next log line, so the
- * following cross-origin navigation sat at "Loading..." until it timed out.
- * Drain and discard it from every wait/poll loop. */
- static void fetch_tty_drain(void)
- {
- char sink[512];
- int i;
- if (fetch_tty <= 0)
- return;
- for (i = 0; i < 16; i++)
- if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
- break;
- }
- static int fetch_worker_start(struct fetch_worker *w, char *err,
- unsigned int errcap)
- {
- char arg[40];
- unsigned int n = 0;
- if (w->pid > 0 && u_alive((unsigned int)w->pid))
- return 0;
- w->pid = -1;
- fetch_pool_init();
- if (fetch_tty == -2) {
- int t = u_tty_create();
- fetch_tty = t > 0 ? t : 0;
- }
- s_append(arg, &n, "__serve ", sizeof(arg));
- s_append_dec(arg, &n, fetch_session, sizeof(arg));
- s_append(arg, &n, " ", sizeof(arg));
- s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
- w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
- if (w->pid <= 0) {
- w->pid = -1;
- s_copy(err, "cannot start network helper", errcap);
- return -1;
- }
- return 0;
- }
- static struct fetch_worker *fetch_worker_alloc(void)
- {
- int i;
- fetch_pool_init();
- for (i = 0; i < FETCH_WORKERS; i++)
- if (!fetch_workers[i].busy)
- return &fetch_workers[i];
- return 0;
- }
- static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
- unsigned int cap, const char *method,
- const char *ctype, const char *post,
- unsigned int post_len, unsigned int node,
- int bg, unsigned int dec_w,
- unsigned int dec_h, char *err,
- unsigned int errcap);
- static int fetch_worker_submit(struct fetch_worker *w, const char *url,
- unsigned int cap, const char *post,
- unsigned int post_len, unsigned int node,
- int bg, char *err, unsigned int errcap)
- {
- /* A body pointer with no bytes is still a POST: the classic request
- * line would turn it into a GET. */
- if (post && !post_len)
- return fetch_worker_submit_req(w, url, cap, "POST",
- "application/x-www-form-urlencoded", post, 0, node,
- bg, 0, 0, err, errcap);
- return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
- node, bg, 0, 0, err, errcap);
- }
- /* Image job: ask the helper to decode at these display bounds as well. */
- static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
- unsigned int cap, unsigned int node,
- int bg, unsigned int dec_w,
- unsigned int dec_h, char *err,
- unsigned int errcap)
- {
- return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
- dec_w, dec_h, err, errcap);
- }
- /* `method` NULL keeps the classic GET / form-POST request line; otherwise
- * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
- static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
- unsigned int cap, const char *method,
- const char *ctype, const char *post,
- unsigned int post_len, unsigned int node,
- int bg, unsigned int dec_w,
- unsigned int dec_h, char *err,
- unsigned int errcap)
- {
- static char req[BR_URL_MAX + 256];
- unsigned int n = 0;
- fetch_seq++;
- if (!fetch_seq)
- fetch_seq = 1;
- w->seq = fetch_seq;
- w->ready = 0;
- w->image_job = 0;
- w->retried = 0;
- w->m.error = 0;
- w->node = node;
- w->bg = bg;
- w->dec_w = dec_w;
- w->dec_h = dec_h;
- w->dec_retried = 0;
- s_copy(w->url, url, sizeof(w->url));
- s_append_dec(req, &n, w->seq, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- s_append_dec(req, &n, cap, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- if (dec_w || dec_h) {
- s_append(req, &n, "D ", sizeof(req));
- s_append_dec(req, &n, dec_w, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- s_append_dec(req, &n, dec_h, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- } else if (method) {
- unsigned int k;
- s_append(req, &n, "X ", sizeof(req));
- s_append(req, &n, method, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- s_append_dec(req, &n, post_len, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- if (!ctype || !ctype[0])
- s_append(req, &n, "-", sizeof(req));
- /* One token on the request line: drop the spaces
- * ("application/json; charset=utf-8" stays valid). */
- for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
- if (ctype[k] != ' ')
- req[n++] = ctype[k];
- req[n] = '\0';
- s_append(req, &n, " ", sizeof(req));
- } else if (post_len) {
- s_append(req, &n, "POST ", sizeof(req));
- s_append_dec(req, &n, post_len, sizeof(req));
- s_append(req, &n, " ", sizeof(req));
- }
- s_append(req, &n, url, sizeof(req));
- s_append(req, &n, "\n", sizeof(req));
- if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
- (int)post, (int)post_len) < 0) {
- s_copy(err, "cannot queue form body", errcap);
- return -1;
- }
- u_syscall1(SYS_UNLINK, (int)w->done);
- u_syscall1(SYS_UNLINK, (int)w->meta);
- if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
- s_copy(err, "cannot queue network request", errcap);
- return -1;
- }
- if (fetch_worker_start(w, err, errcap) != 0)
- return -1;
- w->busy = 1;
- w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
- return 0;
- }
- /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
- static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
- unsigned int errcap)
- {
- static char meta[BR_URL_MAX + 1024];
- char *p;
- int rn, mseq;
- rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
- (int)(sizeof(meta) - 1));
- if (rn <= 0) {
- s_copy(err, "network helper failed", errcap);
- return -1;
- }
- meta[rn] = '\0';
- p = meta;
- mseq = (int)meta_uint(&p);
- if (mseq != (int)w->seq) {
- s_copy(err, "stale network response", errcap);
- return -1;
- }
- w->m.status = (int)meta_uint(&p);
- w->m.error = (int)meta_uint(&p);
- w->m.trunc = (int)meta_uint(&p);
- meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
- meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
- meta_str(&p, w->m.final, sizeof(w->m.final));
- w->m.len = meta_uint(&p);
- w->m.open_ms = 0;
- w->m.first_ms = 0;
- w->m.total_ms = 0;
- if (*p) {
- w->m.open_ms = meta_uint(&p);
- w->m.first_ms = meta_uint(&p);
- w->m.total_ms = meta_uint(&p);
- }
- w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
- w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
- w->m.dec_err = 0;
- if (*p) {
- w->m.dw = meta_uint(&p);
- w->m.dh = meta_uint(&p);
- w->m.nw = meta_uint(&p);
- w->m.nh = meta_uint(&p);
- w->m.alpha = meta_uint(&p);
- w->m.px_len = meta_uint(&p);
- w->m.dec_err = (int)meta_uint(&p);
- w->m.dec_ms = meta_uint(&p);
- }
- if (w->m.error) {
- s_copy(err, uhttp_error_string(w->m.error), errcap);
- return -1;
- }
- w->ready = 1;
- return 0;
- }
- /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
- static int fetch_worker_poll(struct fetch_worker *w, char *err,
- unsigned int errcap)
- {
- static char done[24];
- char *p;
- int rn, mseq;
- fetch_tty_drain();
- if (!w->busy)
- return -1;
- if (w->ready)
- return 1;
- rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
- (int)(sizeof(done) - 1));
- if (rn > 0) {
- done[rn] = '\0';
- p = done;
- mseq = (int)meta_uint(&p);
- if (mseq == (int)w->seq) {
- if (fetch_worker_read_meta(w, err, errcap) != 0) {
- fetch_worker_stop(w);
- return -1;
- }
- return 1;
- }
- }
- if (!u_alive((unsigned int)w->pid)) {
- w->pid = -1;
- if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
- w->retried = 1;
- return 0;
- }
- s_copy(err, "network helper stopped", errcap);
- fetch_worker_stop(w);
- return -1;
- }
- if ((int)(u_ticks_ms() - w->deadline) >= 0) {
- s_copy(err, "network request timed out", errcap);
- fetch_worker_stop(w);
- return -1;
- }
- return 0;
- }
- /* Copy the completed body, inflating it if the server ignored our identity
- * request. Mirrors the old fetch_remote body path. */
- static int fetch_worker_read_body(struct fetch_worker *w,
- unsigned char *plain,
- unsigned int plaincap,
- unsigned char *comp,
- unsigned int compcap,
- int *truncated, char *err,
- unsigned int errcap)
- {
- int rv, zr, was_trunc;
- if (contains_ci(w->m.encoding, "gzip") ||
- contains_ci(w->m.encoding, "deflate")) {
- unsigned int comp_len = 0, plen = 0;
- rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
- (int)compcap);
- if (rv < 0) {
- s_copy(err, "empty response", errcap);
- return -1;
- }
- comp_len = (unsigned int)rv;
- if (comp_len < w->m.len) {
- s_copy(err, "compressed response is too large", errcap);
- return -1;
- }
- if (contains_ci(w->m.encoding, "deflate"))
- zr = inflate_trunc(comp, comp_len, plain, plaincap,
- &plen, 0, &was_trunc);
- else
- zr = inflate_trunc(comp, comp_len, plain, plaincap,
- &plen, 1, &was_trunc);
- if (zr != 0) {
- s_copy(err, "compressed response is corrupt", errcap);
- return -1;
- }
- *truncated = w->m.trunc || was_trunc;
- return (int)plen;
- }
- rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
- if (rv < 0) {
- s_copy(err, "empty response", errcap);
- return -1;
- }
- *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
- return rv;
- }
- static void fetch_worker_release(struct fetch_worker *w)
- {
- u_syscall1(SYS_UNLINK, (int)w->done);
- u_syscall1(SYS_UNLINK, (int)w->meta);
- u_syscall1(SYS_UNLINK, (int)w->body);
- u_syscall1(SYS_UNLINK, (int)w->post);
- u_syscall1(SYS_UNLINK, (int)w->px);
- u_syscall1(SYS_UNLINK, (int)w->req);
- w->busy = 0;
- w->ready = 0;
- w->image_job = 0;
- w->dec_w = 0;
- w->dec_h = 0;
- w->dec_retried = 0;
- }
- /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
- static int fetch_worker_wait(struct fetch_worker *w, char *err,
- unsigned int errcap)
- {
- for (;;) {
- int rv;
- if (!fetch_wait_passive)
- worker_wait_ui();
- if (cancel_fetch || pending_action) {
- fetch_workers_cancel_busy();
- return FETCH_ABORT;
- }
- rv = fetch_worker_poll(w, err, errcap);
- if (rv != 0)
- return rv == 1 ? 0 : -1;
- u_sleep_ms(10);
- }
- }
- static int fetch_remote(const char *url, unsigned int cap,
- const char *post, unsigned int post_len,
- unsigned char *plain, unsigned int plaincap,
- unsigned char *comp, unsigned int compcap,
- struct fetch_meta *m, int *truncated,
- char *err, unsigned int errcap)
- {
- struct fetch_worker *w = fetch_worker_alloc();
- int rv;
- fetch_last_error = 0;
- if (!w) {
- s_copy(err, "network busy", errcap);
- return -1;
- }
- if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
- err, errcap) != 0) {
- fetch_worker_release(w);
- return -1;
- }
- rv = fetch_worker_wait(w, err, errcap);
- if (rv == FETCH_ABORT) {
- fetch_worker_release(w);
- return FETCH_ABORT;
- }
- if (rv != 0) {
- fetch_last_error = w->m.error;
- fetch_worker_release(w);
- return -1;
- }
- *m = w->m;
- rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
- truncated, err, errcap);
- fetch_worker_release(w);
- if (rv >= 0 && (cancel_fetch || pending_action))
- return FETCH_ABORT;
- return rv;
- }
- static int fetch_worker_status(const struct fetch_worker *w)
- {
- return w->m.status;
- }
- /* fetch()/XHR through a helper: one request, the status and body come back
- * whatever the HTTP status (a 401 is an answer, not a network error). */
- static int js_worker_http(const char *method, const char *url,
- const char *ctype, const char *body,
- unsigned int body_len, struct js_http_resp *r,
- char *err, int errcap)
- {
- struct fetch_worker *w = fetch_worker_alloc();
- unsigned char *plain;
- int rv, tr = 0;
- if (!w) {
- s_copy(err, "network busy", (unsigned int)errcap);
- return -1;
- }
- if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
- body_len, 0, 0, 0, 0, err,
- (unsigned int)errcap) != 0) {
- fetch_worker_release(w);
- return -1;
- }
- fetch_wait_passive++;
- rv = fetch_worker_wait(w, err, (unsigned int)errcap);
- fetch_wait_passive--;
- if (rv != 0) {
- if (rv == FETCH_ABORT)
- s_copy(err, "page is navigating", (unsigned int)errcap);
- fetch_worker_release(w);
- return -1;
- }
- r->status = w->m.status;
- s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
- s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
- plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
- if (!plain) {
- fetch_worker_release(w);
- s_copy(err, "out of memory", (unsigned int)errcap);
- return -1;
- }
- if (w->m.len == 0) {
- rv = 0; /* 204, an empty 200: no body file */
- } else {
- rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
- image_io_buf, BR_PAGE_COMP_MAX,
- &tr, err, (unsigned int)errcap);
- }
- fetch_worker_release(w);
- if (rv < 0) {
- free(plain);
- return -1;
- }
- plain[rv] = '\0';
- r->body = (char *)plain;
- r->len = (unsigned int)rv;
- return 0;
- }
- /* ---- HTTP / file fetch ---- */
- static int read_url(const char *url, unsigned int cap, unsigned char **out,
- unsigned int *outlen, int *is_local, char *ctype,
- unsigned int ctcap, char *final, unsigned int finalcap,
- char *err, unsigned int errcap, int *truncated,
- const char *post, unsigned int post_len)
- {
- unsigned char *buf;
- unsigned int len;
- int tr = 0;
- int rv;
- *out = 0;
- *outlen = 0;
- *truncated = 0;
- if (final && finalcap)
- final[0] = '\0';
- if (ctype && ctcap)
- ctype[0] = '\0';
- if (url[0] == '/') {
- char pathbuf[BR_URL_MAX];
- const char *open_url = url;
- unsigned int i = 0;
- /* A local form GET keeps ?query in the address bar but the
- * file lookup uses the path alone, like a real browser. */
- while (url[i] && url[i] != '?' && url[i] != '#')
- i++;
- if (url[i]) {
- s_copy(pathbuf, url, i + 1);
- open_url = pathbuf;
- }
- buf = (unsigned char *)malloc(cap);
- if (!buf) {
- s_copy(err, "out of memory", errcap);
- return -1;
- }
- rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
- if (rv < 0) {
- free(buf);
- s_copy(err, "file not found", errcap);
- return -1;
- }
- *out = buf;
- *outlen = (unsigned int)rv;
- *is_local = 1;
- if (ctype)
- s_copy(ctype, "text/html", ctcap);
- if (final)
- s_copy(final, url, finalcap);
- if ((unsigned int)rv == cap)
- *truncated = 1;
- return 0;
- }
- buf = (unsigned char *)malloc(cap);
- if (!buf) {
- s_copy(err, "out of memory", errcap);
- return -1;
- }
- rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
- BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
- if (rv == FETCH_ABORT) {
- free(buf);
- return FETCH_ABORT;
- }
- if (rv < 0) {
- free(buf);
- return -1;
- }
- len = (unsigned int)rv;
- if (len == 0) {
- free(buf);
- s_copy(err, "empty response", errcap);
- return -1;
- }
- if (ctype)
- s_copy(ctype, fetch_meta.ctype, ctcap);
- if (final && fetch_meta.final[0])
- s_copy(final, fetch_meta.final, finalcap);
- *is_local = 0;
- *out = buf;
- *outlen = len;
- *truncated = tr;
- return 0;
- }
- static unsigned int css_cache_hash(const char *s);
- /* Remote fonts are cached under /share for the current boot like the
- * stylesheets, as the raw response (a WOFF stays compressed). */
- static int font_cache_count;
- static void font_cache_path(const char *url, char *out, unsigned int cap)
- {
- unsigned int n = 0;
- s_append(out, &n, "/share/" FONT_CACHE_PREFIX, cap);
- s_append_dec(out, &n, css_cache_hash(url), cap);
- }
- static void font_cache_init(void)
- {
- struct sys_dirent d;
- int i;
- font_cache_count = 0;
- for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
- (int)&d) == 1; i++)
- if (starts_with(d.name, FONT_CACHE_PREFIX))
- font_cache_count++;
- }
- /* Read one font file (local path, boot cache or network) into a fresh
- * malloc'ed buffer. Returns its length, or -1. */
- static int font_fetch(const char *abs, unsigned char **out)
- {
- unsigned char *buf;
- char path[96];
- int rv;
- *out = 0;
- buf = (unsigned char *)malloc(UFONT_MAX_FILE + 512u);
- if (!buf)
- return -1;
- if (abs[0] == '/') {
- struct sys_stat st;
- /* FAT reads may write past the length: the 512 bytes of
- * slack above cover the final partial sector. */
- if (u_stat(abs, &st) != 0 || st.is_dir || st.size == 0 ||
- st.size > UFONT_MAX_FILE) {
- free(buf);
- return -1;
- }
- rv = u_syscall3(SYS_READ_FILE, (int)abs, (int)buf,
- (int)st.size);
- if (rv != (int)st.size) {
- free(buf);
- return -1;
- }
- *out = buf;
- return rv;
- }
- if (!is_http(abs)) {
- free(buf);
- return -1;
- }
- font_cache_path(abs, path, sizeof(path));
- rv = u_syscall3(SYS_READ_FILE, (int)path, (int)buf,
- (int)UFONT_MAX_FILE);
- if (rv > 0 && (unsigned int)rv < UFONT_MAX_FILE) {
- *out = buf;
- return rv;
- }
- {
- char err[64];
- int tr = 0;
- rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
- UFONT_MAX_FILE, image_io_buf,
- BR_PAGE_COMP_MAX, &fetch_meta, &tr, err,
- sizeof(err));
- /* An error page is not a font: never parse or cache it. */
- if (rv > 0 && !tr && fetch_meta.status >= 300) {
- snprintf(err, sizeof(err), "HTTP %d", fetch_meta.status);
- rv = 0;
- }
- if (rv <= 0 || tr) {
- u_puts("[font] failed: ");
- u_puts(abs);
- u_puts(rv <= 0 ? " " : " truncated ");
- u_puts(rv <= 0 ? err : "");
- u_putc('\n');
- free(buf);
- return -1;
- }
- }
- if (font_cache_count < FONT_CACHE_MAX &&
- u_syscall3(SYS_WRITE_FILE, (int)path, (int)buf, rv) >= 0)
- font_cache_count++;
- *out = buf;
- return rv;
- }
- /* Open one @font-face entry: fetch, unwrap WOFF, parse into the ufont
- * arena. A WOFF2 or CFF (OTTO) file is reported and left unloaded. */
- static struct ufont_face *font_open_entry(int id)
- {
- const char *url = br_font_face_url(id);
- const char *base = br_font_face_base(id);
- char abs[BR_URL_MAX];
- unsigned char *buf, *sfnt;
- unsigned int slen = 0;
- struct ufont_face *f = 0;
- const char *why = 0;
- int n;
- if (!url || !url[0] ||
- resolve_link(base && base[0] ? base : page_url, url, abs,
- sizeof(abs)) != 0)
- return 0;
- n = font_fetch(abs, &buf);
- if (n <= 0)
- return 0;
- sfnt = buf;
- slen = (unsigned int)n;
- if (ufont_is_woff2(buf, slen)) {
- why = "WOFF2 not supported";
- } else if (ufont_is_woff(buf, slen)) {
- sfnt = ufont_woff_decode(buf, slen, &slen);
- if (!sfnt)
- why = "bad WOFF";
- }
- if (!why) {
- f = ufont_face_open_mem(sfnt, slen);
- if (!f)
- why = (slen >= 4 && sfnt[0] == 'O' && sfnt[1] == 'T' &&
- sfnt[2] == 'T' && sfnt[3] == 'O') ?
- "CFF outlines not supported" :
- "not a TrueType font or arena full";
- }
- if (sfnt && sfnt != buf)
- free(sfnt);
- free(buf);
- u_puts(f ? "[font] loaded " : "[font] skipped ");
- u_puts(br_font_face_family(id));
- u_puts(": ");
- u_puts(abs);
- if (why) {
- u_puts(" (");
- u_puts(why);
- u_putc(')');
- }
- u_putc('\n');
- return f;
- }
- /* Distance of a face from the requested weight: 0 inside its range. A
- * bold request prefers heavier faces and a normal one lighter faces, as
- * the CSS font-matching steps do. */
- static unsigned int font_weight_dist(const struct br_font_face_info *fi,
- unsigned int want)
- {
- if (want >= fi->wmin && want <= fi->wmax)
- return 0;
- if (want > fi->wmax)
- return (want - fi->wmax) * 2u + (want >= 500 ? 1u : 0u);
- return (fi->wmin - want) * 2u + (want < 500 ? 1u : 0u);
- }
- /* Load the @font-face entries a font-family declaration named: per family
- * the regular face first, then bold, italic and the rest, so a full arena
- * drops the least common variants. Then precompute, for every family and
- * (bold, italic) combination, the loaded face CSS font matching picks;
- * layout reads only that table. A family with no loaded face keeps
- * font_pick 0, and its text uses the built-in set. */
- static void load_font_faces(void)
- {
- int n = br_font_face_count(), pass, id;
- memset(font_faces, 0, sizeof(font_faces));
- memset(font_pick, 0, sizeof(font_pick));
- if (n > BR_MAX_FACES)
- n = BR_MAX_FACES;
- for (pass = 0; pass < 4; pass++) {
- for (id = 1; id <= n; id++) {
- struct br_font_face_info fi;
- int cls;
- if (br_font_face_info(id, &fi) != 0 || !fi.used)
- continue;
- if (!fi.italic && fi.wmin <= 400 && fi.wmax >= 400)
- cls = 0;
- else if (!fi.italic && fi.wmin <= 700 &&
- fi.wmax >= 700)
- cls = 1;
- else if (fi.italic && fi.wmin <= 400 &&
- fi.wmax >= 400)
- cls = 2;
- else
- cls = 3;
- if (cls == pass)
- font_faces[id - 1] = font_open_entry(id);
- }
- }
- for (id = 1; id <= n; id++) {
- struct br_font_face_info fam;
- int combo;
- if (br_font_face_info(id, &fam) != 0 || fam.family_id != id)
- continue;
- for (combo = 0; combo < 4; combo++) {
- unsigned int want = (combo & 2) ? 700u : 400u;
- int italic = combo & 1, k, best = 0;
- unsigned int best_score = 0;
- for (k = 1; k <= n; k++) {
- struct br_font_face_info fi;
- unsigned int score;
- if (!font_faces[k - 1] ||
- br_font_face_info(k, &fi) != 0 ||
- fi.family_id != id)
- continue;
- score = font_weight_dist(&fi, want) +
- ((fi.italic != 0) != (italic != 0) ?
- 100000u : 0u);
- if (!best || score < best_score) {
- best = k;
- best_score = score;
- }
- }
- font_pick[id - 1][combo] = (unsigned char)best;
- }
- }
- }
- /* Remote scripts are cached under /share for the current boot, like the
- * stylesheet cache, so reloads and later visits skip the network. */
- static int script_cache_count;
- static unsigned int script_cache_hash(const char *s)
- {
- unsigned int h = 2166136261u;
- while (*s) {
- h ^= (unsigned char)*s++;
- h *= 16777619u;
- }
- return h;
- }
- static void script_cache_path(const char *url, char *out, unsigned int cap)
- {
- unsigned int n = 0;
- s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
- s_append_dec(out, &n, script_cache_hash(url), cap);
- }
- static void script_cache_clear(void)
- {
- struct sys_dirent d;
- char path[96];
- for (;;) {
- int i, found = 0;
- for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
- (int)&d) == 1; i++) {
- unsigned int n = 0;
- if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
- continue;
- s_append(path, &n, "/share/", sizeof(path));
- s_append(path, &n, d.name, sizeof(path));
- if (u_syscall1(SYS_UNLINK, (int)path) < 0)
- return;
- found = 1;
- break;
- }
- if (!found)
- break;
- }
- script_cache_count = 0;
- }
- static void script_cache_init(void)
- {
- struct sys_dirent d;
- int i, count = 0;
- for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
- (int)&d) == 1; i++)
- if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
- count++;
- if (count >= SCRIPT_CACHE_MAX) {
- script_cache_clear();
- return;
- }
- script_cache_count = count;
- }
- static int script_cache_get(const char *url, unsigned char **out,
- unsigned int *outlen)
- {
- char path[96];
- struct sys_stat st;
- unsigned char *buf;
- int rn;
- script_cache_path(url, path, sizeof(path));
- if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
- st.size >= SCRIPT_CACHE_FILE_MAX)
- return 0;
- buf = (unsigned char *)malloc(st.size + 1);
- if (!buf)
- return 0;
- rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
- if (rn != (int)st.size) {
- free(buf);
- return 0;
- }
- buf[st.size] = '\0';
- *out = buf;
- *outlen = st.size;
- return 1;
- }
- static void script_cache_put(const char *url, const unsigned char *data,
- unsigned int len)
- {
- char path[96];
- if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
- len >= SCRIPT_CACHE_FILE_MAX)
- return;
- script_cache_path(url, path, sizeof(path));
- if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
- (int)len) >= 0)
- script_cache_count++;
- }
- static int script_cache_has(const char *url)
- {
- char path[96];
- struct sys_stat st;
- script_cache_path(url, path, sizeof(path));
- return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
- st.size < SCRIPT_CACHE_FILE_MAX;
- }
- /* Fetch one external script into a heap buffer and NUL-terminate it. */
- static int fetch_script_text(const char *url, unsigned char **out,
- unsigned int *outlen, char *err,
- unsigned int errcap)
- {
- unsigned char *buf;
- unsigned int len;
- int local, truncated = 0;
- char ctype[64], final[BR_URL_MAX];
- int rv;
- *out = 0;
- *outlen = 0;
- if (url[0] != '/' && script_cache_get(url, out, outlen))
- return 0;
- rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
- sizeof(ctype), final, sizeof(final), err, errcap,
- &truncated, 0, 0);
- if (rv != 0)
- return rv;
- if (truncated || len >= BR_SCRIPT_MAX) {
- free(buf);
- s_copy(err, "script is too large", errcap);
- return -1;
- }
- buf[len] = '\0';
- if (!local)
- script_cache_put(url, buf, len);
- *out = buf;
- *outlen = len;
- return 0;
- }
- /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
- * the heap, so images must not allocate their file body from it as well. */
- static int fetch_image(const char *url, unsigned int cap,
- unsigned char **out, unsigned int *outlen,
- char *err, unsigned int errcap)
- {
- unsigned int len;
- int tr = 0;
- int rv;
- *out = 0;
- *outlen = 0;
- if (cap > BR_IMG_FILE_MAX)
- cap = BR_IMG_FILE_MAX;
- if (url[0] == '/') {
- rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
- (int)cap);
- if (rv < 0) {
- s_copy(err, "file not found", errcap);
- return -1;
- }
- *out = image_file_buf;
- *outlen = (unsigned int)rv;
- return 0;
- }
- rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
- BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
- if (rv == FETCH_ABORT)
- return FETCH_ABORT;
- if (rv < 0)
- return -1;
- len = (unsigned int)rv;
- if (len == 0) {
- s_copy(err, "empty image", errcap);
- return -1;
- }
- *out = image_file_buf;
- *outlen = len;
- return 0;
- }
- /* Remote stylesheets are immutable enough for the current boot: keep
- * successful responses under /share so a reload, a second visit or a fresh
- * browser launch does not fetch the same five sheets over the network again.
- * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
- static int css_cache_count;
- static unsigned int css_cache_hash(const char *s)
- {
- unsigned int h = 2166136261u;
- while (*s) {
- h ^= (unsigned char)*s++;
- h *= 16777619u;
- }
- return h;
- }
- static void css_cache_path(const char *url, char *out, unsigned int cap)
- {
- unsigned int n = 0;
- s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
- s_append_dec(out, &n, css_cache_hash(url), cap);
- }
- static void css_cache_clear(void)
- {
- struct sys_dirent d;
- char path[96];
- for (;;) {
- int i, found = 0;
- for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
- (int)&d) == 1; i++) {
- unsigned int n = 0;
- if (!starts_with(d.name, CSS_CACHE_PREFIX))
- continue;
- s_append(path, &n, "/share/", sizeof(path));
- s_append(path, &n, d.name, sizeof(path));
- if (u_syscall1(SYS_UNLINK, (int)path) < 0)
- return;
- found = 1;
- break;
- }
- if (!found)
- break;
- }
- css_cache_count = 0;
- }
- static void css_cache_init(void)
- {
- struct sys_dirent d;
- int i, count = 0;
- for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
- (int)&d) == 1; i++)
- if (starts_with(d.name, CSS_CACHE_PREFIX))
- count++;
- if (count >= CSS_CACHE_MAX) {
- css_cache_clear();
- return;
- }
- css_cache_count = count;
- }
- static int css_cache_get(const char *url, unsigned char **out,
- unsigned int *outlen)
- {
- char path[96];
- int rn;
- css_cache_path(url, path, sizeof(path));
- rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
- (int)CSS_CACHE_FILE_MAX);
- if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
- return 0;
- *out = image_io_buf;
- *outlen = (unsigned int)rn;
- return 1;
- }
- static void css_cache_put(const char *url, const unsigned char *data,
- unsigned int len)
- {
- char path[96];
- if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
- len >= CSS_CACHE_FILE_MAX)
- return;
- css_cache_path(url, path, sizeof(path));
- if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
- (int)len) >= 0)
- css_cache_count++;
- }
- static int css_cache_has(const char *url)
- {
- char path[96];
- struct sys_stat st;
- css_cache_path(url, path, sizeof(path));
- return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
- st.size < CSS_CACHE_FILE_MAX;
- }
- /* Read one stylesheet into the shared static buffer. CSS is parsed
- * immediately, so it does not need the page heap; this leaves the heap for
- * the 2 MB page body, the rules and the scaled image bitmaps. */
- static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
- char *err, unsigned int errcap)
- {
- unsigned int len;
- int tr = 0;
- int rv;
- *out = 0;
- *outlen = 0;
- if (url[0] == '/') {
- rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
- (int)BR_CSS_MAX);
- if (rv < 0) {
- s_copy(err, "stylesheet not found", errcap);
- return -1;
- }
- *out = image_io_buf;
- *outlen = (unsigned int)rv;
- return 0;
- }
- if (css_cache_get(url, out, outlen))
- return 0;
- rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
- image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
- &fetch_meta, &tr, err, errcap);
- if (rv == FETCH_ABORT)
- return FETCH_ABORT;
- if (rv < 0)
- return -1;
- len = (unsigned int)rv;
- if (len == 0) {
- s_copy(err, "empty stylesheet", errcap);
- return -1;
- }
- *out = image_io_buf;
- *outlen = len;
- css_cache_put(url, image_io_buf, len);
- return 0;
- }
- static void redraw_now(void);
- static char error_page[1024];
- static void show_error(const char *title, const char *detail)
- {
- char *page = error_page;
- unsigned int n = 0;
- s_append(page, &n, "<html><body><h2>", sizeof(error_page));
- s_append(page, &n, title, sizeof(error_page));
- s_append(page, &n, "</h2><p>", sizeof(error_page));
- {
- const char *p = detail;
- while (*p && n + 1 < sizeof(error_page)) {
- if (*p == '<') s_append(page, &n, "<", sizeof(error_page));
- else if (*p == '>') s_append(page, &n, ">", sizeof(error_page));
- else if (*p == '&') s_append(page, &n, "&", sizeof(error_page));
- else page[n++] = *p;
- p++;
- }
- }
- page[n] = '\0';
- s_append(page, &n, "</p><p>", sizeof(error_page));
- s_append(page, &n, page_url, sizeof(error_page));
- s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
- sizeof(error_page));
- br_parse(&doc, page, n);
- layout_valid = 0;
- preload_active = 0;
- preload_pending = 0;
- preload_wait = 0;
- fetch_workers_cancel_busy();
- s_copy(page_title, title, sizeof(page_title));
- page_loading = 0;
- set_status(title, 1, 0);
- ngui_invalidate(&ui);
- }
- static int decode_direct_image(const unsigned char *data, unsigned int len,
- unsigned int node)
- {
- if (image_count >= BR_MAX_IMAGES)
- return -1;
- if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
- return -1;
- doc.nodes[node].img_index = 0;
- image_count = 1;
- return 0;
- }
- static int ancestor_is(unsigned int node, unsigned int tag)
- {
- unsigned int p = doc.nodes[node].parent;
- while (p) {
- if (doc.nodes[p].tag == tag)
- return 1;
- p = doc.nodes[p].parent;
- }
- return 0;
- }
- /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
- * parallel but parsed in document order, so the cascade is unchanged. */
- static int load_stylesheets(void)
- {
- static char urls[BR_MAX_SHEETS][BR_URL_MAX];
- static unsigned char remote[BR_MAX_SHEETS];
- struct fetch_worker *slot[BR_MAX_SHEETS];
- unsigned int i, n = 0, next = 0, k;
- char err[64];
- for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
- struct br_node *nd = &doc.nodes[i];
- const char *rel, *href;
- char url[BR_URL_MAX];
- int dup = 0;
- if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
- continue;
- rel = br_rel(&doc, i);
- if (!contains_ci(rel, "stylesheet"))
- continue;
- href = br_href(&doc, i);
- if (!href[0])
- continue;
- if (resolve_link(page_url, href, url, sizeof(url)) != 0)
- continue;
- for (k = 0; k < n; k++)
- if (s_eq(urls[k], url)) {
- dup = 1;
- break;
- }
- if (dup)
- continue;
- s_copy(urls[n], url, BR_URL_MAX);
- remote[n] = url[0] != '/' && !css_cache_has(url);
- n++;
- }
- for (i = 0; i < BR_MAX_SHEETS; i++)
- slot[i] = 0;
- /* Start as many remote sheets as there are free workers. */
- for (; next < n; next++) {
- struct fetch_worker *w;
- if (!remote[next])
- continue;
- w = fetch_worker_alloc();
- if (!w)
- break;
- if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
- err, sizeof(err)) != 0) {
- fetch_worker_release(w);
- remote[next] = 0;
- continue;
- }
- slot[next] = w;
- }
- for (i = 0; i < n; i++) {
- unsigned char *data = 0;
- unsigned int len = 0;
- int rv;
- if (!remote[i]) {
- rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
- if (rv == FETCH_ABORT) {
- fetch_workers_stop_all();
- return FETCH_ABORT;
- }
- if (rv != 0 || !len)
- continue;
- } else {
- struct fetch_worker *w = slot[i];
- int tr = 0;
- if (!w) {
- w = fetch_worker_alloc();
- if (!w) {
- rv = -1;
- goto css_failed;
- }
- if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
- 0, 0, 0, 0, err,
- sizeof(err)) != 0) {
- fetch_worker_release(w);
- remote[i] = 0;
- if (i == next)
- next++;
- continue;
- }
- slot[i] = w;
- if (i == next)
- next++;
- }
- rv = fetch_worker_wait(w, err, sizeof(err));
- if (rv == FETCH_ABORT) {
- fetch_workers_stop_all();
- return FETCH_ABORT;
- }
- if (rv == 0)
- rv = fetch_worker_read_body(w, image_io_buf,
- BR_CSS_MAX,
- image_io_buf + BR_CSS_MAX,
- BR_CSS_COMP_MAX, &tr,
- err, sizeof(err));
- else
- rv = -1;
- fetch_worker_release(w);
- slot[i] = 0;
- /* Refill the worker window before parsing this sheet. */
- for (; next < n; next++) {
- struct fetch_worker *nw;
- if (!remote[next])
- continue;
- nw = fetch_worker_alloc();
- if (!nw)
- break;
- if (fetch_worker_submit(nw, urls[next],
- BR_CSS_MAX, 0, 0, 0, 0,
- err, sizeof(err)) != 0) {
- fetch_worker_release(nw);
- remote[next] = 0;
- continue;
- }
- slot[next] = nw;
- }
- css_failed:
- if (rv <= 0) {
- /* One synchronous retry: a dropped sheet leaves the
- * whole page unstyled (seen intermittently on
- * arstechnica's CDN). */
- u_puts("[css] retry ");
- u_puts(urls[i]);
- u_puts(": ");
- u_puts(err[0] ? err : "no worker/empty body");
- u_putc('\n');
- err[0] = '\0';
- rv = fetch_css(urls[i], &data, &len, err,
- sizeof(err));
- if (rv == FETCH_ABORT) {
- fetch_workers_stop_all();
- return FETCH_ABORT;
- }
- if (rv != 0 || !len) {
- u_puts("[css] failed: ");
- u_puts(err);
- u_putc('\n');
- continue;
- }
- } else {
- len = (unsigned int)rv;
- data = image_io_buf;
- css_cache_put(urls[i], data, len);
- }
- }
- if (len) {
- br_set_font_base(urls[i]);
- br_parse_css_text(&doc, (const char *)data, len);
- }
- }
- br_set_font_base(page_url);
- br_parse_inline_css(&doc);
- load_font_faces();
- br_reset_styles(&doc);
- layout_valid = 0;
- return 0;
- }
- static void preload_begin(void)
- {
- preload_active = 1;
- preload_pending = 0;
- preload_wait = 1;
- preload_max_jobs = FETCH_WORKERS;
- preload_node = 0;
- preload_loaded = 0;
- preload_scroll = 0;
- img_stat_start = u_ticks_ms();
- img_stat_wall = 0;
- img_stat_net = img_stat_open = img_stat_first = 0;
- img_stat_io = img_stat_dec = img_stat_scale = 0;
- img_stat_paint = img_stat_reflow = 0;
- img_stat_bytes = 0;
- img_stat_n = 0;
- img_stat_log_len = 0;
- if (img_stat_log[0])
- img_stat_log[0] = '\0';
- img_repaint_ms = 0;
- img_repaint_pending = 0;
- }
- /* Styles are computed top-down during layout, but images inside a hidden
- * menu/carousel are never visited and keep img_top == 0. Without this check
- * the preloader walks the DOM in node order and spends the whole image
- * budget on logos and off-canvas thumbnails the reader cannot see. */
- static struct br_style base_style(void);
- static int node_hidden(unsigned int node)
- {
- unsigned int path[32], n = 0, p = node, i;
- struct br_style st, parent;
- while (p && n < sizeof(path) / sizeof(path[0])) {
- path[n++] = p;
- p = doc.nodes[p].parent;
- }
- /* Node 0 is the <html> element when the page starts with one: it
- * is an ancestor too. Styles are cached per node, so the chain
- * must start from the same base as style_for_node(); seeding it
- * with a zeroed style left <body> cached with black text and no
- * line-height once an image job ran (docs.cloudron.io). */
- if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
- doc.nodes[0].type == BR_NODE_ELEM &&
- doc.nodes[0].tag == BR_TAG_HTML &&
- !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
- path[n++] = 0;
- parent = base_style();
- for (i = n; i > 0; i--) {
- br_style_for(&doc, path[i - 1], &parent, &st);
- if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
- st.opacity_hidden)
- return 1;
- parent = st;
- }
- return 0;
- }
- static struct br_style base_style(void);
- static int style_width_px(const struct br_style *st, int base);
- static int style_height_px(const struct br_style *st, int base);
- static void style_for_node(unsigned int node, struct br_style *out)
- {
- unsigned int p = doc.nodes[node].parent;
- struct br_style parent;
- /* Parent index 0 is ambiguous: it is the <html> element when the page
- * starts with one (see root_style()), but also the parent field of a
- * detached subtree root. */
- if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
- doc.nodes[0].tag == BR_TAG_HTML &&
- !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
- style_for_node(p, &parent);
- br_style_for(&doc, node, &parent, out);
- } else {
- parent = base_style();
- br_style_for(&doc, node, &parent, out);
- }
- }
- /* ---- parallel image preloading ---- *
- *
- * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
- * preload_step() only starts jobs and harvests completed ones; the browser
- * main loop keeps drawing between calls, instead of blocking on one fetch.
- */
- static int preload_active_jobs(void)
- {
- int i, n = 0;
- for (i = 0; i < FETCH_WORKERS; i++)
- if (fetch_workers[i].busy && fetch_workers[i].image_job)
- n++;
- return n;
- }
- static void preload_job_error(struct fetch_worker *w)
- {
- if (w->node < doc.nnode) {
- if (w->bg)
- doc.nodes[w->node].bg_img_index = -2;
- else
- doc.nodes[w->node].img_index = -2;
- image_repaint();
- }
- }
- /* Is the image's box anywhere near the visible page? A decode below the
- * fold changes the layout (scroll extent) but not a single on-screen pixel,
- * so it does not need a repaint. top/h come from the last layout; treat an
- * unknown box as visible to stay safe. */
- static int image_preload_visible(unsigned int node, int bg)
- {
- int top, h, scroll;
- if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
- return 1;
- if (bg) {
- top = (int)block_top[node];
- h = (int)block_h[node];
- } else {
- top = (int)img_top[node];
- h = (int)img_h[node];
- }
- if (!top && !h)
- return 1;
- scroll = (int)page_scroll.offset;
- if (top > scroll + page_rect.h + 160)
- return 0;
- if (top + h + 160 < scroll)
- return 0;
- return 1;
- }
- /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
- * decode_image_data applies one scale to both axes so the aspect ratio is
- * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
- * from being decoded and box-filtered to the 1000 px layout cap first. */
- static void image_fit_size(unsigned int node, int *out_w, int *out_h)
- {
- struct br_style st;
- struct br_node *nd;
- unsigned int p;
- int cw, w = 0, h = 0;
- *out_w = *out_h = 0;
- if (node >= doc.nnode)
- return;
- nd = &doc.nodes[node];
- style_for_node(node, &st);
- cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
- p = doc.nodes[node].parent;
- if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
- layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
- cw = layout_boxes[p].w;
- if (st.width_kind)
- w = style_width_px(&st, cw);
- else if (nd->width_attr)
- w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
- (int)nd->width_attr;
- if (st.height_kind)
- h = style_height_px(&st, cw);
- else if (nd->height_attr)
- h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
- (int)nd->height_attr;
- if (st.max_width_kind) {
- int mw = st.max_width_kind == 3 ?
- cw * st.max_width_calc_pct / 100 +
- st.max_width_calc_px :
- st.max_width_kind == 2 ?
- cw * (int)st.max_width / 100 :
- (int)st.max_width;
- if (mw > 0 && (w == 0 || w > mw))
- w = mw;
- }
- if (st.max_height_kind) {
- int mh = st.max_height_kind == 3 ?
- cw * st.max_height_calc_pct / 100 +
- st.max_height_calc_px :
- st.max_height_kind == 2 ?
- cw * (int)st.max_height / 100 :
- (int)st.max_height;
- if (mh > 0 && (h == 0 || h > mh))
- h = mh;
- }
- if (w > BR_IMG_LAYOUT_W)
- w = BR_IMG_LAYOUT_W;
- if (h > 4096)
- h = 4096;
- if (w < 0)
- w = 0;
- if (h < 0)
- h = 0;
- *out_w = w;
- *out_h = h;
- }
- static void preload_accept_image(unsigned int node, int bg, const char *url)
- {
- /* An <img> bitmap only depends on its URL, so the next <img> with the
- * same source reuses it (heise repeats one comment icon 85 times).
- * Backgrounds are scaled to their box and are not shared. */
- images[image_count].url_hash =
- !bg && url ? script_cache_hash(url) | 1u : 0;
- if (bg)
- doc.nodes[node].bg_img_index = (short)image_count;
- else
- doc.nodes[node].img_index = (short)image_count;
- image_count++;
- preload_loaded++;
- /* A background bitmap never changes its box, so keep the (expensive)
- * measured layout and only repaint the pixels. */
- if (bg)
- page_cache_valid = 0;
- else
- layout_valid = 0;
- if (image_preload_visible(node, bg))
- image_repaint();
- }
- /* Install a bitmap decoded by the fetch helper. The helper already applied
- * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
- * on the UI thread instead of a decode. */
- static int preload_store_helper(unsigned int node, int bg,
- unsigned char *px, unsigned int pxlen,
- unsigned int dw, unsigned int dh,
- int alpha, unsigned int nw, unsigned int nh,
- const char *url)
- {
- struct br_image *bi;
- unsigned int npx;
- if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
- dw > 4096 || dh > 4096) {
- free(px);
- return -1;
- }
- npx = dw * dh;
- if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
- pxlen < npx * 2u + (alpha ? npx : 0)) {
- free(px);
- return -1;
- }
- bi = &images[image_count];
- bi->img.format = 0;
- bi->img.w = dw;
- bi->img.h = dh;
- bi->img.px = (unsigned short *)px;
- bi->img.alpha = alpha ? px + npx * 2u : 0;
- bi->img.flags = 0;
- bi->native_w = nw ? (int)nw : (int)dw;
- bi->native_h = nh ? (int)nh : (int)dh;
- bi->state = 1;
- image_pixels += npx;
- preload_accept_image(node, bg, url);
- return 0;
- }
- static void preload_decode(unsigned int node, int bg,
- const unsigned char *data, unsigned int len,
- const char *url)
- {
- int fit_w = 0, fit_h = 0;
- if (image_count >= BR_MAX_IMAGES) {
- if (bg)
- doc.nodes[node].bg_img_index = -2;
- else
- doc.nodes[node].img_index = -2;
- return;
- }
- if (!bg)
- image_fit_size(node, &fit_w, &fit_h);
- if (decode_image_data(data, len, &images[image_count],
- bg && node < BR_MAX_NODES &&
- layout_boxes[node].valid ? layout_boxes[node].w : 0,
- bg && node < BR_MAX_NODES &&
- layout_boxes[node].valid ? layout_boxes[node].h : 0,
- fit_w, fit_h) == 0) {
- preload_accept_image(node, bg, url);
- } else {
- if (bg)
- doc.nodes[node].bg_img_index = -2;
- else
- doc.nodes[node].img_index = -2;
- layout_valid = 0;
- }
- if (image_preload_visible(node, bg))
- image_repaint();
- }
- /* ---- data: URLs ----
- *
- * `data:[<type>][;base64],<payload>` decoded to bytes from the page heap
- * (the caller frees them). The payload is percent-decoded, then base64-
- * decoded when the header says so. Infima's menu chevron and many icon
- * fonts' fallbacks are inline SVGs written this way. */
- static int b64_val(int c)
- {
- if (c >= 'A' && c <= 'Z') return c - 'A';
- if (c >= 'a' && c <= 'z') return c - 'a' + 26;
- if (c >= '0' && c <= '9') return c - '0' + 52;
- if (c == '+' || c == '-') return 62;
- if (c == '/' || c == '_') return 63;
- return -1;
- }
- static int hex_val(int c)
- {
- if (c >= '0' && c <= '9') return c - '0';
- c |= 32;
- if (c >= 'a' && c <= 'f') return c - 'a' + 10;
- return -1;
- }
- static int data_url_decode(const char *url, unsigned char **out,
- unsigned int *out_len)
- {
- const char *comma, *p;
- unsigned int n = 0, len, i;
- unsigned char *buf;
- int base64 = 0;
- *out = 0;
- *out_len = 0;
- if (!starts_with(url, "data:"))
- return -1;
- comma = url + 5;
- while (*comma && *comma != ',')
- comma++;
- if (!*comma)
- return -1;
- for (p = url + 5; p + 7 <= comma; p++)
- if (!strncmp(p, ";base64", 7))
- base64 = 1;
- len = s_len(comma + 1);
- buf = (unsigned char *)malloc(len + 1);
- if (!buf)
- return -1;
- for (i = 0, p = comma + 1; i < len; i++) {
- int c = (unsigned char)p[i];
- if (c == '%' && i + 2 < len &&
- hex_val(p[i + 1]) >= 0 && hex_val(p[i + 2]) >= 0) {
- c = hex_val(p[i + 1]) * 16 + hex_val(p[i + 2]);
- i += 2;
- }
- buf[n++] = (unsigned char)c;
- }
- if (base64) {
- unsigned int acc = 0, o = 0;
- int bits = 0;
- for (i = 0; i < n; i++) {
- int v = b64_val(buf[i]);
- if (v < 0)
- continue; /* padding, whitespace */
- acc = (acc << 6) | (unsigned int)v;
- bits += 6;
- if (bits >= 8) {
- bits -= 8;
- buf[o++] = (unsigned char)(acc >> bits);
- }
- }
- n = o;
- }
- buf[n] = 0;
- *out = buf;
- *out_len = n;
- return 0;
- }
- static unsigned int data_img_key(const char *url, int w, int h)
- {
- return (script_cache_hash(url) ^ ((unsigned int)w * 2654435761u) ^
- ((unsigned int)h * 40503u)) | 1u;
- }
- /* The image index of a data: URL decoded for a w x h box (an SVG is
- * rasterized at that size), decoding it on first use; -1 on failure.
- * Decoded bitmaps are found again through url_hash, which is distinct
- * from the <img> sharing hash because it mixes in the size. */
- static int data_url_image(const char *url, int w, int h)
- {
- unsigned int key, len;
- unsigned char *data;
- int i;
- if (!starts_with(url, "data:") || w <= 0 || h <= 0)
- return -1;
- key = data_img_key(url, w, h);
- for (i = 0; i < image_count; i++)
- if (images[i].state == 1 && images[i].url_hash == key)
- return i;
- for (i = 0; i < data_img_nfail; i++)
- if (data_img_fail[i] == key)
- return -1;
- if (image_count < BR_MAX_IMAGES &&
- data_url_decode(url, &data, &len) == 0) {
- int r = decode_image_data(data, len, &images[image_count],
- w, h, w, h);
- free(data);
- if (r == 0) {
- images[image_count].url_hash = key;
- return image_count++;
- }
- }
- if (data_img_nfail < DATA_IMG_FAIL_MAX)
- data_img_fail[data_img_nfail++] = key;
- return -1;
- }
- /* A local file image bypasses the helpers: count its decode so a page opened
- * from /share or /data still produces the same timing breakdown. */
- static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
- {
- img_stat_n++;
- img_stat_bytes += bytes;
- img_stat_io += io_ms;
- if (image_count > before) {
- struct br_image *bi = &images[image_count - 1];
- img_stat_dec += img_last_dec_ms;
- img_stat_scale += img_last_scale_ms;
- if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
- unsigned int n = img_stat_log_len;
- s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, bytes,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, img_last_dec_ms,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, img_last_scale_ms,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- (unsigned int)bi->native_w,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- (unsigned int)bi->native_h,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, bi->img.w,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, bi->img.h,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- bi->img.alpha ? 1u : 0u,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
- img_stat_log_len = n;
- }
- }
- }
- /* Harvest one completed worker. Returns 1 when a job was finished. */
- static int preload_finish_worker(struct fetch_worker *w)
- {
- char err[64];
- int rv, tr = 0;
- unsigned int t0, io_ms;
- int before;
- int used_px = 0;
- rv = fetch_worker_poll(w, err, sizeof(err));
- if (rv < 0) {
- /* A helper from an older pack does not understand the image
- * decode request; retry once without it and decode in-process. */
- if (w->image_job && w->dec_w && !w->dec_retried &&
- fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
- 0, 0, 0, 0, w->node, w->bg,
- 0, 0, err, sizeof(err)) == 0) {
- w->image_job = 1;
- w->dec_retried = 1;
- w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
- return 0;
- }
- preload_job_error(w);
- if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
- unsigned int n = img_stat_log_len;
- char u[48];
- s_copy(u, w->url, sizeof(u));
- s_append(img_stat_log, &n, u, sizeof(img_stat_log));
- s_append(img_stat_log, &n, " error\n",
- sizeof(img_stat_log));
- img_stat_log_len = n;
- }
- img_stat_n++;
- fetch_worker_release(w);
- return 1;
- }
- if (rv == 0)
- return 0;
- t0 = u_ticks_ms();
- rv = -1;
- before = image_count;
- if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
- w->m.px_len <= 8u * 1024u * 1024u) {
- unsigned char *px = (unsigned char *)malloc(w->m.px_len);
- int pr = -1;
- if (px)
- pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
- (int)w->m.px_len);
- if (pr == (int)w->m.px_len) {
- if (preload_store_helper(w->node, w->bg, px,
- w->m.px_len, w->m.dw,
- w->m.dh, (int)w->m.alpha,
- w->m.nw, w->m.nh,
- w->url) == 0) {
- rv = (int)w->m.len;
- img_last_dec_ms = w->m.dec_ms;
- img_last_scale_ms = 0;
- used_px = 1;
- } else {
- px = 0; /* the helper freed it */
- }
- }
- if (px && !(pr == (int)w->m.px_len))
- free(px);
- }
- io_ms = u_ticks_ms() - t0;
- if (rv < 0) {
- t0 = u_ticks_ms();
- rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
- image_comp_buf, BR_IMG_FILE_MAX,
- &tr, err, sizeof(err));
- io_ms += u_ticks_ms() - t0;
- before = image_count;
- if (rv >= 0)
- preload_decode(w->node, w->bg, image_file_buf,
- (unsigned int)rv, w->url);
- else
- preload_job_error(w);
- }
- img_stat_n++;
- img_stat_net += w->m.total_ms;
- img_stat_open += w->m.open_ms;
- img_stat_first += w->m.first_ms;
- img_stat_io += io_ms;
- img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
- img_stat_dec += w->m.dec_ms;
- if (rv >= 0 && !used_px) {
- img_stat_dec += img_last_dec_ms;
- img_stat_scale += img_last_scale_ms;
- }
- if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
- unsigned int n = img_stat_log_len;
- char u[48];
- s_copy(u, w->url, sizeof(u));
- s_append(img_stat_log, &n, u, sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- rv > 0 ? (unsigned int)rv : 0,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, w->m.open_ms,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, w->m.first_ms,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, w->m.total_ms,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- rv >= 0 ? img_last_dec_ms : 0,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- rv >= 0 ? img_last_scale_ms : 0,
- sizeof(img_stat_log));
- if (image_count > before) {
- struct br_image *bi = &images[image_count - 1];
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- (unsigned int)bi->native_w,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- (unsigned int)bi->native_h,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, bi->img.w,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n, bi->img.h,
- sizeof(img_stat_log));
- s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
- s_append_dec(img_stat_log, &n,
- bi->img.alpha ? 1u : 0u,
- sizeof(img_stat_log));
- }
- s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
- img_stat_log_len = n;
- }
- fetch_worker_release(w);
- return 1;
- }
- /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
- * the number of jobs started. */
- static int preload_fill_jobs(void)
- {
- int started = 0;
- char err[64];
- while (preload_active && preload_node < doc.nnode) {
- unsigned int i = preload_node;
- struct br_node *nd = &doc.nodes[i];
- const char *src;
- char url[BR_URL_MAX];
- struct fetch_worker *w;
- if (preload_active_jobs() >= preload_max_jobs)
- break;
- if (nd->type != BR_NODE_ELEM) {
- preload_node++;
- continue;
- }
- if (nd->tag != BR_TAG_IMG) {
- if (nd->bg_img_index == -1) {
- struct br_style bs;
- style_for_node(i, &bs);
- if (bs.display != BR_DISPLAY_NONE &&
- !bs.vis_hidden && bs.bg_image) {
- const char *bsrc =
- br_bg_image_url(bs.bg_image - 1);
- /* Lazy like <img>: a background box
- * below the viewport (or not laid
- * out yet) waits for the next scan. */
- if (bsrc[0] &&
- (!layout_boxes[i].valid ||
- block_top[i] >
- (unsigned int)(page_scroll.offset +
- page_rect.h + 160))) {
- preload_pending = 1;
- preload_node++;
- continue;
- }
- if (starts_with(bsrc, "data:")) {
- /* Inline image: decode now,
- * no fetch helper. */
- unsigned char *data;
- unsigned int len;
- preload_node = i + 1;
- if (data_url_decode(bsrc, &data,
- &len) == 0) {
- preload_decode(i, 1, data,
- len, 0);
- free(data);
- } else {
- nd->bg_img_index = -2;
- }
- continue;
- }
- if (bsrc[0] &&
- resolve_link(page_url, bsrc, url,
- sizeof(url)) == 0) {
- if (image_count +
- preload_active_jobs() >=
- BR_MAX_IMAGES) {
- preload_node = doc.nnode;
- break;
- }
- if (url[0] == '/') {
- unsigned char *data = 0;
- unsigned int len = 0;
- unsigned int t0;
- int before;
- preload_node = i + 1;
- before = image_count;
- t0 = u_ticks_ms();
- if (fetch_image(url,
- BR_IMG_FILE_MAX,
- &data, &len,
- err,
- sizeof(err)) == 0) {
- preload_decode(i, 1, data, len, 0);
- img_stat_local(before, len,
- u_ticks_ms() - t0);
- } else {
- nd->bg_img_index = -2;
- }
- continue;
- }
- w = fetch_worker_alloc();
- if (!w)
- return started;
- preload_node = i + 1;
- if (fetch_worker_submit(w, url,
- BR_IMG_FILE_MAX,
- 0, 0, i, 1,
- err,
- sizeof(err)) != 0) {
- nd->bg_img_index = -2;
- fetch_worker_release(w);
- continue;
- }
- w->image_job = 1;
- w->deadline = u_ticks_ms() +
- BR_IMG_JOB_TIMEOUT_MS;
- /* in flight: rescans skip it */
- nd->bg_img_index = -3;
- started++;
- continue;
- }
- }
- nd->bg_img_index = -2;
- }
- preload_node++;
- continue;
- }
- if (nd->img_index != -1) {
- preload_node++;
- continue;
- }
- if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
- preload_node++;
- continue;
- }
- src = br_src(&doc, i);
- if (starts_with(src, "data:")) {
- unsigned char *data;
- unsigned int len;
- preload_node = i + 1;
- if (data_url_decode(src, &data, &len) == 0) {
- preload_decode(i, 0, data, len, 0);
- free(data);
- } else {
- doc.nodes[i].img_index = -2;
- }
- continue;
- }
- if (!src[0]) {
- preload_node++;
- continue;
- }
- if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
- preload_node++;
- continue;
- }
- if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
- preload_node = doc.nnode;
- break;
- }
- /* Do not stop at the first below-fold image: DOM order is
- * not visual order, and a footer/ad image early in the DOM
- * used to hide every later article image from the loader. */
- if (img_top[i] >
- (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
- preload_pending = 1;
- preload_node++;
- continue;
- }
- {
- unsigned int uh = script_cache_hash(url) | 1u;
- int k;
- for (k = 0; k < image_count; k++)
- if (images[k].state == 1 &&
- images[k].url_hash == uh)
- break;
- if (k < image_count) {
- nd->img_index = (short)k;
- layout_valid = 0;
- preload_node = i + 1;
- image_repaint();
- continue;
- }
- }
- if (url[0] == '/') {
- unsigned char *data = 0;
- unsigned int len = 0;
- unsigned int t0;
- int before;
- preload_node = i + 1;
- before = image_count;
- t0 = u_ticks_ms();
- if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
- err, sizeof(err)) == 0) {
- preload_decode(i, 0, data, len, url);
- img_stat_local(before, len, u_ticks_ms() - t0);
- } else {
- nd->img_index = -2;
- }
- continue;
- }
- w = fetch_worker_alloc();
- if (!w)
- return started;
- preload_node = i + 1;
- {
- char msg[64];
- unsigned int n = 0;
- s_append(msg, &n, "Loading images ", sizeof(msg));
- s_append_dec(msg, &n,
- (unsigned int)preload_loaded + 1,
- sizeof(msg));
- s_append(msg, &n, "...", sizeof(msg));
- set_status_quiet(msg);
- image_repaint();
- }
- {
- int fit_w = 0, fit_h = 0;
- image_fit_size(i, &fit_w, &fit_h);
- if (!fit_w)
- fit_w = BR_IMG_LAYOUT_W;
- if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
- i, 0,
- (unsigned int)fit_w,
- (unsigned int)fit_h,
- err, sizeof(err)) != 0) {
- nd->img_index = -2;
- fetch_worker_release(w);
- continue;
- }
- }
- w->image_job = 1;
- w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
- nd->img_index = -3; /* in flight: rescans skip it */
- started++;
- }
- return started;
- }
- /* Report where the image batch spent its time: status bar for the headline,
- * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
- static void img_stats_report(void)
- {
- char msg[80];
- static char out[BR_IMG_STAT_LOG + 512];
- unsigned int n = 0, o = 0;
- if (!img_stat_n)
- return;
- img_stat_wall = img_stat_start ?
- u_ticks_ms() - img_stat_start : 1;
- if (!img_stat_wall)
- img_stat_wall = 1;
- /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
- s_append(msg, &n, "img ", sizeof(msg));
- s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
- s_append(msg, &n, " ", sizeof(msg));
- s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
- s_append(msg, &n, "ms net ", sizeof(msg));
- s_append_dec(msg, &n, img_stat_net, sizeof(msg));
- s_append(msg, &n, " dec ", sizeof(msg));
- s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
- s_append(msg, &n, " sc ", sizeof(msg));
- s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
- s_append(msg, &n, " paint ", sizeof(msg));
- s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
- /* Keep the page's phase breakdown and append the image summary when
- * it fits; never hide a JS error or a truncation notice. */
- if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
- unsigned int plen = s_len(post_status_text);
- if (!plen) {
- s_copy(post_status_text, msg, sizeof(post_status_text));
- } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
- unsigned int pn = plen;
- s_append(post_status_text, &pn, " | ",
- sizeof(post_status_text));
- s_append(post_status_text, &pn, msg,
- sizeof(post_status_text));
- } else {
- s_copy(post_status_text, msg, sizeof(post_status_text));
- }
- post_status_ttl = 12000;
- }
- s_append(out, &o, "browser image stats\n", sizeof(out));
- s_append(out, &o, "n=", sizeof(out));
- s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
- s_append(out, &o, " wall=", sizeof(out));
- s_append_dec(out, &o, img_stat_wall, sizeof(out));
- s_append(out, &o, " net=", sizeof(out));
- s_append_dec(out, &o, img_stat_net, sizeof(out));
- s_append(out, &o, " open=", sizeof(out));
- s_append_dec(out, &o, img_stat_open, sizeof(out));
- s_append(out, &o, " first=", sizeof(out));
- s_append_dec(out, &o, img_stat_first, sizeof(out));
- s_append(out, &o, " io=", sizeof(out));
- s_append_dec(out, &o, img_stat_io, sizeof(out));
- s_append(out, &o, " dec=", sizeof(out));
- s_append_dec(out, &o, img_stat_dec, sizeof(out));
- s_append(out, &o, " scale=", sizeof(out));
- s_append_dec(out, &o, img_stat_scale, sizeof(out));
- s_append(out, &o, " paint=", sizeof(out));
- s_append_dec(out, &o, img_stat_paint, sizeof(out));
- s_append(out, &o, " reflow=", sizeof(out));
- s_append_dec(out, &o, img_stat_reflow, sizeof(out));
- s_append(out, &o, " bytes=", sizeof(out));
- s_append_dec(out, &o, img_stat_bytes, sizeof(out));
- s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
- sizeof(out));
- s_append(out, &o, img_stat_log, sizeof(out));
- u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
- (int)s_len(out));
- }
- static void preload_step(void)
- {
- int i;
- unsigned int t0;
- if (!preload_active)
- return;
- if (cancel_fetch || pending_action) {
- preload_active = 0;
- preload_pending = 0;
- fetch_workers_cancel_busy();
- return;
- }
- preload_fill_jobs();
- /* Decode completed images in a short batch instead of one per pass.
- * A pass used to decode one image and then sleep 10 ms, so a page of
- * small icons trickled in at the decode rate. The budget keeps a
- * single huge JPEG from monopolising the UI while small images
- * finish together. */
- t0 = u_ticks_ms();
- for (i = 0; i < FETCH_WORKERS; i++) {
- if (!fetch_workers[i].busy)
- continue;
- if (preload_finish_worker(&fetch_workers[i]) &&
- u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
- break;
- }
- if (preload_active && preload_node >= doc.nnode &&
- preload_active_jobs() == 0) {
- preload_active = 0;
- if (preload_pending)
- preload_scroll = page_scroll.offset;
- else
- preload_pending = 0;
- /* Keep the now idle helpers and their connections; a later
- * navigation reuses them. They exit after ten idle seconds,
- * and losing window focus stops them at once. */
- if (img_repaint_pending) {
- img_repaint_pending = 0;
- ngui_invalidate(&ui);
- }
- img_stats_report();
- set_status(post_status_text, post_status_error, post_status_ttl);
- ngui_invalidate(&ui);
- }
- }
- /* Set by navigate() when it turned a typed bare host into https://; the next
- * load_page() consumes it and may retry over http. */
- static int nav_https_upgraded;
- /* Errors that mean "https is not served here" rather than "the site is
- * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
- static int https_fallback_error(int e)
- {
- return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
- e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
- e == UHTTP_ERR_RESET;
- }
- static void history_push(const char *url)
- {
- if (!url || !url[0])
- return;
- if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
- s_eq(history[hist_pos], url))
- return;
- if (hist_len > 0 && hist_pos + 1 < hist_len)
- hist_len = hist_pos + 1;
- if (hist_len < BR_HISTORY) {
- s_copy(history[hist_len], url, BR_URL_MAX);
- hist_pos = hist_len;
- hist_len++;
- } else {
- int i;
- for (i = 1; i < BR_HISTORY; i++)
- s_copy(history[i - 1], history[i], BR_URL_MAX);
- s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
- hist_pos = BR_HISTORY - 1;
- }
- }
- static void load_page(const char *url, int local, int push)
- {
- unsigned char *body = 0;
- unsigned int len = 0;
- int truncated = 0;
- struct img_info image_info;
- char ctype[64];
- char final[BR_URL_MAX];
- char err[80];
- const char *detail = 0;
- const char *post = pending_post_is ? pending_post : 0;
- unsigned int post_len = pending_post_len;
- unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
- /* Phase timings for the status line: where a slow load spends it. */
- unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
- unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
- int upgraded = nav_https_upgraded;
- int retried = 0;
- int rv;
- nav_https_upgraded = 0;
- final[0] = '\0';
- pending_post_len = 0;
- pending_post_is = 0;
- cancel_fetch = 0;
- preload_active = 0;
- preload_pending = 0;
- fetch_workers_prepare_nav(url);
- js_browser_stop();
- js_last_status[0] = '\0';
- js_last_error = 0;
- heap_clear();
- image_reset();
- form_reset_state();
- layout_valid = 0;
- page_scroll.offset = 0;
- page_scroll.dragging = 0;
- page_title[0] = '\0';
- page_loading = 1;
- page_is_local = local;
- s_copy(page_url, url, sizeof(page_url));
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- ngui_set_focus(&ui, 0);
- if (final[0])
- final[0] = '\0';
- if (push)
- history_push(url);
- set_status("Loading...", 0, 0);
- ngui_invalidate(&ui);
- /* heap_clear() detaches the fonts, so attach them again before the
- * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
- if (heap_start() != 0) {
- show_error("Out of memory", "Cannot allocate the page buffer");
- return;
- }
- br_parse_plain(&doc, "", 0); /* blank while loading */
- ngui_font_attach(&ui);
- redraw_now();
- browser_rules_alloc();
- rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
- sizeof(ctype), final, sizeof(final), err, sizeof(err),
- &truncated, post, post_len);
- if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
- fetch_last_error == UHTTP_ERR_DNS) {
- /* A busy previous page can leave the receiver ring full just
- * long enough to lose a DNS reply. Tear the old helpers down
- * and try once more before giving up. */
- retried = 1;
- fetch_workers_stop_all();
- u_sleep_ms(500);
- rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
- sizeof(ctype), final, sizeof(final), err,
- sizeof(err), &truncated, post, post_len);
- }
- if (rv == FETCH_ABORT)
- return;
- t_fetch = u_ticks_ms() - t_start;
- /* Capture the page timing before CSS/script/image fetches overwrite the
- * shared fetch_meta block. */
- if (rv == 0 && !local) {
- page_open_ms = fetch_meta.open_ms;
- page_first_ms = fetch_meta.first_ms;
- page_total_ms = fetch_meta.total_ms;
- }
- if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
- https_fallback_error(fetch_last_error)) {
- char http_url[BR_URL_MAX];
- unsigned int n = 0;
- s_append(http_url, &n, "http://", sizeof(http_url));
- s_append(http_url, &n, url + 8, sizeof(http_url));
- /* Replace the https entry instead of adding a second one. */
- if (push && hist_pos >= 0 && hist_pos < hist_len &&
- s_eq(history[hist_pos], url))
- s_copy(history[hist_pos], http_url, BR_URL_MAX);
- load_page(http_url, 0, 0);
- return;
- }
- if (rv != 0) {
- detail = err;
- show_error("Cannot load this page", detail);
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- return;
- }
- if (!local)
- origin_cache_learn(url, final[0] ? final : url);
- page_is_local = local;
- if (final[0]) {
- s_copy(page_url, final, sizeof(page_url));
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- }
- if (contains_ci(ctype, "text/plain")) {
- br_parse_plain(&doc, (const char *)body, len);
- } else if (contains_ci(ctype, "image/") ||
- (!contains_ci(ctype, "text/html") &&
- img_sniff(body, len, &image_info) == 0)) {
- unsigned int node = br_parse_image_doc(&doc, page_url);
- if (node)
- decode_direct_image(body, len, node);
- s_copy(page_title, "Image", sizeof(page_title));
- } else {
- br_set_viewport(ui.w);
- t_mark = u_ticks_ms();
- br_parse(&doc, (const char *)body, len);
- t_parse = u_ticks_ms() - t_mark;
- s_copy(page_title, doc.title[0] ? doc.title : page_url,
- sizeof(page_title));
- t_mark = u_ticks_ms();
- if (load_stylesheets() == FETCH_ABORT)
- return;
- t_css = u_ticks_ms() - t_mark;
- if (pending_action)
- return;
- }
- preload_begin();
- page_loading = 0;
- hist_visit(page_url, page_title);
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- ngui_set_focus(&ui, 0);
- /* Paint the parsed page before fetching/running scripts. A slow
- * remote <script src> then does not hide the page behind the loading
- * screen; the fetch helper pumps this UI while it waits. */
- set_status("Loading scripts...", 0, 0);
- t_mark = u_ticks_ms();
- redraw_now();
- t_paint = u_ticks_ms() - t_mark;
- /* Start one image download before the scripts. The other workers
- * fetch the external script bodies in parallel, and the remaining
- * images start as soon as the script phase ends. */
- preload_max_jobs = 1;
- preload_fill_jobs();
- preload_wait = 0;
- t_mark = u_ticks_ms();
- run_page_scripts();
- t_js = u_ticks_ms() - t_mark;
- preload_max_jobs = FETCH_WORKERS;
- if (pending_action)
- return;
- post_status_text[0] = '\0';
- post_status_error = 0;
- post_status_ttl = 0;
- if (js_last_status[0]) {
- s_copy(post_status_text, js_last_status,
- sizeof(post_status_text));
- post_status_error = js_last_error;
- post_status_ttl = 8000;
- } else if (truncated) {
- s_copy(post_status_text, "Page truncated at the buffer limit",
- sizeof(post_status_text));
- post_status_ttl = 6000;
- } else if (doc.truncated) {
- s_copy(post_status_text, "Page truncated by the parser",
- sizeof(post_status_text));
- post_status_ttl = 6000;
- } else if (page_total_ms) {
- /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
- * paint 220, js 1750" -- the phases of this load. */
- unsigned int n = 0;
- static const char *const names[] = {
- ", parse ", ", css ", ", paint ", ", js "
- };
- unsigned int vals[4];
- int k;
- vals[0] = t_parse;
- vals[1] = t_css;
- vals[2] = t_paint;
- vals[3] = t_js;
- (void)page_first_ms;
- if (starts_with(page_url, "https://"))
- s_append(post_status_text, &n,
- "HTTPS (not verified), ",
- sizeof(post_status_text));
- s_append(post_status_text, &n, "Loaded in ",
- sizeof(post_status_text));
- s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
- sizeof(post_status_text));
- s_append(post_status_text, &n, " ms: page ",
- sizeof(post_status_text));
- s_append_dec(post_status_text, &n, t_fetch,
- sizeof(post_status_text));
- s_append(post_status_text, &n, " (headers ",
- sizeof(post_status_text));
- s_append_dec(post_status_text, &n, page_open_ms,
- sizeof(post_status_text));
- s_append(post_status_text, &n, ")", sizeof(post_status_text));
- for (k = 0; k < 4; k++) {
- s_append(post_status_text, &n, names[k],
- sizeof(post_status_text));
- s_append_dec(post_status_text, &n, vals[k],
- sizeof(post_status_text));
- }
- post_status_ttl = 12000;
- } else if (starts_with(page_url, "https://")) {
- s_copy(post_status_text, "HTTPS: certificate NOT verified",
- sizeof(post_status_text));
- post_status_ttl = 6000;
- }
- set_status(post_status_text, post_status_error, post_status_ttl);
- ngui_invalidate(&ui);
- }
- static void load_home(int push)
- {
- pending_post_len = 0;
- pending_post_is = 0;
- cancel_fetch = 0;
- preload_active = 0;
- preload_pending = 0;
- js_browser_stop();
- js_last_status[0] = '\0';
- js_last_error = 0;
- heap_clear();
- image_reset();
- form_reset_state();
- layout_valid = 0;
- page_scroll.offset = 0;
- page_scroll.dragging = 0;
- page_loading = 1;
- page_is_local = 0;
- s_copy(page_url, "about:home", sizeof(page_url));
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- ngui_set_focus(&ui, 0);
- if (push)
- history_push(page_url);
- ngui_invalidate(&ui);
- /* See load_page(): reattach the fonts before the first redraw. */
- if (heap_start() != 0) {
- show_error("Out of memory", "Cannot allocate the browser heap");
- return;
- }
- br_parse_plain(&doc, "", 0);
- ngui_font_attach(&ui);
- redraw_now();
- browser_rules_alloc();
- {
- static const char home[] =
- "<html><head><title>NebOS Browser</title><style>"
- "body { margin: 10px; color: #e4e6f0; }"
- "h1 { color: #7fb0ff; }"
- ".box { background-color: #262b3a; margin: 12px; "
- "padding: 10px; }"
- "a { color: #7fb0ff; }"
- "pre { background-color: #32384a; }"
- "</style></head><body>"
- "<h1>NebOS Browser</h1>"
- "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
- "shared HTTP client and the image library.</p>"
- "<div class=\"box\"><b>Try:</b>"
- "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
- "floppy1/DEMO.HTM</a> on the root floppy</li>"
- "<li><a href=\"/floppy1/JS.HTM\">/"
- "floppy1/JS.HTM</a> inline JavaScript demo</li>"
- "<li><a href=\"http://10.0.2.2:8000/\">"
- "http://10.0.2.2:8000/</a> on the QEMU host</li>"
- "<li><a href=\"https://example.com/\">"
- "https://example.com/</a> (TLS, not verified)</li>"
- "</ul></div>"
- "<p>Type a URL in the bar above. Esc closes the "
- "window, Ctrl+L focuses the address bar.</p>"
- "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
- "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
- "</body></html>";
- br_set_viewport(ui.w);
- br_parse(&doc, home, sizeof(home) - 1);
- br_parse_inline_css(&doc);
- br_reset_styles(&doc);
- s_copy(page_title, doc.title, sizeof(page_title));
- }
- post_status_text[0] = '\0';
- post_status_error = 0;
- post_status_ttl = 0;
- page_loading = 0;
- set_status("", 0, 0);
- s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
- url_in.len = s_len(url_in.text);
- url_in.cursor = url_in.len;
- url_in.scroll = 0;
- ngui_set_focus(&ui, 0);
- ngui_invalidate(&ui);
- }
- /* Extensions the browser opens from the local filesystem. A dotted input
- * with one of these still resolves relative to the cwd. */
- static int local_file_ext(const char *s)
- {
- static const char *const exts[] = {
- "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
- "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
- "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
- "cfg", "conf", 0
- };
- unsigned int i = 0, start = 0, len = 0, e;
- while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
- s[i] != '#') {
- if (s[i] == '.') {
- start = i + 1;
- len = 0;
- } else if (start) {
- len++;
- }
- i++;
- }
- if (!len)
- return 0;
- for (e = 0; exts[e]; e++) {
- const char *x = exts[e];
- unsigned int xn = s_len(x), k;
- if (xn != len)
- continue;
- for (k = 0; k < len; k++) {
- char a = s[start + k];
- if (a >= 'A' && a <= 'Z')
- a = (char)(a - 'A' + 'a');
- if (a != x[k])
- break;
- }
- if (k == len)
- return 1;
- }
- return 0;
- }
- /* A dotted first component (cloudron.io) is a hostname, not a local file.
- * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
- * Enter to the first network request. */
- static int looks_like_host(const char *s)
- {
- unsigned int i = 0;
- int dot = 0;
- while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
- s[i] != ':') {
- char c = s[i];
- if (c == '.') {
- dot = 1;
- } else if (!((c >= 'a' && c <= 'z') ||
- (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') ||
- c == '-' || c == '_')) {
- return 0;
- }
- i++;
- }
- return dot && i > 0 && !local_file_ext(s);
- }
- static void load_remote(const char *url, int push)
- {
- char canon[BR_URL_MAX];
- s_copy(canon, url, sizeof(canon));
- origin_cache_apply(canon, sizeof(canon));
- load_page(canon, 0, push);
- }
- static void navigate(const char *input, int push)
- {
- char target[BR_URL_MAX];
- char *t;
- if (!input)
- return;
- s_copy(target, input, sizeof(target));
- t = trim(target);
- if (!t[0])
- return;
- if (s_eq(t, "about:home")) {
- load_home(push);
- return;
- }
- if (starts_with(t, "file://")) {
- make_abs_local(t + 7, target, sizeof(target));
- load_page(target, 1, push);
- return;
- }
- if (is_http(t)) {
- load_remote(t, push);
- return;
- }
- if (t[0] == '/') {
- make_abs_local(t, target, sizeof(target));
- load_page(target, 1, push);
- return;
- }
- if (!looks_like_host(t)) {
- struct sys_stat st;
- if (u_stat(t, &st) == 0 && !st.is_dir) {
- make_abs_local(t, target, sizeof(target));
- load_page(target, 1, push);
- return;
- }
- }
- {
- /* A typed bare host tries https first: nearly every site
- * redirects http -> https anyway, and that hop costs a whole
- * extra connection. load_page() falls back to http when the
- * https connection itself fails. */
- char with_scheme[BR_URL_MAX];
- unsigned int n = 0;
- s_append(with_scheme, &n, "https://", sizeof(with_scheme));
- s_append(with_scheme, &n, t, sizeof(with_scheme));
- nav_https_upgraded = 1;
- load_remote(with_scheme, push);
- }
- }
- /* ---- layout ---- */
- static struct ufont_face *face_for(unsigned int family, int bold, int italic)
- {
- unsigned int id;
- if (!family || family > BR_MAX_FACES)
- return 0;
- id = font_pick[family - 1][(bold ? 2 : 0) | (italic ? 1 : 0)];
- return id ? font_faces[id - 1] : 0;
- }
- static struct ufont_face *style_face(const struct br_style *st)
- {
- return st ? face_for(st->font_face, st->bold, st->italic) : 0;
- }
- static struct ufont_face *run_face(const struct lay_run *r)
- {
- return face_for(r->font_face, r->bold, r->italic);
- }
- static unsigned int face_text_width(struct ngui *gui,
- const struct br_style *st,
- const char *s, unsigned int n)
- {
- return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
- st->bold, st->italic, st->mono);
- }
- static int face_line_height(struct ngui *gui, const struct br_style *st)
- {
- return ngui_text_line_height_face(gui, style_face(st), st->font_px,
- st->mono);
- }
- static unsigned int run_text_width(struct ngui *gui,
- const struct lay_run *r,
- const char *s, unsigned int n)
- {
- return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
- r->bold, r->italic, r->mono);
- }
- static int run_line_height(struct ngui *gui, const struct lay_run *r)
- {
- return ngui_text_line_height_face(gui, run_face(r), r->font_px,
- r->mono);
- }
- static int run_ascent(struct ngui *gui, const struct lay_run *r)
- {
- return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
- }
- static struct br_style base_style(void)
- {
- struct br_style s = { 0 };
- s.color = ui.theme.text;
- s.bg = ui.theme.bg;
- s.has_bg = 0;
- for (int i = 0; i < 4; i++) {
- s.border_c[i] = 0;
- s.border_w[i] = 0;
- s.border_s[i] = BR_BORDER_SOLID;
- }
- s.font_px = 16;
- s.bold = 0;
- s.italic = 0;
- s.mono = 0;
- s.underline = 0;
- s.strike = 0;
- s.overline = 0;
- s.align = BR_ALIGN_LEFT;
- s.display = BR_DISPLAY_BLOCK;
- s.no_bullet = 0;
- s.list_style = BR_LIST_AUTO;
- s.uppercase = 0;
- s.width_kind = s.max_width_kind = s.min_width_kind = 0;
- s.height_kind = s.min_height_kind = s.max_height_kind = 0;
- s.width = s.max_width = s.min_width = 0;
- s.height = s.min_height = s.max_height = 0;
- s.box_sizing = 0;
- s.ml_auto = s.mr_auto = 0;
- s.line_h_pct = 0;
- s.line_h_px = 0;
- s.mt = s.mb = s.ml = s.mr = 0;
- s.pt = s.pb = s.pl = s.pr = 0;
- return s;
- }
- /* The style node 0's children inherit. Node 0 is the first parsed node:
- * a minified page that starts `<!doctype html><html ...>` makes it the
- * <html> element itself, and the layout walks only its children, so its
- * own cascade (html { color; font } -- Docusaurus/Infima put the page
- * colour and font there) used to be skipped and the theme defaults showed
- * through. Only inherited properties are taken: the root's box (margins,
- * display, background) is not a container style for its children here. */
- static struct br_style root_style(void)
- {
- struct br_style base = base_style(), st;
- if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
- doc.nodes[doc.root].tag != BR_TAG_HTML)
- return base;
- br_style_for(&doc, doc.root, &base, &st);
- base.color = st.color;
- base.font_px = st.font_px;
- base.bold = st.bold;
- base.italic = st.italic;
- base.mono = st.mono;
- base.font_face = st.font_face;
- base.align = st.align;
- base.line_h_pct = st.line_h_pct;
- base.line_h_px = st.line_h_px;
- base.nowrap = st.nowrap;
- base.uppercase = st.uppercase;
- base.cursor = st.cursor;
- base.vis_hidden = st.vis_hidden;
- base.fill_mode = st.fill_mode;
- base.fill = st.fill;
- base.stroke_mode = st.stroke_mode;
- base.stroke = st.stroke;
- base.stroke_w = st.stroke_w;
- base.fill_evenodd = st.fill_evenodd;
- return base;
- }
- /* Resolve a margin/padding raw value. Percentages use the containing
- * block width for all four sides, as CSS specifies. */
- static int css_mp_px(const struct br_style *st, int v, int unit, int base)
- {
- if (unit == 1)
- return base * v / 10000;
- if (unit == 2)
- return st->font_px * v / 100;
- if (unit == 3)
- return (int)br_root_font_px() * v / 100;
- if (unit == 4)
- return 0;
- return v;
- }
- static int mp_px(const struct br_style *st, int side, int base)
- {
- int raw;
- switch (side) {
- case 0: raw = st->mt; break;
- case 1: raw = st->mr; break;
- case 2: raw = st->mb; break;
- case 3: raw = st->ml; break;
- case 4: raw = st->pt; break;
- case 5: raw = st->pr; break;
- case 6: raw = st->pb; break;
- default: raw = st->pl; break;
- }
- if (st->mp_unit[side] == 5)
- return base * raw / 100 + st->mp_calc_px[side];
- return css_mp_px(st, raw, st->mp_unit[side], base);
- }
- static int style_width_px(const struct br_style *st, int base)
- {
- if (st->width_kind == 1)
- return st->width;
- if (st->width_kind == 2)
- return base * (int)st->width / 100;
- if (st->width_kind == 3)
- return base * st->width_calc_pct / 100 + st->width_calc_px;
- return 0;
- }
- static int style_height_px(const struct br_style *st, int base)
- {
- if (st->height_kind == 1)
- return st->height;
- if (st->height_kind == 2)
- return base * (int)st->height / 100;
- if (st->height_kind == 3)
- return base * st->height_calc_pct / 100 + st->height_calc_px;
- return 0;
- }
- static int css_size(unsigned char kind, int val, int base)
- {
- if (kind == 1)
- return val;
- if (kind == 2)
- return base * val / 100;
- return -1;
- }
- static void draw_border_side(struct ngui *ui, int x, int y, int len,
- int thick, int horizontal, unsigned short color,
- unsigned char style)
- {
- int pos;
- if (len <= 0 || thick <= 0)
- return;
- if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
- if (horizontal)
- ngui_fill_rect(ui, (struct ngui_rect){
- x, y, len, thick}, color);
- else
- ngui_fill_rect(ui, (struct ngui_rect){
- x, y, thick, len}, color);
- return;
- }
- for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
- int seg = len - pos;
- if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
- seg = style == BR_BORDER_DASHED ? 4 : 2;
- if (horizontal)
- ngui_fill_rect(ui, (struct ngui_rect){
- x + pos, y, seg, thick}, color);
- else
- ngui_fill_rect(ui, (struct ngui_rect){
- x, y + pos, thick, seg}, color);
- }
- }
- static void draw_border_box(struct ngui *ui, struct ngui_rect r,
- const struct br_style *st)
- {
- int top = st->border_w[0], right = st->border_w[1];
- int bottom = st->border_w[2], left = st->border_w[3];
- if (r.w <= 0 || r.h <= 0)
- return;
- if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
- int i;
- for (i = 0; i < 4; i++)
- if (st->border_w[i] && !st->border_t[i]) {
- ngui_fill_rect(ui, r, st->border_c[i]);
- break;
- }
- return;
- }
- if (top && !st->border_t[0])
- draw_border_side(ui, r.x, r.y, r.w, top, 1,
- st->border_c[0], st->border_s[0]);
- if (bottom && !st->border_t[2])
- draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
- st->border_c[2], st->border_s[2]);
- if (left && !st->border_t[3])
- draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
- left, 0, st->border_c[3], st->border_s[3]);
- if (right && !st->border_t[1])
- draw_border_side(ui, r.x + r.w - right, r.y + top,
- r.h - top - bottom, right, 0,
- st->border_c[1], st->border_s[1]);
- }
- static void transform_origin(const struct br_style *st, int w, int h,
- int *ox, int *oy)
- {
- *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
- *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
- }
- static unsigned short blend_rgb565(unsigned short d, unsigned short s,
- unsigned int a)
- {
- unsigned int dr, dg, db, sr, sg, sb;
- if (a >= 255)
- return s;
- dr = (d >> 11) & 31;
- dg = (d >> 5) & 63;
- db = d & 31;
- sr = (s >> 11) & 31;
- sg = (s >> 5) & 63;
- sb = s & 31;
- dr = (dr * (255 - a) + sr * a) / 255;
- dg = (dg * (255 - a) + sg * a) / 255;
- db = (db * (255 - a) + sb * a) / 255;
- return (unsigned short)((dr << 11) | (dg << 5) | db);
- }
- /* Paint a solid box through scale()/rotate() around transform-origin. This
- * transforms the element's own background box; text and descendants keep
- * their layout (documented approximation). */
- static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
- unsigned short color,
- const struct br_style *st)
- {
- double sx = st->scale_x / 100.0;
- double sy = st->scale_y / 100.0;
- double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
- double c = cos(th), sn = sin(th);
- int ox, oy, minx, miny, maxx, maxy, x, y;
- double ax, ay;
- double px[4], py[4];
- int cx1, cy1, cx2, cy2, i;
- if (sx == 0)
- sx = 0.01;
- if (sy == 0)
- sy = 0.01;
- transform_origin(st, box.w, box.h, &ox, &oy);
- ax = box.x + ox;
- ay = box.y + oy;
- px[0] = -ox; py[0] = -oy;
- px[1] = box.w - ox; py[1] = -oy;
- px[2] = box.w - ox; py[2] = box.h - oy;
- px[3] = -ox; py[3] = box.h - oy;
- minx = miny = 1000000;
- maxx = maxy = -1000000;
- for (i = 0; i < 4; i++) {
- double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
- double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
- int dx = (int)(ax + rx), dy = (int)(ay + ry);
- if (dx < minx) minx = dx;
- if (dx > maxx) maxx = dx;
- if (dy < miny) miny = dy;
- if (dy > maxy) maxy = dy;
- }
- cx1 = page_rect.x > 0 ? page_rect.x : 0;
- cy1 = page_rect.y > 0 ? page_rect.y : 0;
- cx2 = page_rect.x + page_rect.w - 12;
- cy2 = page_rect.y + page_rect.h;
- if (cx2 > gui->w) cx2 = gui->w;
- if (cy2 > gui->h) cy2 = gui->h;
- if (minx < cx1) minx = cx1;
- if (miny < cy1) miny = cy1;
- if (maxx > cx2 - 1) maxx = cx2 - 1;
- if (maxy > cy2 - 1) maxy = cy2 - 1;
- for (y = miny; y <= maxy; y++) {
- for (x = minx; x <= maxx; x++) {
- double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
- double rx = dx * c + dy * sn;
- double ry = -dx * sn + dy * c;
- double bx = rx / sx + ox;
- double by = ry / sy + oy;
- if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
- gui->px[y * gui->w + x] = color;
- }
- }
- }
- static void draw_image_transformed(struct ngui *gui,
- const struct img_image *im,
- int x, int y, int w, int h,
- int sx100, int sy100, int rot100,
- int origin_x, int origin_y,
- int origin_x_kind, int origin_y_kind)
- {
- double sx = sx100 / 100.0, sy = sy100 / 100.0;
- double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
- double c = cos(th), sn = sin(th);
- int ox, oy, minx, miny, maxx, maxy, px, py, i;
- double ax, ay;
- double bx[4], by[4];
- int cx1, cy1, cx2, cy2;
- if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
- return;
- ox = origin_x_kind ? w * origin_x / 100 : origin_x;
- oy = origin_y_kind ? h * origin_y / 100 : origin_y;
- ax = x + ox;
- ay = y + oy;
- bx[0] = -ox; by[0] = -oy;
- bx[1] = w - ox; by[1] = -oy;
- bx[2] = w - ox; by[2] = h - oy;
- bx[3] = -ox; by[3] = h - oy;
- minx = miny = 1000000;
- maxx = maxy = -1000000;
- for (i = 0; i < 4; i++) {
- double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
- double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
- int dx = (int)(ax + rx), dy = (int)(ay + ry);
- if (dx < minx) minx = dx;
- if (dx > maxx) maxx = dx;
- if (dy < miny) miny = dy;
- if (dy > maxy) maxy = dy;
- }
- cx1 = page_rect.x > 0 ? page_rect.x : 0;
- cy1 = page_rect.y > 0 ? page_rect.y : 0;
- cx2 = page_rect.x + page_rect.w - 12;
- cy2 = page_rect.y + page_rect.h;
- if (cx2 > gui->w) cx2 = gui->w;
- if (cy2 > gui->h) cy2 = gui->h;
- if (minx < cx1) minx = cx1;
- if (miny < cy1) miny = cy1;
- if (maxx > cx2 - 1) maxx = cx2 - 1;
- if (maxy > cy2 - 1) maxy = cy2 - 1;
- for (py = miny; py <= maxy; py++) {
- for (px = minx; px <= maxx; px++) {
- double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
- double rx = dx * c + dy * sn;
- double ry = -dx * sn + dy * c;
- double fx = rx / sx + ox;
- double fy = ry / sy + oy;
- int ix, iy;
- unsigned int si, a;
- unsigned short src;
- if (fx < 0 || fx >= w || fy < 0 || fy >= h)
- continue;
- ix = (int)(fx * (double)im->w / w);
- iy = (int)(fy * (double)im->h / h);
- if (ix < 0 || ix >= (int)im->w ||
- iy < 0 || iy >= (int)im->h)
- continue;
- si = (unsigned int)iy * im->w + (unsigned int)ix;
- src = im->px[si];
- a = im->alpha ? im->alpha[si] : 255;
- gui->px[py * gui->w + px] =
- a >= 255 ? src :
- blend_rgb565(gui->px[py * gui->w + px],
- src, a);
- }
- }
- }
- static void draw_bg_image(struct lay *l, struct ngui_rect box,
- unsigned int node, const struct br_style *st);
- /* draw_bg_image() clipped to rounded corners: the corner squares are saved
- * first and every pixel outside a corner's arc is restored afterwards. */
- #define BG_ROUND_MAX 64
- static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
- static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
- unsigned int node, const struct br_style *st,
- int rtl, int rtr, int rbr, int rbl)
- {
- struct ngui *ui = l->ui;
- struct ngui_rect clip = { 0, 0, ui->w, ui->h };
- int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
- if (ui->nclip > 0)
- clip = ui->clip[ui->nclip - 1];
- for (c = 0; c < 4; c++) {
- if (r[c] > BG_ROUND_MAX)
- r[c] = BG_ROUND_MAX;
- if (r[c] > box.w / 2)
- r[c] = box.w / 2;
- if (r[c] > box.h / 2)
- r[c] = box.h / 2;
- }
- for (c = 0; c < 4; c++) {
- int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
- int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
- for (dy = 0; dy < r[c]; dy++)
- for (dx = 0; dx < r[c]; dx++) {
- int px = ox + dx, py = oy + dy;
- if (px >= clip.x && py >= clip.y &&
- px < clip.x + clip.w && py < clip.y + clip.h)
- bg_round_save[c][dy * BG_ROUND_MAX + dx] =
- ui->px[py * ui->w + px];
- }
- }
- draw_bg_image(l, box, node, st);
- for (c = 0; c < 4; c++) {
- int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
- int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
- /* arc centre, in corner-square coordinates */
- int cx = (c == 1 || c == 2) ? 0 : r[c];
- int cy = (c >= 2) ? 0 : r[c];
- for (dy = 0; dy < r[c]; dy++)
- for (dx = 0; dx < r[c]; dx++) {
- int px = ox + dx, py = oy + dy;
- int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
- if (ex * ex + ey * ey <= 4 * r[c] * r[c])
- continue;
- if (px >= clip.x && py >= clip.y &&
- px < clip.x + clip.w && py < clip.y + clip.h)
- ui->px[py * ui->w + px] =
- bg_round_save[c][dy * BG_ROUND_MAX + dx];
- }
- }
- }
- static void draw_bg_image(struct lay *l, struct ngui_rect box,
- unsigned int node, const struct br_style *st)
- {
- struct br_image *bi;
- struct img_blit b;
- int tw, th, x, y, rep_x, rep_y, posx, posy;
- unsigned int scale = 65536;
- int legacy, tiles = 0, rows = 0;
- int cx1, cy1, cx2, cy2;
- if (!st->bg_image || box.w <= 0 || box.h <= 0)
- return;
- if (doc.nodes[node].bg_img_index < 0 ||
- doc.nodes[node].bg_img_index >= image_count)
- return;
- bi = &images[doc.nodes[node].bg_img_index];
- if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
- return;
- legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
- st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
- st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
- if (legacy) {
- scale = ((unsigned int)box.w << 16) / bi->img.w;
- tw = box.w;
- th = (int)(((unsigned int)bi->img.h * scale) >> 16);
- x = box.x;
- y = box.y;
- rep_x = rep_y = 0;
- } else {
- if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
- unsigned int sx = ((unsigned int)box.w << 16) /
- bi->img.w;
- unsigned int sy = ((unsigned int)box.h << 16) /
- bi->img.h;
- scale = st->bg_size_kind == 3 ?
- (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
- } else if (st->bg_size_kind == 1 ||
- st->bg_size_kind == 2) {
- int w = st->bg_size_w;
- int h = st->bg_size_h;
- if (st->bg_size_kind == 2) {
- if (w)
- w = box.w * w / 100;
- if (h)
- h = box.h * h / 100;
- }
- if (w)
- scale = ((unsigned int)w << 16) / bi->img.w;
- else if (h)
- scale = ((unsigned int)h << 16) / bi->img.h;
- }
- tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
- th = (int)(((unsigned int)bi->img.h * scale) >> 16);
- if (tw < 1)
- tw = 1;
- if (th < 1)
- th = 1;
- posx = st->bg_pos_x_kind == 1 ?
- (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
- posy = st->bg_pos_y_kind == 1 ?
- (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
- x = box.x + posx;
- y = box.y + posy;
- rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
- rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
- if (rep_x) {
- int m = (x - box.x) % tw;
- if (m > 0)
- m -= tw;
- x = box.x + m;
- }
- if (rep_y) {
- int m = (y - box.y) % th;
- if (m > 0)
- m -= th;
- y = box.y + m;
- }
- }
- cx1 = box.x > page_rect.x ? box.x : page_rect.x;
- cy1 = box.y > page_rect.y ? box.y : page_rect.y;
- cx2 = box.x + box.w;
- cy2 = box.y + box.h;
- if (cx2 > page_rect.x + page_rect.w - 12)
- cx2 = page_rect.x + page_rect.w - 12;
- if (cy2 > page_rect.y + page_rect.h)
- cy2 = page_rect.y + page_rect.h;
- if (cx1 >= cx2 || cy1 >= cy2)
- return;
- b.dst = l->ui->px;
- b.dst_w = l->ui->w;
- b.dst_h = l->ui->h;
- b.clip_x = cx1;
- b.clip_y = cy1;
- b.clip_w = cx2 - cx1;
- b.clip_h = cy2 - cy1;
- b.bg = ui.theme.bg;
- b.bg2 = ui.theme.bg;
- b.dst_a = 0;
- {
- struct img_image *src = image_display_get(bi, tw, th);
- int row_x;
- if (!src)
- src = &bi->img;
- b.scale = ((unsigned int)tw << 16) / src->w;
- b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
- row_x = x;
- for (;;) {
- for (;;) {
- b.x = x;
- b.y = y;
- img_draw(src, &b);
- if (!rep_x || ++tiles > 512)
- break;
- x += tw;
- if (x >= box.x + box.w)
- break;
- }
- if (!rep_y || ++rows > 64)
- break;
- y += th;
- if (y >= box.y + box.h)
- break;
- x = row_x;
- }
- }
- }
- static void svg_size(unsigned int node, const struct br_style *st, int cw,
- int *out_w, int *out_h);
- static void svg_paint_box(struct ngui *ui, unsigned int node,
- const struct br_style *st, int x, int y, int w,
- int h);
- /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
- * RUN_SVG an inline <svg> icon (its node in off), RUN_PBOX an empty
- * ::before/::after box with a background (Infima's menu chevrons). */
- #define RUN_SVG (-3)
- #define RUN_PBOX (-4)
- static int run_width(const struct lay_run *r)
- {
- if (r->img >= 0)
- return r->iw;
- if (r->img == -2 || r->img == RUN_SVG || r->img == RUN_PBOX)
- return r->iw;
- return (int)r->w;
- }
- static void start_line(struct lay *l, const struct br_style *st)
- {
- (void)st;
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- }
- l->line_left = l->left;
- l->line_right = l->right;
- if (l->float_active && l->line_y < l->float_bottom) {
- if (l->float_left > l->line_left)
- l->line_left = l->float_left;
- if (l->float_right < l->line_right)
- l->line_right = l->float_right;
- }
- if (l->line_right < l->line_left + 8)
- l->line_right = l->line_left + 8;
- l->line_x = l->line_left;
- l->run_x = l->line_left;
- }
- static void inline_box_add(const struct lay *l, unsigned int owner, int x,
- int w)
- {
- int y = l->line_y;
- int h = l->line_h ? l->line_h : 16;
- int depth = 0;
- while (owner && owner <= BR_MAX_NODES && depth++ < 16) {
- unsigned int node = owner - 1;
- struct br_layout_box *b = &layout_boxes[node];
- if (b->valid && inline_box_pass[node] == inline_box_pass_id &&
- (inline_box_flush[node] == inline_box_flush_id ||
- inline_box_y[node] < y)) {
- int x1 = b->x + b->w, y1 = b->y + b->h;
- if (x < b->x)
- b->x = x;
- if (y < b->y)
- b->y = y;
- if (x + w > x1)
- x1 = x + w;
- if (y + h > y1)
- y1 = y + h;
- b->w = x1 - b->x;
- b->h = y1 - b->y;
- } else {
- b->x = x;
- b->y = y;
- b->w = w;
- b->h = h;
- b->valid = 1;
- }
- inline_box_pass[node] = inline_box_pass_id;
- inline_box_flush[node] = inline_box_flush_id;
- inline_box_y[node] = y;
- owner = inline_box_parent[node];
- }
- }
- static void flush_line(struct lay *l)
- {
- int total, x, i, vis;
- inline_box_flush_id++;
- if (!l->nruns && l->line_x == l->line_left) {
- l->line_h = 0;
- return;
- }
- total = l->line_x - l->line_left;
- x = l->line_left;
- vis = 1;
- if (l->draw) {
- int lh = l->line_h ? l->line_h : 16;
- vis = l->line_y + lh >= page_rect.y &&
- l->line_y <= page_rect.y + page_rect.h;
- }
- if (l->align == BR_ALIGN_CENTER)
- x += (l->line_right - l->line_left - total) / 2;
- else if (l->align == BR_ALIGN_RIGHT)
- x = l->line_right - total;
- if (x < l->line_left)
- x = l->line_left;
- for (i = 0; i < l->nruns; i++) {
- struct lay_run *r = &l->runs[i];
- int w = run_width(r);
- int ry = l->line_y + r->dy;
- x += r->gap;
- if (l->draw && vis) {
- if (r->form) {
- unsigned int node = r->form - 1;
- struct form_state *fs = form_get(node, 1);
- int hh = r->ih ? r->ih : 20;
- int focused = form_focus == node;
- int disabled = r->form_disabled;
- unsigned short bg = l->ui->theme.panel_alt;
- unsigned short fg = disabled ? 0x8410 : r->color;
- struct ngui_rect box = {x, ry, w, hh};
- if (r->form_kind == FORM_CHECKBOX ||
- r->form_kind == FORM_RADIO) {
- ngui_fill_rect(l->ui, box, bg);
- ngui_frame(l->ui, box,
- focused ? l->ui->theme.accent :
- l->ui->theme.border);
- if (fs && fs->checked) {
- struct ngui_rect dot = {
- x + 4, ry + 4,
- w > 8 ? w - 8 : 1,
- hh > 8 ? hh - 8 : 1
- };
- if (r->form_kind == FORM_RADIO)
- ngui_fill_round_rect(
- l->ui, dot, 4,
- 4, 4, 4,
- l->ui->theme.accent);
- else
- ngui_fill_rect(l->ui,
- dot,
- l->ui->theme.accent);
- }
- } else {
- int editable =
- r->form_kind == FORM_TEXT ||
- r->form_kind == FORM_PASSWORD ||
- r->form_kind == FORM_TEXTAREA;
- int scroll = 0;
- /* Editable fields draw the live value
- * (r->lit is a short copy). */
- static char shown[FORM_VALUE_MAX + 1];
- const char *txt = r->lit;
- unsigned int tl = s_len(r->lit);
- if (editable && fs && fs->len) {
- unsigned int k;
- if (r->form_kind == FORM_PASSWORD) {
- for (k = 0; k < fs->len; k++)
- shown[k] = '*';
- shown[k] = '\0';
- txt = shown;
- } else {
- txt = fs->value;
- }
- tl = fs->len;
- }
- struct br_style fst;
- int author, tx = x + 6, pr = 6;
- style_for_node(node, &fst);
- author = form_author_styled(&fst);
- if (author) {
- /* The page styled the control:
- * its background, border, radius
- * and text colour. */
- form_paint_author(l->ui, box, &fst,
- focused);
- tx = x + fst.border_w[3] +
- mp_px(&fst, 7, w);
- pr = fst.border_w[1] +
- mp_px(&fst, 5, w);
- if (tx < x + 2 && !editable)
- tx = x + 2;
- if (!disabled)
- fg = editable && fs &&
- !fs->len ?
- 0x8410 : fst.color;
- if (!editable) {
- int tw0 = (int)
- run_text_width(l->ui,
- r, txt, tl);
- tx = x + (w - tw0) / 2;
- }
- } else {
- /* The box is drawn in theme colours, so
- * the text is too: the page's CSS colour
- * (dark on a light page) would vanish on
- * the dark field. */
- if (!disabled)
- fg = editable && fs && !fs->len ?
- l->ui->theme.text_dim :
- l->ui->theme.text;
- ngui_fill_rect(l->ui, box, bg);
- ngui_frame(l->ui, box,
- focused ? l->ui->theme.accent :
- l->ui->theme.border);
- }
- /* A value wider than the field shows its
- * tail (where typing happens). */
- if (editable && fs && fs->len &&
- w > (tx - x) + pr) {
- int tw = (int)run_text_width(l->ui,
- r, txt, tl);
- int room = w - (tx - x) - pr;
- if (tw > room)
- scroll = tw - room;
- }
- ngui_push_clip(l->ui, (struct ngui_rect){
- x + 1, ry + 1,
- w > 2 ? w - 2 : 1,
- hh > 2 ? hh - 2 : 1 });
- ngui_text_px_face(l->ui, run_face(r),
- tx - scroll,
- ry + (hh - r->font_px) / 2 - 1,
- txt, tl, fg, r->font_px,
- r->bold, r->italic, r->mono);
- if (focused && fs && editable) {
- int cw = 0;
- if (fs->len && fs->caret)
- cw = (int)run_text_width(
- l->ui, r, txt,
- fs->caret < fs->len ?
- fs->caret : fs->len);
- ngui_fill_rect(l->ui,
- (struct ngui_rect){
- tx + cw - scroll,
- ry + 4, 1,
- hh > 8 ? hh - 8 : 1
- },
- l->ui->theme.accent);
- }
- ngui_pop_clip(l->ui);
- if (r->form_kind == FORM_SELECT) {
- ngui_text_px(l->ui, x + w - 12,
- ry + 2, "v", 1, fg,
- r->font_px, 0, 0, 0);
- }
- }
- } else if (r->img == RUN_PBOX) {
- struct ngui_rect bx = { x, ry, w, r->ih };
- ngui_push_clip(l->ui, bx);
- if (r->pb_has_bg)
- ngui_fill_rect(l->ui, bx, r->pb_bg);
- if (r->pb_img >= 0 && r->pb_img < image_count &&
- images[r->pb_img].state == 1) {
- /* Rotate about the box centre: the
- * image is centred in it here. */
- draw_image_transformed(l->ui,
- &images[r->pb_img].img,
- x + r->pb_x, ry + r->pb_y,
- r->pb_w, r->pb_h,
- r->transform_scale ?
- r->scale_x : 100,
- r->transform_scale ?
- r->scale_y : 100,
- r->transform_scale ?
- r->rotate_x100 : 0,
- 50, 50, 1, 1);
- }
- ngui_pop_clip(l->ui);
- } else if (r->img == RUN_SVG) {
- struct br_style sst;
- style_for_node(r->off, &sst);
- svg_paint_box(l->ui, r->off, &sst, x, ry, w,
- r->ih);
- } else if (r->img == -2) {
- int hh = r->ih ? r->ih : 20;
- ngui_fill_rect(l->ui,
- (struct ngui_rect){x, ry, w, hh},
- l->ui->theme.panel_alt);
- ngui_frame(l->ui,
- (struct ngui_rect){x, ry, w, hh},
- l->ui->theme.border);
- ngui_text_px_face(l->ui, run_face(r),
- x + 6, ry + 2, r->lit,
- s_len(r->lit), r->color,
- r->font_px, r->bold, r->italic,
- r->mono);
- } else if (r->img >= 0) {
- struct br_image *bi = &images[r->img];
- if (bi->state == 1 && r->transform_scale) {
- draw_image_transformed(l->ui, &bi->img,
- x, ry, r->iw, r->ih,
- r->scale_x, r->scale_y,
- r->rotate_x100, r->origin_x,
- r->origin_y, r->origin_x_kind,
- r->origin_y_kind);
- } else if (bi->state == 1) {
- struct img_image *src =
- image_display_get(bi, r->iw, r->ih);
- struct img_blit b;
- if (!src)
- src = &bi->img;
- b.dst = l->ui->px;
- b.dst_w = l->ui->w;
- b.dst_h = l->ui->h;
- b.clip_x = page_rect.x;
- b.clip_y = page_rect.y;
- b.clip_w = page_rect.w - 12;
- b.clip_h = page_rect.h;
- b.x = x;
- b.y = ry;
- b.scale = ((unsigned int)r->iw << 16) /
- src->w;
- b.bg = ui.theme.bg;
- b.bg2 = ui.theme.bg;
- b.dst_a = 0;
- b.flags = src->alpha ?
- IMG_BLIT_OVER_DST : 0;
- img_draw(src, &b);
- }
- } else {
- const char *s = r->has_lit ? r->lit :
- doc.text + r->off;
- unsigned int n = r->has_lit ? s_len(r->lit) :
- r->len;
- ngui_text_px_face(l->ui, run_face(r), x, ry,
- s, n, r->color, r->font_px,
- r->bold, r->italic, r->mono);
- if (r->underline)
- ngui_fill_rect(l->ui,
- (struct ngui_rect){x,
- ry + run_ascent(l->ui, r) + 2,
- w, 1}, r->color);
- if (r->strike)
- ngui_fill_rect(l->ui,
- (struct ngui_rect){x,
- ry + run_ascent(l->ui, r) -
- (r->font_px > 3 ?
- r->font_px / 3 : 1),
- w, 1}, r->color);
- if (r->overline)
- ngui_fill_rect(l->ui,
- (struct ngui_rect){x, ry,
- w, 1}, r->color);
- }
- if (r->form || r->href) {
- if (nhits < HIT_MAX) {
- struct hit *h = &hits[nhits];
- unsigned int target = r->form ?
- r->form - 1 : r->href;
- int hh = (r->form || r->img >= 0 ||
- r->img == RUN_SVG) ?
- r->ih :
- run_line_height(l->ui, r);
- int merge = nhits > 0 &&
- hits[nhits - 1].node == target &&
- hits[nhits - 1].y == ry &&
- hits[nhits - 1].h == hh &&
- x <= hits[nhits - 1].x +
- hits[nhits - 1].w + 2;
- if (merge) {
- struct hit *p = &hits[nhits - 1];
- int end = x + w;
- if (end > p->x + p->w)
- p->w = end - p->x;
- } else {
- h->x = x;
- h->y = ry;
- h->w = w;
- h->h = hh;
- h->node = (unsigned short)target;
- nhits++;
- }
- }
- }
- }
- if (r->box)
- inline_box_add(l, r->box, x, w);
- x += w;
- }
- l->y += l->line_h + 2;
- if (l->float_active && l->y >= l->float_bottom)
- l->float_active = 0;
- l->nruns = 0;
- l->line_x = l->left;
- l->run_x = l->left;
- l->line_left = l->left;
- l->line_right = l->right;
- l->line_h = 0;
- l->space_pending = 0;
- }
- static void add_run(struct lay *l, unsigned int off, unsigned short len,
- const struct br_style *st, unsigned short href,
- const char *lit)
- {
- unsigned int n = lit ? s_len(lit) : len;
- const char *tp = lit ? lit : doc.text + off;
- int w = (int)face_text_width(l->ui, st, tp, n);
- if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
- flush_line(l);
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- start_line(l, st);
- }
- {
- struct lay_run *r = &l->runs[l->nruns++];
- int gap = l->line_x - l->run_x;
- if (gap < 0)
- gap = 0;
- r->box = l->box_owner;
- r->gap = (unsigned short)gap;
- r->off = off;
- r->len = len;
- r->color = st->color;
- r->href = href;
- r->dy = 0;
- r->has_lit = 0;
- r->form = 0;
- r->form_kind = 0;
- r->form_disabled = 0;
- r->lit[0] = '\0';
- if (lit && lit[0]) {
- unsigned int i;
- for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
- r->lit[i] = lit[i];
- r->lit[i] = '\0';
- r->has_lit = 1;
- }
- r->img = -1;
- r->iw = r->ih = 0;
- r->font_px = st->font_px;
- r->bold = st->bold;
- r->italic = st->italic;
- r->mono = st->mono;
- r->font_face = st->font_face;
- /* A control with its own background is a button, not body copy;
- * an inherited link underline would strike through the fill. */
- r->underline = st->underline && !st->has_bg;
- r->strike = st->strike && !st->has_bg;
- r->overline = st->overline && !st->has_bg;
- r->w = (unsigned short)w;
- if (r->has_lit)
- r->w = (unsigned short)run_text_width(
- l->ui, r, r->lit, s_len(r->lit));
- w = r->w;
- }
- l->line_x += w;
- l->run_x = l->line_x;
- {
- int lh = face_line_height(l->ui, st);
- if (st->line_h_px)
- lh = st->line_h_px;
- else if (st->line_h_pct)
- lh = st->font_px * st->line_h_pct / 100;
- if (lh < face_line_height(l->ui, st))
- lh = face_line_height(l->ui, st);
- if (l->line_h < lh)
- l->line_h = lh;
- }
- }
- static void add_image_run(struct lay *l, unsigned int node,
- const struct br_style *st, unsigned short href)
- {
- struct br_image *bi = 0;
- int idx = doc.nodes[node].img_index;
- int dw, dh, maxw;
- if (idx >= 0 && idx < image_count && images[idx].state == 1)
- bi = &images[idx];
- if (l->nruns == 0)
- start_line(l, st);
- if (l->space_pending &&
- (l->nruns > 0 || l->line_x > l->line_left)) {
- int sp = (int)face_text_width(l->ui, st, " ", 1);
- if (l->line_x + sp <= l->line_right)
- l->line_x += sp;
- }
- l->space_pending = 0;
- if (!bi) {
- const char *alt = br_alt(&doc, node);
- struct br_style gs = *st;
- char tmp[96];
- unsigned int n = 0;
- int w;
- gs.color = BR_GRAY;
- gs.underline = 0;
- s_append(tmp, &n, "[", sizeof(tmp));
- s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
- s_append(tmp, &n, "]", sizeof(tmp));
- w = (int)face_text_width(l->ui, &gs, tmp, n);
- if (l->line_x + w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left))
- flush_line(l);
- add_run(l, 0, 0, &gs, href, tmp);
- if (!l->draw) {
- int t = l->line_y < 0 ? 0 : l->line_y;
- int hh = face_line_height(l->ui, &gs);
- if (t > 65535)
- t = 65535;
- if (hh > 65535)
- hh = 65535;
- img_top[node] = (unsigned short)t;
- img_h[node] = (unsigned short)hh;
- }
- return;
- }
- maxw = l->line_right - l->line_left;
- if (maxw < 8)
- maxw = 8;
- {
- int iw = bi->native_w, ih = bi->native_h;
- int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
- if (iw <= 0 || ih <= 0) {
- iw = (int)bi->img.w;
- ih = (int)bi->img.h;
- }
- dw = iw;
- dh = ih;
- if (doc.nodes[node].width_attr) {
- int want = doc.nodes[node].width_attr;
- dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
- have_w = 1;
- }
- if (doc.nodes[node].height_attr) {
- int want = doc.nodes[node].height_attr;
- dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
- have_h = 1;
- }
- if (have_w && !have_h)
- dh = ih ? ih * dw / iw : 0;
- if (have_h && !have_w)
- dw = iw ? iw * dh / ih : 0;
- if (st->width_kind) {
- css_w = 1;
- if (st->width_kind == 3)
- dw = maxw * st->width_calc_pct / 100 +
- st->width_calc_px;
- else
- dw = st->width_kind == 2 ?
- maxw * (int)st->width / 100 :
- (int)st->width;
- }
- /* Percentage heights resolve against the containing block's
- * definite height (Docusaurus' logo: `.navbar__logo { height:
- * 2rem }` holding an `img { height: 100% }`), and are auto
- * when it has none; they used to use the width. */
- if (st->height_kind == 1 ||
- ((st->height_kind == 2 || st->height_kind == 3) &&
- l->cb_h > 0)) {
- css_h = 1;
- if (st->height_kind == 3)
- dh = l->cb_h * st->height_calc_pct / 100 +
- st->height_calc_px;
- else
- dh = st->height_kind == 2 ?
- l->cb_h * (int)st->height / 100 :
- (int)st->height;
- }
- if (css_w && !css_h)
- dh = ih ? ih * dw / iw : 0;
- if (css_h && !css_w)
- dw = iw ? iw * dh / ih : 0;
- if (st->max_width_kind) {
- int mw = st->max_width_kind == 3 ?
- maxw * st->max_width_calc_pct / 100 +
- st->max_width_calc_px :
- st->max_width_kind == 2 ?
- maxw * (int)st->max_width / 100 :
- (int)st->max_width;
- if (mw > 0 && dw > mw) {
- dh = iw ? ih * mw / iw : 0;
- dw = mw;
- }
- }
- }
- if (dw < 8)
- dw = 8;
- if (dh < 8)
- dh = 8;
- if (dw > maxw) {
- dh = dw ? dh * maxw / dw : dh;
- dw = maxw;
- }
- if (!l->draw) {
- int t = l->line_y < 0 ? 0 : l->line_y;
- if (t > 65535)
- t = 65535;
- if (dh > 65535)
- dh = 65535;
- img_top[node] = (unsigned short)t;
- img_h[node] = (unsigned short)dh;
- }
- if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
- l->line_x > l->line_left))
- flush_line(l);
- if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
- flush_line(l);
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- start_line(l, st);
- }
- {
- struct lay_run *r = &l->runs[l->nruns++];
- int gap = l->line_x - l->run_x;
- if (gap < 0)
- gap = 0;
- r->box = l->box_owner;
- r->gap = (unsigned short)gap;
- r->off = 0;
- r->len = 0;
- r->color = 0;
- r->href = href;
- r->form = 0;
- r->form_kind = 0;
- r->form_disabled = 0;
- /* Inline replaced elements honour their vertical margins; this
- * is how Bootstrap's negative logo margins centre the wordmark. */
- {
- int idy = mp_px(st, 0, l->right - l->left);
- if (idy < -2048)
- idy = -2048;
- if (idy > 2048)
- idy = 2048;
- r->dy = (signed short)idy;
- }
- r->has_lit = 0;
- r->lit[0] = '\0';
- r->img = (short)idx;
- r->iw = (unsigned short)dw;
- r->ih = (unsigned short)dh;
- r->w = (unsigned short)dw;
- r->font_px = st->font_px;
- r->bold = st->bold;
- r->italic = st->italic;
- r->mono = st->mono;
- r->font_face = st->font_face;
- r->transform_scale = st->transform_scale;
- r->scale_x = st->scale_x;
- r->scale_y = st->scale_y;
- r->rotate_x100 = st->rotate_x100;
- r->origin_x = st->origin_x;
- r->origin_y = st->origin_y;
- r->origin_x_kind = st->origin_x_kind;
- r->origin_y_kind = st->origin_y_kind;
- r->underline = 0;
- }
- if (node < BR_MAX_NODES) {
- layout_boxes[node].x = l->line_x;
- layout_boxes[node].y = l->line_y +
- mp_px(st, 0, l->right - l->left);
- layout_boxes[node].w = dw;
- layout_boxes[node].h = dh;
- layout_boxes[node].valid = 1;
- }
- l->line_x += dw;
- l->run_x = l->line_x;
- if (l->line_h < dh)
- l->line_h = dh;
- }
- /* An inline (or inline-block) <svg> is a replaced element in the text
- * line, like an <img>: comment bubbles and arrows sit next to their label
- * instead of starting a block of their own. */
- static void add_svg_run(struct lay *l, unsigned int node,
- const struct br_style *st, unsigned short href)
- {
- struct lay_run *r;
- int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
- if (lw < 8)
- lw = 8;
- cw = st->width_kind ? style_width_px(st, lw) : lw;
- if (cw < 1)
- cw = 1;
- svg_size(node, st, cw, &dw, &dh);
- if (dw > lw)
- dw = lw;
- ml = mp_px(st, 3, lw);
- mr = mp_px(st, 1, lw);
- if (ml < 0)
- ml = 0;
- if (mr < 0)
- mr = 0;
- if (l->line_x + ml + dw > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left))
- flush_line(l);
- if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
- flush_line(l);
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- start_line(l, st);
- }
- l->line_x += ml;
- r = &l->runs[l->nruns++];
- memset(r, 0, sizeof(*r));
- r->box = l->box_owner;
- r->gap = (unsigned short)(l->line_x > l->run_x ?
- l->line_x - l->run_x : 0);
- r->off = node;
- r->color = st->color;
- r->href = href;
- r->img = RUN_SVG;
- r->iw = (unsigned short)dw;
- r->ih = (unsigned short)dh;
- r->w = (unsigned short)dw;
- r->font_px = st->font_px;
- if (node < BR_MAX_NODES) {
- layout_boxes[node].x = l->line_x;
- layout_boxes[node].y = l->line_y;
- layout_boxes[node].w = dw;
- layout_boxes[node].h = dh;
- layout_boxes[node].valid = 1;
- }
- l->line_x += dw + mr;
- l->run_x = l->line_x;
- if (l->line_h < dh)
- l->line_h = dh;
- }
- static int text_width(struct lay *l, const char *s, unsigned int n,
- const struct br_style *st)
- {
- return (int)face_text_width(l->ui, st, s, n);
- }
- /* Longest prefix that fits in maxw, at least one byte. */
- static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
- const struct br_style *st, int maxw)
- {
- unsigned int take = 0;
- while (take < n) {
- if (text_width(l, s, take + 1, st) > maxw)
- break;
- take++;
- }
- return take ? take : 1;
- }
- static void emit_word(struct lay *l, const char *s, unsigned int start,
- unsigned int n, unsigned int base,
- const struct br_style *st, unsigned short href)
- {
- int avail;
- int w = text_width(l, s + start, n, st);
- unsigned int off = start;
- if (l->nruns == 0)
- start_line(l, st);
- avail = l->line_right - l->line_left;
- if (st->nowrap) {
- if (n)
- add_run(l, base + start,
- (unsigned short)n, st, href, 0);
- return;
- }
- /* A padded/bordered one-word button can be a few pixels wider than
- * the content box; keep it on one line instead of splitting it. */
- if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
- add_run(l, base + start,
- (unsigned short)n, st, href, 0);
- return;
- }
- if (l->line_x + w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left)) {
- flush_line(l);
- start_line(l, st);
- avail = l->line_right - l->line_left;
- }
- if (w <= avail) {
- if (n)
- add_run(l, base + start,
- (unsigned short)n, st, href, 0);
- return;
- }
- while (n > 0) {
- unsigned int take = fit_prefix(l, s + off, n, st, avail);
- add_run(l, base + off,
- (unsigned short)take, st, href, 0);
- off += take;
- n -= take;
- if (n) {
- flush_line(l);
- start_line(l, st);
- avail = l->line_right - l->line_left;
- }
- }
- }
- static void emit_text(struct lay *l, const char *s, unsigned int len,
- const struct br_style *st, unsigned short href, int pre)
- {
- unsigned int i = 0;
- unsigned int base;
- int space_w = (int)face_text_width(l->ui, st, " ", 1);
- if (!s || !len)
- return;
- if (space_w <= 0)
- space_w = 8;
- if (l->nruns == 0)
- start_line(l, st);
- base = (unsigned int)(s - doc.text);
- if (st->uppercase) {
- char *p = (char *)s;
- unsigned int j;
- for (j = 0; j < len; j++)
- if (p[j] >= 'a' && p[j] <= 'z')
- p[j] = (char)(p[j] - 'a' + 'A');
- }
- if (pre) {
- while (i < len) {
- unsigned int start;
- if (s[i] == '\n') {
- flush_line(l);
- start_line(l, st);
- i++;
- continue;
- }
- if (s[i] == ' ') {
- if (l->line_x + space_w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left)) {
- flush_line(l);
- start_line(l, st);
- } else {
- l->line_x += space_w;
- }
- i++;
- continue;
- }
- start = i;
- while (i < len && s[i] != ' ' && s[i] != '\n')
- i++;
- emit_word(l, s, start, i - start, base, st, href);
- }
- return;
- }
- while (i < len) {
- unsigned int start, n;
- if (s[i] == ' ') {
- l->space_pending = 1;
- i++;
- continue;
- }
- start = i;
- while (i < len && s[i] != ' ')
- i++;
- n = i - start;
- if (l->space_pending &&
- (l->nruns > 0 || l->line_x > l->line_left)) {
- if (st->nowrap ||
- l->line_x + space_w <= l->line_right)
- l->line_x += space_w;
- }
- l->space_pending = 0;
- emit_word(l, s, start, n, base, st, href);
- }
- }
- static int list_index(unsigned int parent, unsigned int node)
- {
- unsigned int n = 0, i;
- for (i = doc.nodes[parent].first; i && i != node;
- i = doc.nodes[i].next)
- if (doc.nodes[i].tag == BR_TAG_LI)
- n++;
- return (int)n + 1;
- }
- static void list_roman(char *m, unsigned int *n, int v, int upper,
- unsigned int cap)
- {
- static const int val[] = { 1000, 900, 500, 400, 100, 90,
- 50, 40, 10, 9, 5, 4, 1 };
- static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
- "l", "xl", "x", "ix", "v", "iv", "i" };
- static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
- "L", "XL", "X", "IX", "V", "IV", "I" };
- unsigned int i;
- for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
- while (v >= val[i] && *n + 1 < cap) {
- const char *s = upper ? up[i] : lo[i];
- while (*s && *n + 1 < cap)
- m[(*n)++] = *s++;
- v -= val[i];
- }
- }
- }
- static void list_marker_text(char *m, unsigned int cap, int style, int idx)
- {
- unsigned int n = 0;
- if (style == BR_LIST_DISC) {
- m[n++] = '-';
- } else if (style == BR_LIST_CIRCLE) {
- m[n++] = 'o';
- } else if (style == BR_LIST_SQUARE) {
- m[n++] = '+';
- } else if (style == BR_LIST_LOWER_ALPHA ||
- style == BR_LIST_UPPER_ALPHA) {
- if (idx >= 1 && idx <= 26)
- m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
- 'A' : 'a') + idx - 1);
- else
- m[n++] = '?';
- m[n++] = '.';
- } else if (style == BR_LIST_LOWER_ROMAN ||
- style == BR_LIST_UPPER_ROMAN) {
- list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
- if (n + 1 < cap)
- m[n++] = '.';
- } else {
- s_append_dec(m, &n, (unsigned int)idx, cap);
- if (n + 1 < cap)
- m[n++] = '.';
- }
- m[n] = '\0';
- }
- /* A control the page styled itself (background, border or radius in author
- * CSS -- `background:transparent;border:none` counts) is painted with that
- * style, sized from its padding/height and keeps the page's text colour.
- * Unstyled controls keep the ngui theme look. */
- static int form_author_styled(const struct br_style *st)
- {
- int i;
- if (st->bg_set)
- return 1;
- for (i = 0; i < 4; i++)
- if (st->border_w[i] || st->radius[i])
- return 1;
- return 0;
- }
- /* Set by the layout when the control is stretched to its line: a flex item
- * (its box width was assigned by the flex row) or a child of a flex column,
- * whose default align-items: stretch makes inputs full width. */
- static int form_fill_line;
- static void add_form_run(struct lay *l, unsigned int node,
- const struct br_style *st, unsigned short href)
- {
- struct form_state *fs = form_get(node, 1);
- char shown[FORM_VALUE_MAX + 1];
- char opt[64];
- const char *text = "";
- struct lay_run *r;
- int kind = form_kind_of(node);
- int disabled = form_disabled(node);
- int author = form_author_styled(st);
- int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
- int ml = 0, mr = 0, mt = 0, mb = 0;
- if (!fs)
- return;
- if (l->nruns == 0)
- start_line(l, st);
- if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
- text = "";
- w = 16;
- h = 16;
- } else if (kind == FORM_SELECT) {
- if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
- s_copy(opt, "Select", sizeof(opt));
- text = opt;
- w = 120;
- } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
- kind == FORM_RESET) {
- if (fs->len)
- text = fs->value;
- else if (doc.nodes[node].tag == BR_TAG_BUTTON)
- /* A <button>'s label is its content: an empty one
- * (Docusaurus' sidebar caret, drawn by a CSS
- * ::before icon) shows none. Only <input> buttons
- * get the UA's default label. */
- text = "";
- else
- text = kind == FORM_SUBMIT ? "Submit" :
- kind == FORM_RESET ? "Reset" : "Button";
- } else if (kind == FORM_PASSWORD) {
- for (i = 0; i < fs->len; i++)
- shown[i] = '*';
- shown[fs->len] = '\0';
- text = fs->len ? shown : br_placeholder(&doc, node);
- } else {
- if (fs->len)
- text = fs->value;
- else
- text = br_placeholder(&doc, node);
- if (kind == FORM_TEXTAREA) {
- w = 180;
- h = 40;
- }
- }
- tw = (int)face_text_width(l->ui, st, text, s_len(text));
- line_w = l->line_right - l->line_left;
- pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
- st->border_w[1] + st->border_w[3];
- pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
- st->border_w[0] + st->border_w[2];
- if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
- /* Buttons are border-box in every UA stylesheet: an
- * explicit width/height is the whole box. */
- if (author || pad_x) {
- w = tw + pad_x;
- } else {
- w = tw + 18;
- if (w < 64)
- w = 64;
- }
- if (st->width_kind)
- w = style_width_px(st, line_w);
- if (st->min_width_kind == 1 && w < (int)st->min_width)
- w = st->min_width;
- if (st->height_kind == 1)
- h = st->height;
- else if (author)
- h = st->font_px + 6 + pad_y;
- else
- h = 22;
- } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
- kind == FORM_TEXTAREA) {
- int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
- st->display == BR_DISPLAY_FLEX;
- int boxed = st->box_sizing ? 0 : pad_x;
- if (st->width_kind)
- w = style_width_px(st, line_w) + boxed;
- else if (fill)
- w = line_w - (l->line_x - l->line_left);
- else
- w = kind == FORM_TEXTAREA ? 180 : 120;
- if (kind == FORM_TEXTAREA) {
- const char *ra = br_find_attr(&doc, node, "rows");
- int rows = 0;
- int lh = st->line_h_px ? st->line_h_px :
- st->font_px * 5 / 4;
- while (ra && *ra >= '0' && *ra <= '9')
- rows = rows * 10 + (*ra++ - '0');
- if (rows < 1 || rows > 40)
- rows = 2;
- h = author ? rows * lh + pad_y : 40;
- } else if (author) {
- h = st->font_px + 8 + pad_y;
- } else if (st->font_px + 8 > h) {
- /* Taller fields for large text (min-height/padding
- * on login pages): keep the box around the glyphs. */
- h = st->font_px + 8;
- }
- if (st->height_kind == 1)
- h = st->height + (st->box_sizing ? 0 : pad_y);
- if (st->min_height_kind == 1 && h < (int)st->min_height)
- h = st->min_height;
- } else if (kind == FORM_SELECT) {
- w = st->width_kind == 1 ? st->width : 120;
- }
- if (author) {
- /* Inline margins (Google's `margin:11px 4px` between its
- * two submit buttons). */
- ml = mp_px(st, 3, line_w);
- mr = mp_px(st, 1, line_w);
- mt = mp_px(st, 0, line_w);
- mb = mp_px(st, 2, line_w);
- if (ml < 0 || ml > 64) ml = 0;
- if (mr < 0 || mr > 64) mr = 0;
- if (mt < 0 || mt > 64) mt = 0;
- if (mb < 0 || mb > 64) mb = 0;
- }
- if (w > line_w - ml - mr)
- w = line_w - ml - mr;
- if (w < 8)
- w = 8;
- if (h > 400)
- h = 400;
- if (l->line_x + ml + w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left))
- flush_line(l);
- if (l->nruns >= 96)
- return;
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- start_line(l, st);
- }
- l->line_x += ml;
- r = &l->runs[l->nruns++];
- r->box = l->box_owner;
- r->gap = (unsigned short)(l->line_x - l->run_x);
- r->off = r->len = 0;
- r->color = st->color;
- r->href = href;
- r->dy = (signed short)mt;
- r->has_lit = 1;
- for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
- r->lit[i] = text[i];
- r->lit[i] = '\0';
- r->img = -2;
- r->iw = (unsigned short)w;
- r->ih = (unsigned short)h;
- r->w = (unsigned short)w;
- r->font_px = st->font_px;
- r->bold = st->bold;
- r->italic = st->italic;
- r->mono = st->mono;
- r->font_face = st->font_face;
- r->underline = 0;
- r->form = node + 1;
- r->form_kind = (unsigned char)kind;
- r->form_disabled = (unsigned char)disabled;
- if (node < BR_MAX_NODES) {
- layout_boxes[node].x = l->line_x;
- layout_boxes[node].y = l->line_y + mt;
- layout_boxes[node].w = w;
- layout_boxes[node].h = h;
- layout_boxes[node].valid = 1;
- }
- l->line_x += w;
- l->run_x = l->line_x;
- l->line_x += mr;
- if (l->line_h < h + mt + mb)
- l->line_h = h + mt + mb;
- }
- /* Background, border and corner radius of an author-styled control, the
- * same decoration rules as a block box. */
- static void form_paint_author(struct ngui *ui, struct ngui_rect box,
- const struct br_style *st, int focused)
- {
- int rtl = css_radius(st, 0, box.w, box.h);
- int rtr = css_radius(st, 1, box.w, box.h);
- int rbr = css_radius(st, 2, box.w, box.h);
- int rbl = css_radius(st, 3, box.w, box.h);
- int bw = st->border_t[0] ? 0 : st->border_w[0];
- (void)focused;
- if (box.w <= 0 || box.h <= 0)
- return;
- if (rtl || rtr || rbr || rbl) {
- if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
- box.w > bw * 2 && box.h > bw * 2) {
- struct ngui_rect in = { box.x + bw, box.y + bw,
- box.w - bw * 2,
- box.h - bw * 2 };
- ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
- st->border_c[0]);
- ngui_fill_round_rect(ui, in,
- rtl > bw ? rtl - bw : 0,
- rtr > bw ? rtr - bw : 0,
- rbr > bw ? rbr - bw : 0,
- rbl > bw ? rbl - bw : 0, st->bg);
- } else if (st->has_bg) {
- ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
- st->bg);
- } else if (bw > 0) {
- ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
- st->border_c[0]);
- }
- return;
- }
- if (st->has_bg)
- ngui_fill_rect(ui, box, st->bg);
- if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
- st->border_w[3])
- draw_border_box(ui, box, st);
- }
- /* A poster wrapper is absolutely positioned over the media slot; the
- * measured height of its picture is normally added back to the flow. When a
- * loading-skeleton sibling already reserves that slot, adding both doubles
- * the media height and pushes the article text a full screen down. */
- static int has_skeleton_sibling(unsigned int node)
- {
- unsigned int p = doc.nodes[node].parent, c;
- for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
- if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
- continue;
- if (doc.nodes[c].class_off &&
- contains_ci(doc.attrs + doc.nodes[c].class_off,
- "skeleton"))
- return 1;
- }
- return 0;
- }
- static void layout_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link);
- static void layout_flex_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link);
- static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
- struct br_style *ps, int base);
- static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
- const struct br_style *ps, unsigned short link);
- static void layout_grid_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link);
- static void layout_grid_auto(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link);
- static int flex_item_width(struct lay *l, unsigned int n,
- const struct br_style *cs, int avail);
- static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
- const struct br_style *pst, int depth,
- unsigned short link);
- static void layout_table_row(struct lay *l, unsigned int row,
- const struct br_style *pst, int depth,
- unsigned short link);
- static int table_has_rowspan(unsigned int table);
- static void layout_table(struct lay *l, unsigned int table,
- const struct br_style *st, int depth,
- unsigned short link);
- /* A flex container whose items are only inline spans is usually just a
- * heading/icon pair. Our flex row positions such items without emitting
- * their inline text in some deep page contexts; normal inline flow renders
- * the same content correctly. */
- static int layout_out_of_flow(struct lay *l, unsigned int n,
- const struct br_style *cs, int depth,
- unsigned short lk);
- static void layout_flex_column(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link);
- static void emit_pseudo(struct lay *l, unsigned int node,
- const struct br_style *st, int pe, unsigned short link);
- static int flex_wants_row(unsigned int parent, const struct br_style *pst)
- {
- unsigned int c;
- int items = 0;
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- struct br_style cs;
- if (nd->type == BR_NODE_TEXT)
- continue;
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- /* `justify-content: space-between` spreads even two plain
- * inline items (a "Password ... Reset password" label row)
- * across the line; inline flow would set them side by side. */
- if (++items >= 2 && pst->justify >= 3)
- return 1;
- if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
- cs.width_kind || cs.has_bg ||
- cs.border_w[0] || cs.border_w[1] ||
- cs.border_w[2] || cs.border_w[3] ||
- nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
- return 1;
- }
- return 0;
- }
- static int css_radius(const struct br_style *st, int corner,
- int w, int h)
- {
- int r = st->radius[corner];
- if (r <= 0)
- return 0;
- if (r > w / 2)
- r = w / 2;
- if (r > h / 2)
- r = h / 2;
- return r;
- }
- /* ---- inline SVG ----
- *
- * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
- * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
- * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
- * opacity and solid paint; a gradient paints the average of its stops) and
- * the layer is blitted on every repaint. <text> is drawn per frame on top. */
- #define SVG_CACHE_MAX 48
- #define SVG_CACHE_PIXELS (640 * 1024)
- #define SVG_MAX_POINTS 24576
- struct svg_cache_ent {
- unsigned int node;
- int w, h;
- unsigned short *px;
- unsigned char *a;
- unsigned int stamp;
- };
- static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
- static unsigned int svg_cache_pixels, svg_cache_clock;
- static struct svgr svg_geom;
- static void *svg_geom_buf;
- /* Current viewport in user units: percentage lengths resolve against it
- * (the viewBox size, not the device pixels). */
- static double svg_vp_w = 300, svg_vp_h = 150;
- /* The layers live in the page heap: forget them before heap_reset(). */
- static void svg_cache_clear(void)
- {
- memset(svg_cache, 0, sizeof(svg_cache));
- svg_cache_pixels = 0;
- svg_geom_buf = 0;
- }
- static int svg_name_is(const char *a, const char *b)
- {
- while (*a && *b) {
- char x = *a, y = *b;
- if (x >= 'A' && x <= 'Z')
- x = (char)(x - 'A' + 'a');
- if (x != y)
- return 0;
- a++;
- b++;
- }
- return *a == *b;
- }
- static const char *svg_elem_name(unsigned int node)
- {
- const struct br_node *nd = &doc.nodes[node];
- if (nd->name_off)
- return doc.attrs + nd->name_off;
- return br_tag_name(nd->tag);
- }
- /* A numeric attribute; a percentage resolves against `base`. */
- static double svg_attr_num(unsigned int node, const char *name, double def,
- double base)
- {
- const char *v = br_find_attr(&doc, node, name);
- const char *p = v;
- int ok = 0;
- double x;
- if (!v)
- return def;
- x = svgr_num(&p, &ok);
- if (!ok)
- return def;
- if (*p == '%')
- x = x * base / 100.0;
- return x;
- }
- /* viewBox="minx miny w h"; 0 when absent or invalid. */
- static int svg_viewbox4(unsigned int node, double vb[4])
- {
- const char *v = br_find_attr(&doc, node, "viewbox");
- const char *p = v;
- int i, ok = 1;
- if (!v)
- return 0;
- for (i = 0; i < 4 && ok; i++)
- vb[i] = svgr_num(&p, &ok);
- return ok && vb[2] > 0 && vb[3] > 0;
- }
- /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
- * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
- static void svg_viewport_matrix(unsigned int node, const double vb[4],
- double w, double h, double m[6])
- {
- const char *par = br_find_attr(&doc, node, "preserveaspectratio");
- double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
- int ax = 1, ay = 1;
- if (par && contains_ci(par, "none")) {
- m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
- m[4] = -vb[0] * sx;
- m[5] = -vb[1] * sy;
- return;
- }
- if (par) {
- if (contains_ci(par, "xmin"))
- ax = 0;
- else if (contains_ci(par, "xmax"))
- ax = 2;
- if (contains_ci(par, "ymin"))
- ay = 0;
- else if (contains_ci(par, "ymax"))
- ay = 2;
- }
- s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
- (sx < sy ? sx : sy);
- tx = (w - vb[2] * s) * ax / 2.0;
- ty = (h - vb[3] * s) * ay / 2.0;
- m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
- m[4] = tx - vb[0] * s;
- m[5] = ty - vb[1] * s;
- }
- /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
- * the paint attribute, then average the gradient's stops. */
- static int svg_url_paint(unsigned int node, const char *attr,
- unsigned short *color, unsigned int *alpha)
- {
- const char *v = 0, *h;
- char id[64];
- unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
- for (k = 0; node && k < 32 && !v; k++) {
- v = br_find_attr(&doc, node, attr);
- if (!v) {
- const char *style = br_find_attr(&doc, node, "style");
- if (style && contains_ci(style, "url(#"))
- v = strstr(style, "url(#");
- }
- if (v && !contains_ci(v, "url("))
- v = 0;
- node = doc.nodes[node].parent;
- }
- if (!v || !(h = strstr(v, "#")))
- return 0;
- h++;
- while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
- id[n++] = *h++;
- id[n] = '\0';
- g = br_find_id(&doc, id);
- /* Follow href chains (a gradient that only references another one's
- * stops), at most a few hops. */
- for (k = 0; g && k < 4; k++) {
- unsigned int gi = g - 1;
- const char *ref;
- for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
- const char *nm, *sc, *so;
- unsigned short col = 0;
- double op = 1;
- if (doc.nodes[c].type != BR_NODE_ELEM)
- continue;
- nm = svg_elem_name(c);
- if (!svg_name_is(nm, "stop"))
- continue;
- sc = br_find_attr(&doc, c, "stop-color");
- so = br_find_attr(&doc, c, "stop-opacity");
- {
- const char *st = br_find_attr(&doc, c, "style");
- const char *q;
- if (st && (q = strstr(st, "stop-color:")) != 0)
- sc = q + 11;
- if (st && (q = strstr(st, "stop-opacity:")) != 0)
- so = q + 13;
- }
- if (sc) {
- unsigned int L = 0;
- while (sc[L] && sc[L] != ';' && sc[L] != '"')
- L++;
- if (!br_parse_color(sc, L, &col))
- col = 0;
- }
- if (so) {
- const char *p = so;
- int ok = 0;
- double x = svgr_num(&p, &ok);
- if (ok)
- op = x < 0 ? 0 : x > 1 ? 1 : x;
- }
- sr += (col >> 11) & 31;
- sg += (col >> 5) & 63;
- sb += col & 31;
- sa += (unsigned int)(op * 255);
- cnt++;
- }
- if (cnt)
- break;
- ref = br_find_attr(&doc, gi, "href");
- if (!ref)
- ref = br_find_attr(&doc, gi, "xlink:href");
- if (!ref || ref[0] != '#')
- break;
- g = br_find_id(&doc, ref + 1);
- }
- if (!cnt)
- return 0;
- *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
- (sb / cnt));
- *alpha = sa / cnt;
- return 1;
- }
- static int svg_paint(unsigned int node, const struct br_style *st, int fill,
- unsigned short *color, unsigned int *alpha)
- {
- int mode = fill ? st->fill_mode : st->stroke_mode;
- const char *op = br_find_attr(&doc, node,
- fill ? "fill-opacity" : "stroke-opacity");
- *alpha = 255;
- switch (mode) {
- case BR_PAINT_UNSET:
- if (!fill)
- return 0;
- *color = 0;
- break;
- case BR_PAINT_COLOR:
- *color = fill ? st->fill : st->stroke;
- break;
- case BR_PAINT_CURRENT:
- *color = st->color;
- break;
- case BR_PAINT_URL:
- if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
- alpha))
- return 0;
- break;
- default:
- return 0;
- }
- if (op) {
- const char *p = op;
- int ok = 0;
- double x = svgr_num(&p, &ok);
- if (ok)
- *alpha = (unsigned int)(*alpha *
- (x < 0 ? 0 : x > 1 ? 1 : x));
- }
- return *alpha > 0;
- }
- static void svg_draw_node(struct svgr_layer *L, unsigned int node,
- const double m[6], const struct br_style *pst,
- unsigned int alpha, int depth);
- static void svg_draw_children(struct svgr_layer *L, unsigned int node,
- const double m[6], const struct br_style *st,
- unsigned int alpha, int depth)
- {
- unsigned int c;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
- if (doc.nodes[c].type == BR_NODE_ELEM)
- svg_draw_node(L, c, m, st, alpha, depth + 1);
- }
- static void svg_draw_node(struct svgr_layer *L, unsigned int node,
- const double pm[6], const struct br_style *pst,
- unsigned int alpha, int depth)
- {
- struct br_style st;
- const char *nm = svg_elem_name(node);
- const char *tf;
- double m[6];
- unsigned short color;
- unsigned int pa;
- int shape = 0, fillable = 1;
- if (depth > 24 || !nm)
- return;
- if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
- svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
- svg_name_is(nm, "lineargradient") ||
- svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
- svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
- svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
- svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
- svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
- svg_name_is(nm, "foreignobject"))
- return;
- br_style_for(&doc, node, pst, &st);
- if (st.display == BR_DISPLAY_NONE)
- return;
- memcpy(m, pm, sizeof(m));
- tf = br_find_attr(&doc, node, "transform");
- if (tf)
- svgr_transform(m, tf);
- {
- const char *op = br_find_attr(&doc, node, "opacity");
- if (op) {
- const char *p = op;
- int ok = 0;
- double x = svgr_num(&p, &ok);
- if (ok)
- alpha = (unsigned int)(alpha *
- (x < 0 ? 0 :
- x > 1 ? 1 : x));
- }
- }
- if (!alpha)
- return;
- if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
- svg_name_is(nm, "switch")) {
- svg_draw_children(L, node, m, &st, alpha, depth);
- return;
- }
- if (svg_name_is(nm, "svg")) {
- double vb[4], x = svg_attr_num(node, "x", 0, 0),
- y = svg_attr_num(node, "y", 0, 0);
- double t[6] = { 1, 0, 0, 1, 0, 0 };
- t[4] = x;
- t[5] = y;
- svgr_mat_mul(m, m, t);
- double ow = svg_vp_w, oh = svg_vp_h;
- if (svg_viewbox4(node, vb)) {
- double w = svg_attr_num(node, "width", vb[2], ow);
- double h = svg_attr_num(node, "height", vb[3], oh);
- double vm[6];
- svg_viewport_matrix(node, vb, w, h, vm);
- svgr_mat_mul(m, m, vm);
- svg_vp_w = vb[2];
- svg_vp_h = vb[3];
- }
- svg_draw_children(L, node, m, &st, alpha, depth);
- svg_vp_w = ow;
- svg_vp_h = oh;
- return;
- }
- if (svg_name_is(nm, "use")) {
- const char *ref = br_find_attr(&doc, node, "href");
- unsigned int tgt;
- double t[6] = { 1, 0, 0, 1, 0, 0 };
- if (!ref)
- ref = br_find_attr(&doc, node, "xlink:href");
- if (!ref || ref[0] != '#')
- return;
- tgt = br_find_id(&doc, ref + 1);
- if (!tgt || tgt - 1 == node)
- return;
- tgt--;
- t[4] = svg_attr_num(node, "x", 0, 0);
- t[5] = svg_attr_num(node, "y", 0, 0);
- svgr_mat_mul(m, m, t);
- if (svg_name_is(svg_elem_name(tgt), "symbol")) {
- double vb[4];
- double ow = svg_vp_w, oh = svg_vp_h;
- if (svg_viewbox4(tgt, vb)) {
- /* A <use> without width/height sizes the
- * symbol to 100% of the viewport: Docusaurus'
- * 13.5px external-link icon references a
- * 24-unit symbol and showed only its corner. */
- double w = svg_attr_num(node, "width",
- ow > 0 ? ow : vb[2], ow);
- double h = svg_attr_num(node, "height",
- oh > 0 ? oh : vb[3], oh);
- double vm[6];
- svg_viewport_matrix(tgt, vb, w, h, vm);
- svgr_mat_mul(m, m, vm);
- svg_vp_w = vb[2];
- svg_vp_h = vb[3];
- }
- svg_draw_children(L, tgt, m, &st, alpha, depth);
- svg_vp_w = ow;
- svg_vp_h = oh;
- } else {
- svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
- }
- return;
- }
- svgr_reset(&svg_geom, m);
- if (svg_name_is(nm, "path")) {
- const char *d = br_find_attr(&doc, node, "d");
- if (d) {
- svgr_path(&svg_geom, d);
- shape = 1;
- }
- } else if (svg_name_is(nm, "rect")) {
- double w = svg_attr_num(node, "width", 0, svg_vp_w);
- double h = svg_attr_num(node, "height", 0, svg_vp_h);
- double rx = svg_attr_num(node, "rx", -1, w);
- double ry = svg_attr_num(node, "ry", -1, h);
- if (rx < 0)
- rx = ry < 0 ? 0 : ry;
- if (ry < 0)
- ry = rx;
- svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
- svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
- shape = 1;
- } else if (svg_name_is(nm, "circle")) {
- double r = svg_attr_num(node, "r", 0, svg_vp_w);
- svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
- svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
- shape = 1;
- } else if (svg_name_is(nm, "ellipse")) {
- svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
- svg_attr_num(node, "cy", 0, svg_vp_h),
- svg_attr_num(node, "rx", 0, svg_vp_w),
- svg_attr_num(node, "ry", 0, svg_vp_h));
- shape = 1;
- } else if (svg_name_is(nm, "line")) {
- svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
- svg_attr_num(node, "y1", 0, svg_vp_h));
- svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
- svg_attr_num(node, "y2", 0, svg_vp_h));
- shape = 1;
- fillable = 0;
- } else if (svg_name_is(nm, "polyline") ||
- svg_name_is(nm, "polygon")) {
- const char *pts = br_find_attr(&doc, node, "points");
- if (pts) {
- svgr_points(&svg_geom, pts,
- svg_name_is(nm, "polygon"));
- shape = 1;
- }
- }
- if (!shape)
- return;
- if (fillable && svg_paint(node, &st, 1, &color, &pa))
- svgr_fill(&svg_geom, L, color, pa * alpha / 255,
- st.fill_evenodd);
- if (svg_paint(node, &st, 0, &color, &pa)) {
- double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
- double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
- svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
- }
- }
- /* <text> elements: drawn straight onto the page every frame (the glyph
- * renderer targets the ngui canvas, not a layer). x/y map through the
- * accumulated transform; the font size scales with it. */
- static void svg_draw_text(struct ngui *ui, unsigned int node,
- const double pm[6], const struct br_style *pst,
- int ox, int oy, int depth)
- {
- unsigned int c;
- if (depth > 24)
- return;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- struct br_style st;
- const char *nm, *tf;
- double m[6];
- if (doc.nodes[c].type != BR_NODE_ELEM)
- continue;
- nm = svg_elem_name(c);
- if (!nm || svg_name_is(nm, "defs") ||
- svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
- svg_name_is(nm, "clippath"))
- continue;
- br_style_for(&doc, c, pst, &st);
- if (st.display == BR_DISPLAY_NONE)
- continue;
- memcpy(m, pm, sizeof(m));
- tf = br_find_attr(&doc, c, "transform");
- if (tf)
- svgr_transform(m, tf);
- if (svg_name_is(nm, "text")) {
- unsigned int t = doc.nodes[c].first;
- const char *s;
- unsigned int n, tw;
- double x = svg_attr_num(c, "x", 0, 0),
- y = svg_attr_num(c, "y", 0, 0);
- double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
- int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
- int tx, ty, anchor;
- unsigned short col;
- unsigned int pa;
- if (!t || doc.nodes[t].type != BR_NODE_TEXT)
- continue;
- if (px < 6)
- px = 6;
- if (px > 72)
- px = 72;
- if (!svg_paint(c, &st, 1, &col, &pa))
- continue;
- s = doc.text + doc.nodes[t].text_off;
- n = doc.nodes[t].text_len;
- st.font_px = (unsigned char)px;
- tw = face_text_width(ui, &st, s, n);
- tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
- ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
- ngui_text_ascent_face(ui, style_face(&st), px,
- st.mono);
- anchor = st.align;
- if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
- anchor = BR_ALIGN_CENTER;
- else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
- anchor = BR_ALIGN_RIGHT;
- if (anchor == BR_ALIGN_CENTER)
- tx -= (int)tw / 2;
- else if (anchor == BR_ALIGN_RIGHT)
- tx -= (int)tw;
- ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
- col, px, st.bold, st.italic,
- st.mono);
- } else {
- svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
- }
- }
- }
- static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
- {
- double vb[4];
- if (svg_viewbox4(node, vb)) {
- svg_viewport_matrix(node, vb, w, h, m);
- } else {
- m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
- }
- }
- static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
- const struct br_style *st)
- {
- struct svg_cache_ent *e = 0;
- struct svgr_layer L;
- double m[6];
- unsigned int i, need = (unsigned int)w * (unsigned int)h;
- svg_cache_clock++;
- for (i = 0; i < SVG_CACHE_MAX; i++)
- if (svg_cache[i].px && svg_cache[i].node == node &&
- svg_cache[i].w == w && svg_cache[i].h == h) {
- svg_cache[i].stamp = svg_cache_clock;
- return &svg_cache[i];
- }
- if (need > SVG_CACHE_PIXELS)
- return 0;
- /* Evict least recently used layers until this one fits. */
- for (;;) {
- struct svg_cache_ent *lru = 0, *free_slot = 0;
- for (i = 0; i < SVG_CACHE_MAX; i++) {
- if (!svg_cache[i].px) {
- if (!free_slot)
- free_slot = &svg_cache[i];
- } else if (!lru || svg_cache[i].stamp < lru->stamp) {
- lru = &svg_cache[i];
- }
- }
- if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
- e = free_slot;
- break;
- }
- if (!lru)
- return 0;
- svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
- free(lru->px);
- free(lru->a);
- memset(lru, 0, sizeof(*lru));
- }
- if (!svg_geom_buf) {
- svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
- if (!svg_geom_buf)
- return 0;
- }
- svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
- e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
- e->a = (unsigned char *)calloc(need, 1);
- if (!e->px || !e->a) {
- free(e->px);
- free(e->a);
- memset(e, 0, sizeof(*e));
- return 0;
- }
- e->node = node;
- e->w = w;
- e->h = h;
- e->stamp = svg_cache_clock;
- svg_cache_pixels += need;
- L.px = e->px;
- L.a = e->a;
- L.w = w;
- L.h = h;
- svg_root_matrix(node, w, h, m);
- {
- double vb[4];
- if (svg_viewbox4(node, vb)) {
- svg_vp_w = vb[2];
- svg_vp_h = vb[3];
- } else {
- svg_vp_w = w;
- svg_vp_h = h;
- }
- }
- svg_draw_children(&L, node, m, st, 255, 0);
- return e;
- }
- /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
- *
- * The markup is parsed into a detached subtree of the page document and
- * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
- * bitmap, which then behaves like any decoded image. currentColor is
- * black (an image has no inherited text colour); <text> is not drawn. */
- static int svg_text_sniff(const unsigned char *d, unsigned int len)
- {
- unsigned int i = 0;
- if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
- i = 3;
- while (i < len) {
- while (i < len && (d[i] == ' ' || d[i] == '\t' ||
- d[i] == '\r' || d[i] == '\n'))
- i++;
- if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
- return 1;
- if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
- i += 4;
- while (i + 3 <= len && memcmp(d + i, "-->", 3))
- i++;
- i += 3;
- continue;
- }
- if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
- while (i < len && d[i] != '>')
- i++;
- i++;
- continue;
- }
- return 0;
- }
- return 0;
- }
- static int svg_len_attr(unsigned int node, const char *name)
- {
- const char *v = br_find_attr(&doc, node, name);
- int n = 0, any = 0;
- if (!v)
- return 0;
- while (*v == ' ')
- v++;
- while (*v >= '0' && *v <= '9') {
- n = n * 10 + (*v++ - '0');
- any = 1;
- }
- if (*v == '.')
- while (*++v >= '0' && *v <= '9')
- ;
- if (!any || *v == '%')
- return 0;
- return n;
- }
- static int svg_decode_image(const unsigned char *data, unsigned int len,
- struct br_image *bi, int box_w, int box_h)
- {
- unsigned int holder, svg = 0, c, need, i;
- struct br_style base = base_style(), st;
- struct svgr_layer L;
- double vb[4], m[6];
- int w, h, have_vb, nat_w, nat_h;
- holder = br_create_element(&doc, "div", 3);
- if (!holder) {
- s_copy(bi->err, "page is full", sizeof(bi->err));
- return -1;
- }
- holder--;
- br_set_inner_html(&doc, holder, (const char *)data, len);
- for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
- if (doc.nodes[c].type == BR_NODE_ELEM &&
- doc.nodes[c].tag == BR_TAG_SVG) {
- svg = c;
- break;
- }
- if (!svg) {
- s_copy(bi->err, "bad SVG", sizeof(bi->err));
- return -1;
- }
- have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
- w = svg_len_attr(svg, "width");
- h = svg_len_attr(svg, "height");
- if (box_w > 0 && box_h > 0) {
- w = box_w;
- h = box_h;
- } else if (!w && !h) {
- w = have_vb ? (int)(vb[2] + 0.5) : 150;
- h = have_vb ? (int)(vb[3] + 0.5) : 150;
- } else if (!w) {
- w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
- } else if (!h) {
- h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
- }
- /* Layout uses the intrinsic size; small icons are drawn at up to 4x
- * so CSS scaling stays crisp. */
- nat_w = w;
- nat_h = h;
- while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
- w *= 2;
- h *= 2;
- }
- if (w > BR_IMG_LAYOUT_W) {
- h = (int)((long)h * BR_IMG_LAYOUT_W / w);
- w = BR_IMG_LAYOUT_W;
- }
- if (h > 2048)
- h = 2048;
- if (w < 1)
- w = 1;
- if (h < 1)
- h = 1;
- need = (unsigned int)w * (unsigned int)h;
- if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
- s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
- return -1;
- }
- if (!svg_geom_buf) {
- svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
- if (!svg_geom_buf) {
- s_copy(bi->err, "out of memory", sizeof(bi->err));
- return -1;
- }
- }
- svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
- L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
- L.a = (unsigned char *)calloc(need, 1);
- if (!L.px || !L.a) {
- free(L.px);
- free(L.a);
- s_copy(bi->err, "out of memory", sizeof(bi->err));
- return -1;
- }
- for (i = 0; i < need; i++)
- L.px[i] = 0xFFFF;
- L.w = w;
- L.h = h;
- base.color = 0x0000;
- br_style_for(&doc, svg, &base, &st);
- svg_root_matrix(svg, w, h, m);
- if (!have_vb && nat_w > 0 && nat_h > 0) {
- /* No viewBox: user units are CSS pixels of the natural size,
- * so the up-to-4x raster (and a box size) must scale them.
- * A 40x20 icon used to fill only the top-left quarter of its
- * 160x80 bitmap and was drawn at a quarter of its size. */
- m[0] = (double)w / nat_w;
- m[3] = (double)h / nat_h;
- }
- svg_vp_w = have_vb ? vb[2] : nat_w;
- svg_vp_h = have_vb ? vb[3] : nat_h;
- svg_draw_children(&L, svg, m, &st, 255, 0);
- bi->native_w = nat_w;
- bi->native_h = nat_h;
- bi->img.format = 0;
- bi->img.w = (unsigned int)w;
- bi->img.h = (unsigned int)h;
- bi->img.px = L.px;
- bi->img.alpha = L.a;
- bi->img.flags = 0;
- bi->state = 1;
- image_pixels += need;
- return 0;
- }
- /* Intrinsic size of an inline <svg> in a w-wide containing box. */
- static void svg_size(unsigned int node, const struct br_style *st, int cw,
- int *out_w, int *out_h)
- {
- double vb[4];
- int has_vb = svg_viewbox4(node, vb);
- double aw = svg_attr_num(node, "width", -1, cw);
- double ah = svg_attr_num(node, "height", -1, 0);
- int w, h;
- if (st->width_kind)
- w = cw;
- else if (aw > 0)
- w = (int)(aw + 0.5);
- else if (st->height_kind == 1 && has_vb)
- w = (int)(st->height * vb[2] / vb[3] + 0.5);
- else if (ah > 0 && has_vb)
- w = (int)(ah * vb[2] / vb[3] + 0.5);
- else if (has_vb)
- w = cw;
- else
- w = 300;
- if (st->max_width_kind == 1 && w > st->max_width)
- w = st->max_width;
- if (w > cw && cw > 0 && !(aw > 0))
- w = cw;
- if (w < 1)
- w = 1;
- if (w > 2000)
- w = 2000;
- if (st->height_kind == 1)
- h = st->height;
- else if (ah > 0)
- h = (int)(ah + 0.5);
- else if (has_vb)
- h = (int)(w * vb[3] / vb[2] + 0.5);
- else
- h = 150;
- if (h < 1)
- h = 1;
- if (h > 1400)
- h = 1400;
- *out_w = w;
- *out_h = h;
- }
- static void svg_paint_box(struct ngui *ui, unsigned int node,
- const struct br_style *st, int x, int y, int w, int h)
- {
- struct svg_cache_ent *e;
- struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
- int cx0, cy0, cx1, cy1, px, py;
- double m[6];
- if (ui->nclip > 0)
- clip = ui->clip[ui->nclip - 1];
- cx0 = r.x > clip.x ? r.x : clip.x;
- cy0 = r.y > clip.y ? r.y : clip.y;
- cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
- cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
- if (cx0 >= cx1 || cy0 >= cy1)
- return;
- e = svg_layer(node, w, h, st);
- if (e) {
- for (py = cy0; py < cy1; py++) {
- unsigned int srow = (unsigned int)(py - y) *
- (unsigned int)w;
- unsigned short *dst = ui->px + py * ui->w;
- for (px = cx0; px < cx1; px++) {
- unsigned int si = srow + (unsigned int)(px - x);
- unsigned int a = e->a[si];
- if (!a)
- continue;
- dst[px] = a >= 255 ? e->px[si] :
- blend_rgb565(dst[px], e->px[si], a);
- }
- }
- }
- svg_root_matrix(node, w, h, m);
- ngui_push_clip(ui, r);
- svg_draw_text(ui, node, m, st, x, y, 0);
- ngui_pop_clip(ui);
- }
- /* Size and paint a block-level/absolutely positioned <img>. Inline images
- * keep using add_image_run(); this covers the CSS `position:absolute;
- * width:100%` poster pattern used by news sites. */
- static void image_block_size(unsigned int node, const struct br_style *st,
- int cbw, int *out_w, int *out_h)
- {
- struct br_node *nd = &doc.nodes[node];
- int idx = nd->img_index;
- int iw = 0, ih = 0, w, h, aw, ah;
- if (idx >= 0 && idx < image_count && images[idx].state == 1) {
- iw = (int)images[idx].img.w;
- ih = (int)images[idx].img.h;
- if (iw <= 0 || ih <= 0) {
- iw = (int)images[idx].native_w;
- ih = (int)images[idx].native_h;
- }
- }
- if (st->width_kind)
- w = style_width_px(st, cbw);
- else if (nd->width_attr)
- w = nd->width_pct ? cbw * nd->width_attr / 100 :
- (int)nd->width_attr;
- else if (nd->height_attr && !nd->height_pct && iw && ih)
- w = iw * (int)nd->height_attr / ih;
- else if (iw)
- w = iw;
- else
- w = 64;
- /* max-width/min-width against the containing block: Tailwind's
- * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
- * 300x300 thumbnail to its 75 px avatar box. */
- if (st->max_width_kind) {
- int mw = st->max_width_kind == 3 ?
- cbw * st->max_width_calc_pct / 100 +
- st->max_width_calc_px :
- st->max_width_kind == 2 ?
- cbw * (int)st->max_width / 100 : (int)st->max_width;
- if (mw > 0 && w > mw)
- w = mw;
- }
- if (st->min_width_kind) {
- int mn = st->min_width_kind == 3 ?
- cbw * st->min_width_calc_pct / 100 +
- st->min_width_calc_px :
- st->min_width_kind == 2 ?
- cbw * (int)st->min_width / 100 : (int)st->min_width;
- if (mn > w)
- w = mn;
- }
- if (w < 8)
- w = 8;
- if (cbw > 0 && w > cbw)
- w = cbw;
- /* Without a CSS height the attributes (or the bitmap) only give the
- * aspect ratio: a width clamped by max-width scales the height too,
- * instead of letterboxing the image into its attribute height. */
- aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
- ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
- if (st->height_kind)
- h = style_height_px(st, cbw);
- else if (aw > 0 && ah > 0)
- h = w * ah / aw;
- else if (nd->height_attr)
- h = nd->height_pct ? cbw * nd->height_attr / 100 :
- (int)nd->height_attr;
- else
- h = 64;
- if (h < 8)
- h = 8;
- *out_w = w;
- *out_h = h;
- }
- static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
- int dw, int dh)
- {
- int idx = doc.nodes[node].img_index;
- if (idx >= 0 && idx < image_count && images[idx].state == 1) {
- struct img_image *src = image_display_get(&images[idx], dw, dh);
- struct img_blit b;
- if (!src)
- src = &images[idx].img;
- b.dst = l->ui->px;
- b.dst_w = l->ui->w;
- b.dst_h = l->ui->h;
- b.clip_x = page_rect.x;
- b.clip_y = page_rect.y;
- b.clip_w = page_rect.w - 12;
- b.clip_h = page_rect.h;
- b.x = x;
- b.y = y;
- b.scale = ((unsigned int)dw << 16) / src->w;
- b.bg = ui.theme.bg;
- b.bg2 = ui.theme.bg;
- b.dst_a = 0;
- /* OVER_DST is only needed for an alpha source; an opaque one can
- * take img_draw's 1:1 copy path. */
- b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
- img_draw(src, &b);
- } else if (l->draw) {
- ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
- 0xD69A);
- ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
- ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
- }
- }
- static void layout_block(struct lay *l, unsigned int node,
- const struct br_style *st, int depth,
- unsigned short link)
- {
- int old_left = l->left, old_right = l->right, old_align = l->align;
- int parent_cb_h = l->cb_h;
- int saved_parent_top = l->parent_top;
- int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
- int saved_cb_top = l->cb_top;
- int top, l0, r0;
- int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
- int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
- int deco_w, deco_h, content_w, content_h, box_h;
- int img_dh = 0;
- int definite_w = 0;
- int normal_top = 0;
- int rel_dx = 0, rel_dy = 0;
- int clip_pushed = 0;
- struct ngui_rect clip_rect;
- /* A DOM level costs about two depth units (layout_block ->
- * layout_children), so 48 covers a ~24-level page. Real news pages
- * nest a teaser 12+ levels deep; the old 24 skipped its text. */
- if (depth > 48 || st->display == BR_DISPLAY_NONE)
- return;
- flow_y = l->y;
- flow_left = l->left;
- flow_right = l->right;
- positioned = st->pos == 1 || st->pos == 2;
- relative = st->pos == 3;
- sticky = st->pos == 4;
- shifted = relative || sticky || st->transform_set;
- if (positioned) {
- int def_w = st->width_kind == 1 ? st->width : -1;
- if (st->pos == 2) {
- int avail_w = page_rect.w - 12;
- if (st->right_set && def_w >= 0)
- l->left = page_rect.x + avail_w - st->right -
- def_w;
- else if (!st->left_set && !st->right_set)
- l->left = flow_left; /* static position */
- else
- l->left = page_rect.x +
- (st->left_set ? st->left : 0);
- l->right = def_w >= 0 ? l->left + def_w :
- st->width_kind == 2 ?
- l->left + avail_w * (int)st->width / 100 :
- page_rect.x + avail_w;
- /* Placed by `bottom` (a page footer): an auto
- * height is the measured one. */
- if (st->bottom_set && st->height_kind)
- l->y = page_rect.y + page_rect.h -
- st->bottom -
- style_height_px(st, page_rect.w);
- else if (st->bottom_set && !st->top_set &&
- block_h[node])
- l->y = page_rect.y + page_rect.h -
- st->bottom - (int)block_h[node] -
- mp_px(st, 0, avail_w) -
- mp_px(st, 2, avail_w);
- else
- l->y = page_rect.y +
- (st->top_set ? st->top : 0);
- } else {
- int left = flow_left + (st->left_set ? st->left : 0);
- unsigned int parent = doc.nodes[node].parent;
- if (st->right_set && def_w >= 0)
- left = flow_right - st->right - def_w;
- l->left = left;
- l->right = def_w >= 0 ? left + def_w :
- flow_right +
- (st->left_set ? st->left : 0);
- l->y = flow_y + (st->top_set ? st->top : 0);
- if (st->bottom_set && st->height_kind &&
- parent < BR_MAX_NODES && block_h[parent] > 0)
- l->y = flow_y + block_h[parent] - st->bottom -
- style_height_px(st, old_right - old_left);
- else if (st->bottom_set && !st->top_set &&
- parent < BR_MAX_NODES && block_h[parent] > 0 &&
- block_h[node] > 0)
- l->y = flow_y + block_h[parent] - st->bottom -
- (int)block_h[node] -
- mp_px(st, 0, old_right - old_left) -
- mp_px(st, 2, old_right - old_left);
- }
- /* `left: 100%` parks a box (Docusaurus' "Skip to main
- * content" link) past the containing block's right edge
- * until it is focused. An auto width then has no room: it
- * used to collapse to 8 px and wrap one word per line into a
- * tall column painted over the page. Lay it out at the
- * containing block's width so it stays one line and
- * overflows (off-screen) like in a real browser. */
- if (def_w < 0 && l->right - l->left < 8) {
- int avail = st->pos == 2 ? page_rect.w - 12 :
- flow_right - flow_left;
- l->right = l->left + (avail > 8 ? avail : 8);
- }
- old_left = l->left;
- old_right = l->right;
- } else if (relative) {
- rel_dx = st->left_set ? st->left :
- (st->right_set ? -st->right : 0);
- rel_dy = st->top_set ? st->top :
- (st->bottom_set ? -st->bottom : 0);
- }
- if (st->transform_set) {
- rel_dx += st->tx;
- rel_dy += st->ty;
- }
- if ((doc.nodes[node].tag == BR_TAG_INPUT ||
- doc.nodes[node].tag == BR_TAG_TEXTAREA ||
- doc.nodes[node].tag == BR_TAG_SELECT ||
- doc.nodes[node].tag == BR_TAG_BUTTON) &&
- !button_has_elements(node)) {
- if (doc.nodes[node].tag == BR_TAG_INPUT &&
- s_eq(br_type(&doc, node), "hidden"))
- return;
- /* Reached as a block-level box (a flex item): the control
- * fills the box the caller assigned, and its line is flushed
- * here; flex layout resets the run list for the next item, so
- * a queued run would never be drawn. */
- form_fill_line = 1;
- add_form_run(l, node, st, link);
- form_fill_line = 0;
- flush_line(l);
- return;
- }
- flush_line(l);
- cbw = old_right - old_left;
- if (cbw < 8)
- cbw = 8;
- l->y += mp_px(st, 0, cbw);
- top = l->y;
- ml = mp_px(st, 3, cbw);
- mr = mp_px(st, 1, cbw);
- bl = st->border_w[3];
- br = st->border_w[1];
- pl = mp_px(st, 7, cbw);
- pr = mp_px(st, 5, cbw);
- bt = st->border_w[0];
- bb = st->border_w[2];
- pt = mp_px(st, 4, cbw);
- pb = mp_px(st, 6, cbw);
- deco_w = bl + br + pl + pr;
- deco_h = bt + bb + pt + pb;
- if (st->width_kind) {
- int w;
- if (st->width_kind == 3)
- w = cbw * st->width_calc_pct / 100 +
- st->width_calc_px;
- else
- w = css_size(st->width_kind, st->width, cbw);
- if (w < 0)
- w = 0;
- content_w = st->box_sizing ? w - deco_w : w;
- definite_w = 1;
- } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
- doc.nodes[node].tag == BR_TAG_TD ||
- doc.nodes[node].tag == BR_TAG_TH) &&
- doc.nodes[node].width_attr) {
- /* Legacy table/cell width attributes: percentages resolve
- * against the containing block, bare numbers are pixels. */
- int w = doc.nodes[node].width_pct ?
- cbw * doc.nodes[node].width_attr / 100 :
- doc.nodes[node].width_attr;
- if (w < 0)
- w = 0;
- content_w = st->box_sizing ? w - deco_w : w;
- definite_w = 1;
- } else {
- content_w = cbw - ml - mr - deco_w;
- }
- if (content_w < 0)
- content_w = 0;
- if (st->max_width_kind) {
- int mw = st->max_width_kind == 3 ?
- cbw * st->max_width_calc_pct / 100 +
- st->max_width_calc_px :
- css_size(st->max_width_kind, st->max_width, cbw);
- int max_box = st->box_sizing ? mw : mw + deco_w;
- /* A clamped auto width is used as the width, so auto
- * margins share the rest (Google's 688 px search box). */
- if (content_w + deco_w > max_box) {
- content_w = max_box - deco_w;
- definite_w = 1;
- }
- }
- if (st->min_width_kind) {
- int mw = st->min_width_kind == 3 ?
- cbw * st->min_width_calc_pct / 100 +
- st->min_width_calc_px :
- css_size(st->min_width_kind, st->min_width, cbw);
- int min_box = st->box_sizing ? mw : mw + deco_w;
- if (content_w + deco_w < min_box) {
- content_w = min_box - deco_w;
- definite_w = 1;
- }
- }
- if (content_w < 8)
- content_w = 8;
- if (definite_w) {
- int free_w = cbw - ml - mr - deco_w - content_w;
- if (free_w < 0)
- free_w = 0;
- if (st->ml_auto && st->mr_auto) {
- ml = free_w / 2;
- mr = free_w - ml;
- } else if (st->ml_auto) {
- ml = free_w;
- } else if (st->mr_auto) {
- mr = free_w;
- }
- }
- if (doc.nodes[node].tag == BR_TAG_IMG) {
- int iw, ih;
- image_block_size(node, st, cbw, &iw, &ih);
- content_w = iw;
- img_dh = ih;
- }
- l0 = old_left + ml;
- r0 = l0 + deco_w + content_w;
- if (r0 < l0 + 8)
- r0 = l0 + 8;
- normal_top = top;
- if (sticky) {
- if (st->top_set) {
- int stick = page_rect.y + st->top;
- if (normal_top < stick)
- rel_dy += stick - normal_top;
- } else if (st->bottom_set && block_h[node]) {
- int stick = page_rect.y + page_rect.h - st->bottom -
- block_h[node];
- if (normal_top > stick)
- rel_dy += stick - normal_top;
- }
- if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
- block_h[doc.nodes[node].parent]) {
- unsigned int p = doc.nodes[node].parent;
- int ptop = l->parent_top;
- int pbottom = ptop + block_h[p];
- int eh = block_h[node];
- int moved_top = normal_top + rel_dy;
- int moved_bottom = moved_top + eh;
- if (moved_bottom > pbottom)
- rel_dy -= moved_bottom - pbottom;
- moved_top = normal_top + rel_dy;
- if (moved_top < ptop)
- rel_dy += ptop - moved_top;
- }
- }
- if (shifted && l->draw) {
- top += rel_dy;
- l0 += rel_dx;
- r0 += rel_dx;
- }
- l->parent_top = top;
- if (st->pos != 0) {
- /* Positioned boxes establish the containing block for their
- * absolutely positioned descendants. */
- l->cb_left = l0;
- l->cb_right = r0;
- l->cb_top = top;
- }
- if (l->draw && block_h[node] &&
- top < page_rect.y + page_rect.h &&
- top + block_h[node] > page_rect.y) {
- struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
- int rtl = css_radius(st, 0, box.w, box.h);
- int rtr = css_radius(st, 1, box.w, box.h);
- int rbr = css_radius(st, 2, box.w, box.h);
- int rbl = css_radius(st, 3, box.w, box.h);
- if (st->transform_scale) {
- if (st->has_bg)
- fill_transformed_rect(l->ui, box, st->bg, st);
- } else if (rtl || rtr || rbr || rbl) {
- if (st->has_bg) {
- int bw = st->border_w[0];
- if (bw > 0 && !st->border_t[0] &&
- st->border_c[0] != st->bg &&
- box.w > bw * 2 && box.h > bw * 2) {
- struct ngui_rect inner = {
- box.x + bw, box.y + bw,
- box.w - bw * 2, box.h - bw * 2
- };
- int itl = rtl > bw ? rtl - bw : 0;
- int itr = rtr > bw ? rtr - bw : 0;
- int ibr = rbr > bw ? rbr - bw : 0;
- int ibl = rbl > bw ? rbl - bw : 0;
- ngui_fill_round_rect(l->ui, box, rtl,
- rtr, rbr, rbl,
- st->border_c[0]);
- ngui_fill_round_rect(l->ui, inner,
- itl, itr, ibr,
- ibl, st->bg);
- } else {
- ngui_fill_round_rect(l->ui, box, rtl,
- rtr, rbr, rbl,
- st->bg);
- }
- } else if (st->border_w[0] && !st->border_t[0]) {
- ngui_frame_round(l->ui, box, rtl, rtr, rbr,
- rbl, st->border_w[0],
- st->border_c[0]);
- }
- /* Rounded boxes paint their background image too
- * (app icons are rounded squares), kept inside the
- * corner arcs. */
- if (st->bg_image)
- draw_bg_image_round(l, box, node, st, rtl, rtr,
- rbr, rbl);
- } else {
- if (st->has_bg)
- ngui_fill_rect(l->ui, box, st->bg);
- if (st->bg_image)
- draw_bg_image(l, box, node, st);
- if (st->border_w[0] || st->border_w[1] ||
- st->border_w[2] || st->border_w[3])
- draw_border_box(l->ui, box, st);
- }
- }
- if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
- draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
- content_w, img_dh);
- if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
- l->ui && l->ui->nclip < 4) {
- clip_rect.x = l0 + bl;
- clip_rect.y = top + bt;
- clip_rect.w = (r0 - l0) - bl - br;
- clip_rect.h = (int)block_h[node] - bt - bb;
- if (clip_rect.w > 0 && clip_rect.h > 0) {
- ngui_push_clip(l->ui, clip_rect);
- clip_pushed = 1;
- }
- }
- l->left = l0 + bl + pl;
- l->right = l->left + content_w;
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->align = st->align;
- l->line_left = l->left;
- l->line_right = l->right;
- l->y = top + bt + pt;
- if (doc.nodes[node].tag == BR_TAG_HR) {
- if (l->draw)
- ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
- l->y + 2, l->right - l->left, 1}, BR_GRAY);
- l->y += 8;
- } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
- int vw = l->right - l->left;
- int vh;
- if (doc.nodes[node].width_pct)
- vw = vw * doc.nodes[node].width_attr / 100;
- else if (doc.nodes[node].width_attr)
- vw = doc.nodes[node].width_attr;
- if (vw > l->right - l->left)
- vw = l->right - l->left;
- if (vw < 8)
- vw = 8;
- vh = vw * 9 / 16;
- if (vh > 240)
- vh = 240;
- if (vh < 80)
- vh = 80;
- if (l->draw) {
- ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
- vw, vh}, 0xD69A);
- ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
- vw, vh}, 0x8410);
- ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
- 0x4208);
- }
- l->y += vh + 4;
- } else if (doc.nodes[node].tag == BR_TAG_SVG) {
- int dw, dh, cw = l->right - l->left;
- svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
- if (l->draw && l->y < page_rect.y + page_rect.h &&
- l->y + dh > page_rect.y)
- svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
- l->y += dh;
- } else {
- if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
- !st->no_bullet) {
- char *m = li_marker[node];
- if (!m[0]) {
- unsigned int parent = doc.nodes[node].parent;
- int style = st->list_style;
- int idx = parent ? list_index(parent, node) : 1;
- if (style == BR_LIST_AUTO)
- style = (parent &&
- doc.nodes[parent].tag ==
- BR_TAG_OL) ?
- BR_LIST_DECIMAL : BR_LIST_DISC;
- list_marker_text(m, sizeof(li_marker[node]),
- style, idx);
- }
- if (l->draw && m[0]) {
- int mw = (int)ngui_text_width_ui(l->ui, m);
- ngui_text(l->ui, l->left - mw - 6, l->y, m,
- st->color);
- }
- }
- /* This box's definite content height, for its children's
- * percentage heights. */
- if (doc.nodes[node].tag == BR_TAG_HTML ||
- doc.nodes[node].tag == BR_TAG_BODY)
- l->cb_h = layout_view_h;
- else if (st->height_kind == 1)
- l->cb_h = (int)st->height -
- (st->box_sizing ? deco_h : 0);
- else if (st->height_kind == 2 && parent_cb_h > 0)
- l->cb_h = parent_cb_h * (int)st->height / 100 -
- (st->box_sizing ? deco_h : 0);
- else if (!st->height_kind && st->aspect_w && st->aspect_h)
- l->cb_h = content_w * (int)st->aspect_h /
- (int)st->aspect_w;
- else if (!st->height_kind && node < BR_MAX_NODES &&
- flex_stretch_h[node] > deco_h)
- l->cb_h = flex_stretch_h[node] - deco_h;
- else
- l->cb_h = 0;
- if (l->cb_h < 0)
- l->cb_h = 0;
- if (doc.nodes[node].tag == BR_TAG_TR)
- layout_table_row(l, node, st, depth + 1, link);
- else if (doc.nodes[node].tag == BR_TAG_TABLE &&
- table_has_rowspan(node))
- layout_table(l, node, st, depth + 1, link);
- else if (st->grid_auto)
- layout_grid_auto(l, node, st, depth + 1, link);
- else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
- st->grid_gap > 0)
- layout_grid_children(l, node, st, depth + 1, link);
- else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
- flex_wants_row(node, st))
- layout_flex_children(l, node, st, depth + 1, link);
- else if (st->display == BR_DISPLAY_FLEX && st->flex_col)
- layout_flex_column(l, node, st, depth + 1, link);
- else
- layout_children(l, node, st, depth + 1, link);
- l->cb_h = parent_cb_h;
- }
- flush_line(l);
- if (clip_pushed)
- ngui_pop_clip(l->ui);
- if (l->float_active) {
- if (l->y < l->float_bottom)
- l->y = l->float_bottom;
- l->float_active = 0;
- }
- if (doc.nodes[node].tag == BR_TAG_IMG) {
- content_h = img_dh;
- } else if (st->height_kind == 2 &&
- doc.nodes[node].tag != BR_TAG_HTML &&
- doc.nodes[node].tag != BR_TAG_BODY) {
- /* A percentage of the containing block's definite height, or
- * auto when it has none (it used to resolve against the
- * width). The result is a minimum: without scrollable inner
- * boxes, an app shell's height:100%; overflow:hidden column
- * would otherwise clip everything past the first screen. */
- int auto_h = l->y - (top + bt + pt);
- content_h = parent_cb_h > 0 ?
- parent_cb_h * (int)st->height / 100 -
- (st->box_sizing ? deco_h : 0) : 0;
- if (content_h < auto_h)
- content_h = auto_h;
- } else if (st->height_kind &&
- !((doc.nodes[node].tag == BR_TAG_HTML ||
- doc.nodes[node].tag == BR_TAG_BODY) &&
- st->height_kind == 2)) {
- content_h = style_height_px(st, cbw);
- if (st->box_sizing)
- content_h -= deco_h;
- } else {
- /* Percentage heights on html/body resolve against the
- * viewport, but their content still defines the document
- * scroll height. Treating them as auto avoids collapsing
- * the measured page to the containing block width. */
- content_h = l->y - (top + bt + pt);
- /* aspect-ratio: the preferred height of an auto-height box
- * (Tailwind aspect-video image frames); content can still
- * make it taller, as with min-height: auto. */
- if (st->aspect_w && st->aspect_h && content_w > 0) {
- int ah = content_w * (int)st->aspect_h /
- (int)st->aspect_w;
- if (content_h < ah)
- content_h = ah;
- }
- }
- if (content_h < 0)
- content_h = 0;
- if (!st->height_kind && node < BR_MAX_NODES &&
- content_h + deco_h < flex_stretch_h[node])
- content_h = flex_stretch_h[node] - deco_h;
- if (st->max_height_kind) {
- int mh = st->max_height_kind == 3 ?
- cbw * st->max_height_calc_pct / 100 +
- st->max_height_calc_px :
- css_size(st->max_height_kind, st->max_height, cbw);
- int max_box = st->box_sizing ? mh : mh + deco_h;
- if (content_h + deco_h > max_box)
- content_h = max_box - deco_h;
- }
- if (st->min_height_kind &&
- !((doc.nodes[node].tag == BR_TAG_HTML ||
- doc.nodes[node].tag == BR_TAG_BODY) &&
- st->min_height_kind == 2)) {
- int mh = st->min_height_kind == 3 ?
- cbw * st->min_height_calc_pct / 100 +
- st->min_height_calc_px :
- css_size(st->min_height_kind, st->min_height, cbw);
- int min_box = st->box_sizing ? mh : mh + deco_h;
- if (content_h + deco_h < min_box)
- content_h = min_box - deco_h;
- }
- if (content_h < 0)
- content_h = 0;
- box_h = deco_h + content_h;
- if (box_h < 0)
- box_h = 0;
- l->y = (shifted ? normal_top : top) + box_h;
- if (node < BR_MAX_NODES) {
- layout_boxes[node].x = l0;
- layout_boxes[node].y = top;
- layout_boxes[node].w = r0 - l0;
- layout_boxes[node].h = box_h;
- layout_boxes[node].valid = r0 > l0;
- }
- l->left = old_left;
- l->right = old_right;
- l->align = old_align;
- l->y += mp_px(st, 2, cbw);
- if (!l->draw) {
- if (box_h > 65535)
- box_h = 65535;
- block_h[node] = (unsigned short)box_h;
- block_top[node] = (unsigned short)(top < 0 ? 0 :
- top > 65535 ? 65535 : top);
- }
- if (positioned) {
- l->y = flow_y;
- l->left = flow_left;
- l->right = flow_right;
- }
- l->parent_top = saved_parent_top;
- l->cb_left = saved_cb_left;
- l->cb_right = saved_cb_right;
- l->cb_top = saved_cb_top;
- }
- static int text_node_blank(const struct br_node *nd)
- {
- const char *t = doc.text + nd->text_off;
- unsigned int i;
- for (i = 0; i < nd->text_len; i++)
- if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
- t[i] != '\r')
- return 0;
- return 1;
- }
- /* Rough shrink-to-fit width for a float without an explicit width: sum the
- * text/image widths in the subtree, plus padding and margins. This keeps
- * Bootstrap's floated nav items on one line instead of giving each the whole
- * row. */
- static int text_space(char c)
- {
- return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
- }
- static int intrinsic_width(struct ngui *ui, unsigned int node,
- const struct br_style *pst, int depth, int base)
- {
- unsigned int c;
- int line_w = 0, max_w = 0;
- int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
- if (depth > 32)
- return 0;
- if (doc.npe_rules) {
- struct br_style ps;
- /* Icon boxes (::before/::after with a size) are inline
- * content of the element. */
- line_w += pseudo_box_w(node, pst, 1, &ps, base) +
- pseudo_box_w(node, pst, 2, &ps, base);
- }
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- struct br_style cs;
- if (nd->type == BR_NODE_TEXT) {
- const char *t = doc.text + nd->text_off;
- unsigned int tn = nd->text_len;
- if (doc.nodes[node].tag == BR_TAG_PRE) {
- line_w += (int)face_text_width(ui, pst, t, tn);
- } else {
- unsigned int ti = 0;
- int first = 1;
- int lead = line_w > 0 && tn > 0 && text_space(t[0]);
- int sp = (int)face_text_width(ui, pst, " ", 1);
- while (ti < tn) {
- unsigned int ts;
- while (ti < tn && text_space(t[ti]))
- ti++;
- ts = ti;
- while (ti < tn && !text_space(t[ti]))
- ti++;
- if (ti == ts)
- break;
- if (!first || lead)
- line_w += sp;
- lead = 0;
- line_w += (int)face_text_width(ui, pst,
- t + ts, ti - ts);
- first = 0;
- }
- }
- continue;
- }
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- if (nd->tag == BR_TAG_BR) {
- if (line_w > max_w)
- max_w = line_w;
- line_w = 0;
- continue;
- }
- if (nd->tag == BR_TAG_IMG) {
- /* Measure the image as layout will draw it: a CSS or
- * attribute height keeps the intrinsic aspect ratio, and
- * a CSS width overrides the native pixel width. Bootstrap
- * sizes the Cloudron logo with height:40px only. */
- int idx = nd->img_index;
- int iw = 0, ih = 0;
- if (idx >= 0 && idx < image_count &&
- images[idx].state == 1) {
- iw = (int)images[idx].native_w;
- ih = (int)images[idx].native_h;
- if (iw <= 0 || ih <= 0) {
- iw = (int)images[idx].img.w;
- ih = (int)images[idx].img.h;
- }
- }
- if (cs.width_kind) {
- int ww = style_width_px(&cs, base);
- line_w += ww > 0 ? ww : 64;
- } else if (nd->width_attr) {
- line_w += nd->width_attr;
- } else if (nd->height_attr && iw && ih) {
- line_w += iw * (int)nd->height_attr / ih;
- } else if (cs.height_kind && iw && ih) {
- /* A percentage height needs the parent's
- * definite height (the logo's 2rem box), as in
- * add_image_run(); otherwise it is auto. */
- int hh = cs.height_kind == 1 ?
- style_height_px(&cs, base) :
- cs.height_kind == 2 &&
- pst->height_kind == 1 ?
- (int)pst->height * (int)cs.height / 100 :
- 0;
- line_w += hh > 0 ? iw * hh / ih : iw;
- } else if (iw) {
- line_w += iw;
- } else {
- line_w += 64;
- }
- continue;
- }
- if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
- nd->tag == BR_TAG_TEXTAREA) &&
- !s_eq(br_type(&doc, c), "hidden")) {
- /* Form controls are replaced: CSS width applies even
- * when they are inline (add_form_run's sizes). */
- int fw = cs.width_kind ? style_width_px(&cs, base) :
- nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
- if (s_eq(br_type(&doc, c), "checkbox") ||
- s_eq(br_type(&doc, c), "radio"))
- fw = 16;
- line_w += (fw > 0 ? fw : 120) +
- mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
- mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
- continue;
- }
- if (nd->tag == BR_TAG_SVG) {
- /* A replaced element: its own size, like add_svg_run()
- * (its path children have no width). */
- int sw, sh, sb = cs.width_kind ?
- style_width_px(&cs, base) : base;
- svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
- sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
- if (flex_row || cs.display == BR_DISPLAY_INLINE ||
- cs.display == BR_DISPLAY_INLINE_BLOCK) {
- line_w += sw;
- } else {
- if (line_w > max_w)
- max_w = line_w;
- line_w = 0;
- if (sw > max_w)
- max_w = sw;
- }
- continue;
- }
- {
- int cw = mp_px(&cs, 7, base) +
- mp_px(&cs, 5, base) +
- mp_px(&cs, 3, base) +
- mp_px(&cs, 1, base) +
- cs.border_w[1] + cs.border_w[3];
- /* width/height do not apply to non-replaced inline
- * boxes. The tagesschau home label is an inline span
- * with width:1px for the mobile icon-only header; using
- * that width made the whole subnav collapse to a
- * one-character column. */
- if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
- cw += cs.width_kind == 1 ? cs.width :
- style_width_px(&cs, base);
- else
- cw += intrinsic_width(ui, c, &cs, depth + 1,
- base);
- if (flex_row || cs.float_left ||
- cs.display == BR_DISPLAY_INLINE ||
- cs.display == BR_DISPLAY_INLINE_BLOCK) {
- line_w += cw;
- } else {
- if (line_w > max_w)
- max_w = line_w;
- line_w = 0;
- if (cw > max_w)
- max_w = cw;
- }
- }
- if (line_w > 4096 || max_w > 4096)
- break;
- }
- return line_w > max_w ? line_w : max_w;
- }
- /* Lay consecutive floated block children side by side. Bootstrap's grid is
- * the main user: .row > .col-md-* with float:left and a percentage width.
- * Each column is laid out with its own left/right edge and the row advances
- * to the tallest column. Returns the first child not consumed. */
- static unsigned int layout_float_group(struct lay *l, unsigned int first,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n = first;
- int row_left = l->left, row_right = l->right;
- int row_top, row_bottom, xl, xr, any = 0;
- int fl_left = row_left, fl_right = row_right, fl_bottom;
- flush_line(l);
- row_top = l->y;
- row_bottom = l->y;
- fl_bottom = row_top;
- xl = row_left;
- xr = row_right;
- while (n) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- unsigned short lk = link;
- int colw, right;
- if (nd->type == BR_NODE_TEXT) {
- if (text_node_blank(nd)) {
- n = nd->next;
- continue;
- }
- break;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE) {
- n = nd->next;
- continue;
- }
- /* A float blockifies its box: Bootstrap floats inline
- * anchors too (the navbar brand and its text links), and
- * their padding must be honoured. */
- if (!cs.float_left)
- break;
- if (nd->tag == BR_TAG_A && nd->href_off)
- lk = (unsigned short)n;
- right = cs.float_left == 2;
- if (cs.width_kind == 1 || cs.width_kind == 2 ||
- cs.width_kind == 3) {
- /* The column is the margin box: `width` is the
- * content (or, with border-box, the border) box,
- * and layout_block() takes margins, padding and
- * borders back out of the column. A 200px float
- * with margin-right:20px used to get 180px of
- * content. */
- int base = row_right - row_left;
- colw = cs.width_kind == 1 ? (int)cs.width :
- style_width_px(&cs, base);
- colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
- if (!cs.box_sizing)
- colw += mp_px(&cs, 7, base) +
- mp_px(&cs, 5, base) +
- cs.border_w[1] + cs.border_w[3];
- } else {
- int base = row_right - row_left;
- /* Shrink-to-fit outer width: borders too (Google's
- * 1px-bordered "Anmelden" pill wrapped otherwise). */
- colw = intrinsic_width(l->ui, n, &cs, 0, base) +
- mp_px(&cs, 7, base) +
- mp_px(&cs, 5, base) +
- mp_px(&cs, 3, base) +
- mp_px(&cs, 1, base) +
- cs.border_w[1] + cs.border_w[3];
- if (colw < 8)
- colw = 8;
- }
- if (colw < 8)
- colw = 8;
- if (colw > row_right - row_left)
- colw = row_right - row_left;
- /* The float column width is already resolved. */
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- if (right) {
- if (any && xr - colw < xl) {
- row_top = row_bottom;
- row_bottom = row_top;
- xl = row_left;
- xr = row_right;
- }
- if (xr - colw < xl)
- colw = xr - xl;
- if (colw < 8)
- colw = 8;
- l->left = xr - colw;
- if (l->left < row_left)
- l->left = row_left;
- l->right = xr;
- xr = l->left;
- if (xr < fl_right)
- fl_right = xr;
- } else {
- if (any && xl + colw > xr) {
- row_top = row_bottom;
- row_bottom = row_top;
- xl = row_left;
- xr = row_right;
- }
- l->left = xl;
- l->right = xl + colw;
- xl += colw;
- if (xl > fl_left)
- fl_left = xl;
- }
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->y = row_top;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, n, &cs, depth + 1, lk);
- if (l->y > row_bottom)
- row_bottom = l->y;
- if (l->y > fl_bottom)
- fl_bottom = l->y;
- any = 1;
- n = nd->next;
- }
- l->left = row_left;
- l->right = row_right;
- if (n && any) {
- struct br_node *nd = &doc.nodes[n];
- int inline_next = 0;
- if (nd->type == BR_NODE_TEXT) {
- inline_next = 1;
- } else if (nd->type == BR_NODE_ELEM) {
- struct br_style cs;
- br_style_for(&doc, n, pst, &cs);
- inline_next = cs.display != BR_DISPLAY_BLOCK &&
- cs.display != BR_DISPLAY_NONE &&
- !br_tag_is_block(nd->tag);
- }
- if (inline_next) {
- if (l->float_active) {
- if (l->float_left > fl_left)
- fl_left = l->float_left;
- if (l->float_right < fl_right)
- fl_right = l->float_right;
- if (l->float_bottom > fl_bottom)
- fl_bottom = l->float_bottom;
- }
- l->float_active = 1;
- l->float_left = fl_left;
- l->float_right = fl_right;
- l->float_bottom = fl_bottom;
- l->y = row_top;
- } else {
- l->float_active = 0;
- l->y = row_bottom;
- }
- } else {
- l->float_active = 0;
- l->y = row_bottom;
- }
- l->line_x = l->left;
- l->run_x = l->left;
- l->line_left = l->left;
- l->line_right = l->right;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- return n;
- }
- static int flex_item_width(struct lay *l, unsigned int n,
- const struct br_style *cs, int avail)
- {
- struct br_node *nd = &doc.nodes[n];
- (void)l;
- int w;
- if (cs->width_kind == 2 || cs->width_kind == 3)
- w = style_width_px(cs, avail);
- else if (cs->width_kind == 1)
- w = (int)cs->width;
- else if (nd->tag == BR_TAG_IMG) {
- int idx = nd->img_index;
- if (idx >= 0 && idx < image_count &&
- images[idx].state == 1)
- w = (int)images[idx].img.w;
- else if (nd->width_attr)
- w = (int)nd->width_attr;
- else
- w = 64;
- } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
- nd->tag == BR_TAG_TEXTAREA) {
- /* A control has no content to measure: its default size
- * (a search field in a filter bar). */
- w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
- } else {
- w = intrinsic_width(l->ui, n, cs, 0, avail);
- }
- /* Explicit widths are content-box sizes; the flex item's outer width
- * must include padding, borders and margins. */
- w += mp_px(cs, 7, avail);
- w += mp_px(cs, 5, avail);
- w += mp_px(cs, 3, avail);
- w += mp_px(cs, 1, avail);
- w += cs->border_w[1] + cs->border_w[3];
- if (w < 24)
- w = 24;
- if (w > avail)
- w = avail;
- return w;
- }
- static int inline_block_flows(unsigned int node, const struct br_style *cs,
- int depth);
- /* An inline child of a text-only inline-block: the same test minus the
- * display check (an inline <span> may have padding/background in CSS, but
- * the inline path paints those for spans anyway). */
- static int inline_block_flows_inline(unsigned int node,
- const struct br_style *cs, int depth)
- {
- unsigned int c;
- if (depth > 3 || cs->pos)
- return 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- const struct br_node *nd = &doc.nodes[c];
- struct br_style ch;
- if (nd->type != BR_NODE_ELEM)
- continue;
- if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
- br_tag_is_block(nd->tag))
- return 0;
- br_style_for(&doc, c, cs, &ch);
- if (ch.display == BR_DISPLAY_NONE)
- continue;
- if (ch.display != BR_DISPLAY_INLINE ||
- !inline_block_flows_inline(c, &ch, depth + 1))
- return 0;
- }
- return 1;
- }
- /* An inline-block that is only text in a line (a <time> in a byline, a
- * label) with no box of its own -- no size, background, border or padding
- * -- lays out exactly like an inline element, so it stays in the text line
- * instead of ending it. Boxes with any of those keep the row path. */
- static int inline_block_flows(unsigned int node, const struct br_style *cs,
- int depth)
- {
- unsigned int c;
- int i;
- if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
- cs->min_height_kind || cs->has_bg || cs->bg_image ||
- cs->pos || depth > 3)
- return 0;
- for (i = 0; i < 4; i++)
- if (cs->border_w[i])
- return 0;
- for (i = 4; i < 8; i++)
- if (mp_px(cs, i, 0) > 0)
- return 0;
- for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
- const struct br_node *nd = &doc.nodes[c];
- struct br_style ch;
- if (nd->type != BR_NODE_ELEM)
- continue;
- if (nd->tag == BR_TAG_SVG) {
- /* An icon box (Docusaurus' admonition heading:
- * `<span inline-block><svg/></span>Note`): the SVG
- * is an inline replaced run, so the box can stay in
- * the text line. */
- br_style_for(&doc, c, cs, &ch);
- if (ch.display == BR_DISPLAY_NONE ||
- ch.display == BR_DISPLAY_INLINE ||
- ch.display == BR_DISPLAY_INLINE_BLOCK)
- continue;
- return 0;
- }
- if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
- return 0;
- br_style_for(&doc, c, cs, &ch);
- if (ch.display == BR_DISPLAY_NONE)
- continue;
- if (ch.display != BR_DISPLAY_INLINE ||
- !inline_block_flows_inline(c, &ch, depth + 1))
- return 0;
- }
- return 1;
- }
- /* A run of display:inline-block siblings (file tags, small buttons) belongs
- * on one line, not one full-width block each. Place intrinsic widths from
- * left to right and wrap when the row is full. */
- static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n = first;
- int row_left = l->left, row_right = l->right;
- int avail = row_right - row_left;
- int x = row_left, y = l->y, row_h = 0, any = 0;
- /* Each box sets l->align from its own style; the text after the row
- * must keep the container's (a centred .fa-fw icon centred the menu
- * label that followed it). */
- unsigned char row_align = l->align;
- flush_line(l);
- y = l->y;
- while (n) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- unsigned short lk = link;
- int colw, h;
- if (nd->type == BR_NODE_TEXT) {
- if (!text_node_blank(nd))
- break;
- if (any)
- x += 4;
- n = nd->next;
- continue;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE) {
- n = nd->next;
- continue;
- }
- if (cs.display != BR_DISPLAY_INLINE_BLOCK)
- break;
- if (nd->tag == BR_TAG_A && nd->href_off)
- lk = (unsigned short)n;
- colw = flex_item_width(l, n, &cs, avail);
- /* A few pixels of slack keep a single long token (boot.S)
- * from wrapping at the exact content width. */
- colw += 8;
- if (colw > avail)
- colw = avail;
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- if (any && x + colw > row_right) {
- y += row_h + 2;
- x = row_left;
- row_h = 0;
- any = 0;
- }
- if (any && x > row_left)
- x += 4;
- l->left = x;
- l->right = x + colw;
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->y = y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, n, &cs, depth + 1, lk);
- h = l->y - y;
- if (h > row_h)
- row_h = h;
- x += colw;
- any = 1;
- n = nd->next;
- }
- if (any)
- y += row_h;
- l->left = row_left;
- l->right = row_right;
- l->align = row_align;
- l->y = y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- return n;
- }
- struct flex_item {
- unsigned int node;
- unsigned short link;
- int w;
- };
- /* An item's min-width/max-width as outer (margin-box) widths in the flex
- * row, or -1 when unset. Percentages and calc() resolve against the
- * container width. */
- static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
- {
- unsigned char kind = which_max ? cs->max_width_kind :
- cs->min_width_kind;
- int w;
- if (kind == 3)
- w = which_max ?
- avail * cs->max_width_calc_pct / 100 +
- cs->max_width_calc_px :
- avail * cs->min_width_calc_pct / 100 +
- cs->min_width_calc_px;
- else
- w = css_size(kind, which_max ? cs->max_width : cs->min_width,
- avail);
- if (w < 0)
- return -1;
- if (!cs->box_sizing)
- w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
- cs->border_w[1] + cs->border_w[3];
- return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
- }
- static int flex_clamp_w(const struct br_style *cs, int w, int avail)
- {
- int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
- if (mx >= 0 && w > mx)
- w = mx;
- if (mn >= 0 && w < mn)
- w = mn;
- return w;
- }
- /* Does a flex row stretch this item to the line height? Only items with
- * no height of their own and align-self/align-items stretch; replaced
- * content (images, icons) keeps its aspect ratio. */
- static int flex_item_stretches(unsigned int node, const struct br_style *cs,
- const struct br_style *pst)
- {
- int ai = cs->align_self ? cs->align_self - 1 : pst->align_items;
- unsigned char tag = doc.nodes[node].tag;
- return ai == 0 && !cs->height_kind && !cs->max_height_kind &&
- tag != BR_TAG_IMG && tag != BR_TAG_SVG && tag != BR_TAG_INPUT &&
- tag != BR_TAG_SELECT && tag != BR_TAG_TEXTAREA &&
- tag != BR_TAG_BUTTON;
- }
- static void flex_set_stretch(unsigned int node, const struct br_style *cs,
- int line_h, int cbw)
- {
- int h = line_h - mp_px(cs, 0, cbw) - mp_px(cs, 2, cbw);
- if (node >= BR_MAX_NODES || h <= 0)
- return;
- if (h > 65535)
- h = 65535;
- flex_stretch_h[node] = (unsigned short)h;
- if (block_h[node] < h)
- block_h[node] = (unsigned short)h;
- }
- static void layout_flex_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- struct flex_item it[32];
- unsigned int c;
- int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
- int grow_need = 0; /* growing items at their content width */
- int row_left = l->left, row_right = l->right;
- int avail = row_right - row_left;
- int idx, row_top;
- unsigned char row_align = l->align;
- int box_left = l->left, box_right = l->right, row_top0 = l->y;
- int bw = 0, aw = 0, first_h = -1;
- int cont_h = l->cb_h; /* the container's definite content height */
- struct br_style bps, aps;
- if (avail < 8 || depth > 48) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- /* If direct text is not just whitespace, normal block flow handles it
- * better than pretending it is a flex item. */
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- }
- /* ::before/::after icon boxes are the row's first and last items
- * (Docusaurus' sidebar chevron): reserve their columns. */
- if (doc.npe_rules) {
- bw = pseudo_box_w(parent, pst, 1, &bps, avail);
- aw = pseudo_box_w(parent, pst, 2, &aps, avail);
- if (bw + aw > avail - 8) {
- bw = 0;
- aw = 0;
- }
- row_left += bw;
- row_right -= aw;
- avail = row_right - row_left;
- }
- for (c = doc.nodes[parent].first;
- c && nitem < (int)(sizeof(it) / sizeof(it[0]));
- c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- struct br_style cs;
- if (nd->type == BR_NODE_TEXT)
- continue;
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- if ((cs.pos == 1 || cs.pos == 2) &&
- layout_out_of_flow(l, c, &cs, depth,
- (nd->tag == BR_TAG_A && nd->href_off) ?
- (unsigned short)c : link))
- continue; /* absolutely positioned: not an item */
- it[nitem].node = c;
- it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
- (unsigned short)c : link;
- it[nitem].w = 0;
- if (cs.flex_grow && !cs.width_kind) {
- grow_count++;
- grow_need += flex_item_width(l, c, &cs, avail);
- } else
- fixed += flex_clamp_w(&cs,
- flex_item_width(l, c, &cs, avail),
- avail);
- nitem++;
- }
- /* A narrow container (an icon row sized to its content, Google's
- * mic + lens buttons) is still a row when its items fit; only a
- * narrow one that would overflow or squeeze growing items falls
- * back to block flow. */
- if (avail < 160 && fixed + grow_need > avail) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- grow_w = grow_count ? (avail - fixed) / grow_count : 0;
- /* A growing item capped by max-width (Docusaurus' doc column,
- * `max-width: 75%`; its main container, `calc(100% - 300px)`)
- * keeps its cap and leaves the rest of the free space to the other
- * growing items. */
- if (grow_count) {
- int pass, capped[32] = { 0 };
- for (pass = 0; pass < nitem; pass++) {
- int changed = 0;
- for (idx = 0; idx < nitem; idx++) {
- struct br_style cs;
- int lim;
- if (capped[idx])
- continue;
- br_style_for(&doc, it[idx].node, pst, &cs);
- if (!cs.flex_grow || cs.width_kind)
- continue;
- lim = flex_clamp_w(&cs, grow_w, avail);
- if (lim == grow_w)
- continue;
- capped[idx] = lim + 1;
- fixed += lim;
- grow_count--;
- changed = 1;
- }
- if (!changed || !grow_count)
- break;
- grow_w = (avail - fixed) / grow_count;
- }
- for (idx = 0; idx < nitem; idx++)
- it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
- }
- if (grow_w < 96 && avail >= 160)
- grow_w = 96;
- for (idx = 0; idx < nitem; idx++) {
- struct br_style cs;
- if (it[idx].w)
- continue; /* capped growing item */
- br_style_for(&doc, it[idx].node, pst, &cs);
- if (cs.flex_grow && !cs.width_kind)
- it[idx].w = grow_w;
- else
- it[idx].w = flex_clamp_w(&cs,
- flex_item_width(l,
- it[idx].node,
- &cs, avail),
- avail);
- if (it[idx].w > avail)
- it[idx].w = avail;
- if (it[idx].w < 8)
- it[idx].w = 8;
- }
- row_top = l->y;
- idx = 0;
- while (idx < nitem) {
- int start = idx, count = 0, row_w = 0;
- int free_w, x, extra = 0, row_h = 0, k;
- while (idx < nitem) {
- int add = it[idx].w + (count ? gap : 0);
- /* CSS default is nowrap; only flex-wrap: wrap (1)
- * starts a new row. */
- if (count && pst->flex_wrap == 1 &&
- row_w + add > avail)
- break;
- row_w += add;
- count++;
- idx++;
- }
- if (!count) {
- count = 1;
- row_w = it[start].w;
- idx = start + 1;
- }
- free_w = avail - row_w;
- if (free_w < 0)
- free_w = 0;
- x = row_left;
- if (pst->justify == 1) {
- x += free_w / 2;
- } else if (pst->justify == 2) {
- x += free_w;
- } else if (pst->justify == 3) {
- extra = count > 1 ? free_w / (count - 1) : 0;
- } else if (pst->justify == 4) {
- extra = count ? free_w / count : 0;
- x += extra / 2;
- } else if (pst->justify == 5) {
- extra = count ? free_w / (count + 1) : 0;
- x += extra;
- }
- for (k = 0; k < count; k++) {
- int node = (int)it[start + k].node;
- int h = block_h[node];
- if (h > row_h)
- row_h = h;
- }
- /* A single line fills a definite container height (an app
- * shell's `height: 100%` sidebar + content row). */
- if (pst->flex_wrap != 1 && cont_h > row_h)
- row_h = cont_h;
- else if (pst->height_kind == 1 && (int)pst->height > row_h)
- row_h = pst->height;
- for (k = 0; k < count; k++) {
- struct br_style cs;
- int node = (int)it[start + k].node;
- int yoff = 0;
- br_style_for(&doc, node, pst, &cs);
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- /* align-items: stretch. With a definite line height
- * the item is laid out at it, so its own children see
- * a definite height; otherwise the measure pass
- * stretches it once the line is known (below). */
- if (!l->draw && row_h > 0 && flex_item_stretches(node,
- &cs, pst))
- flex_set_stretch(node, &cs, row_h, avail);
- {
- int ai = cs.align_self ? cs.align_self - 1 :
- pst->align_items;
- if (l->draw && ai && row_h > block_h[node]) {
- if (ai == 1)
- yoff = (row_h -
- block_h[node]) / 2;
- else if (ai == 2)
- yoff = row_h - block_h[node];
- }
- }
- l->left = x;
- l->right = x + it[start + k].w;
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->y = row_top + yoff;
- /* line_left too: a stale one from the previous item
- * made flush_line() see a non-empty line and push
- * every later item down by an empty line's height. */
- l->line_left = l->line_x = l->run_x = l->left;
- l->line_right = l->right;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, node, &cs, depth + 1, it[start + k].link);
- {
- /* Both passes: a form control item has no
- * block_h of its own, so the draw pass would
- * otherwise end a row of only an <input> at
- * height 0 and pull the content below up. */
- int h = l->y - row_top;
- if (h > row_h)
- row_h = h;
- }
- x += it[start + k].w;
- if (k + 1 < count)
- x += gap + extra;
- }
- if (!l->draw) {
- for (k = 0; k < count; k++) {
- struct br_style cs;
- int node = (int)it[start + k].node;
- br_style_for(&doc, node, pst, &cs);
- if (!flex_item_stretches(node, &cs, pst))
- continue;
- /* To the line's bottom edge from where the
- * item really starts (its top margin, or a
- * line box above it). */
- if (layout_boxes[node].valid)
- flex_set_stretch(node, &cs,
- row_top + row_h -
- layout_boxes[node].y +
- mp_px(&cs, 0, avail), avail);
- else
- flex_set_stretch(node, &cs, row_h, avail);
- }
- }
- if (first_h < 0)
- first_h = row_h;
- row_top += row_h;
- }
- if (bw || aw) {
- int pass;
- for (pass = 0; pass < 2; pass++) {
- const struct br_style *ps = pass ? &aps : &bps;
- int a = pass ? row_right : box_left;
- int b = pass ? box_right : row_left;
- int h = ps->height_kind ?
- style_height_px(ps, box_right - box_left) : 0;
- if (!(pass ? aw : bw))
- continue;
- l->left = l->line_left = l->line_x = l->run_x = a;
- l->right = l->line_right = b;
- l->y = row_top0;
- if (pst->align_items == 1 && first_h > h)
- l->y += (first_h - h) / 2;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- emit_pseudo_box(l, pst, ps, link);
- flush_line(l);
- /* The box sits inside the first row; it only makes
- * the row taller when it is taller itself. */
- if (row_top0 + h > row_top)
- row_top = row_top0 + h;
- }
- }
- l->left = box_left;
- l->right = box_right;
- l->align = row_align;
- l->y = row_top;
- l->line_left = l->line_x = l->run_x = l->left;
- l->line_right = l->right;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- }
- /* flex-direction: column. Items stack in order with the gap and never
- * collapse margins. In the draw pass justify-content shares out the free
- * height of the container's measured box (a definite or min-height, or a
- * row stretch), and align-items places each item: stretch (the default)
- * fills the line, start/center/end shrink an item to its content width
- * (a login form's "Log in" button, a centred logo and name). */
- static void layout_flex_column(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int c;
- int box_left = l->left, box_right = l->right;
- int avail = box_right - box_left;
- int gap = pst->grid_gap, y0 = l->y;
- int n = 0, k = 0, total = 0, lead = 0, extra = 0;
- unsigned char row_align = l->align;
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- if (nd->type == BR_NODE_TEXT && !text_node_blank(nd))
- break;
- }
- if (c || avail < 8 || depth > 48) {
- /* Loose text: block flow, with centred lines standing in
- * for align-items: center. */
- struct br_style cst = *pst;
- if (pst->align_items == 1) {
- cst.align = BR_ALIGN_CENTER;
- l->align = BR_ALIGN_CENTER;
- }
- layout_children(l, parent, &cst, depth, link);
- return;
- }
- emit_pseudo(l, parent, pst, 1, link);
- flush_line(l);
- y0 = l->y;
- if (l->draw && parent < BR_MAX_NODES && block_h[parent]) {
- int inner = (int)block_h[parent] - pst->border_w[0] -
- pst->border_w[2] - mp_px(pst, 4, avail) -
- mp_px(pst, 6, avail) - (y0 - l->parent_top -
- pst->border_w[0] - mp_px(pst, 4, avail));
- int free_h;
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_style cs;
- if (doc.nodes[c].type != BR_NODE_ELEM)
- continue;
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE || cs.pos == 1 ||
- cs.pos == 2)
- continue;
- total += block_h[c] + mp_px(&cs, 0, avail) +
- mp_px(&cs, 2, avail);
- n++;
- }
- if (n > 1)
- total += gap * (n - 1);
- free_h = inner - total;
- if (n && free_h > 0) {
- if (pst->justify == 1) {
- lead = free_h / 2;
- } else if (pst->justify == 2) {
- lead = free_h;
- } else if (pst->justify == 3) {
- extra = n > 1 ? free_h / (n - 1) : 0;
- } else if (pst->justify == 4) {
- extra = free_h / n;
- lead = extra / 2;
- } else if (pst->justify == 5) {
- extra = free_h / (n + 1);
- lead = extra;
- }
- }
- }
- l->y = y0 + lead;
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- unsigned short lk = (nd->tag == BR_TAG_A && nd->href_off) ?
- (unsigned short)c : link;
- struct br_style cs;
- int ai, left = box_left, right = box_right;
- if (nd->type != BR_NODE_ELEM)
- continue;
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- if ((cs.pos == 1 || cs.pos == 2) &&
- layout_out_of_flow(l, c, &cs, depth, lk))
- continue;
- if (k++)
- l->y += gap + extra;
- ai = cs.align_self ? cs.align_self - 1 : pst->align_items;
- if (ai) {
- int w = flex_clamp_w(&cs, flex_item_width(l, c, &cs,
- avail),
- avail);
- if (ai == 1)
- left += (avail - w) / 2;
- else if (ai == 2)
- left += avail - w;
- right = left + w;
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- }
- l->left = l->line_left = l->line_x = l->run_x = left;
- l->right = l->line_right = right;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, c, &cs, depth + 1, lk);
- }
- l->left = l->line_left = l->line_x = l->run_x = box_left;
- l->right = l->line_right = box_right;
- l->align = row_align;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- emit_pseudo(l, parent, pst, 2, link);
- }
- /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
- * plus the grid-area hints used by site shells (site notice/footer full
- * width, column-start left, page-content right). Anything more elaborate
- * falls back to normal block flow. */
- static int grid_track_width(unsigned char kind, unsigned short val,
- int avail, int other)
- {
- if (kind == 2)
- return avail * (int)val / 100;
- if (kind == 1)
- return val;
- return other;
- }
- static void layout_grid_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n;
- int row_left = l->left, row_right = l->right;
- int avail = row_right - row_left;
- int gap = pst->grid_gap;
- int track_total = avail - gap;
- int col0, col1, x0, x1;
- int row_y, row_bottom, have_left = 0, have_right = 0;
- unsigned int c;
- if (avail < 32 || depth > 48)
- return;
- if (track_total < 16)
- track_total = 16;
- col0 = grid_track_width((unsigned char)(pst->width_kind),
- pst->width, track_total, 0);
- col1 = grid_track_width((unsigned char)(pst->max_width_kind),
- pst->max_width, track_total, 0);
- if (pst->width_kind == 3 && pst->max_width_kind == 3) {
- int w0 = pst->width ? pst->width : 1;
- int w1 = pst->max_width ? pst->max_width : 1;
- col0 = track_total * w0 / (w0 + w1);
- col1 = track_total - col0;
- } else if (pst->width_kind == 3) {
- col0 = track_total - col1;
- if (col0 < 24)
- col0 = 24;
- } else if (pst->max_width_kind == 3) {
- col1 = track_total - col0;
- if (col1 < 24)
- col1 = 24;
- }
- if (col0 < 24)
- col0 = 24;
- if (col1 < 24)
- col1 = 24;
- if (col0 + col1 > track_total) {
- col1 = track_total - col0;
- if (col1 < 24)
- col1 = 24;
- }
- x0 = row_left;
- x1 = row_left + col0 + gap;
- /* Direct text makes a grid ambiguous; use block flow instead. */
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- }
- row_y = row_bottom = l->y;
- n = doc.nodes[parent].first;
- while (n) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- unsigned short lk = link;
- int slot, x, w;
- if (nd->type == BR_NODE_TEXT) {
- n = nd->next;
- continue;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE) {
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_A && nd->href_off)
- lk = (unsigned short)n;
- slot = cs.grid_slot;
- if (!slot) {
- if (!have_left)
- slot = 2;
- else if (!have_right)
- slot = 3;
- else
- slot = 2;
- }
- if (slot == 1) {
- if (have_left || have_right) {
- row_y = row_bottom;
- have_left = have_right = 0;
- }
- x = row_left;
- w = avail;
- } else if (slot == 2) {
- if (have_left) {
- row_y = row_bottom;
- have_left = have_right = 0;
- }
- x = x0;
- w = col0;
- have_left = 1;
- } else {
- if (have_right) {
- row_y = row_bottom;
- have_left = have_right = 0;
- }
- x = x1;
- w = col1;
- have_right = 1;
- }
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- l->left = x;
- l->right = x + w;
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->y = row_y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, n, &cs, depth + 1, lk);
- if (l->y > row_bottom)
- row_bottom = l->y;
- n = nd->next;
- }
- l->left = row_left;
- l->right = row_right;
- l->y = row_bottom;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- }
- /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
- * capped at four. Used by the project docs' card grids. A fixed
- * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
- static void layout_grid_auto(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n, c;
- int row_left = l->left, row_right = l->right;
- int avail = row_right - row_left;
- int gap = pst->grid_gap;
- int minw = pst->width_kind == 1 ? pst->width : 200;
- int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
- if (avail < 32 || depth > 48) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
- struct br_node *nd = &doc.nodes[c];
- if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
- layout_children(l, parent, pst, depth, link);
- return;
- }
- }
- if (minw < 80)
- minw = 80;
- ncols = (avail + gap) / (minw + gap);
- if (ncols < 1)
- ncols = 1;
- if (ncols > 4)
- ncols = 4;
- if (pst->grid_auto > BR_GRID_FIXED) {
- /* grid-template-columns: repeat(N, 1fr) */
- ncols = pst->grid_auto - BR_GRID_FIXED;
- while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
- ncols--;
- }
- colw = (avail - gap * (ncols - 1)) / ncols;
- if (colw < 24)
- colw = 24;
- x = row_left;
- n = doc.nodes[parent].first;
- while (n) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- unsigned short lk = link;
- int h;
- if (nd->type == BR_NODE_TEXT) {
- n = nd->next;
- continue;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE) {
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_A && nd->href_off)
- lk = (unsigned short)n;
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- l->left = x;
- l->right = x + colw;
- if (l->right < l->left + 8)
- l->right = l->left + 8;
- l->y = y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, n, &cs, depth + 1, lk);
- h = l->y - y;
- if (h > row_h)
- row_h = h;
- col++;
- n = nd->next;
- if (col == ncols) {
- y += row_h + gap;
- x = row_left;
- row_h = 0;
- col = 0;
- } else {
- x += colw + gap;
- }
- }
- if (col)
- y += row_h;
- else if (y > start_y)
- y -= gap;
- l->left = row_left;
- l->right = row_right;
- l->y = y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- }
- /* Column widths are the widest cell in each column across every row, so all
- * rows line up. The table model is still deliberately basic: no colspan,
- * border-collapse or percentage columns. */
- static void table_columns(struct lay *l, unsigned int table,
- const struct br_style *pst, int avail,
- int *raw, int maxcols, int *out_cols,
- int *out_total)
- {
- unsigned int r, c;
- int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
- int fixed[12];
- for (c = 0; c < (unsigned int)maxcols; c++) {
- raw[c] = 0;
- fixed[c] = 0;
- }
- /* Intrinsic widths of single-column cells. */
- for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
- struct br_node *rn = &doc.nodes[r];
- int col = 0;
- if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
- continue;
- for (c = rn->first; c; c = doc.nodes[c].next) {
- struct br_node *cn = &doc.nodes[c];
- struct br_style cs;
- int w, span;
- if (cn->type != BR_NODE_ELEM ||
- (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
- continue;
- span = cn->colspan ? cn->colspan : 1;
- br_style_for(&doc, c, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- if (col + span > maxcols)
- span = maxcols - col;
- if (span < 1)
- break;
- w = intrinsic_width(l->ui, c, &cs, 0, avail) +
- mp_px(&cs, 7, avail) +
- mp_px(&cs, 5, avail) +
- mp_px(&cs, 3, avail) +
- mp_px(&cs, 1, avail) +
- cs.border_w[0] + cs.border_w[1] +
- cs.border_w[2] + cs.border_w[3];
- if (w < 24)
- w = 24;
- if (span == 1) {
- if (w > raw[col])
- raw[col] = w;
- }
- if (col + span > cols)
- cols = col + span;
- col += span;
- }
- }
- /* A colspan cell only has to be as wide as the sum of its columns. */
- for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
- struct br_node *rn = &doc.nodes[r];
- int col = 0;
- if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
- continue;
- for (c = rn->first; c; c = doc.nodes[c].next) {
- struct br_node *cn = &doc.nodes[c];
- struct br_style cs;
- int span, w, sum, i;
- if (cn->type != BR_NODE_ELEM ||
- (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
- continue;
- span = cn->colspan ? cn->colspan : 1;
- if (col + span > maxcols)
- span = maxcols - col;
- if (span < 1)
- break;
- if (span > 1) {
- br_style_for(&doc, c, pst, &cs);
- if (cs.display != BR_DISPLAY_NONE) {
- w = intrinsic_width(l->ui, c, &cs,
- 0, avail) +
- mp_px(&cs, 7, avail) +
- mp_px(&cs, 5, avail) +
- mp_px(&cs, 3, avail) +
- mp_px(&cs, 1, avail) +
- cs.border_w[0] + cs.border_w[1] +
- cs.border_w[2] + cs.border_w[3];
- sum = 0;
- for (i = 0; i < span; i++)
- sum += raw[col + i];
- if (w > sum)
- raw[col + span - 1] += w - sum;
- }
- }
- col += span;
- }
- }
- /* Explicit and percentage widths override intrinsic widths. */
- for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
- struct br_node *rn = &doc.nodes[r];
- int col = 0;
- if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
- continue;
- for (c = rn->first; c; c = doc.nodes[c].next) {
- struct br_node *cn = &doc.nodes[c];
- struct br_style cs;
- int span;
- if (cn->type != BR_NODE_ELEM ||
- (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
- continue;
- span = cn->colspan ? cn->colspan : 1;
- if (col + span > maxcols)
- span = maxcols - col;
- if (span < 1)
- break;
- if (span == 1) {
- br_style_for(&doc, c, pst, &cs);
- if (cs.display != BR_DISPLAY_NONE) {
- if (cs.width_kind == 1) {
- raw[col] = cs.width;
- fixed[col] = 1;
- } else if (cs.width_kind == 2 ||
- cs.width_kind == 3) {
- raw[col] = style_width_px(&cs,
- avail);
- fixed[col] = 1;
- }
- }
- }
- col += span;
- }
- }
- for (c = 0; c < (unsigned int)cols; c++) {
- if (raw[c] < 8)
- raw[c] = 8;
- total += raw[c];
- if (fixed[c])
- fixed_sum += raw[c];
- else {
- free_raw += raw[c];
- free_cols++;
- }
- }
- if (fixed_sum > 0 && fixed_sum < avail) {
- int free_avail = avail - fixed_sum;
- int i;
- if (free_raw > 0) {
- for (i = 0; i < cols; i++)
- if (!fixed[i])
- raw[i] = free_avail * raw[i] /
- free_raw;
- } else if (free_cols > 0) {
- for (i = 0; i < cols; i++)
- if (!fixed[i])
- raw[i] = free_avail / free_cols;
- }
- total = 0;
- for (i = 0; i < cols; i++)
- total += raw[i];
- } else if (total < avail && total > 0) {
- int i;
- for (i = 0; i < cols; i++)
- raw[i] = raw[i] * avail / total;
- total = 0;
- for (i = 0; i < cols; i++)
- total += raw[i];
- }
- *out_cols = cols;
- *out_total = total;
- }
- static void layout_table_row(struct lay *l, unsigned int row,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n, cell[12];
- int raw[12], colstart[12], colspan[12];
- int prefix[13];
- int ncell = 0, total = 0, cols = 0, col = 0;
- int row_left = l->left, row_right = l->right;
- int avail = row_right - row_left;
- int y = l->y, bottom = l->y;
- for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- int span;
- if (nd->type == BR_NODE_TEXT) {
- if (text_node_blank(nd))
- continue;
- layout_children(l, row, pst, depth, link);
- return;
- }
- if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
- layout_children(l, row, pst, depth, link);
- return;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- if (ncell >= 12) {
- layout_children(l, row, pst, depth, link);
- return;
- }
- span = nd->colspan ? nd->colspan : 1;
- if (span > 12 - col)
- span = 12 - col;
- if (span < 1)
- continue;
- cell[ncell] = n;
- colstart[ncell] = col;
- colspan[ncell] = span;
- col += span;
- ncell++;
- }
- if (ncell < 1 || avail < 32) {
- layout_children(l, row, pst, depth, link);
- return;
- }
- table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
- &total);
- if (cols < 2 || total <= 0) {
- int c;
- total = 0;
- for (c = 0; c < ncell; c++) {
- struct br_style cs;
- br_style_for(&doc, cell[c], pst, &cs);
- raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
- avail) +
- mp_px(&cs, 7, avail) +
- mp_px(&cs, 5, avail) +
- mp_px(&cs, 3, avail) +
- mp_px(&cs, 1, avail);
- if (raw[c] < 24)
- raw[c] = 24;
- total += raw[c];
- }
- /* A one-column table still has to fill its own width; the
- * intrinsic fallback above otherwise leaves the cell at its
- * text width (HN's outer table and nested story table). */
- if (total > 0 && total < avail) {
- int c;
- for (c = 0; c < ncell; c++)
- raw[c] = raw[c] * avail / total;
- total = avail;
- }
- }
- prefix[0] = row_left;
- for (n = 0; n < (unsigned int)cols && n < 12; n++)
- prefix[n + 1] = prefix[n] + raw[n];
- for (n = 0; n < (unsigned int)ncell; n++) {
- struct br_style cs;
- int start = colstart[n];
- int end = start + colspan[n];
- int w;
- if (end > cols)
- end = cols;
- if (start >= cols)
- continue;
- w = prefix[end] - prefix[start];
- br_style_for(&doc, cell[n], pst, &cs);
- /* The column width already reflects the cell's width property. */
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- if (w < 24)
- w = 24;
- if (w < 8)
- w = 8;
- l->left = prefix[start];
- l->right = l->left + w;
- l->y = y;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, cell[n], &cs, depth + 1, link);
- if (l->y > bottom)
- bottom = l->y;
- }
- l->left = row_left;
- l->right = row_right;
- l->y = bottom;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- }
- #define TBL_MAX_ROWS 32
- #define TBL_MAX_COLS 12
- #define TBL_MAX_CELLS 128
- struct tbl_cell {
- unsigned int node;
- unsigned char row, col, rowspan, colspan;
- int height;
- };
- static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
- static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
- static int table_active;
- static int table_has_rowspan(unsigned int table)
- {
- unsigned int r, c;
- for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
- struct br_node *rn = &doc.nodes[r];
- if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
- continue;
- for (c = rn->first; c; c = doc.nodes[c].next) {
- struct br_node *cn = &doc.nodes[c];
- if (cn->type == BR_NODE_ELEM &&
- (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
- cn->rowspan > 1)
- return 1;
- }
- }
- return 0;
- }
- static void table_cell_style(unsigned int row, unsigned int cell,
- const struct br_style *st, struct br_style *out)
- {
- struct br_style trs;
- br_style_for(&doc, row, st, &trs);
- br_style_for(&doc, cell, &trs, out);
- }
- /* Tables that use rowspan need row heights before anything is painted. This
- * path builds a small occupancy grid, measures the natural cell heights, then
- * lays every cell out at its row/column position. Tables without rowspan
- * keep the lighter per-row path in layout_table_row(). */
- static void layout_table(struct lay *l, unsigned int table,
- const struct br_style *st, int depth,
- unsigned short link)
- {
- unsigned int rows[TBL_MAX_ROWS];
- int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
- int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
- int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
- int free_raw = 0, free_cols = 0;
- int table_left = l->left, table_right = l->right;
- int top = l->y, avail = table_right - table_left;
- unsigned int r, c;
- int i, rr, cc;
- if (depth > 48 || table_active) {
- layout_children(l, table, st, depth, link);
- return;
- }
- table_active = 1;
- for (r = doc.nodes[table].first;
- r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
- struct br_node *rn = &doc.nodes[r];
- if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
- rows[nrows++] = r;
- }
- if (!nrows) {
- table_active = 0;
- layout_children(l, table, st, depth, link);
- return;
- }
- for (rr = 0; rr < nrows; rr++)
- for (cc = 0; cc < TBL_MAX_COLS; cc++)
- tbl_at[rr][cc] = 0;
- for (rr = 0; rr < nrows; rr++) {
- int col = 0;
- for (c = doc.nodes[rows[rr]].first; c;
- c = doc.nodes[c].next) {
- struct br_node *cn = &doc.nodes[c];
- struct br_style cs;
- int rs, csn;
- if (cn->type != BR_NODE_ELEM ||
- (cn->tag != BR_TAG_TD &&
- cn->tag != BR_TAG_TH))
- continue;
- table_cell_style(rows[rr], c, st, &cs);
- if (cs.display == BR_DISPLAY_NONE)
- continue;
- while (col < TBL_MAX_COLS && tbl_at[rr][col])
- col++;
- if (col >= TBL_MAX_COLS)
- break;
- rs = cn->rowspan ? cn->rowspan : 1;
- csn = cn->colspan ? cn->colspan : 1;
- if (rr + rs > nrows)
- rs = nrows - rr;
- if (col + csn > TBL_MAX_COLS)
- csn = TBL_MAX_COLS - col;
- if (rs < 1 || csn < 1)
- continue;
- if (ncells >= TBL_MAX_CELLS)
- break;
- tbl_cells[ncells].node = c;
- tbl_cells[ncells].row = (unsigned char)rr;
- tbl_cells[ncells].col = (unsigned char)col;
- tbl_cells[ncells].rowspan = (unsigned char)rs;
- tbl_cells[ncells].colspan = (unsigned char)csn;
- tbl_cells[ncells].height = 0;
- for (i = rr; i < rr + rs; i++)
- for (int j = col; j < col + csn; j++)
- tbl_at[i][j] =
- (unsigned short)(ncells + 1);
- ncells++;
- col += csn;
- if (col > cols)
- cols = col;
- }
- }
- if (!ncells || cols < 1) {
- table_active = 0;
- layout_children(l, table, st, depth, link);
- return;
- }
- for (i = 0; i < cols; i++) {
- raw[i] = 0;
- fixed[i] = 0;
- }
- /* Intrinsic widths of single-column cells. */
- for (i = 0; i < ncells; i++) {
- struct br_style cs;
- int w;
- table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
- st, &cs);
- w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
- mp_px(&cs, 7, avail) +
- mp_px(&cs, 5, avail) +
- mp_px(&cs, 3, avail) +
- mp_px(&cs, 1, avail) +
- cs.border_w[0] + cs.border_w[1] +
- cs.border_w[2] + cs.border_w[3];
- if (w < 24)
- w = 24;
- if (tbl_cells[i].colspan == 1) {
- int col = tbl_cells[i].col;
- if (w > raw[col])
- raw[col] = w;
- }
- }
- /* A spanning cell only needs the sum of its columns to be large
- * enough; put the deficit in the last column. */
- for (i = 0; i < ncells; i++) {
- struct br_style cs;
- int w, sum, col, span;
- if (tbl_cells[i].colspan < 2)
- continue;
- table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
- st, &cs);
- w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
- mp_px(&cs, 7, avail) +
- mp_px(&cs, 5, avail) +
- mp_px(&cs, 3, avail) +
- mp_px(&cs, 1, avail) +
- cs.border_w[0] + cs.border_w[1] +
- cs.border_w[2] + cs.border_w[3];
- col = tbl_cells[i].col;
- span = tbl_cells[i].colspan;
- sum = 0;
- for (int j = 0; j < span; j++)
- sum += raw[col + j];
- if (w > sum)
- raw[col + span - 1] += w - sum;
- }
- /* Explicit/percentage widths, as in table_columns(). */
- for (i = 0; i < ncells; i++) {
- struct br_style cs;
- int col;
- if (tbl_cells[i].colspan != 1)
- continue;
- table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
- st, &cs);
- col = tbl_cells[i].col;
- if (cs.width_kind == 1) {
- raw[col] = cs.width;
- fixed[col] = 1;
- } else if (cs.width_kind == 2 || cs.width_kind == 3) {
- raw[col] = style_width_px(&cs, avail);
- fixed[col] = 1;
- }
- }
- for (i = 0; i < cols; i++) {
- if (raw[i] < 8)
- raw[i] = 8;
- total += raw[i];
- if (fixed[i])
- fixed_sum += raw[i];
- else {
- free_raw += raw[i];
- free_cols++;
- }
- }
- if (fixed_sum > 0 && fixed_sum < avail) {
- int free_avail = avail - fixed_sum;
- if (free_raw > 0) {
- for (i = 0; i < cols; i++)
- if (!fixed[i])
- raw[i] = free_avail * raw[i] /
- free_raw;
- } else if (free_cols > 0) {
- for (i = 0; i < cols; i++)
- if (!fixed[i])
- raw[i] = free_avail / free_cols;
- }
- } else if (total < avail && total > 0) {
- for (i = 0; i < cols; i++)
- raw[i] = raw[i] * avail / total;
- }
- prefix[0] = table_left;
- for (i = 0; i < cols; i++)
- prefix[i + 1] = prefix[i] + raw[i];
- /* Measure natural cell heights with the column widths. */
- for (i = 0; i < ncells; i++) {
- struct br_style cs;
- int col = tbl_cells[i].col;
- int span = tbl_cells[i].colspan;
- int w = prefix[col + span] - prefix[col];
- int sl = l->left, sr = l->right, sy = l->y;
- int slx = l->line_x, srx = l->run_x, sly = l->line_y;
- int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
- int sal = l->align, sdraw = l->draw;
- struct ngui *sui = l->ui;
- if (w < 8)
- w = 8;
- table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
- st, &cs);
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- l->draw = 0;
- l->ui = 0;
- l->left = prefix[col];
- l->right = l->left + w;
- l->y = 0;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = 0;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
- tbl_cells[i].height = block_h[tbl_cells[i].node];
- l->left = sl;
- l->right = sr;
- l->y = sy;
- l->line_x = slx;
- l->run_x = srx;
- l->line_y = sly;
- l->line_h = slh;
- l->nruns = snr;
- l->space_pending = ssp;
- l->align = sal;
- l->draw = sdraw;
- l->ui = sui;
- }
- for (i = 0; i < nrows; i++)
- rowh[i] = 0;
- for (i = 0; i < ncells; i++) {
- int row = tbl_cells[i].row;
- if (tbl_cells[i].rowspan == 1) {
- if (tbl_cells[i].height > rowh[row])
- rowh[row] = tbl_cells[i].height;
- }
- }
- for (i = 0; i < ncells; i++) {
- int row = tbl_cells[i].row;
- int span = tbl_cells[i].rowspan;
- int sum = 0;
- if (span < 2)
- continue;
- for (int j = 0; j < span; j++)
- sum += rowh[row + j];
- if (sum < tbl_cells[i].height)
- rowh[row + span - 1] +=
- tbl_cells[i].height - sum;
- }
- for (i = 0; i < nrows; i++)
- if (rowh[i] < 8)
- rowh[i] = 8;
- rowy[0] = top;
- for (i = 1; i < nrows; i++)
- rowy[i] = rowy[i - 1] + rowh[i - 1];
- if (!l->draw) {
- l->y = rowy[nrows - 1] + rowh[nrows - 1];
- table_active = 0;
- return;
- }
- for (i = 0; i < ncells; i++) {
- struct br_style cs;
- int col = tbl_cells[i].col;
- int span = tbl_cells[i].colspan;
- int row = tbl_cells[i].row;
- int rspan = tbl_cells[i].rowspan;
- int w = prefix[col + span] - prefix[col];
- int h = 0;
- int sl = l->left, sr = l->right, sy = l->y;
- int slx = l->line_x, srx = l->run_x, sly = l->line_y;
- int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
- int sal = l->align;
- int deco;
- for (int j = 0; j < rspan; j++)
- h += rowh[row + j];
- table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
- cs.width_kind = 0;
- cs.max_width_kind = 0;
- cs.box_sizing = 0;
- deco = mp_px(&cs, 4, avail) +
- mp_px(&cs, 6, avail) +
- cs.border_w[0] + cs.border_w[2];
- cs.height_kind = 1;
- cs.height = h > deco ? h - deco : 0;
- /* The block painter reads block_h[] from the measure pass; make
- * the table cell fill its row/rowspan, not just its content. */
- if (h > 0 && h < 65536)
- block_h[tbl_cells[i].node] = (unsigned short)h;
- l->left = prefix[col];
- l->right = l->left + w;
- l->y = rowy[row];
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = cs.align;
- layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
- l->left = sl;
- l->right = sr;
- l->y = sy;
- l->line_x = slx;
- l->run_x = srx;
- l->line_y = sly;
- l->line_h = slh;
- l->nruns = snr;
- l->space_pending = ssp;
- l->align = sal;
- }
- l->y = rowy[nrows - 1] + rowh[nrows - 1];
- table_active = 0;
- }
- /* Positioned elements (fixed headers, overlays) are drawn after the normal
- * flow so they sit above it, like CSS painting order. Their flow origin is
- * saved for absolute boxes; fixed boxes only need the viewport rect. */
- struct br_deferred {
- unsigned int node;
- int flow_y, flow_left, flow_right;
- int parent_top; /* the parent box top, for sticky clamping */
- unsigned short link;
- signed short z_index;
- unsigned char z_set;
- unsigned int order;
- };
- /* Positioned boxes painted after the flow. News front pages have one or two
- * per teaser (an absolute poster wrapper and its absolute <img>); with the
- * old 16 entries the rest fell back into the flow, so a hero image landed
- * below its padding-top aspect box instead of on top of it. */
- #define BR_MAX_DEFERRED 256
- static struct br_deferred deferred[BR_MAX_DEFERRED];
- static int ndeferred;
- /* Outer width of an element's empty ::before (pe 1) / ::after (pe 2) icon
- * box, 0 when it has none; *ps receives the pseudo-element's style. */
- static int pseudo_box_w(unsigned int node, const struct br_style *st, int pe,
- struct br_style *ps, int base)
- {
- char buf[8];
- int w, h;
- if (!doc.npe_rules ||
- br_pseudo(&doc, node, pe, st, ps, buf, sizeof(buf)) ||
- ps->content != BR_CONTENT_EMPTY || ps->display == BR_DISPLAY_NONE)
- return 0;
- w = ps->width_kind ? style_width_px(ps, base) : 0;
- h = ps->height_kind ? style_height_px(ps, base) : 0;
- if (ps->min_width_kind == 1 && w < (int)ps->min_width)
- w = (int)ps->min_width;
- if (w <= 0)
- w = h;
- if (w <= 0 || w > 512)
- return 0;
- return w + (ps->ml_auto ? 0 : mp_px(ps, 3, base)) + mp_px(ps, 1, base);
- }
- /* An empty ::before/::after with a size and a background: one run the
- * size of the box. Only data: background images are drawn (decoded at
- * the background-size); `margin-left: auto` inside a flex parent pushes
- * the box to the line's right edge like the flex row would. */
- static void emit_pseudo_box(struct lay *l, const struct br_style *parent,
- const struct br_style *ps, unsigned short link)
- {
- struct lay_run *r;
- int lw = l->line_right - l->line_left, w, h, ml, mr, tw, th;
- const char *url = ps->bg_image ? br_bg_image_url(ps->bg_image - 1) : "";
- if (lw < 8)
- lw = 8;
- w = ps->width_kind ? style_width_px(ps, lw) : 0;
- h = ps->height_kind ? style_height_px(ps, lw) : 0;
- if (ps->min_width_kind == 1 && w < (int)ps->min_width)
- w = (int)ps->min_width;
- if (w <= 0)
- w = h;
- if (h <= 0)
- h = w;
- if (w <= 0 || w > 512 || h > 512)
- return;
- ml = ps->ml_auto ? 0 : mp_px(ps, 3, lw);
- mr = mp_px(ps, 1, lw);
- if (ml < 0)
- ml = 0;
- if (mr < 0)
- mr = 0;
- if (l->line_x + ml + w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left))
- flush_line(l);
- if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
- flush_line(l);
- if (l->nruns == 0) {
- l->line_y = l->y;
- l->line_h = 0;
- start_line(l, ps);
- }
- if (ps->ml_auto && parent->display == BR_DISPLAY_FLEX &&
- l->line_right - w - mr > l->line_x)
- l->line_x = l->line_right - w - mr;
- else
- l->line_x += ml;
- r = &l->runs[l->nruns++];
- memset(r, 0, sizeof(*r));
- r->box = l->box_owner;
- r->gap = (unsigned short)(l->line_x > l->run_x ?
- l->line_x - l->run_x : 0);
- r->img = RUN_PBOX;
- r->href = link;
- r->iw = (unsigned short)w;
- r->ih = (unsigned short)h;
- r->w = (unsigned short)w;
- r->font_px = ps->font_px;
- r->pb_has_bg = ps->has_bg;
- r->pb_bg = ps->bg;
- r->pb_img = -1;
- if (ps->transform_set) {
- r->transform_scale = 1;
- r->scale_x = ps->scale_x;
- r->scale_y = ps->scale_y;
- r->rotate_x100 = ps->rotate_x100;
- }
- /* Background size and position, as draw_bg_image() resolves them. */
- tw = w;
- th = h;
- if (ps->bg_size_kind == 1 || ps->bg_size_kind == 2) {
- int bw = ps->bg_size_w, bh = ps->bg_size_h;
- if (ps->bg_size_kind == 2) {
- bw = bw ? w * bw / 100 : 0;
- bh = bh ? h * bh / 100 : 0;
- }
- tw = bw ? bw : (bh ? bh : w);
- th = bh ? bh : tw;
- }
- if (tw > 0 && th > 0 && tw <= 512 && th <= 512 && url[0])
- r->pb_img = (short)data_url_image(url, tw, th);
- r->pb_w = (short)tw;
- r->pb_h = (short)th;
- r->pb_x = (short)(ps->bg_pos_x_kind == 1 ?
- (w - tw) * ps->bg_pos_x / 100 : ps->bg_pos_x);
- r->pb_y = (short)(ps->bg_pos_y_kind == 1 ?
- (h - th) * ps->bg_pos_y / 100 : ps->bg_pos_y);
- l->line_x += w + mr;
- l->run_x = l->line_x;
- if (l->line_h < h)
- l->line_h = h;
- }
- /* ::before/::after generated text (br_pseudo()) as literal runs in the
- * element's line. A block-level pseudo-element gets its own line; its box
- * (margins, padding, background) is not drawn. */
- static void emit_pseudo(struct lay *l, unsigned int node,
- const struct br_style *st, int pe, unsigned short link)
- {
- char buf[160];
- struct br_style ps;
- unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
- unsigned int i = 0;
- int block, space_w;
- if (!n && ps.content == BR_CONTENT_EMPTY &&
- ps.display != BR_DISPLAY_NONE) {
- emit_pseudo_box(l, st, &ps, link);
- return;
- }
- if (!n)
- return;
- block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
- if (block)
- flush_line(l);
- if (ps.uppercase)
- for (i = 0; i < n; i++)
- if (buf[i] >= 'a' && buf[i] <= 'z')
- buf[i] = (char)(buf[i] - 'a' + 'A');
- space_w = (int)face_text_width(l->ui, &ps, " ", 1);
- if (space_w <= 0)
- space_w = 8;
- i = 0;
- while (i < n) {
- char word[28];
- unsigned int k = 0;
- int w;
- if (buf[i] == ' ') {
- l->space_pending = 1;
- i++;
- continue;
- }
- while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
- word[k++] = buf[i++];
- word[k] = '\0';
- if (l->space_pending &&
- (l->nruns > 0 || l->line_x > l->line_left) &&
- l->line_x + space_w <= l->line_right)
- l->line_x += space_w;
- l->space_pending = 0;
- w = (int)face_text_width(l->ui, &ps, word, k);
- if (l->line_x + w > l->line_right &&
- (l->nruns > 0 || l->line_x > l->line_left))
- flush_line(l);
- add_run(l, 0, 0, &ps, link, word);
- }
- if (block)
- flush_line(l);
- }
- /* An out-of-flow child (absolute/fixed, or a relative/sticky box with a
- * z-index): measured in place, painted from the deferred stacked pass
- * against its containing block. Shared by block and flex layout, so an
- * absolute icon inside a flex row (a password field's reveal button) is
- * not laid out as one of the row's items. Returns 1 when it handled n. */
- static int layout_out_of_flow(struct lay *l, unsigned int n,
- const struct br_style *cs, int depth,
- unsigned short lk)
- {
- if (!(cs->pos == 1 || cs->pos == 2 ||
- ((cs->pos == 3 || cs->pos == 4) && cs->z_set)))
- return 0;
- if ((cs->pos == 3 || cs->pos == 4) && l->draw &&
- ndeferred < BR_MAX_DEFERRED) {
- /* Relative or sticky z-index (a sticky site
- * header): measure and advance the flow without
- * painting, then paint it in the deferred
- * (stacked) pass, above the content after it. */
- int fy = l->y, fl = l->left, fr = l->right;
- int save_draw = l->draw;
- l->draw = 0;
- layout_block(l, n, cs, depth + 1, lk);
- l->draw = save_draw;
- deferred[ndeferred].node = n;
- deferred[ndeferred].parent_top = l->parent_top;
- deferred[ndeferred].flow_y = fy;
- deferred[ndeferred].flow_left = fl;
- deferred[ndeferred].flow_right = fr;
- deferred[ndeferred].link = lk;
- deferred[ndeferred].z_index = cs->z_index;
- deferred[ndeferred].z_set = cs->z_set;
- deferred[ndeferred].order = (unsigned int)ndeferred;
- ndeferred++;
- } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
- deferred[ndeferred].node = n;
- deferred[ndeferred].parent_top = l->parent_top;
- deferred[ndeferred].flow_y =
- cs->pos == 1 ? l->cb_top : l->y;
- deferred[ndeferred].flow_left =
- cs->pos == 1 ? l->cb_left : l->left;
- deferred[ndeferred].flow_right =
- cs->pos == 1 ? l->cb_right : l->right;
- deferred[ndeferred].link = lk;
- deferred[ndeferred].z_index = cs->z_index;
- deferred[ndeferred].z_set = cs->z_set;
- deferred[ndeferred].order = (unsigned int)ndeferred;
- ndeferred++;
- } else if (l->draw && cs->pos == 1) {
- /* Deferred list full: paint in place, but still
- * against the containing block, not the flow. */
- int fy = l->y, fl = l->left, fr = l->right;
- l->y = l->cb_top;
- l->left = l->cb_left;
- l->right = l->cb_right;
- layout_block(l, n, cs, depth + 1, lk);
- l->y = fy;
- l->left = fl;
- l->right = fr;
- } else {
- layout_block(l, n, cs, depth + 1, lk);
- }
- if (cs->pos == 1 && block_h[n] &&
- doc.nodes[n].class_off) {
- const char *cl = doc.attrs +
- doc.nodes[n].class_off;
- if ((contains_ci(cl, "poster-wrapper") ||
- contains_ci(cl, "ts-picture")) &&
- !has_skeleton_sibling(n))
- l->y += block_h[n];
- }
- return 1;
- }
- /* An element laid out in the text line (an inline span, or an inline-block
- * that flows like one): its runs are tagged with it, so flush_line() can
- * record its box for getBoundingClientRect() and click targeting. */
- static void layout_inline_box(struct lay *l, unsigned int node,
- const struct br_style *cs, int depth,
- unsigned short link)
- {
- unsigned short saved = l->box_owner;
- if (node < BR_MAX_NODES) {
- inline_box_parent[node] = saved;
- l->box_owner = (unsigned short)(node + 1);
- }
- layout_children(l, node, cs, depth + 1, link);
- l->box_owner = saved;
- }
- static void layout_children(struct lay *l, unsigned int parent,
- const struct br_style *pst, int depth,
- unsigned short link)
- {
- unsigned int n;
- if (depth > 48)
- return;
- emit_pseudo(l, parent, pst, 1, link);
- n = doc.nodes[parent].first;
- while (n) {
- struct br_node *nd = &doc.nodes[n];
- struct br_style cs;
- unsigned short lk = link;
- if (nd->type == BR_NODE_TEXT) {
- emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
- link, (nd->flags & BR_NODE_PREFORMAT) != 0);
- n = nd->next;
- continue;
- }
- br_style_for(&doc, n, pst, &cs);
- if (cs.display == BR_DISPLAY_NONE) {
- n = nd->next;
- continue;
- }
- if (cs.clear && l->float_active) {
- flush_line(l);
- if (l->y < l->float_bottom)
- l->y = l->float_bottom;
- l->float_active = 0;
- l->line_x = l->left;
- l->run_x = l->left;
- l->line_left = l->left;
- l->line_right = l->right;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- }
- if (nd->tag == BR_TAG_A && nd->href_off)
- lk = (unsigned short)n;
- if (layout_out_of_flow(l, n, &cs, depth, lk)) {
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_BR) {
- flush_line(l);
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_HR) {
- flush_line(l);
- if (l->draw)
- ngui_fill_rect(l->ui,
- (struct ngui_rect){l->left, l->y + 2,
- l->right - l->left, 1}, BR_GRAY);
- l->y += 8;
- n = nd->next;
- continue;
- }
- if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
- nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
- !button_has_elements(n)) {
- if (!(nd->tag == BR_TAG_INPUT &&
- s_eq(br_type(&doc, n), "hidden"))) {
- form_fill_line = pst->display ==
- BR_DISPLAY_FLEX &&
- pst->flex_col;
- add_form_run(l, n, &cs, lk);
- form_fill_line = 0;
- }
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_IMG) {
- add_image_run(l, n, &cs, lk);
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_SVG &&
- (cs.display == BR_DISPLAY_INLINE ||
- cs.display == BR_DISPLAY_INLINE_BLOCK) &&
- !cs.float_left) {
- add_svg_run(l, n, &cs, lk);
- n = nd->next;
- continue;
- }
- if (nd->tag == BR_TAG_VIDEO) {
- layout_block(l, n, &cs, depth + 1, lk);
- n = nd->next;
- continue;
- }
- if (cs.float_left) {
- n = layout_float_group(l, n, pst, depth, lk);
- continue;
- }
- if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
- inline_block_flows(n, &cs, 0)) {
- layout_inline_box(l, n, &cs, depth, lk);
- n = nd->next;
- continue;
- }
- if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
- n = layout_inline_blocks(l, n, pst, depth, link);
- continue;
- }
- /* A flex container is block-level like any block box even when
- * the element is an inline tag such as <a> (a link card with
- * display:flex is common on news sites). Without the block box
- * its children were laid out in the parent flow with a 0x0 box
- * of their own. */
- /* inline-flex around inline content only ("| mehr" link
- * tails, icon+label pills) stays in the text line. */
- if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
- !br_tag_is_block(nd->tag) && !cs.width_kind &&
- !flex_wants_row(n, &cs)) {
- layout_children(l, n, &cs, depth + 1, lk);
- } else if (cs.display == BR_DISPLAY_BLOCK ||
- cs.display == BR_DISPLAY_FLEX ||
- br_tag_is_block(nd->tag))
- layout_block(l, n, &cs, depth + 1, lk);
- else if (cs.display == BR_DISPLAY_INLINE &&
- nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH)
- layout_inline_box(l, n, &cs, depth, lk);
- else {
- layout_children(l, n, &cs, depth + 1, lk);
- if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
- l->space_pending = 1;
- }
- n = nd->next;
- }
- emit_pseudo(l, parent, pst, 2, link);
- }
- /* One layout state, kept out of the 8 KB user stack: it holds 96 line
- * runs and a recursive page can otherwise overflow the stack. */
- static struct lay layout_state;
- static int measure_page(int left, int right)
- {
- struct lay *l = &layout_state;
- struct br_style base = base_style();
- unsigned int i;
- for (i = 0; i < BR_MAX_NODES; i++) {
- block_h[i] = 0;
- flex_stretch_h[i] = 0;
- img_top[i] = 0;
- block_top[i] = 0;
- img_h[i] = 0;
- layout_boxes[i].valid = 0;
- }
- memset(li_marker, 0, sizeof(li_marker));
- inline_box_pass_id++;
- l->box_owner = 0;
- l->draw = 0;
- l->ui = &ui;
- l->left = left;
- l->right = right;
- l->y = 0;
- l->line_x = left;
- l->run_x = left;
- l->line_left = left;
- l->line_right = right;
- l->line_y = 0;
- l->line_h = 0;
- l->align = BR_ALIGN_LEFT;
- l->cb_h = layout_view_h;
- l->float_active = 0;
- l->parent_top = 0;
- l->cb_left = left;
- l->cb_right = right;
- l->cb_top = 0;
- l->depth = 0;
- l->nruns = 0;
- l->space_pending = 0;
- base = root_style();
- layout_children(l, doc.root, &base, 0, 0);
- return l->y + 8;
- }
- static int deferred_cmp(const struct br_deferred *a,
- const struct br_deferred *b)
- {
- int az = a->z_set ? a->z_index : 0;
- int bz = b->z_set ? b->z_index : 0;
- if (az != bz)
- return az < bz ? -1 : 1;
- if (a->order != b->order)
- return a->order < b->order ? -1 : 1;
- return 0;
- }
- static void sort_deferred(void)
- {
- int i;
- for (i = 1; i < ndeferred; i++) {
- struct br_deferred key = deferred[i];
- int j = i;
- while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
- deferred[j] = deferred[j - 1];
- j--;
- }
- deferred[j] = key;
- }
- }
- static void render_page(int left, int right, int y0)
- {
- struct lay *l = &layout_state;
- struct br_style base = base_style();
- inline_box_pass_id++;
- l->box_owner = 0;
- l->draw = 1;
- l->ui = &ui;
- l->left = left;
- l->right = right;
- l->y = y0;
- l->line_x = left;
- l->run_x = left;
- l->line_left = left;
- l->line_right = right;
- l->line_y = y0;
- l->line_h = 0;
- l->align = BR_ALIGN_LEFT;
- l->cb_h = layout_view_h;
- l->float_active = 0;
- l->parent_top = 0;
- l->cb_left = left;
- l->cb_right = right;
- l->cb_top = y0;
- l->depth = 0;
- l->nruns = 0;
- l->space_pending = 0;
- nhits = 0;
- ndeferred = 0;
- base = root_style();
- layout_children(l, doc.root, &base, 0, 0);
- sort_deferred();
- {
- int i;
- for (i = 0; i < ndeferred; i++) {
- struct br_style st;
- br_style_for(&doc, deferred[i].node, &base, &st);
- if (st.display == BR_DISPLAY_NONE)
- continue;
- l->draw = 1;
- l->left = deferred[i].flow_left;
- l->right = deferred[i].flow_right;
- l->y = deferred[i].flow_y;
- l->parent_top = deferred[i].parent_top;
- l->line_left = l->line_x = l->left;
- l->run_x = l->left;
- l->line_y = l->y;
- l->line_h = 0;
- l->nruns = 0;
- l->space_pending = 0;
- l->align = st.align;
- if (st.pos == 2 && block_h[deferred[i].node]) {
- struct ngui_rect clip;
- int ch = block_h[deferred[i].node] + 24;
- int pr = page_rect.x + page_rect.w - 12;
- int x0 = page_rect.x, x1 = pr;
- int y0 = page_rect.y;
- /* A box placed by `bottom` (a page footer) is
- * clipped and filled where layout_block puts
- * it, against the bottom edge. */
- if (st.bottom_set && !st.top_set) {
- ch = block_h[deferred[i].node] +
- mp_px(&st, 0, pr - page_rect.x) +
- mp_px(&st, 2, pr - page_rect.x);
- y0 = page_rect.y + page_rect.h -
- st.bottom - ch;
- }
- /* The background pre-fill spans the box's own
- * columns, not the whole page: Docusaurus parks
- * a white "Skip to main content" link at
- * `left: 100%` with a z-index above the navbar,
- * and a full-width fill painted over the bar. */
- if (st.left_set)
- x0 = page_rect.x + st.left;
- else if (!st.right_set)
- x0 = deferred[i].flow_left;
- if (st.width_kind == 1) {
- if (st.right_set && !st.left_set)
- x0 = pr - st.right - st.width;
- x1 = x0 + st.width;
- } else if (st.right_set) {
- x1 = pr - st.right;
- }
- if (x0 >= pr || x1 <= page_rect.x)
- continue; /* entirely off-screen */
- if (x0 < page_rect.x)
- x0 = page_rect.x;
- if (x1 > pr)
- x1 = pr;
- if (y0 < page_rect.y) {
- ch -= page_rect.y - y0;
- y0 = page_rect.y;
- }
- clip.x = x0;
- clip.y = y0;
- clip.w = x1 - x0;
- if (ch > page_rect.h)
- ch = page_rect.h;
- if (ch <= 0)
- continue;
- clip.h = ch;
- ngui_push_clip(&ui, clip);
- if (st.has_bg)
- ngui_fill_rect(&ui, clip, st.bg);
- layout_block(l, deferred[i].node, &st, 0,
- deferred[i].link);
- ngui_pop_clip(&ui);
- } else {
- layout_block(l, deferred[i].node, &st, 0,
- deferred[i].link);
- }
- }
- }
- }
- /* ---- UI ---- */
- static int find_hit(int x, int y)
- {
- int i;
- for (i = nhits - 1; i >= 0; i--) {
- struct hit *h = &hits[i];
- if (x >= h->x && y >= h->y && x < h->x + h->w &&
- y < h->y + h->h)
- return (int)h->node;
- }
- return 0;
- }
- /* ---- URL-bar autocomplete ----
- *
- * While the address bar has the focus a dropdown lists up to SUG_MAX
- * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
- * visited/recent sites; typing ranks prefix matches of the URL (with or
- * without the scheme and "www.") above substring matches of the URL, then
- * of the title, and adds visit count and recency. Typing at the end of the
- * text also completes inline to the next '/' of the best prefix match
- * ("clo" -> "cloudron.io/"), with the added part selected so the next
- * keystroke replaces it; Enter on that text opens the history URL it came
- * from (scheme included). Up/Down preview a row in the bar, Delete on a
- * highlighted row forgets it, Esc closes the list (a second Esc leaves the
- * bar), and a click on a row opens it. */
- #define SUG_MAX 6
- #define SUG_ROW_H 36
- static int sug_idx[SUG_MAX];
- static int sug_n, sug_sel = -1, sug_open;
- static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
- static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
- static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
- static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
- static struct ngui_rect url_rect, sug_rect;
- static int url_had_focus;
- static char lc(char c)
- {
- return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
- }
- static int prefix_ci(const char *s, const char *p) /* p is lower case */
- {
- for (; *p; s++, p++)
- if (lc(*s) != *p)
- return 0;
- return 1;
- }
- static unsigned int url_scheme_len(const char *url)
- {
- if (starts_with(url, "https://"))
- return 8;
- if (starts_with(url, "http://"))
- return 7;
- return 0;
- }
- /* Offset in `url` where the lower-case text `t` matches as a prefix: the
- * whole URL, the URL without its scheme, or without scheme and "www.". */
- static int hist_prefix_at(const char *url, const char *t)
- {
- unsigned int s = url_scheme_len(url);
- if (prefix_ci(url, t))
- return 0;
- if (s && prefix_ci(url + s, t))
- return (int)s;
- if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
- return (int)s + 4;
- return -1;
- }
- static int hist_score(const struct hist_ent *e, const char *t,
- unsigned int next)
- {
- unsigned int age = next - e->stamp;
- int sc, at;
- if (!t[0]) {
- sc = 0;
- } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
- /* Shorter rests first: "cloudron.io/" before its subpages. */
- int rest = (int)s_len(e->url + at);
- sc = 4000 - (rest > 400 ? 400 : rest);
- } else if (contains_ci(e->url, t)) {
- sc = 1000;
- } else if (contains_ci(e->title, t)) {
- sc = 600;
- } else {
- return -1;
- }
- sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
- sc += age >= 500 ? 0 : (int)(500 - age);
- return sc;
- }
- static void sug_lower(char *t, unsigned int cap)
- {
- unsigned int k;
- for (k = 0; sug_typed[k] && k + 1 < cap; k++)
- t[k] = lc(sug_typed[k]);
- t[k] = '\0';
- }
- static void sug_refresh(void)
- {
- char t[NGUI_INPUT_MAX];
- int sc[SUG_MAX], i, j;
- unsigned int next = hist_next_stamp();
- sug_lower(t, sizeof(t));
- sug_n = 0;
- for (i = 0; i < hist_n; i++) {
- int s = hist_score(&hist_tab[i], t, next);
- if (s < 0)
- continue;
- j = sug_n;
- if (j == SUG_MAX) {
- if (sc[SUG_MAX - 1] >= s)
- continue;
- j = SUG_MAX - 1;
- }
- while (j > 0 && sc[j - 1] < s) {
- sc[j] = sc[j - 1];
- sug_idx[j] = sug_idx[j - 1];
- j--;
- }
- sc[j] = s;
- sug_idx[j] = i;
- if (sug_n < SUG_MAX)
- sug_n++;
- }
- if (sug_sel >= sug_n)
- sug_sel = -1;
- }
- /* Complete the typed text inline to the next '/' of the best prefix match. */
- static void sug_inline(void)
- {
- char t[NGUI_INPUT_MAX];
- const char *url, *rest;
- unsigned int L, start, end, hs, tn, n = 0;
- unsigned int next = hist_next_stamp();
- int i, best = -1, best_sc = -1, at = 0;
- sug_lower(t, sizeof(t));
- L = s_len(t);
- if (!L)
- return;
- for (i = 0; i < hist_n; i++) {
- int a = hist_prefix_at(hist_tab[i].url, t), s;
- if (a < 0)
- continue;
- s = hist_score(&hist_tab[i], t, next);
- if (s > best_sc) {
- best_sc = s;
- best = i;
- at = a;
- }
- }
- if (best < 0)
- return;
- url = hist_tab[best].url;
- rest = url + at;
- /* Typing the scheme ("htt") completes past "https://", not to it. */
- hs = at == 0 ? url_scheme_len(url) : 0;
- start = L > hs ? L : hs;
- end = start;
- while (rest[end] && rest[end] != '/')
- end++;
- if (rest[end] == '/')
- end++;
- tn = s_len(sug_typed);
- if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
- return;
- s_append(ac_text, &n, sug_typed, sizeof(ac_text));
- for (; L < end && n + 1 < sizeof(ac_text); L++)
- ac_text[n++] = rest[L];
- ac_text[n] = '\0';
- s_copy(ac_url, url, (unsigned int)at + end + 1);
- ngui_input_set(&url_in, ac_text);
- url_in.anchor = tn; /* select the completed part */
- }
- static void sug_close(void)
- {
- sug_open = 0;
- sug_sel = -1;
- ac_text[0] = '\0';
- }
- static int sug_visible(void)
- {
- return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
- }
- /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
- * start page) lists the top sites until something is typed. */
- static int sug_focus_check(void)
- {
- int focused = ngui_focus(&ui) == ID_URL;
- if (focused && !url_had_focus) {
- sug_typed[0] = '\0';
- sug_close();
- sug_open = 1;
- sug_refresh();
- }
- url_had_focus = focused;
- return focused;
- }
- static void url_submit(unsigned int *action)
- {
- if (ac_text[0] && s_eq(url_in.text, ac_text))
- s_copy(click_url, ac_url, sizeof(click_url));
- *action |= ACT_NAV;
- sug_close();
- }
- /* The bar text changed through typing or editing. */
- static void sug_changed(void)
- {
- unsigned int pl = s_len(sug_typed);
- int grew = url_in.len > pl && url_in.cursor == url_in.len &&
- !memcmp(url_in.text, sug_typed, pl);
- s_copy(sug_typed, url_in.text, sizeof(sug_typed));
- ac_text[0] = '\0';
- sug_sel = -1;
- sug_open = 1;
- sug_refresh();
- if (grew)
- sug_inline();
- }
- /* Keys for the list, taken off the queue before the text field sees them.
- * Only a leading run is handled; the rest goes to the field. */
- static void sug_keys(void)
- {
- int k;
- while ((k = ngui_key_peek(&ui)) != 0) {
- if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
- ngui_key(&ui);
- if (!sug_open) {
- sug_open = 1;
- continue;
- }
- if (sug_sel < 0)
- s_copy(sug_restore, url_in.text,
- sizeof(sug_restore));
- if (k == NGUI_KEY_DOWN)
- sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
- else
- sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
- ngui_input_set(&url_in, sug_sel >= 0 ?
- hist_tab[sug_idx[sug_sel]].url :
- sug_restore);
- } else if (k == NGUI_KEY_ESC && sug_visible()) {
- ngui_key(&ui);
- if (sug_sel >= 0)
- ngui_input_set(&url_in, sug_restore);
- else if (ac_text[0] && s_eq(url_in.text, ac_text))
- ngui_input_set(&url_in, sug_typed);
- sug_close();
- } else if (k == NGUI_KEY_DELETE && sug_visible() &&
- sug_sel >= 0) {
- ngui_key(&ui);
- hist_forget(sug_idx[sug_sel]);
- ngui_input_set(&url_in, sug_restore);
- sug_sel = -1;
- sug_refresh();
- } else {
- break;
- }
- }
- }
- /* A press on a row of last frame's list opens it; any press on the list is
- * swallowed so the page underneath does not see it. */
- static void sug_click(unsigned int *action)
- {
- int row;
- if (!(ui.pressed & 1) || !sug_rect.w ||
- !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
- return;
- row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
- if (row >= 0 && row < sug_n) {
- s_copy(click_url, hist_tab[sug_idx[row]].url,
- sizeof(click_url));
- *action |= ACT_NAV;
- sug_close();
- }
- ui.pressed = 0;
- }
- static void draw_suggest(struct ngui_rect page)
- {
- struct ngui_rect r;
- int i, rows = sug_n, hover = -1;
- r.x = url_rect.x;
- r.y = url_rect.y + url_rect.h + 1;
- r.w = url_rect.w < 320 ? 320 : url_rect.w;
- if (r.x + r.w > ui.w - 2)
- r.w = ui.w - 2 - r.x;
- while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
- rows--;
- if (rows <= 0 || r.w < 60) {
- sug_rect.w = 0;
- return;
- }
- r.h = rows * SUG_ROW_H + 2;
- sug_rect = r;
- if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
- hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
- ngui_set_cursor(&ui, CURSOR_POINTER);
- }
- ngui_fill_rect(&ui, r, ui.theme.border);
- for (i = 0; i < rows; i++) {
- const struct hist_ent *e = &hist_tab[sug_idx[i]];
- struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
- r.w - 2, SUG_ROW_H};
- struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
- unsigned short bg = i == sug_sel ? ui.theme.selection :
- i == hover ? ui.theme.panel_alt :
- ui.theme.panel;
- ngui_fill_rect(&ui, rr, bg);
- ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
- e->title[0] ? e->title : e->url,
- ui.theme.text);
- ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
- i == sug_sel ? ui.theme.text :
- ui.theme.text_dim);
- }
- }
- static void draw_toolbar(struct ngui_rect r, unsigned int *action)
- {
- int x = r.x + 4, y = r.y + 4, h = 22;
- int compact = r.w < 560;
- int go_w = r.w < 420 ? 32 : 42;
- int in_x, in_w, res;
- ngui_fill_rect(&ui, r, ui.theme.panel);
- ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
- ui.theme.border);
- if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
- NGUI_ICON_CHEVRON_LEFT))
- *action |= ACT_BACK;
- x += 32;
- if (!compact) {
- if (ngui_icon_button(&ui, ID_FORWARD,
- (struct ngui_rect){x, y, 28, h},
- NGUI_ICON_CHEVRON_RIGHT))
- *action |= ACT_FORWARD;
- x += 32;
- }
- if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
- NGUI_ICON_REFRESH))
- *action |= ACT_RELOAD;
- x += 32;
- if (!compact) {
- if (ngui_icon_button(&ui, ID_HOME,
- (struct ngui_rect){x, y, 28, h},
- NGUI_ICON_HOME))
- *action |= ACT_HOME;
- x += 32;
- }
- in_x = x + 2;
- in_w = r.x + r.w - 6 - go_w - 4 - in_x;
- if (in_w < 60)
- in_w = 60;
- url_rect = (struct ngui_rect){in_x, y, in_w, h};
- if (sug_focus_check())
- sug_keys();
- res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
- sug_focus_check(); /* a click into the bar focuses it here */
- if (res & NGUI_INPUT_CHANGED)
- sug_changed();
- if (res & NGUI_INPUT_SUBMIT)
- url_submit(action);
- if (res & NGUI_INPUT_CANCEL)
- ngui_set_focus(&ui, 0);
- if (ngui_button(&ui, ID_GO,
- (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
- "Go"))
- url_submit(action);
- if (!sug_focus_check())
- sug_close();
- }
- static int page_hover_node(void)
- {
- if (!ui.inside)
- return 0;
- if (ui.mouse_x < page_rect.x ||
- ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
- ui.mouse_y < page_rect.y ||
- ui.mouse_y >= page_rect.y + page_rect.h)
- return 0;
- return find_hit(ui.mouse_x, ui.mouse_y);
- }
- static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
- {
- int x, y, w = page.w, h = page.h;
- if (!src || w <= 0 || h <= 0)
- return;
- for (y = 0; y < h; y++) {
- unsigned short *s = src + (page.y + y) * sw + page.x;
- unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
- for (x = 0; x + 1 < w; x += 2) {
- *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
- }
- if (x < w)
- d[x] = s[x];
- }
- }
- static void draw_page(struct ngui_rect page)
- {
- int left, right, ch;
- int old_panel, old_dim;
- unsigned short *saved_px;
- unsigned short page_bg = ui.theme.bg;
- int saved_w, saved_h, use_buf;
- unsigned int t0 = u_ticks_ms();
- page_rect = page;
- {
- unsigned int root = doc.nnode > 1 ?
- br_find_tag(&doc, BR_TAG_HTML) : 0;
- unsigned int body = doc.nnode > 1 ?
- br_find_tag(&doc, BR_TAG_BODY) : 0;
- struct br_style bs;
- int bg_found = 0;
- if (root) {
- style_for_node(root - 1, &bs);
- if (bs.has_bg) {
- page_bg = bs.bg;
- bg_found = 1;
- }
- }
- if (body) {
- style_for_node(body - 1, &bs);
- if (bs.has_bg) {
- page_bg = bs.bg;
- bg_found = 1;
- }
- }
- /* No canvas colour, but the author made the text dark
- * (Infima's light theme: `--ifm-background-color:
- * transparent` on html, #1c1e21 text): the page expects the
- * white canvas of a normal browser, and dark text on the
- * dark default canvas is unreadable. */
- if (!bg_found && (body || root) && bs.color != ui.theme.text) {
- unsigned int c = bs.color;
- unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
- ((c >> 5) & 63) * 4 * 587 +
- (c & 31) * 8 * 114;
- if (lum < 100 * 1000)
- page_bg = 0xFFFF;
- }
- }
- if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
- page_cache_valid && layout_valid &&
- !ui.pressed && !(ui.buttons & 1) && !ui.released &&
- !(ui.scroll_y &&
- ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
- page_scroll.offset == page_cache_scroll &&
- page_cache_nnode == doc.nnode &&
- page_cache_x == page.x && page_cache_y == page.y &&
- page_cache_w == page.w && page_cache_h == page.h) {
- blit_page(page, page_backbuf, pagebuf_w);
- if (img_stat_n)
- img_stat_paint += u_ticks_ms() - t0;
- return;
- }
- ngui_fill_rect(&ui, page, page_bg);
- if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
- const char *s = page_loading ? "Loading..." : "No page";
- int w = (int)ngui_text_width_ui(&ui, s);
- ngui_text(&ui, page.x + (page.w - w) / 2,
- page.y + page.h / 2 - 8, s, ui.theme.text_dim);
- page_scroll.content_h = 0;
- page_scroll.view_h = page.h;
- page_cache_valid = 0;
- return;
- }
- if (page.w < 40 || page.h < 40) {
- page_cache_valid = 0;
- return;
- }
- saved_px = ui.px;
- saved_w = ui.w;
- saved_h = ui.h;
- use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
- if (use_buf) {
- ui.px = page_backbuf;
- ui.w = pagebuf_w;
- ui.h = pagebuf_h;
- ngui_fill_rect(&ui, page, page_bg);
- }
- /* No gutter of our own: the body's UA margin provides it. The
- * right 12 px stay clear for the scrollbar, like every viewport
- * width below (page_rect.w - 12). */
- left = page.x;
- right = page.x + page.w - 12;
- if (!layout_valid || left != layout_left || right != layout_right ||
- layout_nnode != doc.nnode) {
- unsigned int tm = u_ticks_ms();
- layout_view_h = page.h;
- layout_content_h = measure_page(left, right);
- if (img_stat_n)
- img_stat_reflow += u_ticks_ms() - tm;
- layout_valid = 1;
- layout_left = left;
- layout_right = right;
- layout_nnode = doc.nnode;
- /* Scripts that measured before any layout (offsetWidth on
- * mount) get a resize event once real boxes exist, and again
- * whenever the page width changes. */
- if (js_browser_active() && right - left != resize_sent_w)
- resize_pending = 1;
- }
- ch = layout_content_h;
- page_scroll.content_h = ch;
- page_scroll.view_h = page.h;
- t0 = u_ticks_ms();
- ngui_scroll_begin(&ui, page, &page_scroll);
- ngui_scroll_wheel(&ui, page, &page_scroll);
- render_page(left, right, page.y - page_scroll.offset);
- old_panel = ui.theme.panel_alt;
- old_dim = ui.theme.text_dim;
- ui.theme.panel_alt = 0xC618;
- ui.theme.text_dim = 0x8410;
- ngui_scroll_end(&ui, page, &page_scroll);
- ui.theme.panel_alt = old_panel;
- ui.theme.text_dim = old_dim;
- if (use_buf) {
- ui.px = saved_px;
- ui.w = saved_w;
- ui.h = saved_h;
- blit_page(page, page_backbuf, pagebuf_w);
- page_cache_valid = 1;
- page_cache_scroll = page_scroll.offset;
- page_cache_nnode = doc.nnode;
- page_cache_x = page.x;
- page_cache_y = page.y;
- page_cache_w = page.w;
- page_cache_h = page.h;
- } else {
- page_cache_valid = 0;
- }
- if (img_stat_n)
- img_stat_paint += u_ticks_ms() - t0;
- }
- static void draw_status(struct ngui_rect r)
- {
- static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
- unsigned int n = 0;
- int hover = page_hover_node();
- unsigned short color;
- const char *kind;
- ngui_fill_rect(&ui, r, ui.theme.panel);
- ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
- ui.theme.border);
- /* Only a real link target is shown: a form control, or an element
- * that is merely clickable through a script listener (google.com's
- * jsaction wrapper around its search field), is not a link. */
- if (hover && !br_href(&doc, (unsigned int)hover))
- hover = 0;
- if (hover) {
- const char *href = br_href(&doc, (unsigned int)hover);
- char url[BR_URL_MAX];
- if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
- s_append(msg, &n, "Link: ", sizeof(msg));
- s_append(msg, &n, url, sizeof(msg));
- } else {
- s_copy(msg, "Link", sizeof(msg));
- }
- color = ui.theme.accent;
- } else if (status_text[0]) {
- s_copy(msg, status_text, sizeof(msg));
- color = status_error ? ui.theme.error : ui.theme.text;
- } else if (page_title[0]) {
- s_copy(msg, page_title, sizeof(msg));
- color = ui.theme.text;
- } else {
- s_copy(msg, "Ready", sizeof(msg));
- color = ui.theme.text_dim;
- }
- kind = s_eq(page_url, "about:home") ? "HOME" :
- page_is_local ? "FILE" :
- (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
- ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
- {
- int kw = (int)ngui_text_width_ui(&ui, kind);
- ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
- ui.theme.text_dim);
- }
- }
- /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
- * for `auto`, a hand over links, the I-beam over text fields, and the
- * progress arrow anywhere on the page while it is still loading. The
- * toolbar's URL field sets its own I-beam through ngui. */
- static void page_cursor(void)
- {
- int hover = page_hover_node();
- struct br_style st;
- if (!hover) {
- if (page_loading && ui.inside &&
- ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
- ngui_set_cursor(&ui, CURSOR_PROGRESS);
- return;
- }
- style_for_node((unsigned int)hover, &st);
- if (st.cursor != BR_CURSOR_AUTO) {
- ngui_set_cursor(&ui, (int)st.cursor - 1);
- return;
- }
- if (br_href(&doc, (unsigned int)hover)) {
- ngui_set_cursor(&ui, CURSOR_POINTER);
- return;
- }
- if (form_is_control((unsigned int)hover)) {
- int k = form_kind_of((unsigned int)hover);
- if (form_disabled((unsigned int)hover))
- ngui_set_cursor(&ui, CURSOR_DEFAULT);
- else if (k == FORM_TEXT || k == FORM_PASSWORD ||
- k == FORM_TEXTAREA)
- ngui_set_cursor(&ui, CURSOR_TEXT);
- return;
- }
- if (page_loading)
- ngui_set_cursor(&ui, CURSOR_PROGRESS);
- }
- static void draw(unsigned int *action)
- {
- struct ngui_rect r = {0, 0, ui.w, ui.h};
- struct ngui_rect toolbar, status, page;
- toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
- status = ngui_cut_bottom(&r, BR_STATUS_H);
- page = r;
- if (sug_visible())
- sug_click(action);
- draw_toolbar(toolbar, action);
- draw_page(page);
- draw_status(status);
- page_cursor();
- if (sug_visible())
- draw_suggest(page);
- else
- sug_rect.w = 0;
- }
- static void redraw_now(void)
- {
- unsigned int action = 0;
- ngui_begin(&ui);
- draw(&action);
- ngui_end(&ui);
- }
- static void handle_keys(unsigned int *action)
- {
- int k, scrolled = 0;
- if (form_focus >= doc.nnode)
- form_focus = 0;
- if (form_focus && !ngui_focus(&ui)) {
- while ((k = ngui_key(&ui)) != 0)
- form_key(k);
- return;
- }
- /* Batch queued page keys: a slow full-page render must not make a
- * held Page Down advance only once every few frames. */
- while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
- scrolled++;
- if (scrolled)
- ngui_invalidate(&ui);
- if (ngui_focus(&ui))
- return;
- while ((k = ngui_key(&ui)) != 0) {
- switch (k) {
- case NGUI_KEY_ESC:
- *action |= ACT_CLOSE;
- break;
- case NGUI_KEY_TAB:
- case 0x0C: /* Ctrl+L */
- ngui_set_focus(&ui, ID_URL);
- break;
- case 0x12: /* Ctrl+R */
- *action |= ACT_RELOAD;
- break;
- case NGUI_KEY_BACKSPACE:
- *action |= ACT_BACK;
- break;
- case NGUI_KEY_UP:
- ngui_scroll_to(&page_scroll,
- page_scroll.offset - 24);
- ngui_invalidate(&ui);
- break;
- case NGUI_KEY_DOWN:
- ngui_scroll_to(&page_scroll,
- page_scroll.offset + 24);
- ngui_invalidate(&ui);
- break;
- case NGUI_KEY_HOME:
- ngui_scroll_to(&page_scroll, 0);
- ngui_invalidate(&ui);
- break;
- case NGUI_KEY_END:
- ngui_scroll_to(&page_scroll,
- page_scroll.content_h -
- page_scroll.view_h);
- ngui_invalidate(&ui);
- break;
- default:
- break;
- }
- }
- }
- static unsigned int form_ancestor(unsigned int node)
- {
- unsigned int p = node;
- while (p && p < doc.nnode) {
- if (doc.nodes[p].tag == BR_TAG_FORM &&
- doc.nodes[p].type == BR_NODE_ELEM)
- return p;
- p = doc.nodes[p].parent;
- }
- return 0;
- }
- static int form_descendant(unsigned int node, unsigned int form)
- {
- unsigned int p = node;
- while (p && p < doc.nnode) {
- if (p == form)
- return 1;
- p = doc.nodes[p].parent;
- }
- return 0;
- }
- static void form_reset_form(unsigned int form)
- {
- unsigned int i;
- for (i = 0; i < FORM_MAX; i++)
- if (form_states[i].used &&
- form_descendant(form_states[i].node, form))
- form_states[i].used = 0;
- form_focus = 0;
- }
- static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
- const char *s)
- {
- static const char hex[] = "0123456789ABCDEF";
- while (s && *s && *n + 1 < cap) {
- unsigned char c = (unsigned char)*s++;
- if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
- (c >= '0' && c <= '9') || c == '-' || c == '_' ||
- c == '.' || c == '~') {
- dst[(*n)++] = (char)c;
- } else if (c == ' ') {
- dst[(*n)++] = '+';
- } else if (*n + 3 < cap) {
- dst[(*n)++] = '%';
- dst[(*n)++] = hex[c >> 4];
- dst[(*n)++] = hex[c & 15];
- }
- }
- dst[*n] = '\0';
- }
- static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
- const char *name, const char *value, int *first)
- {
- if (!name || !name[0])
- return;
- if (!*first && *n + 1 < cap)
- dst[(*n)++] = '&';
- *first = 0;
- form_url_append(dst, n, cap, name);
- if (*n + 1 < cap)
- dst[(*n)++] = '=';
- form_url_append(dst, n, cap, value ? value : "");
- dst[*n] = '\0';
- }
- static int form_submit_form(unsigned int node, int fire_event)
- {
- unsigned int form = form_ancestor(node);
- char action[BR_URL_MAX], query[2048];
- unsigned int qn = 0, i;
- int first = 1, is_post = 0;
- const char *a, *method;
- if (!form)
- return 0;
- if (fire_event && !js_browser_event(form, "submit", 1, 1))
- return 0;
- method = br_find_attr(&doc, form, "method");
- if (method && (s_eq(method, "post") || s_eq(method, "POST")))
- is_post = 1;
- a = br_find_attr(&doc, form, "action");
- if (a && a[0]) {
- if (resolve_link(page_url, a, action, sizeof(action)) != 0)
- return 0;
- } else {
- s_copy(action, page_url, sizeof(action));
- }
- query[0] = '\0';
- for (i = 0; i < doc.nnode; i++) {
- struct br_node *nd = &doc.nodes[i];
- struct form_state *fs;
- const char *name;
- const char *value = "";
- if (nd->type != BR_NODE_ELEM || i == form ||
- !form_descendant(i, form))
- continue;
- if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
- nd->tag != BR_TAG_SELECT)
- continue;
- if (form_disabled(i))
- continue;
- name = br_find_attr(&doc, i, "name");
- if (!name || !name[0])
- continue;
- fs = form_get(i, 1);
- if (!fs)
- continue;
- if (nd->tag == BR_TAG_SELECT) {
- char opt[64];
- if (!form_option_text(i, fs->selected, opt,
- sizeof(opt)))
- s_copy(opt, "", sizeof(opt));
- value = opt;
- {
- unsigned int c, oi = 0;
- for (c = nd->first; c;
- c = doc.nodes[c].next) {
- if (doc.nodes[c].type != BR_NODE_ELEM ||
- doc.nodes[c].tag != BR_TAG_OPTION)
- continue;
- if (oi == fs->selected) {
- const char *v =
- br_value(&doc, c);
- if (v && v[0])
- value = v;
- break;
- }
- oi++;
- }
- }
- } else if (nd->tag == BR_TAG_INPUT) {
- int kind = form_kind_of(i);
- if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
- if (!fs->checked)
- continue;
- value = br_value(&doc, i);
- if (!value || !value[0])
- value = "on";
- } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
- kind == FORM_BUTTON) {
- if (i != node)
- continue;
- value = fs->value;
- } else {
- value = fs->value;
- }
- } else {
- value = fs->value;
- }
- form_add_param(query, &qn, sizeof(query), name, value, &first);
- }
- if (is_post) {
- if (action[0] == '/') {
- set_status("POST forms need an HTTP action URL", 1, 4000);
- ngui_invalidate(&ui);
- return 0;
- }
- if (qn >= sizeof(pending_post))
- qn = sizeof(pending_post) - 1;
- if (qn)
- memcpy(pending_post, query, qn);
- pending_post[qn] = '\0';
- pending_post_len = qn;
- pending_post_is = 1;
- } else {
- pending_post_len = 0;
- pending_post_is = 0;
- if (qn) {
- unsigned int an = s_len(action);
- if (an + qn + 2 < sizeof(action)) {
- action[an++] = strchr(action, '?') ? '&' : '?';
- action[an] = '\0';
- s_copy(action + an, query,
- sizeof(action) - an);
- }
- }
- }
- s_copy(pending_url, action, sizeof(pending_url));
- pending_action |= ACT_NAV;
- cancel_fetch = 1;
- ngui_invalidate(&ui);
- return 1;
- }
- static void form_reset_event(unsigned int form)
- {
- if (form && !js_browser_event(form, "reset", 1, 1))
- return;
- if (form)
- form_reset_form(form);
- else
- form_reset_state();
- form_dirty = 0;
- layout_valid = 0;
- ngui_invalidate(&ui);
- }
- static void form_blur(void)
- {
- unsigned int node = form_focus;
- form_focus = 0;
- if (node && form_dirty) {
- form_dirty = 0;
- js_browser_event(node, "change", 1, 0);
- }
- }
- static void form_click(unsigned int node)
- {
- struct form_state *fs;
- int kind, changed = 0;
- if (!form_is_control(node) || form_disabled(node))
- return;
- if (form_focus != node)
- form_blur();
- fs = form_get(node, 1);
- if (!fs)
- return;
- kind = form_kind_of(node);
- /* Focus moves on the press, before `click` is dispatched: a page
- * that cancels the click (a framework's root listener) suppresses
- * the activation behaviour below, never the focus (as in other
- * browsers, where focus follows mousedown). */
- form_focus = node;
- form_dirty = 0;
- if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
- kind == FORM_TEXTAREA)
- fs->caret = fs->len;
- layout_valid = 0;
- ngui_invalidate(&ui);
- if (!js_browser_event(node, "click", 1, 1))
- return;
- fs = form_get(node, 0); /* the handler may have changed the DOM */
- if (!fs)
- return;
- if (kind == FORM_CHECKBOX) {
- fs->checked = !fs->checked;
- changed = 1;
- } else if (kind == FORM_RADIO) {
- const char *name = br_find_attr(&doc, node, "name");
- unsigned int i;
- fs->checked = 1;
- changed = 1;
- if (name) {
- for (i = 0; i < FORM_MAX; i++) {
- struct form_state *o = &form_states[i];
- if (!o->used || o->node == node)
- continue;
- if (form_kind_of(o->node) == FORM_RADIO) {
- const char *on = br_find_attr(&doc,
- o->node,
- "name");
- if (on && s_eq(on, name))
- o->checked = 0;
- }
- }
- }
- } else if (kind == FORM_SELECT) {
- unsigned int n = form_option_count(node);
- if (n) {
- fs->selected = (unsigned char)
- ((fs->selected + 1) % n);
- changed = 1;
- }
- } else if (kind == FORM_SUBMIT) {
- form_submit_form(node, 1);
- return;
- } else if (kind == FORM_RESET) {
- form_reset_event(form_ancestor(node));
- return;
- }
- if (changed) {
- js_browser_event(node, "input", 1, 0);
- js_browser_event(node, "change", 1, 0);
- }
- layout_valid = 0;
- ngui_invalidate(&ui);
- }
- static void form_focus_next(void)
- {
- unsigned int start = form_focus ? form_focus + 1 : 0;
- unsigned int i;
- form_blur();
- for (i = start; i < doc.nnode; i++) {
- if (form_is_control(i) && !form_disabled(i) &&
- !s_eq(br_type(&doc, i), "hidden")) {
- form_focus = i;
- layout_valid = 0;
- ngui_invalidate(&ui);
- return;
- }
- }
- form_focus = 0;
- layout_valid = 0;
- ngui_invalidate(&ui);
- }
- static void form_key(int k)
- {
- struct form_state *fs;
- int kind;
- if (!form_focus || form_focus >= doc.nnode) {
- form_focus = 0;
- return;
- }
- fs = form_get(form_focus, 1);
- if (!fs || form_disabled(form_focus))
- return;
- kind = form_kind_of(form_focus);
- if (kind == FORM_SELECT) {
- unsigned int n = form_option_count(form_focus);
- int changed = 0;
- if (k == NGUI_KEY_UP && n) {
- fs->selected = (unsigned char)
- ((fs->selected + n - 1) % n);
- changed = 1;
- } else if (k == NGUI_KEY_DOWN && n) {
- fs->selected = (unsigned char)
- ((fs->selected + 1) % n);
- changed = 1;
- } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
- form_blur();
- layout_valid = 0;
- ngui_invalidate(&ui);
- return;
- } else {
- return;
- }
- if (changed) {
- js_browser_event(form_focus, "input", 1, 0);
- js_browser_event(form_focus, "change", 1, 0);
- }
- } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
- if (k == ' ') {
- form_click(form_focus);
- return;
- }
- if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
- form_blur();
- layout_valid = 0;
- ngui_invalidate(&ui);
- }
- return;
- } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
- kind == FORM_RESET) {
- if (k == NGUI_KEY_ESC) {
- form_blur();
- layout_valid = 0;
- ngui_invalidate(&ui);
- } else if (k == '\r' || k == '\n' || k == ' ') {
- form_click(form_focus);
- }
- return;
- } else if (k == NGUI_KEY_TAB) {
- form_focus_next();
- return;
- } else if (k == NGUI_KEY_ESC) {
- form_blur();
- layout_valid = 0;
- ngui_invalidate(&ui);
- return;
- } else if (k == '\r' || k == '\n') {
- unsigned int node = form_focus;
- form_blur();
- if (form_ancestor(node))
- form_submit_form(node, 1);
- layout_valid = 0;
- ngui_invalidate(&ui);
- return;
- } else if (k == NGUI_KEY_BACKSPACE) {
- if (fs->caret) {
- unsigned int i = --fs->caret;
- for (; i < fs->len; i++)
- fs->value[i] = fs->value[i + 1];
- if (fs->len)
- fs->len--;
- form_dirty = 1;
- js_browser_event(form_focus, "input", 1, 0);
- }
- } else if (k == NGUI_KEY_DELETE) {
- if (fs->caret < fs->len) {
- unsigned int i;
- for (i = fs->caret; i < fs->len; i++)
- fs->value[i] = fs->value[i + 1];
- fs->len--;
- form_dirty = 1;
- js_browser_event(form_focus, "input", 1, 0);
- }
- } else if (k == NGUI_KEY_LEFT) {
- if (fs->caret)
- fs->caret--;
- } else if (k == NGUI_KEY_RIGHT) {
- if (fs->caret < fs->len)
- fs->caret++;
- } else if (k == NGUI_KEY_HOME) {
- fs->caret = 0;
- } else if (k == NGUI_KEY_END) {
- fs->caret = fs->len;
- } else if (k >= 32 && k < 127) {
- if (fs->len < FORM_VALUE_MAX) {
- unsigned int i;
- for (i = fs->len; i > fs->caret; i--)
- fs->value[i] = fs->value[i - 1];
- fs->value[fs->caret++] = (char)k;
- fs->len++;
- form_dirty = 1;
- js_browser_event(form_focus, "input", 1, 0);
- }
- } else {
- return;
- }
- fs->value[fs->len] = '\0';
- layout_valid = 0;
- ngui_invalidate(&ui);
- }
- /* A link to "#..." (or to this page plus a fragment) on a scripted page is
- * a same-document navigation: update the URL and fire hashchange. Returns
- * 1 when handled. */
- static int link_fragment_nav(unsigned int node)
- {
- const char *href = br_href(&doc, node);
- char url[BR_URL_MAX];
- unsigned int n = 0;
- if (!href || !href[0] || !js_browser_active())
- return 0;
- if (href[0] == '#') {
- while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
- url[n] = page_url[n];
- n++;
- }
- url[n] = '\0';
- s_append(url, &n, href, sizeof(url));
- } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
- return 0;
- }
- if (!same_doc_fragment(url))
- return href[0] == '#';
- page_set_fragment(url, 1);
- js_browser_hashchange();
- return 1;
- }
- /* The innermost laid-out box under a screen point: the smallest valid box
- * that contains it (the last one wins a tie, i.e. the later/deeper node).
- * Used to deliver clicks to elements that are neither links nor controls
- * (a Vue <div role="button">, a card with a click listener). */
- static unsigned int find_box_hit(int x, int y)
- {
- unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
- for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
- const struct br_layout_box *b = &layout_boxes[i];
- unsigned int area;
- if (!b->valid || b->w <= 0 || b->h <= 0 ||
- x < b->x || y < b->y || x >= b->x + b->w ||
- y >= b->y + b->h)
- continue;
- area = (unsigned int)b->w * (unsigned int)b->h;
- if (area <= best_area) {
- best = i;
- best_area = area;
- }
- }
- return best;
- }
- static void handle_page_click(unsigned int *action)
- {
- int node;
- char url[BR_URL_MAX];
- if (!ui.pressed)
- return;
- if (ui.press_x < page_rect.x ||
- ui.press_x >= page_rect.x + page_rect.w - 12 ||
- ui.press_y < page_rect.y ||
- ui.press_y >= page_rect.y + page_rect.h)
- return;
- node = find_hit(ui.press_x, ui.press_y);
- if (!node) {
- unsigned int box;
- if (!js_browser_active())
- return;
- box = find_box_hit(ui.press_x, ui.press_y);
- if (box) {
- form_blur();
- js_browser_event(box, "click", 1, 1);
- }
- return;
- }
- if (form_is_control((unsigned int)node)) {
- form_click((unsigned int)node);
- return;
- }
- form_blur();
- if (!js_browser_event((unsigned int)node, "click", 1, 1))
- return;
- if (link_fragment_nav((unsigned int)node))
- return;
- if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
- sizeof(url)) != 0)
- return;
- s_copy(click_url, url, sizeof(click_url));
- *action |= ACT_NAV;
- }
- void _start(const char *arg)
- {
- struct win_info wi;
- if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
- u_win_create(960, 640, "Browser", &wi) != 0 &&
- u_win_create(780, 540, "Browser", &wi) != 0) {
- u_puts("browser: no graphics window\n");
- u_exit(1);
- }
- ufont_set_arena_bytes(BR_FONT_ARENA);
- ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
- url_in.placeholder = "http://...";
- br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
- ui.theme.accent);
- br_set_viewport(wi.width);
- if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
- s_copy(cwd, "/", sizeof(cwd));
- heap_clear();
- origin_cache_load();
- css_cache_init();
- script_cache_init();
- font_cache_init();
- persist_restore();
- hist_load();
- page_scroll.offset = 0;
- page_scroll.content_h = 0;
- if (arg && arg[0]) {
- navigate(arg, 1);
- } else {
- load_home(1);
- /* Start ready to type: keep the home page, but leave the address
- * bar empty instead of showing "about:home". */
- ngui_input_set(&url_in, "");
- ngui_set_focus(&ui, ID_URL);
- }
- for (;;) {
- unsigned int action = 0;
- unsigned int now;
- click_url[0] = '\0';
- if (pending_action) {
- action |= pending_action & ACT_WAIT_NAV;
- if (pending_url[0])
- s_copy(click_url, pending_url, sizeof(click_url));
- pending_action = 0;
- pending_url[0] = '\0';
- cancel_fetch = 0;
- } else if (preload_active) {
- if (preload_wait)
- preload_wait = 0;
- else
- preload_step();
- } else if ((preload_pending &&
- page_scroll.offset != preload_scroll) ||
- (preload_rescan && layout_valid)) {
- preload_scroll = page_scroll.offset;
- preload_rescan = 0;
- preload_pending = 0;
- preload_node = 0;
- preload_active = 1;
- }
- js_browser_tick();
- if (resize_pending && !pending_action) {
- resize_pending = 0;
- resize_sent_w = layout_right - layout_left;
- js_browser_window_event("resize");
- }
- persist_tick();
- if (pending_action)
- continue;
- now = u_ticks_ms();
- if (status_until && (int)(now - status_until) >= 0) {
- status_text[0] = '\0';
- status_until = 0;
- status_error = 0;
- ngui_invalidate(&ui);
- }
- if (!ngui_begin(&ui)) {
- /* A queued navigation (e.g. Enter in the URL bar during
- * a slow fetch) must be handled even when this frame
- * needs no redraw. */
- if (!action) {
- fetch_workers_stop_if_unfocused();
- u_sleep_ms(10);
- continue;
- }
- } else {
- draw(&action);
- handle_keys(&action);
- handle_page_click(&action);
- ngui_end(&ui);
- }
- if (action & ACT_NAV) {
- if (click_url[0]) {
- navigate(click_url, 1);
- click_url[0] = '\0';
- } else {
- navigate(url_in.text, 1);
- }
- }
- if (action & ACT_BACK) {
- if (hist_pos > 0) {
- hist_pos--;
- if (same_doc_fragment(history[hist_pos])) {
- page_set_fragment(history[hist_pos], 0);
- js_browser_hashchange();
- } else {
- navigate(history[hist_pos], 0);
- }
- }
- }
- if (action & ACT_FORWARD) {
- if (hist_pos + 1 < hist_len) {
- hist_pos++;
- if (same_doc_fragment(history[hist_pos])) {
- page_set_fragment(history[hist_pos], 0);
- js_browser_hashchange();
- } else {
- navigate(history[hist_pos], 0);
- }
- }
- }
- if (action & ACT_RELOAD) {
- if (s_eq(page_url, "about:home"))
- load_home(0);
- else
- navigate(page_url, 0);
- }
- if (action & ACT_HOME)
- load_home(1);
- if (action & ACT_CLOSE)
- quit = 1;
- if (quit)
- break;
- if (pending_action)
- continue;
- fetch_workers_stop_if_unfocused();
- u_sleep_ms(10);
- }
- fetch_workers_stop_all();
- u_win_close();
- u_exit(0);
- }
|