browser.c 340 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826118271182811829118301183111832118331183411835118361183711838118391184011841118421184311844118451184611847118481184911850118511185211853118541185511856118571185811859118601186111862118631186411865118661186711868118691187011871118721187311874118751187611877118781187911880118811188211883118841188511886118871188811889118901189111892118931189411895118961189711898118991190011901119021190311904119051190611907119081190911910119111191211913119141191511916119171191811919119201192111922119231192411925119261192711928119291193011931119321193311934119351193611937119381193911940119411194211943119441194511946119471194811949119501195111952119531195411955119561195711958119591196011961119621196311964119651196611967119681196911970119711197211973119741197511976119771197811979119801198111982119831198411985119861198711988119891199011991119921199311994119951199611997119981199912000120011200212003120041200512006120071200812009120101201112012120131201412015120161201712018120191202012021120221202312024120251202612027120281202912030120311203212033120341203512036120371203812039120401204112042120431204412045120461204712048120491205012051120521205312054120551205612057120581205912060120611206212063120641206512066120671206812069120701207112072120731207412075120761207712078120791208012081120821208312084120851208612087120881208912090120911209212093120941209512096120971209812099121001210112102121031210412105121061210712108121091211012111121121211312114121151211612117121181211912120121211212212123121241212512126121271212812129121301213112132121331213412135121361213712138121391214012141121421214312144121451214612147121481214912150121511215212153121541215512156121571215812159121601216112162121631216412165121661216712168121691217012171121721217312174121751217612177121781217912180121811218212183121841218512186121871218812189121901219112192121931219412195121961219712198121991220012201122021220312204122051220612207122081220912210122111221212213122141221512216122171221812219122201222112222122231222412225122261222712228122291223012231122321223312234122351223612237122381223912240122411224212243122441224512246122471224812249122501225112252122531225412255122561225712258122591226012261122621226312264122651226612267122681226912270122711227212273122741227512276122771227812279122801228112282122831228412285122861228712288122891229012291122921229312294122951229612297122981229912300123011230212303123041230512306123071230812309123101231112312123131231412315123161231712318123191232012321123221232312324123251232612327123281232912330123311233212333123341233512336123371233812339123401234112342123431234412345123461234712348123491235012351123521235312354123551235612357123581235912360123611236212363123641236512366123671236812369123701237112372123731237412375123761237712378123791238012381123821238312384123851238612387123881238912390123911239212393123941239512396123971239812399124001240112402124031240412405124061240712408124091241012411124121241312414124151241612417124181241912420124211242212423124241242512426124271242812429124301243112432124331243412435124361243712438124391244012441124421244312444124451244612447124481244912450124511245212453124541245512456124571245812459124601246112462124631246412465124661246712468124691247012471124721247312474124751247612477124781247912480124811248212483124841248512486124871248812489124901249112492124931249412495124961249712498124991250012501125021250312504125051250612507125081250912510125111251212513125141251512516125171251812519125201252112522125231252412525125261252712528125291253012531125321253312534125351253612537125381253912540125411254212543125441254512546125471254812549125501255112552125531255412555125561255712558125591256012561125621256312564125651256612567125681256912570125711257212573125741257512576125771257812579125801258112582125831258412585125861258712588125891259012591125921259312594125951259612597125981259912600126011260212603126041260512606126071260812609126101261112612126131261412615126161261712618126191262012621126221262312624126251262612627126281262912630126311263212633126341263512636126371263812639126401264112642126431264412645126461264712648126491265012651126521265312654126551265612657126581265912660126611266212663126641266512666126671266812669126701267112672126731267412675126761267712678126791268012681126821268312684126851268612687126881268912690126911269212693126941269512696126971269812699127001270112702127031270412705127061270712708127091271012711127121271312714127151271612717127181271912720127211272212723127241272512726127271272812729127301273112732127331273412735127361273712738127391274012741127421274312744127451274612747127481274912750127511275212753127541275512756127571275812759127601276112762127631276412765127661276712768127691277012771127721277312774127751277612777127781277912780127811278212783127841278512786127871278812789127901279112792127931279412795127961279712798127991280012801128021280312804128051280612807128081280912810128111281212813128141281512816128171281812819128201282112822128231282412825128261282712828128291283012831128321283312834128351283612837128381283912840128411284212843128441284512846128471284812849128501285112852128531285412855128561285712858128591286012861128621286312864128651286612867128681286912870128711287212873128741287512876128771287812879128801288112882128831288412885128861288712888128891289012891128921289312894
  1. /* browser: a small HTML/CSS browser built on ngui, the image library and the
  2. * shared uhttp client.
  3. *
  4. * Page scripts run on the vendored QuickJS engine (modern ECMAScript) through
  5. * the DOM layer in js_browser.c; forms render and submit natively. External CSS is loaded over uhttp, and images are
  6. * decoded with img.c and drawn inline. Page-scoped buffers (page body,
  7. * rules and image bitmaps) come from the ring-3 libc heap; each image gets an
  8. * exact-size decode arena that is freed as soon as the scaled bitmap exists.
  9. * The DOM and the image/CSS I/O scratch use fixed static arenas.
  10. */
  11. #include <stdlib.h>
  12. #include <stdio.h>
  13. #include <string.h>
  14. #include <math.h>
  15. #include <ucmd_heap.h>
  16. #include "ucmd_lib.h"
  17. #include "ngui.h"
  18. #include "browser_html.h"
  19. #include "js_browser.h"
  20. #include "uhttp.h"
  21. #include "uhttp_cookie.h"
  22. #include "img.h"
  23. #include "inflate.h"
  24. #include "ufont.h"
  25. #include "svg_raster.h"
  26. static void svg_cache_clear(void);
  27. static unsigned char *decode_arena; /* see decode_arena_get() */
  28. static unsigned int decode_arena_size;
  29. /* Start wide enough for the desktop nav; smaller screens fall back to
  30. * 960x640 and 780x540, which still fit a 1024x768 panel. */
  31. #define BR_W 1100
  32. #define BR_H 700
  33. #define BR_TOOLBAR_H 30
  34. #define BR_STATUS_H 18
  35. #define BR_PAGE_MAX (2u * 1024u * 1024u)
  36. #define BR_IMG_FILE_MAX (1024u * 1024u)
  37. #define BR_IMG_PIX_MAX (8u * 1024u * 1024u)
  38. #define BR_MAX_IMAGES 256
  39. /* Decoded display bitmaps share the page heap: cap their total pixels
  40. * (RGB565 plus an optional alpha plane) instead of their count. */
  41. #define BR_IMG_PIXEL_BUDGET (4u * 1024u * 1024u)
  42. #define BR_IMG_DISP_BUDGET (6u * 1024u * 1024u)
  43. #define BR_IMG_ARENA_MAX (24u * 1024u * 1024u)
  44. #define BR_IMG_LAYOUT_W 1000
  45. /* Decode completed image jobs for at most this long per main-loop pass, then
  46. * return to input/painting. One image per pass plus a 10 ms sleep made a
  47. * page of small icons trickle in. */
  48. #define BR_IMG_DECODE_BUDGET_MS 40u
  49. /* Coalesce image-driven repaints: each decode invalidates the page, and a
  50. * full repaint per image made loading superlinear on image-heavy pages. */
  51. #define BR_IMG_REPAINT_MS 100u
  52. #define BR_IMG_STAT_LOG 3584
  53. /* An image job may hold a fetch helper this long. The page/script
  54. * deadline (UHTTP_TOTAL_TIMEOUT_MS) is minutes; one unreachable image host
  55. * must not starve the other images of all four helpers that long. */
  56. #define BR_IMG_JOB_TIMEOUT_MS 30000u
  57. #define BR_CSS_MAX (832u * 1024u)
  58. #define BR_CSS_COMP_MAX (192u * 1024u)
  59. /* Scripts and ES modules: Vite bundles reach ~1.7 MB (the Cloudron
  60. * dashboard's main chunk); the helper's FETCH_MAX is the same 2 MB. */
  61. #define BR_SCRIPT_MAX (2u * 1024u * 1024u)
  62. #define FETCH_ABORT (-2)
  63. /* Session cache for remote stylesheets (per launch; cleared at startup). */
  64. #define CSS_CACHE_MAX 16
  65. #define CSS_CACHE_FILE_MAX (256u * 1024u)
  66. #define CSS_CACHE_PREFIX "bcss-"
  67. #define SCRIPT_CACHE_MAX 24
  68. #define SCRIPT_CACHE_FILE_MAX BR_SCRIPT_MAX
  69. #define SCRIPT_CACHE_PREFIX "bjs-"
  70. #define BR_MAX_SHEETS 6
  71. #define BR_HISTORY 16
  72. #define BR_URL_MAX 4096 /* = UHTTP_PATH_MAX: google.com's JS URL is ~3.7 KB */
  73. #define BR_STATUS_MAX 200
  74. #define BR_IMG_RGB565(r, g, b) \
  75. ((unsigned short)((((r) >> 3) << 11) | (((g) >> 2) << 5) | ((b) >> 3)))
  76. #define BR_GRAY 0x8410
  77. enum {
  78. ID_URL = 1,
  79. ID_GO,
  80. ID_BACK,
  81. ID_FORWARD,
  82. ID_RELOAD,
  83. ID_HOME
  84. };
  85. #define ACT_NAV (1u << 0)
  86. #define ACT_BACK (1u << 1)
  87. #define ACT_FORWARD (1u << 2)
  88. #define ACT_RELOAD (1u << 3)
  89. #define ACT_HOME (1u << 4)
  90. #define ACT_CLOSE (1u << 5)
  91. #define ACT_WAIT_NAV (ACT_NAV | ACT_BACK | ACT_FORWARD | ACT_RELOAD | \
  92. ACT_HOME | ACT_CLOSE)
  93. struct br_image {
  94. int state; /* 0 empty, 1 ready */
  95. struct img_image img; /* scaled bitmap at <= BR_IMG_LAYOUT_W */
  96. int native_w, native_h;
  97. unsigned int url_hash; /* <img> source, 0 = not shareable */
  98. char err[32];
  99. /* Display-size cache: the box an image is actually painted in. The
  100. * source bitmap above is deliberately capped at BR_IMG_LAYOUT_W so a
  101. * window resize can re-scale it; the cached copy is exactly dw x dh,
  102. * so every repaint is a 1:1 blit instead of a per-pixel resample. */
  103. struct img_image disp;
  104. unsigned int disp_pixels;
  105. unsigned int disp_last;
  106. };
  107. static struct ngui ui;
  108. static struct ngui_input url_in;
  109. static struct ngui_scroll page_scroll;
  110. static struct br_doc doc;
  111. static struct br_image images[BR_MAX_IMAGES];
  112. static int image_count;
  113. static unsigned int image_pixels;
  114. static unsigned int image_disp_pixels;
  115. static unsigned int image_disp_clock;
  116. /* Per-image pipeline timing for the status line and /share/IMGSTAT. The
  117. * numbers are what decides whether the next work is network, decode or
  118. * display; keep them cheap (one tick read per phase). */
  119. static unsigned int img_stat_start;
  120. static unsigned int img_stat_wall;
  121. static unsigned int img_stat_net;
  122. static unsigned int img_stat_open;
  123. static unsigned int img_stat_first;
  124. static unsigned int img_stat_io;
  125. static unsigned int img_stat_dec;
  126. static unsigned int img_stat_scale;
  127. static unsigned int img_stat_paint;
  128. static unsigned int img_stat_reflow;
  129. static unsigned int img_stat_bytes;
  130. static int img_stat_n;
  131. static unsigned int img_last_dec_ms;
  132. static unsigned int img_last_scale_ms;
  133. static char img_stat_log[BR_IMG_STAT_LOG];
  134. static unsigned int img_stat_log_len;
  135. static unsigned int img_repaint_ms;
  136. static int img_repaint_pending;
  137. /* Painted border boxes, in page/screen coordinates (layout starts at
  138. * page_rect.y + 4 - scroll). getBoundingClientRect() subtracts page_rect. */
  139. struct br_layout_box {
  140. int x, y;
  141. int w, h;
  142. unsigned char valid;
  143. };
  144. static struct br_layout_box layout_boxes[BR_MAX_NODES];
  145. /* Images are loaded one per main-loop iteration so the parsed page stays
  146. * interactive while a slow network/TLS fetch or 4K decode is in progress. */
  147. static int preload_active;
  148. static int preload_max_jobs;
  149. static int preload_pending;
  150. static int preload_wait;
  151. static unsigned int preload_node;
  152. static int preload_loaded;
  153. static int preload_scroll;
  154. static int preload_rescan;
  155. static char post_status_text[BR_STATUS_MAX];
  156. static int post_status_error;
  157. static unsigned int post_status_ttl;
  158. /* Content-relative position/height of each <img>, recorded by the measure
  159. * pass so image loading can be deferred until it is near the viewport. */
  160. static unsigned short img_top[BR_MAX_NODES];
  161. static unsigned short img_h[BR_MAX_NODES];
  162. /* One reusable I/O buffer: the two halves double as the gzip input scratch
  163. * for page/CSS fetches, where the heap has no room for another multi-megabyte
  164. * body. Decode arenas are allocated per image instead of living here. */
  165. static unsigned char *image_io_buf;
  166. static struct ufont_face *font_faces[BR_MAX_FACES];
  167. #define image_file_buf (image_io_buf)
  168. #define image_comp_buf (image_io_buf + BR_IMG_FILE_MAX)
  169. #define BR_PAGE_COMP_MAX (2u * BR_IMG_FILE_MAX)
  170. static struct inflate image_inflate_ws;
  171. #if BR_CSS_MAX + BR_CSS_COMP_MAX > 2u * BR_IMG_FILE_MAX
  172. #error "CSS scratch must fit in image_io_buf"
  173. #endif
  174. static char page_url[BR_URL_MAX];
  175. static char page_title[BR_TITLE_MAX];
  176. static char cwd[64];
  177. static int page_is_local;
  178. static int page_loading;
  179. static char status_text[BR_STATUS_MAX];
  180. static unsigned int status_until;
  181. static int status_error;
  182. static char history[BR_HISTORY][BR_URL_MAX];
  183. static int hist_len, hist_pos;
  184. static char click_url[BR_URL_MAX];
  185. static char pending_url[BR_URL_MAX];
  186. #define BR_POST_MAX 4096
  187. static char pending_post[BR_POST_MAX];
  188. static unsigned int pending_post_len;
  189. /* The pending navigation is a POST even when its body is empty (a form
  190. * without fields, e.g. the OIDC consent auto-submit). */
  191. static int pending_post_is;
  192. /* window "resize" bookkeeping: the page width the last event was for. */
  193. static int resize_sent_w = -1;
  194. static int resize_pending;
  195. static unsigned int pending_action;
  196. static int cancel_fetch;
  197. static int quit;
  198. static struct ngui_rect page_rect;
  199. static unsigned short *page_backbuf;
  200. static int pagebuf_w, pagebuf_h;
  201. static int page_cache_valid;
  202. static int page_cache_scroll;
  203. static unsigned int page_cache_nnode;
  204. static int page_cache_x, page_cache_y, page_cache_w, page_cache_h;
  205. static int layout_valid, layout_left, layout_right;
  206. /* Height of the page viewport: what html/body height:100% resolves to. */
  207. static int layout_view_h;
  208. static unsigned int layout_nnode;
  209. static int layout_content_h;
  210. /* layout output */
  211. struct lay_run {
  212. unsigned int off;
  213. unsigned short len;
  214. unsigned short gap;
  215. unsigned short color;
  216. unsigned short href;
  217. char lit[28];
  218. short img;
  219. signed short dy; /* inline image vertical offset */
  220. unsigned short iw, ih;
  221. unsigned short w;
  222. unsigned char font_px, bold, italic, mono, underline, strike;
  223. unsigned char overline, font_face;
  224. unsigned char transform_scale;
  225. unsigned char origin_x_kind, origin_y_kind;
  226. signed short scale_x, scale_y, rotate_x100;
  227. signed short origin_x, origin_y;
  228. unsigned char has_lit;
  229. unsigned int form; /* node + 1, 0 = not a control */
  230. unsigned char form_kind;
  231. unsigned char form_disabled;
  232. };
  233. struct lay {
  234. int draw;
  235. struct ngui *ui;
  236. int left, right;
  237. int y;
  238. int line_x, line_y, line_h;
  239. int line_left, line_right;
  240. int parent_top;
  241. int cb_left, cb_right, cb_top; /* containing block for absolute boxes */
  242. int cb_h; /* definite content height of the containing block for
  243. * percentage heights; 0 = indefinite (auto) */
  244. int run_x;
  245. int align;
  246. int depth;
  247. int space_pending;
  248. unsigned char float_active;
  249. int float_left, float_right, float_bottom;
  250. struct lay_run runs[96];
  251. int nruns;
  252. };
  253. struct hit {
  254. int x, y, w, h;
  255. unsigned short node;
  256. };
  257. /* Live form state; the DOM attributes stay the initial/default value. */
  258. #define FORM_MAX 64
  259. #define FORM_VALUE_MAX 63
  260. enum {
  261. FORM_TEXT, FORM_PASSWORD, FORM_CHECKBOX, FORM_RADIO,
  262. FORM_BUTTON, FORM_SUBMIT, FORM_RESET, FORM_SELECT, FORM_TEXTAREA
  263. };
  264. struct form_state {
  265. unsigned int node;
  266. char value[FORM_VALUE_MAX + 1];
  267. unsigned char len, caret, checked, selected, used;
  268. };
  269. static struct form_state form_states[FORM_MAX];
  270. static unsigned int form_focus;
  271. static unsigned int form_dirty;
  272. static int form_descendant(unsigned int node, unsigned int form);
  273. static int form_submit_form(unsigned int node, int fire_event);
  274. static int link_fragment_nav(unsigned int node);
  275. static void history_push(const char *url);
  276. static void form_reset_event(unsigned int form);
  277. static unsigned int s_len(const char *s);
  278. static int s_eq(const char *a, const char *b);
  279. static void form_key(int k);
  280. static void form_click(unsigned int node);
  281. static void style_for_node(unsigned int node, struct br_style *out);
  282. static int form_author_styled(const struct br_style *st);
  283. static int css_radius(const struct br_style *st, int corner, int w, int h);
  284. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  285. const struct br_style *st, int focused);
  286. static int form_disabled(unsigned int node)
  287. {
  288. struct br_node *n = &doc.nodes[node];
  289. if (n->attr_flags & BR_ATTR_DISABLED)
  290. return 1;
  291. return br_find_attr(&doc, node, "disabled") != 0;
  292. }
  293. static int form_kind_of(unsigned int node)
  294. {
  295. const char *type = br_type(&doc, node);
  296. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  297. return FORM_TEXTAREA;
  298. if (doc.nodes[node].tag == BR_TAG_SELECT)
  299. return FORM_SELECT;
  300. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  301. if (s_eq(type, "reset"))
  302. return FORM_RESET;
  303. if (s_eq(type, "button"))
  304. return FORM_BUTTON;
  305. return FORM_SUBMIT;
  306. }
  307. if (s_eq(type, "password"))
  308. return FORM_PASSWORD;
  309. if (s_eq(type, "checkbox"))
  310. return FORM_CHECKBOX;
  311. if (s_eq(type, "radio"))
  312. return FORM_RADIO;
  313. if (s_eq(type, "submit"))
  314. return FORM_SUBMIT;
  315. if (s_eq(type, "reset"))
  316. return FORM_RESET;
  317. if (s_eq(type, "button"))
  318. return FORM_BUTTON;
  319. return FORM_TEXT;
  320. }
  321. static unsigned int form_option_count(unsigned int node)
  322. {
  323. unsigned int c, n = 0;
  324. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  325. if (doc.nodes[c].type == BR_NODE_ELEM &&
  326. doc.nodes[c].tag == BR_TAG_OPTION)
  327. n++;
  328. return n;
  329. }
  330. static unsigned int form_option_selected(unsigned int node)
  331. {
  332. unsigned int c, i = 0;
  333. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  334. if (doc.nodes[c].type != BR_NODE_ELEM ||
  335. doc.nodes[c].tag != BR_TAG_OPTION)
  336. continue;
  337. if (br_find_attr(&doc, c, "selected"))
  338. return i;
  339. i++;
  340. }
  341. return 0;
  342. }
  343. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  344. char *out, unsigned int cap)
  345. {
  346. unsigned int c, i = 0;
  347. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  348. if (doc.nodes[c].type != BR_NODE_ELEM ||
  349. doc.nodes[c].tag != BR_TAG_OPTION)
  350. continue;
  351. if (i == idx)
  352. return br_text_content(&doc, c, out, cap);
  353. i++;
  354. }
  355. return 0;
  356. }
  357. static struct form_state *form_get(unsigned int node, int create)
  358. {
  359. struct form_state *slot = 0;
  360. unsigned int i;
  361. for (i = 0; i < FORM_MAX; i++) {
  362. if (form_states[i].used) {
  363. if (form_states[i].node == node)
  364. return &form_states[i];
  365. } else if (!slot) {
  366. slot = &form_states[i];
  367. }
  368. }
  369. if (!create || !slot)
  370. return 0;
  371. slot->node = node;
  372. slot->len = 0;
  373. slot->caret = 0;
  374. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  375. slot->selected = form_option_selected(node);
  376. slot->used = 1;
  377. {
  378. unsigned int n = 0;
  379. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  380. n = br_text_content(&doc, node, slot->value,
  381. FORM_VALUE_MAX + 1);
  382. } else {
  383. const char *v = br_value(&doc, node);
  384. if (v) {
  385. n = s_len(v);
  386. if (n > FORM_VALUE_MAX)
  387. n = FORM_VALUE_MAX;
  388. for (unsigned int j = 0; j < n; j++)
  389. slot->value[j] = v[j];
  390. }
  391. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  392. n = br_text_content(&doc, node, slot->value,
  393. FORM_VALUE_MAX + 1);
  394. }
  395. if (n > FORM_VALUE_MAX)
  396. n = FORM_VALUE_MAX;
  397. slot->value[n] = '\0';
  398. slot->len = (unsigned char)n;
  399. slot->caret = (unsigned char)n;
  400. }
  401. return slot;
  402. }
  403. static void form_reset_state(void)
  404. {
  405. unsigned int i;
  406. for (i = 0; i < FORM_MAX; i++)
  407. form_states[i].used = 0;
  408. form_focus = 0;
  409. }
  410. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  411. * is laid out like a normal element so that content shows; only a text or
  412. * empty button is drawn as a native control. Clicks still reach it
  413. * through the box hit test. */
  414. static int button_has_elements(unsigned int node)
  415. {
  416. unsigned int c;
  417. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  418. return 0;
  419. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  420. if (doc.nodes[c].type == BR_NODE_ELEM)
  421. return 1;
  422. return 0;
  423. }
  424. static int form_is_control(unsigned int node)
  425. {
  426. unsigned int tag;
  427. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  428. return 0;
  429. tag = doc.nodes[node].tag;
  430. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  431. tag == BR_TAG_SELECT ||
  432. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  433. }
  434. #define HIT_MAX 96
  435. static struct hit hits[HIT_MAX];
  436. static int nhits;
  437. static unsigned short block_h[BR_MAX_NODES];
  438. /* Measure-pass top of each block, in the same document coordinates as
  439. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  440. * paint, so it cannot drive the lazy background loader). */
  441. static unsigned short block_top[BR_MAX_NODES];
  442. static char li_marker[BR_MAX_NODES][12];
  443. /* one connection object; the browser fetches one resource at a time */
  444. /* ---- tiny strings ---- */
  445. static unsigned int s_len(const char *s)
  446. {
  447. unsigned int n = 0;
  448. while (s && s[n])
  449. n++;
  450. return n;
  451. }
  452. static void s_copy(char *d, const char *s, unsigned int cap)
  453. {
  454. unsigned int i = 0;
  455. if (!cap)
  456. return;
  457. while (s && s[i] && i + 1 < cap) {
  458. d[i] = s[i];
  459. i++;
  460. }
  461. d[i] = '\0';
  462. }
  463. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  464. {
  465. while (s && *s && *n + 1 < cap)
  466. d[(*n)++] = *s++;
  467. d[*n] = '\0';
  468. }
  469. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  470. unsigned int cap)
  471. {
  472. char tmp[12];
  473. unsigned int i = 0, j;
  474. do {
  475. tmp[i++] = (char)('0' + v % 10);
  476. v /= 10;
  477. } while (v && i < sizeof(tmp));
  478. for (j = 0; j < i && *n + 1 < cap; j++)
  479. d[(*n)++] = tmp[i - 1 - j];
  480. d[*n] = '\0';
  481. }
  482. static int s_eq(const char *a, const char *b)
  483. {
  484. while (*a && *b) {
  485. if (*a != *b)
  486. return 0;
  487. a++;
  488. b++;
  489. }
  490. return *a == *b;
  491. }
  492. static int starts_with(const char *s, const char *p)
  493. {
  494. unsigned int i = 0;
  495. while (p[i]) {
  496. if (s[i] != p[i])
  497. return 0;
  498. i++;
  499. }
  500. return 1;
  501. }
  502. static int contains_ci(const char *s, const char *p)
  503. {
  504. unsigned int i, j;
  505. for (i = 0; s[i]; i++) {
  506. for (j = 0; p[j]; j++) {
  507. char a = s[i + j];
  508. if (a >= 'A' && a <= 'Z')
  509. a = (char)(a - 'A' + 'a');
  510. if (a != p[j])
  511. break;
  512. }
  513. if (!p[j])
  514. return 1;
  515. }
  516. return 0;
  517. }
  518. static char *trim(char *s)
  519. {
  520. unsigned int n;
  521. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  522. s++;
  523. n = s_len(s);
  524. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  525. s[n - 1] == '\r' || s[n - 1] == '\n'))
  526. s[--n] = '\0';
  527. return s;
  528. }
  529. /* ---- per-process heap ---- */
  530. static int heap_start(void)
  531. {
  532. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  533. if (!image_io_buf)
  534. return -1;
  535. page_backbuf = (unsigned short *)malloc(
  536. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  537. pagebuf_w = page_backbuf ? ui.w : 0;
  538. pagebuf_h = page_backbuf ? ui.h : 0;
  539. page_cache_valid = 0;
  540. return 0;
  541. }
  542. static void heap_clear(void)
  543. {
  544. memset(font_faces, 0, sizeof(font_faces));
  545. ngui_font_detach(&ui);
  546. svg_cache_clear();
  547. decode_arena = 0; /* lives in the page heap too */
  548. decode_arena_size = 0;
  549. heap_reset();
  550. /* The document arenas live in that heap; drop the stale pointers so
  551. * the next br_parse_plain() allocates fresh ones. */
  552. doc.nodes = 0;
  553. doc.text = 0;
  554. doc.attrs = 0;
  555. image_io_buf = 0;
  556. page_backbuf = 0;
  557. pagebuf_w = pagebuf_h = 0;
  558. page_cache_valid = 0;
  559. }
  560. static void browser_rules_alloc(void)
  561. {
  562. struct br_rule *rules;
  563. rules = (struct br_rule *)malloc(
  564. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  565. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  566. }
  567. /* ---- status ---- */
  568. static void set_status(const char *s, int err, unsigned int ttl_ms)
  569. {
  570. s_copy(status_text, s, sizeof(status_text));
  571. status_error = err;
  572. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  573. ngui_invalidate(&ui);
  574. }
  575. /* Update the status text without forcing a frame; the throttled image
  576. * repaint picks it up. Starting one helper per image used to invalidate the
  577. * whole page before every decode. */
  578. static void set_status_quiet(const char *s)
  579. {
  580. s_copy(status_text, s, sizeof(status_text));
  581. status_error = 0;
  582. status_until = 0;
  583. }
  584. /* ---- JavaScript ---- */
  585. static int resolve_link(const char *base, const char *href, char *out,
  586. unsigned int cap);
  587. static char js_last_status[BR_STATUS_MAX];
  588. static int js_last_error;
  589. static void js_host_status(const char *msg, int error)
  590. {
  591. s_copy(js_last_status, msg, sizeof(js_last_status));
  592. js_last_error = error;
  593. set_status(msg, error, 6000);
  594. }
  595. static void js_host_report(const char *msg)
  596. {
  597. u_puts("[js] ");
  598. u_puts(msg);
  599. u_putc('\n');
  600. s_copy(js_last_status, msg, sizeof(js_last_status));
  601. js_last_error = 1;
  602. set_status(msg, 1, 8000);
  603. }
  604. static void js_host_navigate(const char *url)
  605. {
  606. char resolved[BR_URL_MAX];
  607. if (!url || !url[0])
  608. return;
  609. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  610. return;
  611. s_copy(pending_url, resolved, sizeof(pending_url));
  612. pending_action |= ACT_NAV;
  613. cancel_fetch = 1;
  614. }
  615. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  616. * back/forward between fragments): the page URL, address bar and history
  617. * follow, nothing is reloaded. `push` adds a history entry. */
  618. static int page_set_fragment(const char *url, int push)
  619. {
  620. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  621. return -1;
  622. s_copy(page_url, url, sizeof(page_url));
  623. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  624. url_in.len = s_len(url_in.text);
  625. url_in.cursor = url_in.len;
  626. url_in.scroll = 0;
  627. if (push)
  628. history_push(page_url);
  629. ngui_invalidate(&ui);
  630. return 0;
  631. }
  632. static int js_host_set_hash(const char *url)
  633. {
  634. return page_set_fragment(url, 1);
  635. }
  636. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  637. * the page, so a hash router can react). */
  638. static int same_doc_fragment(const char *url)
  639. {
  640. unsigned int a = 0, b = 0;
  641. if (!js_browser_active() || !url)
  642. return 0;
  643. while (url[a] && url[a] != '#')
  644. a++;
  645. while (page_url[b] && page_url[b] != '#')
  646. b++;
  647. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  648. !s_eq(url, page_url);
  649. }
  650. static void js_host_changed(void)
  651. {
  652. /* Class/style/attribute mutations change computed styles, not just the
  653. * text: drop the per-node style cache before the next layout. */
  654. br_reset_styles(&doc);
  655. layout_valid = 0;
  656. /* Script-built content (Angular's ng-repeat cards) brings new images
  657. * and inline background styles: rescan once the main loop is idle. */
  658. preload_rescan = 1;
  659. ngui_invalidate(&ui);
  660. }
  661. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  662. {
  663. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  664. return 0;
  665. *x = layout_boxes[node].x - page_rect.x;
  666. *y = layout_boxes[node].y - page_rect.y;
  667. *w = layout_boxes[node].w;
  668. *h = layout_boxes[node].h;
  669. return 1;
  670. }
  671. static void form_copy_out(const char *s, char *buf, int cap)
  672. {
  673. int i = 0;
  674. if (!buf || cap <= 0)
  675. return;
  676. while (s && s[i] && i + 1 < cap) {
  677. buf[i] = s[i];
  678. i++;
  679. }
  680. buf[i] = '\0';
  681. }
  682. static int js_host_form_value(unsigned int node, char *buf, int cap)
  683. {
  684. struct form_state *fs;
  685. int kind;
  686. if (!form_is_control(node))
  687. return 0;
  688. kind = form_kind_of(node);
  689. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  690. return 0;
  691. if (kind == FORM_SELECT) {
  692. char opt[64] = "";
  693. unsigned int c, i = 0;
  694. fs = form_get(node, 1);
  695. if (!fs)
  696. return 0;
  697. form_option_text(node, fs->selected, opt, sizeof(opt));
  698. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  699. if (doc.nodes[c].type != BR_NODE_ELEM ||
  700. doc.nodes[c].tag != BR_TAG_OPTION)
  701. continue;
  702. if (i == fs->selected) {
  703. const char *v = br_value(&doc, c);
  704. if (v && v[0])
  705. form_copy_out(v, buf, cap);
  706. else
  707. form_copy_out(opt, buf, cap);
  708. return 1;
  709. }
  710. i++;
  711. }
  712. form_copy_out(opt, buf, cap);
  713. return 1;
  714. }
  715. fs = form_get(node, 1);
  716. if (!fs)
  717. return 0;
  718. form_copy_out(fs->value, buf, cap);
  719. return 1;
  720. }
  721. static int js_host_form_checked(unsigned int node)
  722. {
  723. struct form_state *fs;
  724. int kind;
  725. if (!form_is_control(node))
  726. return -1;
  727. kind = form_kind_of(node);
  728. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  729. return -1;
  730. fs = form_get(node, 1);
  731. return fs ? fs->checked : 0;
  732. }
  733. static int js_host_form_selected(unsigned int node)
  734. {
  735. struct form_state *fs;
  736. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  737. return -1;
  738. fs = form_get(node, 1);
  739. return fs ? fs->selected : 0;
  740. }
  741. static int js_host_form_set_value(unsigned int node, const char *value)
  742. {
  743. struct form_state *fs;
  744. unsigned int n;
  745. if (!form_is_control(node))
  746. return 0;
  747. fs = form_get(node, 1);
  748. if (!fs)
  749. return 0;
  750. n = s_len(value ? value : "");
  751. if (n > FORM_VALUE_MAX)
  752. n = FORM_VALUE_MAX;
  753. for (unsigned int i = 0; i < n; i++)
  754. fs->value[i] = value[i];
  755. fs->value[n] = '\0';
  756. fs->len = (unsigned char)n;
  757. fs->caret = (unsigned char)n;
  758. layout_valid = 0;
  759. ngui_invalidate(&ui);
  760. return 1;
  761. }
  762. static int js_host_form_set_checked(unsigned int node, int checked)
  763. {
  764. struct form_state *fs;
  765. int kind;
  766. if (!form_is_control(node))
  767. return 0;
  768. kind = form_kind_of(node);
  769. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  770. return 0;
  771. fs = form_get(node, 1);
  772. if (!fs)
  773. return 0;
  774. fs->checked = (unsigned char)(checked != 0);
  775. layout_valid = 0;
  776. ngui_invalidate(&ui);
  777. return 1;
  778. }
  779. static int js_host_form_set_selected(unsigned int node, int index)
  780. {
  781. struct form_state *fs;
  782. unsigned int n;
  783. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  784. return 0;
  785. fs = form_get(node, 1);
  786. if (!fs)
  787. return 0;
  788. n = form_option_count(node);
  789. if (index < 0)
  790. index = 0;
  791. if (n && (unsigned int)index >= n)
  792. index = (int)n - 1;
  793. fs->selected = (unsigned char)index;
  794. layout_valid = 0;
  795. ngui_invalidate(&ui);
  796. return 1;
  797. }
  798. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  799. {
  800. unsigned int i;
  801. int n = 0;
  802. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  803. doc.nodes[form].tag != BR_TAG_FORM)
  804. return 0;
  805. for (i = 0; i < doc.nnode && n < cap; i++) {
  806. struct br_node *nd = &doc.nodes[i];
  807. if (i == form || nd->type != BR_NODE_ELEM)
  808. continue;
  809. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  810. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  811. continue;
  812. if (!form_descendant(i, form))
  813. continue;
  814. out[n++] = i;
  815. }
  816. return n;
  817. }
  818. static int js_host_form_submit(unsigned int form)
  819. {
  820. form_submit_form(form, 0);
  821. return 1;
  822. }
  823. static int js_host_form_reset(unsigned int form)
  824. {
  825. form_reset_event(form);
  826. return 1;
  827. }
  828. static void css_computed_name(const char *p, char *out, int cap)
  829. {
  830. int n = 0;
  831. for (; p && *p && n + 2 < cap; p++) {
  832. char c = *p;
  833. if (c >= 'A' && c <= 'Z') {
  834. out[n++] = '-';
  835. c = (char)(c - 'A' + 'a');
  836. } else if (c == '_') {
  837. c = '-';
  838. } else if (c >= 'a' && c <= 'z') {
  839. /* keep */
  840. }
  841. out[n++] = c;
  842. }
  843. out[n] = '\0';
  844. if (!strcmp(out, "css-float"))
  845. strcpy(out, "float");
  846. }
  847. static void css_rgb(unsigned short c, char *buf, int cap)
  848. {
  849. int r = ((c >> 11) & 31) * 255 / 31;
  850. int g = ((c >> 5) & 63) * 255 / 63;
  851. int b = (c & 31) * 255 / 31;
  852. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  853. }
  854. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  855. int font_px)
  856. {
  857. if (unit == 4) {
  858. snprintf(buf, cap, "auto");
  859. } else if (unit == 0) {
  860. snprintf(buf, cap, "%dpx", raw);
  861. } else if (unit == 1) {
  862. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  863. } else if (unit == 2) {
  864. /* Chrome's getComputedStyle() reports used pixel values. */
  865. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  866. } else if (unit == 3) {
  867. snprintf(buf, cap, "%dpx",
  868. (int)br_root_font_px() * raw / 100);
  869. } else {
  870. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  871. raw / 100, raw % 100, px);
  872. }
  873. }
  874. static int js_host_computed(unsigned int node, const char *property,
  875. char *buf, int cap)
  876. {
  877. struct br_style st;
  878. char name[40];
  879. /* Node 0 is a real element when the page starts with <html>. */
  880. if (!buf || cap <= 0 || node >= doc.nnode ||
  881. (node == 0 && doc.nodes[0].type != BR_NODE_ELEM))
  882. return 0;
  883. buf[0] = '\0';
  884. css_computed_name(property, name, sizeof(name));
  885. style_for_node(node, &st);
  886. if (!strcmp(name, "display")) {
  887. const char *v = "inline";
  888. if (st.display == BR_DISPLAY_BLOCK)
  889. v = "block";
  890. else if (st.display == BR_DISPLAY_NONE)
  891. v = "none";
  892. else if (st.display == BR_DISPLAY_FLEX)
  893. v = "flex";
  894. else if (st.display == BR_DISPLAY_GRID)
  895. v = "grid";
  896. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  897. v = "inline-block";
  898. snprintf(buf, cap, "%s", v);
  899. } else if (!strcmp(name, "position")) {
  900. static const char *pos[] = {
  901. "static", "absolute", "fixed", "relative", "sticky"
  902. };
  903. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  904. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  905. int is_w = name[0] == 'w';
  906. int kind = is_w ? st.width_kind : st.height_kind;
  907. int val = is_w ? st.width : st.height;
  908. if (kind == 3) {
  909. if (is_w)
  910. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  911. st.width_calc_pct / 100,
  912. st.width_calc_pct % 100,
  913. st.width_calc_px);
  914. else
  915. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  916. st.height_calc_pct / 100,
  917. st.height_calc_pct % 100,
  918. st.height_calc_px);
  919. } else if (kind == 1) {
  920. snprintf(buf, cap, "%dpx", val);
  921. } else if (kind == 2) {
  922. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  923. } else {
  924. snprintf(buf, cap, "auto");
  925. }
  926. } else if (!strcmp(name, "color") ||
  927. !strcmp(name, "background-color")) {
  928. if (!strcmp(name, "background-color") && !st.has_bg)
  929. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  930. else
  931. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  932. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  933. int is_fill = name[0] == 'f';
  934. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  935. if (mode == BR_PAINT_COLOR)
  936. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  937. else if (mode == BR_PAINT_CURRENT)
  938. css_rgb(st.color, buf, cap);
  939. else if (mode == BR_PAINT_UNSET && is_fill)
  940. snprintf(buf, cap, "rgb(0, 0, 0)");
  941. else if (mode == BR_PAINT_URL)
  942. snprintf(buf, cap, "url()");
  943. else
  944. snprintf(buf, cap, "none");
  945. } else if (!strcmp(name, "font-size")) {
  946. snprintf(buf, cap, "%dpx", st.font_px);
  947. } else if (!strcmp(name, "font-weight")) {
  948. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  949. } else if (!strcmp(name, "font-style")) {
  950. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  951. } else if (!strcmp(name, "font-family")) {
  952. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  953. br_font_face_family(st.font_face)[0])
  954. snprintf(buf, cap, "%s",
  955. br_font_face_family(st.font_face));
  956. else
  957. snprintf(buf, cap, "%s",
  958. st.mono ? "monospace" : "sans-serif");
  959. } else if (!strcmp(name, "text-align")) {
  960. static const char *al[] = { "left", "center", "right", "justify" };
  961. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  962. } else if (!strcmp(name, "float")) {
  963. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  964. st.float_left == 2 ? "right" : "none");
  965. } else if (!strcmp(name, "clear")) {
  966. static const char *cl[] = { "none", "left", "right", "both" };
  967. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  968. } else if (!strcmp(name, "opacity")) {
  969. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  970. } else if (!strcmp(name, "visibility")) {
  971. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  972. } else if (!strcmp(name, "overflow")) {
  973. snprintf(buf, cap, "%s",
  974. st.overflow_hidden ? "hidden" : "visible");
  975. } else if (!strcmp(name, "white-space")) {
  976. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  977. } else if (!strcmp(name, "text-transform")) {
  978. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  979. } else if (!strcmp(name, "box-sizing")) {
  980. snprintf(buf, cap, "%s",
  981. st.box_sizing ? "border-box" : "content-box");
  982. } else if (!strcmp(name, "line-height")) {
  983. if (st.line_h_px)
  984. snprintf(buf, cap, "%dpx", st.line_h_px);
  985. else if (st.line_h_pct)
  986. snprintf(buf, cap, "%d%%", st.line_h_pct);
  987. else
  988. snprintf(buf, cap, "normal");
  989. } else if (!strcmp(name, "z-index")) {
  990. if (st.z_set)
  991. snprintf(buf, cap, "%d", st.z_index);
  992. else
  993. snprintf(buf, cap, "auto");
  994. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  995. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  996. int set = name[0] == 't' ? st.top_set :
  997. name[0] == 'l' ? st.left_set :
  998. name[0] == 'r' ? st.right_set : st.bottom_set;
  999. int v = name[0] == 't' ? st.top :
  1000. name[0] == 'l' ? st.left :
  1001. name[0] == 'r' ? st.right : st.bottom;
  1002. if (set)
  1003. snprintf(buf, cap, "%dpx", v);
  1004. else
  1005. snprintf(buf, cap, "auto");
  1006. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1007. !strcmp(name, "margin-bottom") ||
  1008. !strcmp(name, "margin-left") ||
  1009. !strcmp(name, "padding-top") ||
  1010. !strcmp(name, "padding-right") ||
  1011. !strcmp(name, "padding-bottom") ||
  1012. !strcmp(name, "padding-left")) {
  1013. int is_pad = name[0] == 'p';
  1014. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1015. name[strlen(name) - 1] == 't' ? 1 :
  1016. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1017. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1018. if (!strcmp(name, "margin-right") ||
  1019. !strcmp(name, "padding-right"))
  1020. side = 1;
  1021. else if (!strcmp(name, "margin-bottom") ||
  1022. !strcmp(name, "padding-bottom"))
  1023. side = 2;
  1024. else if (!strcmp(name, "margin-left") ||
  1025. !strcmp(name, "padding-left"))
  1026. side = 3;
  1027. else
  1028. side = 0;
  1029. side += is_pad ? 4 : 0;
  1030. css_mp_value(buf, cap,
  1031. side == 0 ? st.mt : side == 1 ? st.mr :
  1032. side == 2 ? st.mb : side == 3 ? st.ml :
  1033. side == 4 ? st.pt : side == 5 ? st.pr :
  1034. side == 6 ? st.pb : st.pl,
  1035. st.mp_unit[side], st.mp_calc_px[side],
  1036. st.font_px);
  1037. } else if (!strcmp(name, "border-top-width") ||
  1038. !strcmp(name, "border-right-width") ||
  1039. !strcmp(name, "border-bottom-width") ||
  1040. !strcmp(name, "border-left-width")) {
  1041. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1042. name[7] == 'b' ? 2 : 3;
  1043. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1044. } else if (!strcmp(name, "border-top-color") ||
  1045. !strcmp(name, "border-right-color") ||
  1046. !strcmp(name, "border-bottom-color") ||
  1047. !strcmp(name, "border-left-color")) {
  1048. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1049. name[7] == 'b' ? 2 : 3;
  1050. if (st.border_w[side] && !st.border_t[side])
  1051. css_rgb(st.border_c[side], buf, cap);
  1052. else
  1053. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1054. } else if (!strcmp(name, "background-image")) {
  1055. if (st.bg_image)
  1056. snprintf(buf, cap, "url(\"%s\")",
  1057. br_bg_image_url(st.bg_image - 1));
  1058. else
  1059. snprintf(buf, cap, "none");
  1060. } else if (!strcmp(name, "background-repeat")) {
  1061. static const char *rp[] = {
  1062. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1063. };
  1064. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1065. st.bg_repeat : 0]);
  1066. } else if (!strcmp(name, "background-position")) {
  1067. if (st.bg_pos_x_kind == 1)
  1068. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1069. st.bg_pos_y);
  1070. else
  1071. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1072. st.bg_pos_y);
  1073. } else if (!strcmp(name, "background-size")) {
  1074. if (st.bg_size_kind == 3)
  1075. snprintf(buf, cap, "cover");
  1076. else if (st.bg_size_kind == 4)
  1077. snprintf(buf, cap, "contain");
  1078. else if (st.bg_size_kind == 1)
  1079. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1080. st.bg_size_h);
  1081. else if (st.bg_size_kind == 2)
  1082. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1083. st.bg_size_h);
  1084. else
  1085. snprintf(buf, cap, "auto");
  1086. } else if (!strcmp(name, "transform")) {
  1087. char tmp[128];
  1088. unsigned int n = 0;
  1089. if (!st.transform_set) {
  1090. snprintf(buf, cap, "none");
  1091. } else {
  1092. tmp[0] = '\0';
  1093. if (st.tx || st.ty) {
  1094. snprintf(tmp + n, sizeof(tmp) - n,
  1095. "translate(%dpx, %dpx)", st.tx, st.ty);
  1096. n = (unsigned int)strlen(tmp);
  1097. }
  1098. if (st.transform_scale) {
  1099. snprintf(tmp + n, sizeof(tmp) - n,
  1100. "%sscale(%d.%02d, %d.%02d)",
  1101. n ? " " : "", st.scale_x / 100,
  1102. st.scale_x % 100, st.scale_y / 100,
  1103. st.scale_y % 100);
  1104. n = (unsigned int)strlen(tmp);
  1105. if (st.rotate_x100) {
  1106. snprintf(tmp + n, sizeof(tmp) - n,
  1107. " rotate(%d.%02ddeg)",
  1108. st.rotate_x100 / 100,
  1109. st.rotate_x100 % 100);
  1110. }
  1111. } else if (st.rotate_x100) {
  1112. snprintf(tmp + n, sizeof(tmp) - n,
  1113. "%srotate(%d.%02ddeg)",
  1114. n ? " " : "", st.rotate_x100 / 100,
  1115. st.rotate_x100 % 100);
  1116. }
  1117. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1118. }
  1119. } else {
  1120. return 0;
  1121. }
  1122. return buf[0] != '\0';
  1123. }
  1124. static int js_host_click(unsigned int node)
  1125. {
  1126. char url[BR_URL_MAX];
  1127. const char *href;
  1128. if (node >= doc.nnode)
  1129. return 0;
  1130. if (form_is_control(node)) {
  1131. form_click(node); /* dispatches its own click event */
  1132. return 1;
  1133. }
  1134. /* element.click() fires a bubbling, cancelable click before the
  1135. * default action, like a real click (delegated list handlers). */
  1136. if (!js_browser_event(node, "click", 1, 1))
  1137. return 1;
  1138. if (link_fragment_nav(node))
  1139. return 1;
  1140. href = br_href(&doc, node);
  1141. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1142. return 0;
  1143. s_copy(pending_url, url, sizeof(pending_url));
  1144. pending_action |= ACT_NAV;
  1145. cancel_fetch = 1;
  1146. ngui_invalidate(&ui);
  1147. return 1;
  1148. }
  1149. static int fetch_script_text(const char *url, unsigned char **out,
  1150. unsigned int *outlen, char *err,
  1151. unsigned int errcap);
  1152. struct fetch_worker;
  1153. static struct fetch_worker *fetch_worker_alloc(void);
  1154. static void fetch_worker_release(struct fetch_worker *w);
  1155. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1156. unsigned int cap, const char *post,
  1157. unsigned int post_len, unsigned int node,
  1158. int bg, char *err, unsigned int errcap);
  1159. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1160. unsigned int errcap);
  1161. static int fetch_worker_read_body(struct fetch_worker *w,
  1162. unsigned char *plain,
  1163. unsigned int plaincap,
  1164. unsigned char *comp,
  1165. unsigned int compcap,
  1166. int *truncated, char *err,
  1167. unsigned int errcap);
  1168. static void fetch_workers_stop_all(void);
  1169. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1170. unsigned int cap, const char *method,
  1171. const char *ctype, const char *post,
  1172. unsigned int post_len, unsigned int node,
  1173. int bg, unsigned int dec_w,
  1174. unsigned int dec_h, char *err,
  1175. unsigned int errcap);
  1176. static int script_cache_has(const char *url);
  1177. static void script_cache_put(const char *url, const unsigned char *data,
  1178. unsigned int len);
  1179. static unsigned int script_cache_hash(const char *s);
  1180. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1181. unsigned int errcap);
  1182. static void fetch_workers_cancel_busy(void);
  1183. static void worker_wait_ui(void);
  1184. static int fetch_worker_status(const struct fetch_worker *w);
  1185. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1186. * module load: the wait must not pump input, or a click would dispatch DOM
  1187. * events into the middle of the running script. */
  1188. static int fetch_wait_passive;
  1189. static void script_error(const char *what, const char *url, const char *why)
  1190. {
  1191. char msg[192];
  1192. unsigned int n = 0;
  1193. s_append(msg, &n, what, sizeof(msg));
  1194. if (url && url[0]) {
  1195. s_append(msg, &n, " ", sizeof(msg));
  1196. s_append(msg, &n, url, sizeof(msg));
  1197. }
  1198. if (why && why[0]) {
  1199. s_append(msg, &n, ": ", sizeof(msg));
  1200. s_append(msg, &n, why, sizeof(msg));
  1201. }
  1202. js_host_report(msg);
  1203. }
  1204. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1205. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1206. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1207. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1208. #define JS_HTTP_POST_MAX (16u * 1024u)
  1209. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1210. static int js_worker_http(const char *method, const char *url,
  1211. const char *ctype, const char *body,
  1212. unsigned int body_len, struct js_http_resp *r,
  1213. char *err, int errcap);
  1214. static int js_host_http(const char *method, const char *url,
  1215. const char *ctype, const char *body,
  1216. unsigned int body_len, struct js_http_resp *r,
  1217. char *err, int errcap)
  1218. {
  1219. if (pending_action) {
  1220. s_copy(err, "page is navigating", (unsigned int)errcap);
  1221. return -1;
  1222. }
  1223. if (url[0] == '/') {
  1224. /* Local file: GET only. */
  1225. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1226. int rv;
  1227. if (!buf) {
  1228. s_copy(err, "out of memory", (unsigned int)errcap);
  1229. return -1;
  1230. }
  1231. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1232. (int)JS_HTTP_MAX);
  1233. r->status = rv < 0 ? 404 : 200;
  1234. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1235. buf[r->len] = '\0';
  1236. r->body = (char *)buf;
  1237. s_copy(r->url, url, sizeof(r->url));
  1238. if (contains_ci(url, ".json"))
  1239. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1240. return 0;
  1241. }
  1242. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1243. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1244. return -1;
  1245. }
  1246. if (body_len > JS_HTTP_POST_MAX) {
  1247. s_copy(err, "request body too large", (unsigned int)errcap);
  1248. return -1;
  1249. }
  1250. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1251. errcap);
  1252. }
  1253. /* Module source for the engine's loader: the boot script cache first, then
  1254. * one blocking fetch with input pumping disabled (the loader runs inside
  1255. * JavaScript). */
  1256. static char *js_host_load_script(const char *url, unsigned int *len)
  1257. {
  1258. unsigned char *data = 0;
  1259. char err[64];
  1260. int rv;
  1261. fetch_wait_passive++;
  1262. set_status("Loading module...", 0, 0);
  1263. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1264. fetch_wait_passive--;
  1265. if (rv != 0) {
  1266. script_error("Cannot load module", url,
  1267. rv == FETCH_ABORT ? "navigation" : err);
  1268. return 0;
  1269. }
  1270. return (char *)data;
  1271. }
  1272. /* Web Storage lives in /share, outside the page heap that every navigation
  1273. * resets: localStorage per origin for the boot, sessionStorage per origin
  1274. * and browser window. */
  1275. #define JS_ORIGIN_MAX 160
  1276. /* scheme://host[:port] of the page (a local page's whole path). */
  1277. static void js_page_origin(char *origin, unsigned int cap)
  1278. {
  1279. unsigned int i = 0, slashes = 0;
  1280. while (page_url[i] && i + 1 < cap) {
  1281. if (page_url[i] == '/' && ++slashes == 3)
  1282. break;
  1283. origin[i] = page_url[i];
  1284. i++;
  1285. }
  1286. origin[i] = '\0';
  1287. }
  1288. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1289. {
  1290. unsigned int n = 0;
  1291. s_append(out, &n, "/share/bls", cap);
  1292. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1293. }
  1294. static void js_storage_path(int kind, char *out, unsigned int cap)
  1295. {
  1296. char origin[JS_ORIGIN_MAX];
  1297. unsigned int n = 0;
  1298. js_page_origin(origin, sizeof(origin));
  1299. if (!kind) {
  1300. js_origin_path(origin, out, cap);
  1301. return;
  1302. }
  1303. s_append(out, &n, "/share/bss", cap);
  1304. if (kind) {
  1305. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1306. s_append(out, &n, "-", cap);
  1307. }
  1308. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1309. }
  1310. static void persist_mark_origin(const char *origin);
  1311. static int persist_store_lookup(const char *origin, char *out, int cap);
  1312. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1313. {
  1314. char path[48], origin[JS_ORIGIN_MAX];
  1315. int rv;
  1316. js_storage_path(kind, path, sizeof(path));
  1317. if (set) {
  1318. if (kind) {
  1319. if (!set[0] || !strcmp(set, "{}")) {
  1320. u_syscall1(SYS_UNLINK, (int)path);
  1321. return 0;
  1322. }
  1323. } else {
  1324. /* localStorage keeps an explicit "{}" rather than no
  1325. * file: a missing /share file means "not loaded from
  1326. * /data yet", and a cleared store must not come back
  1327. * from the disk copy before it is flushed. */
  1328. if (!set[0])
  1329. set = "{}";
  1330. js_page_origin(origin, sizeof(origin));
  1331. persist_mark_origin(origin);
  1332. }
  1333. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1334. (int)strlen(set)) < 0 ? -1 : 0;
  1335. }
  1336. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1337. if (rv < 0 && !kind) {
  1338. /* First use this boot: the persistent copy on /data. */
  1339. js_page_origin(origin, sizeof(origin));
  1340. rv = persist_store_lookup(origin, out, cap);
  1341. if (rv >= 0)
  1342. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1343. }
  1344. if (rv < 0)
  1345. return -1;
  1346. out[rv] = '\0';
  1347. return rv;
  1348. }
  1349. /* ---- persistence on /data ----
  1350. *
  1351. * /share is the working copy (RAM, shared by every helper and window); the
  1352. * installed disk's /data volume keeps the cookie jar and localStorage
  1353. * across reboots when it is mounted. The browser owns the disk copies: at
  1354. * start it restores the jar into /share, and its main loop writes back
  1355. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1356. * setItem updates costs one FAT write. The helpers only touch /share (they
  1357. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1358. * /data mount every disk access simply fails. Both files are plaintext
  1359. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1360. #define PERSIST_MS 3000u
  1361. #define SHARE_COOKIES "/share/bcookies"
  1362. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1363. #define DATA_STORE "/data/BSTORE.DAT"
  1364. #define DATA_STORE_MAGIC "NBLS1\n"
  1365. #define DATA_STORE_MAX (192u * 1024u)
  1366. #define PERSIST_DIRTY_MAX 8
  1367. static unsigned int persist_due;
  1368. static unsigned int cookie_sum_saved;
  1369. static int cookie_sum_valid;
  1370. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1371. static int persist_ndirty;
  1372. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1373. {
  1374. unsigned int h = 2166136261u, i;
  1375. for (i = 0; i < n; i++)
  1376. h = (h ^ p[i]) * 16777619u;
  1377. return h;
  1378. }
  1379. /* Called once at startup, before any helper runs. */
  1380. static void persist_restore(void)
  1381. {
  1382. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1383. int n;
  1384. if (!jar)
  1385. return;
  1386. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1387. (int)sizeof(struct uhttp_jar));
  1388. if (n != (int)sizeof(struct uhttp_jar)) {
  1389. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1390. (int)sizeof(struct uhttp_jar));
  1391. if (n == (int)sizeof(struct uhttp_jar)) {
  1392. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1393. (int)jar, n);
  1394. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1395. cookie_sum_valid = 1;
  1396. }
  1397. }
  1398. free(jar);
  1399. persist_due = u_ticks_ms() + PERSIST_MS;
  1400. }
  1401. static void persist_mark_origin(const char *origin)
  1402. {
  1403. int i;
  1404. for (i = 0; i < persist_ndirty; i++)
  1405. if (s_eq(persist_dirty[i], origin))
  1406. return;
  1407. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1408. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1409. }
  1410. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1411. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1412. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1413. unsigned int *o_off, unsigned int *o_len,
  1414. unsigned int *d_off, unsigned int *d_len,
  1415. unsigned int *rec_end)
  1416. {
  1417. unsigned int p = *pos, v = 0;
  1418. if (p >= len)
  1419. return 0;
  1420. *o_off = p;
  1421. while (p < len && buf[p] != '\n')
  1422. p++;
  1423. if (p >= len)
  1424. return 0;
  1425. *o_len = p - *o_off;
  1426. p++;
  1427. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1428. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1429. if (p >= len || buf[p] != '\n')
  1430. return 0;
  1431. p++;
  1432. if (v > len - p)
  1433. return 0;
  1434. *d_off = p;
  1435. *d_len = v;
  1436. p += v;
  1437. if (p < len && buf[p] == '\n')
  1438. p++;
  1439. *rec_end = p;
  1440. *pos = p;
  1441. return 1;
  1442. }
  1443. static int store_load(char **out)
  1444. {
  1445. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1446. int n;
  1447. *out = buf;
  1448. if (!buf)
  1449. return -1;
  1450. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1451. (int)DATA_STORE_MAX);
  1452. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1453. !starts_with(buf, DATA_STORE_MAGIC))
  1454. return 0;
  1455. return n;
  1456. }
  1457. static int persist_store_lookup(const char *origin, char *out, int cap)
  1458. {
  1459. char *buf;
  1460. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1461. unsigned int olen = s_len(origin);
  1462. int n = store_load(&buf), rv = -1;
  1463. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1464. &dl, &e)) {
  1465. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1466. if ((int)dl < cap) {
  1467. memcpy(out, buf + d, dl);
  1468. out[dl] = '\0';
  1469. rv = (int)dl;
  1470. }
  1471. break;
  1472. }
  1473. }
  1474. free(buf);
  1475. return rv;
  1476. }
  1477. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1478. static void persist_store_flush(void)
  1479. {
  1480. char *old, *nb, path[48];
  1481. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1482. int n = store_load(&old), i, w;
  1483. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1484. if (n < 0 || !nb) {
  1485. free(old);
  1486. free(nb);
  1487. return;
  1488. }
  1489. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1490. /* Untouched origins first, in their old order. */
  1491. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1492. &dl, &e)) {
  1493. int dirty = 0;
  1494. for (i = 0; i < persist_ndirty; i++)
  1495. if (s_len(persist_dirty[i]) == ol &&
  1496. !memcmp(persist_dirty[i], old + oo, ol))
  1497. dirty = 1;
  1498. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1499. continue;
  1500. memcpy(nb + nn, old + oo, e - oo);
  1501. nn += e - oo;
  1502. }
  1503. /* Then the changed ones (an emptied store is dropped). */
  1504. for (i = 0; i < persist_ndirty; i++) {
  1505. char num[12];
  1506. unsigned int k = 0;
  1507. js_origin_path(persist_dirty[i], path, sizeof(path));
  1508. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1509. (int)DATA_STORE_MAX);
  1510. if (w <= 2) /* missing or "{}" */
  1511. continue;
  1512. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1513. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1514. DATA_STORE_MAX) {
  1515. set_status("Saved site data is full; a site's "
  1516. "localStorage was not saved", 1, 6000);
  1517. continue;
  1518. }
  1519. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1520. nb[nn++] = '\n';
  1521. s_append(nb, &nn, num, DATA_STORE_MAX);
  1522. nb[nn++] = '\n';
  1523. memcpy(nb + nn, old, (unsigned int)w);
  1524. nn += (unsigned int)w;
  1525. nb[nn++] = '\n';
  1526. }
  1527. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1528. persist_ndirty = 0;
  1529. free(old);
  1530. free(nb);
  1531. }
  1532. static void persist_cookies_flush(void)
  1533. {
  1534. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1535. unsigned int sum;
  1536. int n;
  1537. if (!jar)
  1538. return;
  1539. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1540. (int)sizeof(struct uhttp_jar));
  1541. if (n == (int)sizeof(struct uhttp_jar)) {
  1542. sum = persist_sum(jar, (unsigned int)n);
  1543. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1544. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1545. (int)jar, n) >= 0) {
  1546. cookie_sum_saved = sum;
  1547. cookie_sum_valid = 1;
  1548. }
  1549. }
  1550. }
  1551. free(jar);
  1552. }
  1553. /* ---- visit history (URL-bar autocomplete) ----
  1554. *
  1555. * Every page that finishes loading is recorded with its title, a visit
  1556. * count and a stamp: a counter that only grows and travels with the file,
  1557. * so it orders visits across windows and boots without a wall clock. The
  1558. * table lives in BSS, because the page heap is reset on every navigation.
  1559. * The boot's browser windows share it through /share/bhist (rewritten on
  1560. * every visit) and it is persisted to /data/BHIST.DAT from persist_tick()
  1561. * at most every PERSIST_MS, like the cookie jar. A save re-reads
  1562. * /share/bhist and merges it first, so two windows add to one history
  1563. * instead of overwriting each other. File format: "NBHIST1\n", then
  1564. * "<visits> <stamp> <url>\t<title>\n" per entry. Plaintext, like the
  1565. * other browser state on /data. */
  1566. #define HIST_MAX 128
  1567. #define HIST_URL_MAX 512
  1568. #define HIST_FILE_MAX (HIST_MAX * (HIST_URL_MAX + BR_TITLE_MAX + 24) + 16)
  1569. #define HIST_MAGIC "NBHIST1\n"
  1570. #define SHARE_HIST "/share/bhist"
  1571. #define DATA_HIST "/data/BHIST.DAT"
  1572. #define HIST_FORGET_MAX 16
  1573. struct hist_ent {
  1574. unsigned int visits;
  1575. unsigned int stamp;
  1576. char url[HIST_URL_MAX];
  1577. char title[BR_TITLE_MAX];
  1578. };
  1579. static struct hist_ent hist_tab[HIST_MAX];
  1580. static int hist_n;
  1581. static int hist_share_dirty, hist_data_dirty;
  1582. /* URLs removed in this process: a merge must not bring them back. */
  1583. static unsigned int hist_forgot[HIST_FORGET_MAX];
  1584. static int hist_nforgot;
  1585. static unsigned int hist_hash(const char *s)
  1586. {
  1587. return persist_sum((const unsigned char *)s, s_len(s));
  1588. }
  1589. static int hist_is_forgotten(const char *url)
  1590. {
  1591. unsigned int h = hist_hash(url);
  1592. int i;
  1593. for (i = 0; i < hist_nforgot; i++)
  1594. if (hist_forgot[i] == h)
  1595. return 1;
  1596. return 0;
  1597. }
  1598. static int hist_find(const char *url)
  1599. {
  1600. int i;
  1601. for (i = 0; i < hist_n; i++)
  1602. if (s_eq(hist_tab[i].url, url))
  1603. return i;
  1604. return -1;
  1605. }
  1606. static unsigned int hist_next_stamp(void)
  1607. {
  1608. unsigned int m = 0;
  1609. int i;
  1610. for (i = 0; i < hist_n; i++)
  1611. if (hist_tab[i].stamp > m)
  1612. m = hist_tab[i].stamp;
  1613. return m + 1;
  1614. }
  1615. /* Copy a title, turning tabs/newlines (the file separators) into spaces. */
  1616. static void hist_copy_title(char *d, const char *s, unsigned int n)
  1617. {
  1618. unsigned int i;
  1619. for (i = 0; i + 1 < BR_TITLE_MAX && i < n && s[i]; i++)
  1620. d[i] = (unsigned char)s[i] < 0x20 ? ' ' : s[i];
  1621. d[i] = '\0';
  1622. }
  1623. /* Insert or update an entry; the newer stamp wins the title, the larger
  1624. * visit count is kept. A full table evicts the least recent entry, unless
  1625. * the new one is older still. Returns NULL when nothing was stored. */
  1626. static struct hist_ent *hist_put(const char *url, const char *title,
  1627. unsigned int visits, unsigned int stamp)
  1628. {
  1629. struct hist_ent *e;
  1630. int i = hist_find(url);
  1631. if (i < 0) {
  1632. if (hist_n < HIST_MAX) {
  1633. i = hist_n++;
  1634. } else {
  1635. int j;
  1636. i = 0;
  1637. for (j = 1; j < hist_n; j++)
  1638. if (hist_tab[j].stamp < hist_tab[i].stamp)
  1639. i = j;
  1640. if (hist_tab[i].stamp >= stamp)
  1641. return 0;
  1642. }
  1643. e = &hist_tab[i];
  1644. e->visits = 0;
  1645. e->stamp = 0;
  1646. e->title[0] = '\0';
  1647. s_copy(e->url, url, sizeof(e->url));
  1648. }
  1649. e = &hist_tab[i];
  1650. if (visits > e->visits)
  1651. e->visits = visits;
  1652. if (stamp >= e->stamp) {
  1653. e->stamp = stamp;
  1654. if (title && title[0])
  1655. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1656. } else if (!e->title[0] && title) {
  1657. hist_copy_title(e->title, title, BR_TITLE_MAX);
  1658. }
  1659. return e;
  1660. }
  1661. static unsigned int hist_parse_dec(const char *b, int n, int *pos)
  1662. {
  1663. unsigned int v = 0;
  1664. while (*pos < n && b[*pos] >= '0' && b[*pos] <= '9')
  1665. v = v * 10 + (unsigned int)(b[(*pos)++] - '0');
  1666. return v;
  1667. }
  1668. static void hist_merge_buf(const char *b, int n)
  1669. {
  1670. int pos = (int)s_len(HIST_MAGIC);
  1671. char url[HIST_URL_MAX], title[BR_TITLE_MAX];
  1672. if (n < pos || memcmp(b, HIST_MAGIC, (unsigned int)pos))
  1673. return;
  1674. while (pos < n) {
  1675. unsigned int visits, stamp, ul = 0;
  1676. int t0, t1;
  1677. visits = hist_parse_dec(b, n, &pos);
  1678. if (pos < n && b[pos] == ' ')
  1679. pos++;
  1680. stamp = hist_parse_dec(b, n, &pos);
  1681. if (pos < n && b[pos] == ' ')
  1682. pos++;
  1683. while (pos < n && b[pos] != '\t' && b[pos] != '\n') {
  1684. if (ul + 1 < sizeof(url))
  1685. url[ul++] = b[pos];
  1686. pos++;
  1687. }
  1688. url[ul] = '\0';
  1689. t0 = t1 = pos < n && b[pos] == '\t' ? pos + 1 : pos;
  1690. while (t1 < n && b[t1] != '\n')
  1691. t1++;
  1692. pos = t1 + 1;
  1693. hist_copy_title(title, b + t0, (unsigned int)(t1 - t0));
  1694. if (ul && ul + 1 < sizeof(url) && !hist_is_forgotten(url))
  1695. hist_put(url, title, visits, stamp);
  1696. }
  1697. }
  1698. static int hist_serialize(char *b, unsigned int cap)
  1699. {
  1700. unsigned int n = 0;
  1701. int i;
  1702. s_append(b, &n, HIST_MAGIC, cap);
  1703. for (i = 0; i < hist_n; i++) {
  1704. struct hist_ent *e = &hist_tab[i];
  1705. if (n + s_len(e->url) + s_len(e->title) + 26 >= cap)
  1706. break;
  1707. s_append_dec(b, &n, e->visits, cap);
  1708. b[n++] = ' ';
  1709. s_append_dec(b, &n, e->stamp, cap);
  1710. b[n++] = ' ';
  1711. s_append(b, &n, e->url, cap);
  1712. b[n++] = '\t';
  1713. s_append(b, &n, e->title, cap);
  1714. b[n++] = '\n';
  1715. }
  1716. return (int)n;
  1717. }
  1718. /* Merge /share/bhist, then write it back (and /data when asked). */
  1719. static void hist_sync(int to_data)
  1720. {
  1721. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1722. int n;
  1723. if (!b)
  1724. return;
  1725. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1726. (int)HIST_FILE_MAX);
  1727. if (n > 0)
  1728. hist_merge_buf(b, n);
  1729. n = hist_serialize(b, HIST_FILE_MAX);
  1730. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1731. hist_share_dirty = 0;
  1732. if (to_data) {
  1733. /* No /data mount: the write fails, and there is nothing to
  1734. * retry until the next visit. */
  1735. u_syscall3(SYS_WRITE_FILE, (int)DATA_HIST, (int)b, n);
  1736. hist_data_dirty = 0;
  1737. }
  1738. free(b);
  1739. }
  1740. /* Startup: the boot's shared copy, else the saved one from /data. */
  1741. static void hist_load(void)
  1742. {
  1743. char *b = (char *)malloc(HIST_FILE_MAX + 1);
  1744. int n;
  1745. if (!b)
  1746. return;
  1747. n = u_syscall3(SYS_READ_FILE, (int)SHARE_HIST, (int)b,
  1748. (int)HIST_FILE_MAX);
  1749. if (n <= 0) {
  1750. n = u_syscall3(SYS_READ_FILE, (int)DATA_HIST, (int)b,
  1751. (int)HIST_FILE_MAX);
  1752. if (n > 0)
  1753. u_syscall3(SYS_WRITE_FILE, (int)SHARE_HIST, (int)b, n);
  1754. }
  1755. if (n > 0)
  1756. hist_merge_buf(b, n);
  1757. free(b);
  1758. }
  1759. static void hist_visit(const char *url, const char *title)
  1760. {
  1761. struct hist_ent *e;
  1762. unsigned int i;
  1763. if (!url[0] || starts_with(url, "about:") ||
  1764. s_len(url) >= HIST_URL_MAX)
  1765. return;
  1766. for (i = 0; url[i]; i++)
  1767. if ((unsigned char)url[i] < 0x20)
  1768. return;
  1769. e = hist_put(url, title, 0, hist_next_stamp());
  1770. if (!e)
  1771. return;
  1772. e->visits++;
  1773. hist_data_dirty = 1;
  1774. hist_sync(0);
  1775. }
  1776. static void hist_forget(int i)
  1777. {
  1778. if (i < 0 || i >= hist_n)
  1779. return;
  1780. if (hist_nforgot < HIST_FORGET_MAX)
  1781. hist_forgot[hist_nforgot++] = hist_hash(hist_tab[i].url);
  1782. hist_n--;
  1783. for (; i < hist_n; i++)
  1784. hist_tab[i] = hist_tab[i + 1];
  1785. hist_data_dirty = 1;
  1786. hist_sync(0);
  1787. }
  1788. static void hist_tick(void)
  1789. {
  1790. if (hist_share_dirty || hist_data_dirty)
  1791. hist_sync(hist_data_dirty);
  1792. }
  1793. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1794. static void persist_tick(void)
  1795. {
  1796. unsigned int now = u_ticks_ms();
  1797. if ((int)(now - persist_due) < 0)
  1798. return;
  1799. persist_due = now + PERSIST_MS;
  1800. persist_cookies_flush();
  1801. if (persist_ndirty)
  1802. persist_store_flush();
  1803. hist_tick();
  1804. }
  1805. /* <link rel="modulepreload">: download the page's module graph on all
  1806. * helpers at once into the boot script cache, before any script runs. The
  1807. * engine's module loader is sequential (one blocking fetch per import), so
  1808. * without this a Vite app with a dozen chunks pays every round trip in a
  1809. * row. Failures are ignored; the loader fetches what is missing. */
  1810. #define MODULE_PRELOAD_MAX 24
  1811. static void prefetch_module_preloads(void)
  1812. {
  1813. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1814. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1815. unsigned int count = 0, next = 0, done = 0, i;
  1816. char err[64];
  1817. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1818. struct br_node *nd = &doc.nodes[i];
  1819. const char *rel, *href;
  1820. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1821. continue;
  1822. rel = br_rel(&doc, i);
  1823. href = br_href(&doc, i);
  1824. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1825. continue;
  1826. if (resolve_link(page_url, href, urls[count],
  1827. sizeof(urls[count])) != 0 ||
  1828. urls[count][0] == '/' || script_cache_has(urls[count]))
  1829. continue;
  1830. slot[count++] = 0;
  1831. }
  1832. if (!count)
  1833. return;
  1834. set_status("Loading modules...", 0, 0);
  1835. while (done < count) {
  1836. struct fetch_worker *w;
  1837. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1838. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1839. 0, 0, 0, err,
  1840. sizeof(err)) != 0) {
  1841. fetch_worker_release(w);
  1842. done++;
  1843. } else {
  1844. slot[next] = w;
  1845. }
  1846. next++;
  1847. }
  1848. worker_wait_ui();
  1849. if (cancel_fetch || pending_action) {
  1850. fetch_workers_cancel_busy();
  1851. return;
  1852. }
  1853. for (i = 0; i < next; i++) {
  1854. unsigned char *body;
  1855. int rv, tr = 0;
  1856. if (!slot[i])
  1857. continue;
  1858. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1859. if (rv == 0)
  1860. continue;
  1861. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1862. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1863. if (body) {
  1864. rv = fetch_worker_read_body(slot[i], body,
  1865. BR_SCRIPT_MAX, image_io_buf,
  1866. BR_PAGE_COMP_MAX, &tr, err,
  1867. sizeof(err));
  1868. if (rv > 0 && !tr)
  1869. script_cache_put(urls[i], body,
  1870. (unsigned int)rv);
  1871. free(body);
  1872. }
  1873. fetch_worker_release(slot[i]);
  1874. slot[i] = 0;
  1875. done++;
  1876. }
  1877. u_sleep_ms(10);
  1878. }
  1879. }
  1880. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1881. * submitted to helper workers ahead of time, but scripts still execute in
  1882. * document order. */
  1883. #define SCRIPT_INLINE 0
  1884. #define SCRIPT_LOCAL 1
  1885. #define SCRIPT_REMOTE 2
  1886. #define SCRIPT_ERROR 3
  1887. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1888. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1889. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1890. static void script_submit_window(unsigned int *next, char *err,
  1891. unsigned int errcap)
  1892. {
  1893. while (*next < doc.nscripts) {
  1894. struct fetch_worker *w;
  1895. if (script_kind[*next] != SCRIPT_REMOTE) {
  1896. (*next)++;
  1897. continue;
  1898. }
  1899. w = fetch_worker_alloc();
  1900. if (!w)
  1901. return;
  1902. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1903. 0, 0, 0, 0, err, errcap) != 0) {
  1904. fetch_worker_release(w);
  1905. script_kind[*next] = SCRIPT_ERROR;
  1906. (*next)++;
  1907. continue;
  1908. }
  1909. script_slot[*next] = w;
  1910. (*next)++;
  1911. }
  1912. }
  1913. /* Run the page's scripts in document order. External bodies are prefetched
  1914. * in parallel so downloading script N+1 overlaps executing script N; inline
  1915. * bodies are copied because the engine needs NUL-terminated text. */
  1916. static void run_page_scripts(void)
  1917. {
  1918. struct js_browser_host host;
  1919. unsigned int i, next = 0;
  1920. char err[64], ferr[64];
  1921. if (!doc.nscripts)
  1922. return;
  1923. host.status = js_host_status;
  1924. host.report = js_host_report;
  1925. host.navigate = js_host_navigate;
  1926. host.changed = js_host_changed;
  1927. host.rect = js_host_rect;
  1928. host.form_value = js_host_form_value;
  1929. host.form_checked = js_host_form_checked;
  1930. host.form_selected = js_host_form_selected;
  1931. host.form_set_value = js_host_form_set_value;
  1932. host.form_set_checked = js_host_form_set_checked;
  1933. host.form_set_selected = js_host_form_set_selected;
  1934. host.form_elements = js_host_form_elements;
  1935. host.form_submit = js_host_form_submit;
  1936. host.form_reset = js_host_form_reset;
  1937. host.click = js_host_click;
  1938. host.computed = js_host_computed;
  1939. host.http = js_host_http;
  1940. host.load_script = js_host_load_script;
  1941. host.storage = js_host_storage;
  1942. host.set_hash = js_host_set_hash;
  1943. host.page_url = page_url;
  1944. host.width = ui.w;
  1945. host.height = ui.h;
  1946. if (js_browser_start(&doc, &host) != 0) {
  1947. js_host_status("JavaScript: out of memory", 1);
  1948. return;
  1949. }
  1950. resize_sent_w = -1;
  1951. resize_pending = 0;
  1952. prefetch_module_preloads();
  1953. for (i = 0; i < doc.nscripts; i++) {
  1954. struct br_script *script = &doc.scripts[i];
  1955. const char *src_attr = script->src_off ?
  1956. doc.attrs + script->src_off : "";
  1957. script_slot[i] = 0;
  1958. if (!script->src_off) {
  1959. script_kind[i] = SCRIPT_INLINE;
  1960. continue;
  1961. }
  1962. if (!src_attr[0] ||
  1963. resolve_link(page_url, src_attr, script_urls[i],
  1964. sizeof(script_urls[i])) != 0) {
  1965. script_urls[i][0] = '\0';
  1966. script_kind[i] = SCRIPT_ERROR;
  1967. continue;
  1968. }
  1969. if (script_urls[i][0] == '/' ||
  1970. script_cache_has(script_urls[i]))
  1971. script_kind[i] = SCRIPT_LOCAL;
  1972. else
  1973. script_kind[i] = SCRIPT_REMOTE;
  1974. }
  1975. script_submit_window(&next, ferr, sizeof(ferr));
  1976. for (i = 0; i < doc.nscripts; i++) {
  1977. struct br_script *script = &doc.scripts[i];
  1978. /* document.currentScript for classic scripts (null for modules) */
  1979. js_browser_set_current_script(script->module ? 0 : script->node);
  1980. if (script_kind[i] == SCRIPT_INLINE) {
  1981. unsigned int off = script->off;
  1982. unsigned int len = script->len;
  1983. unsigned int k;
  1984. char *src = (char *)malloc(len + 1);
  1985. if (!src) {
  1986. js_host_status("JavaScript: out of memory", 1);
  1987. break;
  1988. }
  1989. for (k = 0; k < len; k++)
  1990. src[k] = doc.script_src[off + k];
  1991. src[len] = '\0';
  1992. if (script->module) {
  1993. /* A distinct module name per inline module
  1994. * (QuickJS registers modules by name); the
  1995. * fragment keeps relative imports resolving
  1996. * against the page. */
  1997. char mname[BR_URL_MAX + 16];
  1998. unsigned int mn = 0;
  1999. s_append(mname, &mn, page_url, sizeof(mname));
  2000. s_append(mname, &mn, "#module", sizeof(mname));
  2001. s_append_dec(mname, &mn, i, sizeof(mname));
  2002. js_browser_run_module(src, mname);
  2003. } else {
  2004. js_browser_run(src, page_url);
  2005. }
  2006. free(src);
  2007. } else if (script->src_off) {
  2008. const char *src_attr = doc.attrs + script->src_off;
  2009. if (script_kind[i] == SCRIPT_ERROR) {
  2010. script_error("Cannot load script", src_attr,
  2011. script_urls[i][0] ?
  2012. "network busy" :
  2013. "unsupported URL");
  2014. continue;
  2015. }
  2016. if (script_kind[i] == SCRIPT_LOCAL) {
  2017. unsigned char *data = 0;
  2018. unsigned int len = 0;
  2019. int rv;
  2020. set_status("Loading script...", 0, 0);
  2021. rv = fetch_script_text(script_urls[i], &data,
  2022. &len, err, sizeof(err));
  2023. if (rv == FETCH_ABORT)
  2024. break;
  2025. if (rv != 0) {
  2026. script_error("Cannot load script",
  2027. script_urls[i], err);
  2028. continue;
  2029. }
  2030. if (script->module)
  2031. js_browser_run_module(
  2032. (const char *)data,
  2033. script_urls[i]);
  2034. else
  2035. js_browser_run((const char *)data,
  2036. script_urls[i]);
  2037. free(data);
  2038. } else {
  2039. struct fetch_worker *w = script_slot[i];
  2040. unsigned char *body = 0;
  2041. int tr = 0, rv;
  2042. if (!w) {
  2043. w = fetch_worker_alloc();
  2044. if (!w)
  2045. continue;
  2046. if (fetch_worker_submit(w,
  2047. script_urls[i],
  2048. BR_SCRIPT_MAX,
  2049. 0, 0, 0, 0, err,
  2050. sizeof(err)) != 0) {
  2051. fetch_worker_release(w);
  2052. script_kind[i] = SCRIPT_ERROR;
  2053. if (i == next)
  2054. next++;
  2055. continue;
  2056. }
  2057. script_slot[i] = w;
  2058. if (i == next)
  2059. next++;
  2060. }
  2061. set_status("Loading script...", 0, 0);
  2062. rv = fetch_worker_wait(w, err, sizeof(err));
  2063. if (rv == FETCH_ABORT) {
  2064. fetch_workers_stop_all();
  2065. break;
  2066. }
  2067. /* The body gets its own buffer (scripts are up
  2068. * to 2 MB); image_io_buf takes the gzip
  2069. * stream. */
  2070. body = rv == 0 ? (unsigned char *)malloc(
  2071. BR_SCRIPT_MAX + 1) : 0;
  2072. if (body)
  2073. rv = fetch_worker_read_body(w, body,
  2074. BR_SCRIPT_MAX, image_io_buf,
  2075. BR_PAGE_COMP_MAX, &tr, err,
  2076. sizeof(err));
  2077. else {
  2078. if (rv == 0)
  2079. s_copy(err, "out of memory",
  2080. sizeof(err));
  2081. rv = -1;
  2082. }
  2083. fetch_worker_release(w);
  2084. script_slot[i] = 0;
  2085. script_submit_window(&next, ferr, sizeof(ferr));
  2086. if (rv <= 0)
  2087. script_error("Cannot load script",
  2088. script_urls[i], err);
  2089. else if (tr || (unsigned int)rv >=
  2090. BR_SCRIPT_MAX)
  2091. script_error("Cannot load script",
  2092. script_urls[i],
  2093. "script is too large");
  2094. else {
  2095. body[rv] = '\0';
  2096. script_cache_put(script_urls[i], body,
  2097. (unsigned int)rv);
  2098. if (script->module)
  2099. js_browser_run_module(
  2100. (const char *)body,
  2101. script_urls[i]);
  2102. else
  2103. js_browser_run(
  2104. (const char *)body,
  2105. script_urls[i]);
  2106. }
  2107. free(body);
  2108. }
  2109. }
  2110. if (pending_action)
  2111. break;
  2112. }
  2113. js_browser_set_current_script(0);
  2114. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  2115. * load_home() stop it before the next navigation. */
  2116. if (doc.scripts_truncated && !js_last_error)
  2117. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  2118. 1);
  2119. }
  2120. /* ---- images ---- */
  2121. static void image_reset(void)
  2122. {
  2123. int i;
  2124. for (i = 0; i < BR_MAX_IMAGES; i++) {
  2125. images[i].state = 0;
  2126. images[i].native_w = images[i].native_h = 0;
  2127. images[i].err[0] = '\0';
  2128. /* heap_clear() ran before us, so these pointers are stale: drop
  2129. * them without calling free(). */
  2130. memset(&images[i].disp, 0, sizeof(images[i].disp));
  2131. images[i].disp_pixels = 0;
  2132. images[i].disp_last = 0;
  2133. }
  2134. image_count = 0;
  2135. image_pixels = 0;
  2136. image_disp_pixels = 0;
  2137. image_disp_clock = 0;
  2138. memset(img_stat_log, 0, sizeof(img_stat_log));
  2139. img_stat_log_len = 0;
  2140. img_stat_start = 0;
  2141. img_stat_wall = 0;
  2142. img_stat_net = img_stat_open = img_stat_first = 0;
  2143. img_stat_io = img_stat_dec = img_stat_scale = 0;
  2144. img_stat_paint = img_stat_reflow = 0;
  2145. img_stat_bytes = 0;
  2146. img_stat_n = 0;
  2147. img_last_dec_ms = img_last_scale_ms = 0;
  2148. img_repaint_ms = 0;
  2149. img_repaint_pending = 0;
  2150. preload_active = 0;
  2151. preload_pending = 0;
  2152. preload_wait = 0;
  2153. preload_node = 0;
  2154. preload_loaded = 0;
  2155. }
  2156. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  2157. * are arriving. The main loop draws once per dirty frame; without this a
  2158. * page of N images did N full layout+paint passes. */
  2159. static void image_repaint(void)
  2160. {
  2161. unsigned int now = u_ticks_ms();
  2162. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  2163. img_repaint_ms = now;
  2164. img_repaint_pending = 0;
  2165. ngui_invalidate(&ui);
  2166. } else {
  2167. img_repaint_pending = 1;
  2168. }
  2169. }
  2170. static void image_disp_drop(struct br_image *bi)
  2171. {
  2172. if (bi->disp.px)
  2173. free(bi->disp.px);
  2174. if (bi->disp.alpha)
  2175. free(bi->disp.alpha);
  2176. memset(&bi->disp, 0, sizeof(bi->disp));
  2177. if (bi->disp_pixels) {
  2178. if (image_disp_pixels >= bi->disp_pixels)
  2179. image_disp_pixels -= bi->disp_pixels;
  2180. bi->disp_pixels = 0;
  2181. }
  2182. }
  2183. /* Free the least recently used display caches until need pixels fit. The
  2184. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  2185. static int image_disp_room(unsigned int need)
  2186. {
  2187. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  2188. unsigned int oldest = ~0u;
  2189. int i, victim = -1;
  2190. for (i = 0; i < image_count; i++) {
  2191. if (!images[i].disp.px)
  2192. continue;
  2193. if (images[i].disp_last < oldest) {
  2194. oldest = images[i].disp_last;
  2195. victim = i;
  2196. }
  2197. }
  2198. if (victim < 0)
  2199. return -1;
  2200. image_disp_drop(&images[victim]);
  2201. }
  2202. return 0;
  2203. }
  2204. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  2205. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  2206. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  2207. {
  2208. struct img_blit b;
  2209. unsigned int px;
  2210. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  2211. return 0;
  2212. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  2213. return &bi->img;
  2214. if (dw > 4096 || dh > 4096)
  2215. return &bi->img;
  2216. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  2217. bi->disp.h == (unsigned int)dh) {
  2218. bi->disp_last = ++image_disp_clock;
  2219. return &bi->disp;
  2220. }
  2221. px = (unsigned int)dw * (unsigned int)dh;
  2222. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  2223. return &bi->img;
  2224. image_disp_drop(bi);
  2225. bi->disp.px = (unsigned short *)malloc(px * 2u);
  2226. if (!bi->disp.px)
  2227. return &bi->img;
  2228. if (bi->img.alpha) {
  2229. bi->disp.alpha = (unsigned char *)malloc(px);
  2230. if (!bi->disp.alpha) {
  2231. free(bi->disp.px);
  2232. bi->disp.px = 0;
  2233. return &bi->img;
  2234. }
  2235. }
  2236. bi->disp.w = (unsigned int)dw;
  2237. bi->disp.h = (unsigned int)dh;
  2238. bi->disp.format = bi->img.format;
  2239. bi->disp.flags = 0;
  2240. memset(&b, 0, sizeof(b));
  2241. b.dst = bi->disp.px;
  2242. b.dst_w = dw;
  2243. b.dst_h = dh;
  2244. b.clip_w = dw;
  2245. b.clip_h = dh;
  2246. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2247. b.dst_a = bi->disp.alpha;
  2248. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2249. img_draw(&bi->img, &b);
  2250. bi->disp_pixels = px;
  2251. image_disp_pixels += px;
  2252. bi->disp_last = ++image_disp_clock;
  2253. return &bi->disp;
  2254. }
  2255. /* Decode into the shared arena, then copy/scale the result into a display
  2256. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2257. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2258. * pixels. Transparent edges are composited over white. */
  2259. /* One decode scratch arena per page, reused across images. Allocating and
  2260. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2261. * each small display bitmap landed in the hole the previous arena left, so
  2262. * the next arena no longer fit and the heap ratcheted up until an app
  2263. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2264. * still released right after their one image. */
  2265. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2266. static unsigned char *decode_arena_get(unsigned int bytes)
  2267. {
  2268. if (decode_arena && decode_arena_size >= bytes)
  2269. return decode_arena;
  2270. free(decode_arena);
  2271. decode_arena = (unsigned char *)malloc(bytes);
  2272. decode_arena_size = decode_arena ? bytes : 0;
  2273. return decode_arena;
  2274. }
  2275. static void decode_arena_put(void)
  2276. {
  2277. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2278. free(decode_arena);
  2279. decode_arena = 0;
  2280. decode_arena_size = 0;
  2281. }
  2282. }
  2283. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2284. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2285. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2286. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2287. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2288. struct br_image *bi, int box_w, int box_h);
  2289. static int decode_image_data(const unsigned char *data, unsigned int len,
  2290. struct br_image *bi, int box_w, int box_h,
  2291. int fit_w, int fit_h)
  2292. {
  2293. struct img_info info;
  2294. struct img_options opt;
  2295. struct img_mem mem;
  2296. struct img_image decoded;
  2297. unsigned char *arena;
  2298. unsigned int est, bytes, i;
  2299. unsigned int t0;
  2300. unsigned short *px;
  2301. unsigned char *alpha = 0;
  2302. int dw, dh, r;
  2303. bi->url_hash = 0;
  2304. img_last_dec_ms = 0;
  2305. img_last_scale_ms = 0;
  2306. if (img_sniff(data, len, &info) != 0) {
  2307. if (svg_text_sniff(data, len))
  2308. return svg_decode_image(data, len, bi,
  2309. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2310. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2311. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2312. return -1;
  2313. }
  2314. est = img_estimate(&info);
  2315. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2316. s_copy(bi->err, "image too large", sizeof(bi->err));
  2317. return -1;
  2318. }
  2319. arena = decode_arena_get(est);
  2320. if (!arena) {
  2321. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2322. return -1;
  2323. }
  2324. img_mem_init(&mem, arena, est);
  2325. opt.max_pixels = BR_IMG_PIX_MAX;
  2326. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2327. (box_w > 0 ? (unsigned int)box_w : 0);
  2328. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2329. (box_h > 0 ? (unsigned int)box_h : 0);
  2330. t0 = u_ticks_ms();
  2331. r = img_decode(data, len, &opt, &mem, &decoded);
  2332. img_last_dec_ms = u_ticks_ms() - t0;
  2333. if (r != 0) {
  2334. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2335. goto fail;
  2336. }
  2337. if (decoded.w == 0 || decoded.h == 0) {
  2338. s_copy(bi->err, "empty image", sizeof(bi->err));
  2339. goto fail;
  2340. }
  2341. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2342. * needs the intrinsic dimensions from the header. */
  2343. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2344. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2345. dw = (int)decoded.w;
  2346. dh = (int)decoded.h;
  2347. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2348. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2349. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2350. * axes with one scale so the aspect ratio is preserved. */
  2351. if (fit_w > 0 || fit_h > 0) {
  2352. unsigned int scw = fit_w > 0 ?
  2353. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2354. unsigned int sch = fit_h > 0 ?
  2355. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2356. unsigned int sc = scw < sch ? scw : sch;
  2357. if (sc < 0x10000u) {
  2358. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2359. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2360. if (dw < 1)
  2361. dw = 1;
  2362. if (dh < 1)
  2363. dh = 1;
  2364. }
  2365. }
  2366. if (box_w > 0 && box_h > 0) {
  2367. /* cover: scale so both box sides are filled, never up */
  2368. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2369. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2370. unsigned int sc = sw > sh ? sw : sh;
  2371. if (sc < 0x10000u) {
  2372. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2373. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2374. }
  2375. }
  2376. if (dw > BR_IMG_LAYOUT_W) {
  2377. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2378. dw = BR_IMG_LAYOUT_W;
  2379. }
  2380. if (dh < 1)
  2381. dh = 1;
  2382. if (dw < 1)
  2383. dw = 1;
  2384. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2385. BR_IMG_PIXEL_BUDGET) {
  2386. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2387. goto fail;
  2388. }
  2389. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2390. px = (unsigned short *)malloc(bytes);
  2391. if (!px) {
  2392. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2393. goto fail;
  2394. }
  2395. /* Keep the alpha plane for the scaled image so transparent logos and
  2396. * icons composite over the page instead of the browser's dark theme
  2397. * background. Very large alpha images stay flattened to bound the
  2398. * heap use. */
  2399. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2400. alpha = (unsigned char *)malloc((unsigned int)dw *
  2401. (unsigned int)dh);
  2402. if (alpha) {
  2403. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2404. alpha[i] = 255;
  2405. }
  2406. }
  2407. /* With an alpha plane the colour under transparent pixels only shows
  2408. * through partially covered edge pixels of the downscale: use white,
  2409. * as documented above, not the dark browser theme (which left a dark
  2410. * fringe around scaled app icons). */
  2411. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2412. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2413. {
  2414. struct img_blit b;
  2415. b.dst = px;
  2416. b.dst_w = dw;
  2417. b.dst_h = dh;
  2418. b.clip_x = 0;
  2419. b.clip_y = 0;
  2420. b.clip_w = dw;
  2421. b.clip_h = dh;
  2422. b.x = 0;
  2423. b.y = 0;
  2424. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2425. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2426. b.bg2 = b.bg;
  2427. b.dst_a = alpha;
  2428. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2429. t0 = u_ticks_ms();
  2430. img_draw(&decoded, &b);
  2431. img_last_scale_ms = u_ticks_ms() - t0;
  2432. }
  2433. bi->img.format = decoded.format;
  2434. bi->img.w = (unsigned int)dw;
  2435. bi->img.h = (unsigned int)dh;
  2436. bi->img.px = px;
  2437. bi->img.alpha = alpha;
  2438. bi->img.flags = 0;
  2439. bi->state = 1;
  2440. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2441. decode_arena_put();
  2442. return 0;
  2443. fail:
  2444. decode_arena_put();
  2445. return -1;
  2446. }
  2447. /* ---- URL / local path handling ---- */
  2448. static int is_http(const char *s)
  2449. {
  2450. return starts_with(s, "http://") || starts_with(s, "https://");
  2451. }
  2452. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2453. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2454. {
  2455. char seg[64];
  2456. unsigned int i = 0, o = 1;
  2457. int depth = 0;
  2458. int trailing;
  2459. if (!in || in[0] != '/' || cap < 2)
  2460. return -1;
  2461. trailing = 0;
  2462. {
  2463. unsigned int n = s_len(in);
  2464. if (n > 1 && in[n - 1] == '/')
  2465. trailing = 1;
  2466. }
  2467. out[0] = '/';
  2468. while (in[i]) {
  2469. unsigned int n = 0;
  2470. while (in[i] == '/')
  2471. i++;
  2472. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2473. if (n + 1 < sizeof(seg))
  2474. seg[n++] = in[i];
  2475. i++;
  2476. }
  2477. seg[n] = '\0';
  2478. if (n == 0)
  2479. break;
  2480. if (s_eq(seg, "."))
  2481. continue;
  2482. if (s_eq(seg, "..")) {
  2483. if (depth > 0) {
  2484. while (o > 1 && out[o - 1] != '/')
  2485. o--;
  2486. if (o > 1)
  2487. o--;
  2488. depth--;
  2489. }
  2490. continue;
  2491. }
  2492. if (o > 1) {
  2493. if (o + 1 >= cap)
  2494. return -1;
  2495. out[o++] = '/';
  2496. }
  2497. if (o + n + 1 >= cap)
  2498. return -1;
  2499. {
  2500. unsigned int j;
  2501. for (j = 0; j < n; j++)
  2502. out[o++] = seg[j];
  2503. }
  2504. depth++;
  2505. }
  2506. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2507. if (o + 1 >= cap)
  2508. return -1;
  2509. out[o++] = '/';
  2510. }
  2511. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2512. if (in[i] == '?' || in[i] == '#') {
  2513. while (in[i]) {
  2514. if (o + 1 >= cap)
  2515. return -1;
  2516. out[o++] = in[i++];
  2517. }
  2518. }
  2519. out[o] = '\0';
  2520. return 0;
  2521. }
  2522. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2523. {
  2524. char joined[BR_URL_MAX];
  2525. if (!in || !in[0]) {
  2526. s_copy(out, cwd[0] ? cwd : "/", cap);
  2527. return;
  2528. }
  2529. if (in[0] == '/') {
  2530. if (normalize_abs(in, out, cap) != 0)
  2531. s_copy(out, in, cap);
  2532. return;
  2533. }
  2534. {
  2535. unsigned int n = 0;
  2536. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2537. s_append(joined, &n, "/", sizeof(joined));
  2538. s_append(joined, &n, in, sizeof(joined));
  2539. }
  2540. if (normalize_abs(joined, out, cap) != 0)
  2541. s_copy(out, joined, cap);
  2542. }
  2543. /* ---- canonical origin cache ---- *
  2544. *
  2545. * Sites commonly redirect http://host to https://host and then to
  2546. * https://www.host. Remember the final scheme/host of the last navigation so
  2547. * a bare domain typed again goes straight there instead of paying for two
  2548. * more connections and TLS handshakes. Only default-port requests are
  2549. * rewritten; explicit ports are left alone. */
  2550. #define ORIGIN_CACHE_MAX 8
  2551. #define ORIGIN_FILE "/share/borigins"
  2552. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2553. UHTTP_HOST_MAX + 2))
  2554. struct origin_cache_entry {
  2555. char host[UHTTP_HOST_MAX];
  2556. char origin[UHTTP_HOST_MAX + 16];
  2557. };
  2558. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2559. static int origin_count;
  2560. static char origin_buf[ORIGIN_BUF_SIZE];
  2561. static int default_port(const struct uhttp_url *u)
  2562. {
  2563. return u->secure ? u->port == 443 : u->port == 80;
  2564. }
  2565. static void url_origin(const struct uhttp_url *u, char *out,
  2566. unsigned int cap)
  2567. {
  2568. unsigned int n = 0;
  2569. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2570. s_append(out, &n, u->host, cap);
  2571. if (!default_port(u)) {
  2572. s_append(out, &n, ":", cap);
  2573. s_append_dec(out, &n, u->port, cap);
  2574. }
  2575. }
  2576. static void origin_cache_apply(char *url, unsigned int cap)
  2577. {
  2578. struct uhttp_url u;
  2579. char out[BR_URL_MAX];
  2580. unsigned int n = 0;
  2581. int i;
  2582. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2583. return;
  2584. for (i = 0; i < origin_count; i++) {
  2585. if (!s_eq(u.host, origins[i].host))
  2586. continue;
  2587. s_append(out, &n, origins[i].origin, sizeof(out));
  2588. s_append(out, &n, u.path, sizeof(out));
  2589. s_copy(url, out, cap);
  2590. return;
  2591. }
  2592. }
  2593. static void origin_cache_save(void)
  2594. {
  2595. unsigned int n = 0;
  2596. int i;
  2597. for (i = 0; i < origin_count; i++) {
  2598. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2599. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2600. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2601. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2602. }
  2603. if (n)
  2604. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2605. (int)origin_buf, (int)n);
  2606. }
  2607. static void origin_cache_load(void)
  2608. {
  2609. char *p;
  2610. int rn;
  2611. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2612. (int)(sizeof(origin_buf) - 1));
  2613. if (rn <= 0)
  2614. return;
  2615. origin_buf[rn] = '\0';
  2616. p = origin_buf;
  2617. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2618. char *line = p, *origin;
  2619. while (*p && *p != '\n')
  2620. p++;
  2621. if (*p)
  2622. *p++ = '\0';
  2623. if (!line[0])
  2624. continue;
  2625. origin = line;
  2626. while (*origin && *origin != ' ')
  2627. origin++;
  2628. if (!*origin)
  2629. continue;
  2630. *origin++ = '\0';
  2631. if (!line[0] || !is_http(origin))
  2632. continue;
  2633. {
  2634. struct uhttp_url uo;
  2635. if (uhttp_parse_url(origin, &uo) != 0 ||
  2636. !s_eq(uo.path, "/"))
  2637. continue;
  2638. }
  2639. s_copy(origins[origin_count].host, line,
  2640. sizeof(origins[origin_count].host));
  2641. s_copy(origins[origin_count].origin, origin,
  2642. sizeof(origins[origin_count].origin));
  2643. origin_count++;
  2644. }
  2645. }
  2646. static int host_is_www_of(const char *host, const char *base)
  2647. {
  2648. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2649. host[3] == '.' && s_eq(host + 4, base);
  2650. }
  2651. static void origin_cache_learn(const char *requested, const char *final)
  2652. {
  2653. struct uhttp_url from, to;
  2654. char origin[UHTTP_HOST_MAX + 16];
  2655. int i;
  2656. if (!is_http(requested) || !is_http(final))
  2657. return;
  2658. if (uhttp_parse_url(requested, &from) != 0 ||
  2659. uhttp_parse_url(final, &to) != 0)
  2660. return;
  2661. if (!default_port(&from))
  2662. return;
  2663. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2664. from.port == to.port)
  2665. return;
  2666. /* Only remember origin-level canonicalisation: the same path, and
  2667. * either the same host or its www./apex sibling. A path- or
  2668. * host-specific redirect (a shortener, a login page) must not poison
  2669. * every request to the typed host. */
  2670. if (!s_eq(from.path, to.path))
  2671. return;
  2672. if (!s_eq(from.host, to.host) &&
  2673. !host_is_www_of(to.host, from.host) &&
  2674. !host_is_www_of(from.host, to.host))
  2675. return;
  2676. url_origin(&to, origin, sizeof(origin));
  2677. for (i = 0; i < origin_count; i++) {
  2678. if (s_eq(origins[i].host, from.host)) {
  2679. if (!s_eq(origins[i].origin, origin)) {
  2680. s_copy(origins[i].origin, origin,
  2681. sizeof(origins[i].origin));
  2682. origin_cache_save();
  2683. }
  2684. return;
  2685. }
  2686. }
  2687. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2688. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2689. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2690. origin_cache_save();
  2691. }
  2692. static int path_dir(const char *path, char *out, unsigned int cap)
  2693. {
  2694. unsigned int i, last = 0;
  2695. for (i = 0; path[i]; i++)
  2696. if (path[i] == '/')
  2697. last = i;
  2698. if (last == 0) {
  2699. if (cap < 2)
  2700. return -1;
  2701. out[0] = '/';
  2702. out[1] = '\0';
  2703. return 0;
  2704. }
  2705. if (last + 1 >= cap)
  2706. return -1;
  2707. {
  2708. unsigned int j;
  2709. for (j = 0; j < last; j++)
  2710. out[j] = path[j];
  2711. out[last] = '\0';
  2712. }
  2713. return 0;
  2714. }
  2715. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2716. static int resolve_link(const char *base, const char *href, char *out,
  2717. unsigned int cap)
  2718. {
  2719. static char joined[BR_URL_MAX]; /* leaf: off the stack */
  2720. if (!href || !href[0] || href[0] == '#')
  2721. return -1;
  2722. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2723. starts_with(href, "data:") || starts_with(href, "tel:"))
  2724. return -1;
  2725. if (starts_with(href, "about:")) {
  2726. s_copy(out, href, cap);
  2727. return 0;
  2728. }
  2729. if (is_http(href)) {
  2730. s_copy(out, href, cap);
  2731. return 0;
  2732. }
  2733. if (starts_with(href, "//")) {
  2734. if (is_http(base)) {
  2735. unsigned int n = 0;
  2736. s_append(out, &n, starts_with(base, "https:") ?
  2737. "https:" : "http:", cap);
  2738. s_append(out, &n, href, cap);
  2739. return 0;
  2740. }
  2741. return -1;
  2742. }
  2743. if (is_http(base)) {
  2744. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2745. }
  2746. /* local page */
  2747. if (href[0] == '/') {
  2748. if (normalize_abs(href, out, cap) != 0)
  2749. return -1;
  2750. return 0;
  2751. }
  2752. {
  2753. static char dir[BR_URL_MAX];
  2754. unsigned int n = 0;
  2755. if (s_eq(base, "about:home"))
  2756. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2757. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2758. s_copy(dir, "/", sizeof(dir));
  2759. s_append(joined, &n, dir, sizeof(joined));
  2760. if (n == 0 || joined[n - 1] != '/')
  2761. s_append(joined, &n, "/", sizeof(joined));
  2762. s_append(joined, &n, href, sizeof(joined));
  2763. }
  2764. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2765. }
  2766. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2767. * rest instead of failing when a page or stylesheet is larger than the
  2768. * buffer. The stream is still walked to the end, so a normal page is
  2769. * verified; a truncated compressed input still returns whatever was decoded
  2770. * so far. */
  2771. struct trunc_buf {
  2772. unsigned char *dst;
  2773. unsigned int cap, pos;
  2774. int full;
  2775. };
  2776. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2777. {
  2778. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2779. if (len > m->cap - m->pos) {
  2780. unsigned int room = m->cap - m->pos;
  2781. if (room) {
  2782. unsigned int i;
  2783. for (i = 0; i < room; i++)
  2784. m->dst[m->pos + i] = data[i];
  2785. m->pos += room;
  2786. }
  2787. m->full = 1;
  2788. return 0;
  2789. }
  2790. {
  2791. unsigned int i;
  2792. for (i = 0; i < len; i++)
  2793. m->dst[m->pos + i] = data[i];
  2794. }
  2795. m->pos += len;
  2796. return 0;
  2797. }
  2798. static void worker_wait_ui(void);
  2799. static void inflate_ui_pump(void *ctx)
  2800. {
  2801. static unsigned int last;
  2802. unsigned int now = u_ticks_ms();
  2803. (void)ctx;
  2804. if ((int)(now - last) >= 50) {
  2805. last = now;
  2806. worker_wait_ui();
  2807. }
  2808. }
  2809. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2810. unsigned char *dst, unsigned int cap,
  2811. unsigned int *outlen, int gzip, int *truncated)
  2812. {
  2813. struct inflate_src in;
  2814. struct inflate_sink sink;
  2815. struct trunc_buf m;
  2816. unsigned int got = 0;
  2817. int r;
  2818. in.p = src;
  2819. in.len = len;
  2820. in.more = 0;
  2821. in.ctx = 0;
  2822. m.dst = dst;
  2823. m.cap = cap;
  2824. m.pos = 0;
  2825. m.full = 0;
  2826. sink.write = trunc_write;
  2827. sink.ctx = &m;
  2828. inflate_init(&image_inflate_ws, &in, &sink);
  2829. image_inflate_ws.progress = inflate_ui_pump;
  2830. image_inflate_ws.progress_ctx = 0;
  2831. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2832. inflate_zlib(&image_inflate_ws, &got);
  2833. *outlen = m.pos;
  2834. *truncated = m.full || r != 0;
  2835. if (r != 0 && m.pos == 0)
  2836. return -1;
  2837. return 0;
  2838. }
  2839. /* ---- headless fetch workers ------------------------------------------ *
  2840. *
  2841. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2842. * writes the raw response, a small metadata file and a done marker under
  2843. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2844. * or a multi-megabyte body never freezes the UI and images download in
  2845. * parallel.
  2846. */
  2847. struct fetch_meta {
  2848. int status;
  2849. int error;
  2850. int trunc;
  2851. unsigned int len;
  2852. unsigned int open_ms;
  2853. unsigned int first_ms;
  2854. unsigned int total_ms;
  2855. /* Optional decoded bitmap produced by the helper (image jobs). */
  2856. unsigned int dw, dh, nw, nh;
  2857. unsigned int alpha;
  2858. unsigned int px_len;
  2859. unsigned int dec_ms;
  2860. int dec_err;
  2861. char encoding[16];
  2862. char ctype[64];
  2863. char final[BR_URL_MAX];
  2864. };
  2865. static void draw(unsigned int *action);
  2866. static void handle_keys(unsigned int *action);
  2867. static void handle_page_click(unsigned int *action);
  2868. #define FETCH_WORKERS 4
  2869. #define FETCH_PATH_MAX 32
  2870. /* One long-lived curl __serve helper per worker. Each worker has its own
  2871. * request/body/meta/done files under /share so several downloads can be in
  2872. * flight at once; the keep-alive connection stays in the helper process, so
  2873. * tls.c's per-process state remains valid. */
  2874. struct fetch_worker {
  2875. int pid;
  2876. int slot;
  2877. int busy;
  2878. int ready;
  2879. int image_job;
  2880. unsigned int seq;
  2881. unsigned int deadline;
  2882. int retried;
  2883. unsigned int dec_w, dec_h;
  2884. int dec_retried;
  2885. char req[FETCH_PATH_MAX];
  2886. char body[FETCH_PATH_MAX];
  2887. char meta[FETCH_PATH_MAX];
  2888. char done[FETCH_PATH_MAX];
  2889. char post[FETCH_PATH_MAX];
  2890. char px[FETCH_PATH_MAX];
  2891. /* Optional preload job attached to this worker. */
  2892. unsigned int node;
  2893. int bg;
  2894. char url[BR_URL_MAX];
  2895. struct fetch_meta m;
  2896. };
  2897. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2898. static int fetch_tty = -2;
  2899. static void fetch_tty_drain(void);
  2900. static unsigned int fetch_session;
  2901. static unsigned int fetch_seq;
  2902. static struct fetch_meta fetch_meta;
  2903. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2904. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2905. static int fetch_last_error;
  2906. static unsigned int meta_uint(char **pp)
  2907. {
  2908. char *p = *pp;
  2909. unsigned int v = 0;
  2910. while (*p >= '0' && *p <= '9') {
  2911. v = v * 10 + (unsigned int)(*p - '0');
  2912. p++;
  2913. }
  2914. while (*p && *p != '\n')
  2915. p++;
  2916. if (*p == '\n')
  2917. p++;
  2918. *pp = p;
  2919. return v;
  2920. }
  2921. static void meta_str(char **pp, char *out, unsigned int cap)
  2922. {
  2923. char *p = *pp;
  2924. unsigned int n = 0;
  2925. while (*p && *p != '\n' && n + 1 < cap)
  2926. out[n++] = *p++;
  2927. out[n] = '\0';
  2928. while (*p && *p != '\n')
  2929. p++;
  2930. if (*p == '\n')
  2931. p++;
  2932. *pp = p;
  2933. }
  2934. static void worker_wait_ui(void)
  2935. {
  2936. unsigned int action = 0;
  2937. if (!ngui_begin(&ui))
  2938. return;
  2939. draw(&action);
  2940. handle_keys(&action);
  2941. handle_page_click(&action);
  2942. if (action & ACT_WAIT_NAV) {
  2943. pending_action |= action & ACT_WAIT_NAV;
  2944. if ((action & ACT_NAV) && click_url[0])
  2945. s_copy(pending_url, click_url, sizeof(pending_url));
  2946. click_url[0] = '\0';
  2947. cancel_fetch = 1;
  2948. }
  2949. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2950. ngui_invalidate(&ui);
  2951. ngui_end(&ui);
  2952. }
  2953. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2954. unsigned int session, int slot)
  2955. {
  2956. unsigned int n = 0;
  2957. s_append(out, &n, "/share/bf", cap);
  2958. s_append_dec(out, &n, session, cap);
  2959. s_append(out, &n, "_", cap);
  2960. s_append_dec(out, &n, (unsigned int)slot, cap);
  2961. s_append(out, &n, kind, cap);
  2962. }
  2963. static void fetch_pool_init(void)
  2964. {
  2965. static int ready;
  2966. int i;
  2967. if (ready)
  2968. return;
  2969. ready = 1;
  2970. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2971. (u_ticks_ms() & 0xFFFFu);
  2972. if (!fetch_session)
  2973. fetch_session = 1;
  2974. for (i = 0; i < FETCH_WORKERS; i++) {
  2975. struct fetch_worker *w = &fetch_workers[i];
  2976. w->pid = -1;
  2977. w->slot = i;
  2978. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2979. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2980. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2981. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2982. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2983. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  2984. }
  2985. }
  2986. static void fetch_worker_stop(struct fetch_worker *w)
  2987. {
  2988. int i;
  2989. /* An abandoned image job leaves its node loadable again. */
  2990. if (w->busy && w->image_job && w->node < doc.nnode) {
  2991. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2992. doc.nodes[w->node].bg_img_index = -1;
  2993. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2994. doc.nodes[w->node].img_index = -1;
  2995. }
  2996. if (w->pid > 0) {
  2997. u_kill((unsigned int)w->pid);
  2998. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2999. u_sleep_ms(5);
  3000. /* Let the reaper close the socket before we reuse the slot. */
  3001. u_sleep_ms(10);
  3002. }
  3003. w->pid = -1;
  3004. w->busy = 0;
  3005. w->ready = 0;
  3006. w->image_job = 0;
  3007. if (w->req[0]) {
  3008. u_syscall1(SYS_UNLINK, (int)w->done);
  3009. u_syscall1(SYS_UNLINK, (int)w->meta);
  3010. u_syscall1(SYS_UNLINK, (int)w->body);
  3011. u_syscall1(SYS_UNLINK, (int)w->post);
  3012. u_syscall1(SYS_UNLINK, (int)w->req);
  3013. }
  3014. }
  3015. static void fetch_workers_stop_all(void)
  3016. {
  3017. int i;
  3018. for (i = 0; i < FETCH_WORKERS; i++)
  3019. fetch_worker_stop(&fetch_workers[i]);
  3020. }
  3021. /* Abandon the transfers of the current page but keep idle helpers and their
  3022. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  3023. * because its response would otherwise land in a reused /share slot. */
  3024. static void fetch_workers_cancel_busy(void)
  3025. {
  3026. int i;
  3027. for (i = 0; i < FETCH_WORKERS; i++)
  3028. if (fetch_workers[i].busy)
  3029. fetch_worker_stop(&fetch_workers[i]);
  3030. }
  3031. static void fetch_workers_prepare_nav(const char *url)
  3032. {
  3033. int i;
  3034. (void)url;
  3035. for (i = 0; i < FETCH_WORKERS; i++) {
  3036. struct fetch_worker *w = &fetch_workers[i];
  3037. if (w->pid <= 0)
  3038. continue;
  3039. /* Only an in-flight transfer must be aborted. Idle helpers
  3040. * stay warm across origins: there are just FETCH_WORKERS of
  3041. * them, and uhttp_open drops the old connection when the
  3042. * next job is for another host. Killing and respawning all
  3043. * four on every navigation churned processes and sockets
  3044. * while images were still loading. */
  3045. if (w->busy)
  3046. fetch_worker_stop(w);
  3047. }
  3048. }
  3049. /* The browser is no longer the active window and no fetch is running: give
  3050. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  3051. static void fetch_workers_stop_if_unfocused(void)
  3052. {
  3053. int i;
  3054. fetch_tty_drain();
  3055. if (ui.focused || page_loading || preload_active)
  3056. return;
  3057. for (i = 0; i < FETCH_WORKERS; i++)
  3058. if (fetch_workers[i].pid > 0) {
  3059. fetch_workers_stop_all();
  3060. return;
  3061. }
  3062. }
  3063. /* The helpers (and this process, since u_tty_create() rebinds our own
  3064. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  3065. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  3066. * a dozen TLS connections every helper hung in its next log line, so the
  3067. * following cross-origin navigation sat at "Loading..." until it timed out.
  3068. * Drain and discard it from every wait/poll loop. */
  3069. static void fetch_tty_drain(void)
  3070. {
  3071. char sink[512];
  3072. int i;
  3073. if (fetch_tty <= 0)
  3074. return;
  3075. for (i = 0; i < 16; i++)
  3076. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  3077. break;
  3078. }
  3079. static int fetch_worker_start(struct fetch_worker *w, char *err,
  3080. unsigned int errcap)
  3081. {
  3082. char arg[40];
  3083. unsigned int n = 0;
  3084. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  3085. return 0;
  3086. w->pid = -1;
  3087. fetch_pool_init();
  3088. if (fetch_tty == -2) {
  3089. int t = u_tty_create();
  3090. fetch_tty = t > 0 ? t : 0;
  3091. }
  3092. s_append(arg, &n, "__serve ", sizeof(arg));
  3093. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  3094. s_append(arg, &n, " ", sizeof(arg));
  3095. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  3096. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  3097. if (w->pid <= 0) {
  3098. w->pid = -1;
  3099. s_copy(err, "cannot start network helper", errcap);
  3100. return -1;
  3101. }
  3102. return 0;
  3103. }
  3104. static struct fetch_worker *fetch_worker_alloc(void)
  3105. {
  3106. int i;
  3107. fetch_pool_init();
  3108. for (i = 0; i < FETCH_WORKERS; i++)
  3109. if (!fetch_workers[i].busy)
  3110. return &fetch_workers[i];
  3111. return 0;
  3112. }
  3113. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3114. unsigned int cap, const char *method,
  3115. const char *ctype, const char *post,
  3116. unsigned int post_len, unsigned int node,
  3117. int bg, unsigned int dec_w,
  3118. unsigned int dec_h, char *err,
  3119. unsigned int errcap);
  3120. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  3121. unsigned int cap, const char *post,
  3122. unsigned int post_len, unsigned int node,
  3123. int bg, char *err, unsigned int errcap)
  3124. {
  3125. /* A body pointer with no bytes is still a POST: the classic request
  3126. * line would turn it into a GET. */
  3127. if (post && !post_len)
  3128. return fetch_worker_submit_req(w, url, cap, "POST",
  3129. "application/x-www-form-urlencoded", post, 0, node,
  3130. bg, 0, 0, err, errcap);
  3131. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  3132. node, bg, 0, 0, err, errcap);
  3133. }
  3134. /* Image job: ask the helper to decode at these display bounds as well. */
  3135. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  3136. unsigned int cap, unsigned int node,
  3137. int bg, unsigned int dec_w,
  3138. unsigned int dec_h, char *err,
  3139. unsigned int errcap)
  3140. {
  3141. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  3142. dec_w, dec_h, err, errcap);
  3143. }
  3144. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  3145. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  3146. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  3147. unsigned int cap, const char *method,
  3148. const char *ctype, const char *post,
  3149. unsigned int post_len, unsigned int node,
  3150. int bg, unsigned int dec_w,
  3151. unsigned int dec_h, char *err,
  3152. unsigned int errcap)
  3153. {
  3154. static char req[BR_URL_MAX + 256];
  3155. unsigned int n = 0;
  3156. fetch_seq++;
  3157. if (!fetch_seq)
  3158. fetch_seq = 1;
  3159. w->seq = fetch_seq;
  3160. w->ready = 0;
  3161. w->image_job = 0;
  3162. w->retried = 0;
  3163. w->m.error = 0;
  3164. w->node = node;
  3165. w->bg = bg;
  3166. w->dec_w = dec_w;
  3167. w->dec_h = dec_h;
  3168. w->dec_retried = 0;
  3169. s_copy(w->url, url, sizeof(w->url));
  3170. s_append_dec(req, &n, w->seq, sizeof(req));
  3171. s_append(req, &n, " ", sizeof(req));
  3172. s_append_dec(req, &n, cap, sizeof(req));
  3173. s_append(req, &n, " ", sizeof(req));
  3174. if (dec_w || dec_h) {
  3175. s_append(req, &n, "D ", sizeof(req));
  3176. s_append_dec(req, &n, dec_w, sizeof(req));
  3177. s_append(req, &n, " ", sizeof(req));
  3178. s_append_dec(req, &n, dec_h, sizeof(req));
  3179. s_append(req, &n, " ", sizeof(req));
  3180. } else if (method) {
  3181. unsigned int k;
  3182. s_append(req, &n, "X ", sizeof(req));
  3183. s_append(req, &n, method, sizeof(req));
  3184. s_append(req, &n, " ", sizeof(req));
  3185. s_append_dec(req, &n, post_len, sizeof(req));
  3186. s_append(req, &n, " ", sizeof(req));
  3187. if (!ctype || !ctype[0])
  3188. s_append(req, &n, "-", sizeof(req));
  3189. /* One token on the request line: drop the spaces
  3190. * ("application/json; charset=utf-8" stays valid). */
  3191. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  3192. if (ctype[k] != ' ')
  3193. req[n++] = ctype[k];
  3194. req[n] = '\0';
  3195. s_append(req, &n, " ", sizeof(req));
  3196. } else if (post_len) {
  3197. s_append(req, &n, "POST ", sizeof(req));
  3198. s_append_dec(req, &n, post_len, sizeof(req));
  3199. s_append(req, &n, " ", sizeof(req));
  3200. }
  3201. s_append(req, &n, url, sizeof(req));
  3202. s_append(req, &n, "\n", sizeof(req));
  3203. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  3204. (int)post, (int)post_len) < 0) {
  3205. s_copy(err, "cannot queue form body", errcap);
  3206. return -1;
  3207. }
  3208. u_syscall1(SYS_UNLINK, (int)w->done);
  3209. u_syscall1(SYS_UNLINK, (int)w->meta);
  3210. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  3211. s_copy(err, "cannot queue network request", errcap);
  3212. return -1;
  3213. }
  3214. if (fetch_worker_start(w, err, errcap) != 0)
  3215. return -1;
  3216. w->busy = 1;
  3217. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  3218. return 0;
  3219. }
  3220. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  3221. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  3222. unsigned int errcap)
  3223. {
  3224. static char meta[BR_URL_MAX + 1024];
  3225. char *p;
  3226. int rn, mseq;
  3227. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  3228. (int)(sizeof(meta) - 1));
  3229. if (rn <= 0) {
  3230. s_copy(err, "network helper failed", errcap);
  3231. return -1;
  3232. }
  3233. meta[rn] = '\0';
  3234. p = meta;
  3235. mseq = (int)meta_uint(&p);
  3236. if (mseq != (int)w->seq) {
  3237. s_copy(err, "stale network response", errcap);
  3238. return -1;
  3239. }
  3240. w->m.status = (int)meta_uint(&p);
  3241. w->m.error = (int)meta_uint(&p);
  3242. w->m.trunc = (int)meta_uint(&p);
  3243. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  3244. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  3245. meta_str(&p, w->m.final, sizeof(w->m.final));
  3246. w->m.len = meta_uint(&p);
  3247. w->m.open_ms = 0;
  3248. w->m.first_ms = 0;
  3249. w->m.total_ms = 0;
  3250. if (*p) {
  3251. w->m.open_ms = meta_uint(&p);
  3252. w->m.first_ms = meta_uint(&p);
  3253. w->m.total_ms = meta_uint(&p);
  3254. }
  3255. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3256. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3257. w->m.dec_err = 0;
  3258. if (*p) {
  3259. w->m.dw = meta_uint(&p);
  3260. w->m.dh = meta_uint(&p);
  3261. w->m.nw = meta_uint(&p);
  3262. w->m.nh = meta_uint(&p);
  3263. w->m.alpha = meta_uint(&p);
  3264. w->m.px_len = meta_uint(&p);
  3265. w->m.dec_err = (int)meta_uint(&p);
  3266. w->m.dec_ms = meta_uint(&p);
  3267. }
  3268. if (w->m.error) {
  3269. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3270. return -1;
  3271. }
  3272. w->ready = 1;
  3273. return 0;
  3274. }
  3275. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3276. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3277. unsigned int errcap)
  3278. {
  3279. static char done[24];
  3280. char *p;
  3281. int rn, mseq;
  3282. fetch_tty_drain();
  3283. if (!w->busy)
  3284. return -1;
  3285. if (w->ready)
  3286. return 1;
  3287. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3288. (int)(sizeof(done) - 1));
  3289. if (rn > 0) {
  3290. done[rn] = '\0';
  3291. p = done;
  3292. mseq = (int)meta_uint(&p);
  3293. if (mseq == (int)w->seq) {
  3294. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3295. fetch_worker_stop(w);
  3296. return -1;
  3297. }
  3298. return 1;
  3299. }
  3300. }
  3301. if (!u_alive((unsigned int)w->pid)) {
  3302. w->pid = -1;
  3303. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3304. w->retried = 1;
  3305. return 0;
  3306. }
  3307. s_copy(err, "network helper stopped", errcap);
  3308. fetch_worker_stop(w);
  3309. return -1;
  3310. }
  3311. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3312. s_copy(err, "network request timed out", errcap);
  3313. fetch_worker_stop(w);
  3314. return -1;
  3315. }
  3316. return 0;
  3317. }
  3318. /* Copy the completed body, inflating it if the server ignored our identity
  3319. * request. Mirrors the old fetch_remote body path. */
  3320. static int fetch_worker_read_body(struct fetch_worker *w,
  3321. unsigned char *plain,
  3322. unsigned int plaincap,
  3323. unsigned char *comp,
  3324. unsigned int compcap,
  3325. int *truncated, char *err,
  3326. unsigned int errcap)
  3327. {
  3328. int rv, zr, was_trunc;
  3329. if (contains_ci(w->m.encoding, "gzip") ||
  3330. contains_ci(w->m.encoding, "deflate")) {
  3331. unsigned int comp_len = 0, plen = 0;
  3332. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3333. (int)compcap);
  3334. if (rv < 0) {
  3335. s_copy(err, "empty response", errcap);
  3336. return -1;
  3337. }
  3338. comp_len = (unsigned int)rv;
  3339. if (comp_len < w->m.len) {
  3340. s_copy(err, "compressed response is too large", errcap);
  3341. return -1;
  3342. }
  3343. if (contains_ci(w->m.encoding, "deflate"))
  3344. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3345. &plen, 0, &was_trunc);
  3346. else
  3347. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3348. &plen, 1, &was_trunc);
  3349. if (zr != 0) {
  3350. s_copy(err, "compressed response is corrupt", errcap);
  3351. return -1;
  3352. }
  3353. *truncated = w->m.trunc || was_trunc;
  3354. return (int)plen;
  3355. }
  3356. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3357. if (rv < 0) {
  3358. s_copy(err, "empty response", errcap);
  3359. return -1;
  3360. }
  3361. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3362. return rv;
  3363. }
  3364. static void fetch_worker_release(struct fetch_worker *w)
  3365. {
  3366. u_syscall1(SYS_UNLINK, (int)w->done);
  3367. u_syscall1(SYS_UNLINK, (int)w->meta);
  3368. u_syscall1(SYS_UNLINK, (int)w->body);
  3369. u_syscall1(SYS_UNLINK, (int)w->post);
  3370. u_syscall1(SYS_UNLINK, (int)w->px);
  3371. u_syscall1(SYS_UNLINK, (int)w->req);
  3372. w->busy = 0;
  3373. w->ready = 0;
  3374. w->image_job = 0;
  3375. w->dec_w = 0;
  3376. w->dec_h = 0;
  3377. w->dec_retried = 0;
  3378. }
  3379. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3380. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3381. unsigned int errcap)
  3382. {
  3383. for (;;) {
  3384. int rv;
  3385. if (!fetch_wait_passive)
  3386. worker_wait_ui();
  3387. if (cancel_fetch || pending_action) {
  3388. fetch_workers_cancel_busy();
  3389. return FETCH_ABORT;
  3390. }
  3391. rv = fetch_worker_poll(w, err, errcap);
  3392. if (rv != 0)
  3393. return rv == 1 ? 0 : -1;
  3394. u_sleep_ms(10);
  3395. }
  3396. }
  3397. static int fetch_remote(const char *url, unsigned int cap,
  3398. const char *post, unsigned int post_len,
  3399. unsigned char *plain, unsigned int plaincap,
  3400. unsigned char *comp, unsigned int compcap,
  3401. struct fetch_meta *m, int *truncated,
  3402. char *err, unsigned int errcap)
  3403. {
  3404. struct fetch_worker *w = fetch_worker_alloc();
  3405. int rv;
  3406. fetch_last_error = 0;
  3407. if (!w) {
  3408. s_copy(err, "network busy", errcap);
  3409. return -1;
  3410. }
  3411. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3412. err, errcap) != 0) {
  3413. fetch_worker_release(w);
  3414. return -1;
  3415. }
  3416. rv = fetch_worker_wait(w, err, errcap);
  3417. if (rv == FETCH_ABORT) {
  3418. fetch_worker_release(w);
  3419. return FETCH_ABORT;
  3420. }
  3421. if (rv != 0) {
  3422. fetch_last_error = w->m.error;
  3423. fetch_worker_release(w);
  3424. return -1;
  3425. }
  3426. *m = w->m;
  3427. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3428. truncated, err, errcap);
  3429. fetch_worker_release(w);
  3430. if (rv >= 0 && (cancel_fetch || pending_action))
  3431. return FETCH_ABORT;
  3432. return rv;
  3433. }
  3434. static int fetch_worker_status(const struct fetch_worker *w)
  3435. {
  3436. return w->m.status;
  3437. }
  3438. /* fetch()/XHR through a helper: one request, the status and body come back
  3439. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3440. static int js_worker_http(const char *method, const char *url,
  3441. const char *ctype, const char *body,
  3442. unsigned int body_len, struct js_http_resp *r,
  3443. char *err, int errcap)
  3444. {
  3445. struct fetch_worker *w = fetch_worker_alloc();
  3446. unsigned char *plain;
  3447. int rv, tr = 0;
  3448. if (!w) {
  3449. s_copy(err, "network busy", (unsigned int)errcap);
  3450. return -1;
  3451. }
  3452. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3453. body_len, 0, 0, 0, 0, err,
  3454. (unsigned int)errcap) != 0) {
  3455. fetch_worker_release(w);
  3456. return -1;
  3457. }
  3458. fetch_wait_passive++;
  3459. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3460. fetch_wait_passive--;
  3461. if (rv != 0) {
  3462. if (rv == FETCH_ABORT)
  3463. s_copy(err, "page is navigating", (unsigned int)errcap);
  3464. fetch_worker_release(w);
  3465. return -1;
  3466. }
  3467. r->status = w->m.status;
  3468. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3469. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3470. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3471. if (!plain) {
  3472. fetch_worker_release(w);
  3473. s_copy(err, "out of memory", (unsigned int)errcap);
  3474. return -1;
  3475. }
  3476. if (w->m.len == 0) {
  3477. rv = 0; /* 204, an empty 200: no body file */
  3478. } else {
  3479. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3480. image_io_buf, BR_PAGE_COMP_MAX,
  3481. &tr, err, (unsigned int)errcap);
  3482. }
  3483. fetch_worker_release(w);
  3484. if (rv < 0) {
  3485. free(plain);
  3486. return -1;
  3487. }
  3488. plain[rv] = '\0';
  3489. r->body = (char *)plain;
  3490. r->len = (unsigned int)rv;
  3491. return 0;
  3492. }
  3493. /* ---- HTTP / file fetch ---- */
  3494. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3495. unsigned int *outlen, int *is_local, char *ctype,
  3496. unsigned int ctcap, char *final, unsigned int finalcap,
  3497. char *err, unsigned int errcap, int *truncated,
  3498. const char *post, unsigned int post_len)
  3499. {
  3500. unsigned char *buf;
  3501. unsigned int len;
  3502. int tr = 0;
  3503. int rv;
  3504. *out = 0;
  3505. *outlen = 0;
  3506. *truncated = 0;
  3507. if (final && finalcap)
  3508. final[0] = '\0';
  3509. if (ctype && ctcap)
  3510. ctype[0] = '\0';
  3511. if (url[0] == '/') {
  3512. char pathbuf[BR_URL_MAX];
  3513. const char *open_url = url;
  3514. unsigned int i = 0;
  3515. /* A local form GET keeps ?query in the address bar but the
  3516. * file lookup uses the path alone, like a real browser. */
  3517. while (url[i] && url[i] != '?' && url[i] != '#')
  3518. i++;
  3519. if (url[i]) {
  3520. s_copy(pathbuf, url, i + 1);
  3521. open_url = pathbuf;
  3522. }
  3523. buf = (unsigned char *)malloc(cap);
  3524. if (!buf) {
  3525. s_copy(err, "out of memory", errcap);
  3526. return -1;
  3527. }
  3528. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3529. if (rv < 0) {
  3530. free(buf);
  3531. s_copy(err, "file not found", errcap);
  3532. return -1;
  3533. }
  3534. *out = buf;
  3535. *outlen = (unsigned int)rv;
  3536. *is_local = 1;
  3537. if (ctype)
  3538. s_copy(ctype, "text/html", ctcap);
  3539. if (final)
  3540. s_copy(final, url, finalcap);
  3541. if ((unsigned int)rv == cap)
  3542. *truncated = 1;
  3543. return 0;
  3544. }
  3545. buf = (unsigned char *)malloc(cap);
  3546. if (!buf) {
  3547. s_copy(err, "out of memory", errcap);
  3548. return -1;
  3549. }
  3550. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3551. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3552. if (rv == FETCH_ABORT) {
  3553. free(buf);
  3554. return FETCH_ABORT;
  3555. }
  3556. if (rv < 0) {
  3557. free(buf);
  3558. return -1;
  3559. }
  3560. len = (unsigned int)rv;
  3561. if (len == 0) {
  3562. free(buf);
  3563. s_copy(err, "empty response", errcap);
  3564. return -1;
  3565. }
  3566. if (ctype)
  3567. s_copy(ctype, fetch_meta.ctype, ctcap);
  3568. if (final && fetch_meta.final[0])
  3569. s_copy(final, fetch_meta.final, finalcap);
  3570. *is_local = 0;
  3571. *out = buf;
  3572. *outlen = len;
  3573. *truncated = tr;
  3574. return 0;
  3575. }
  3576. /* Load every @font-face the parser registered. Local files go through
  3577. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3578. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3579. * to the built-in regular/bold/italic/mono set. */
  3580. static void load_font_faces(void)
  3581. {
  3582. unsigned int i;
  3583. memset(font_faces, 0, sizeof(font_faces));
  3584. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3585. i <= BR_MAX_FACES; i++) {
  3586. const char *url = br_font_face_url((int)i);
  3587. const char *base = br_font_face_base((int)i);
  3588. char abs[BR_URL_MAX];
  3589. if (!url || !url[0])
  3590. continue;
  3591. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3592. sizeof(abs)) != 0)
  3593. continue;
  3594. if (abs[0] == '/') {
  3595. font_faces[i - 1] = ufont_face_open_path(abs);
  3596. } else if (is_http(abs)) {
  3597. unsigned char *buf;
  3598. char err[64];
  3599. int rv, tr = 0;
  3600. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3601. if (!buf)
  3602. continue;
  3603. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3604. UFONT_MAX_FILE, image_io_buf,
  3605. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3606. err, sizeof(err));
  3607. if (rv > 0)
  3608. font_faces[i - 1] = ufont_face_open_mem(buf,
  3609. rv);
  3610. free(buf);
  3611. }
  3612. }
  3613. }
  3614. /* Remote scripts are cached under /share for the current boot, like the
  3615. * stylesheet cache, so reloads and later visits skip the network. */
  3616. static int script_cache_count;
  3617. static unsigned int script_cache_hash(const char *s)
  3618. {
  3619. unsigned int h = 2166136261u;
  3620. while (*s) {
  3621. h ^= (unsigned char)*s++;
  3622. h *= 16777619u;
  3623. }
  3624. return h;
  3625. }
  3626. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3627. {
  3628. unsigned int n = 0;
  3629. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3630. s_append_dec(out, &n, script_cache_hash(url), cap);
  3631. }
  3632. static void script_cache_clear(void)
  3633. {
  3634. struct sys_dirent d;
  3635. char path[96];
  3636. for (;;) {
  3637. int i, found = 0;
  3638. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3639. (int)&d) == 1; i++) {
  3640. unsigned int n = 0;
  3641. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3642. continue;
  3643. s_append(path, &n, "/share/", sizeof(path));
  3644. s_append(path, &n, d.name, sizeof(path));
  3645. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3646. return;
  3647. found = 1;
  3648. break;
  3649. }
  3650. if (!found)
  3651. break;
  3652. }
  3653. script_cache_count = 0;
  3654. }
  3655. static void script_cache_init(void)
  3656. {
  3657. struct sys_dirent d;
  3658. int i, count = 0;
  3659. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3660. (int)&d) == 1; i++)
  3661. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3662. count++;
  3663. if (count >= SCRIPT_CACHE_MAX) {
  3664. script_cache_clear();
  3665. return;
  3666. }
  3667. script_cache_count = count;
  3668. }
  3669. static int script_cache_get(const char *url, unsigned char **out,
  3670. unsigned int *outlen)
  3671. {
  3672. char path[96];
  3673. struct sys_stat st;
  3674. unsigned char *buf;
  3675. int rn;
  3676. script_cache_path(url, path, sizeof(path));
  3677. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3678. st.size >= SCRIPT_CACHE_FILE_MAX)
  3679. return 0;
  3680. buf = (unsigned char *)malloc(st.size + 1);
  3681. if (!buf)
  3682. return 0;
  3683. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3684. if (rn != (int)st.size) {
  3685. free(buf);
  3686. return 0;
  3687. }
  3688. buf[st.size] = '\0';
  3689. *out = buf;
  3690. *outlen = st.size;
  3691. return 1;
  3692. }
  3693. static void script_cache_put(const char *url, const unsigned char *data,
  3694. unsigned int len)
  3695. {
  3696. char path[96];
  3697. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3698. len >= SCRIPT_CACHE_FILE_MAX)
  3699. return;
  3700. script_cache_path(url, path, sizeof(path));
  3701. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3702. (int)len) >= 0)
  3703. script_cache_count++;
  3704. }
  3705. static int script_cache_has(const char *url)
  3706. {
  3707. char path[96];
  3708. struct sys_stat st;
  3709. script_cache_path(url, path, sizeof(path));
  3710. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3711. st.size < SCRIPT_CACHE_FILE_MAX;
  3712. }
  3713. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3714. static int fetch_script_text(const char *url, unsigned char **out,
  3715. unsigned int *outlen, char *err,
  3716. unsigned int errcap)
  3717. {
  3718. unsigned char *buf;
  3719. unsigned int len;
  3720. int local, truncated = 0;
  3721. char ctype[64], final[BR_URL_MAX];
  3722. int rv;
  3723. *out = 0;
  3724. *outlen = 0;
  3725. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3726. return 0;
  3727. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3728. sizeof(ctype), final, sizeof(final), err, errcap,
  3729. &truncated, 0, 0);
  3730. if (rv != 0)
  3731. return rv;
  3732. if (truncated || len >= BR_SCRIPT_MAX) {
  3733. free(buf);
  3734. s_copy(err, "script is too large", errcap);
  3735. return -1;
  3736. }
  3737. buf[len] = '\0';
  3738. if (!local)
  3739. script_cache_put(url, buf, len);
  3740. *out = buf;
  3741. *outlen = len;
  3742. return 0;
  3743. }
  3744. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3745. * the heap, so images must not allocate their file body from it as well. */
  3746. static int fetch_image(const char *url, unsigned int cap,
  3747. unsigned char **out, unsigned int *outlen,
  3748. char *err, unsigned int errcap)
  3749. {
  3750. unsigned int len;
  3751. int tr = 0;
  3752. int rv;
  3753. *out = 0;
  3754. *outlen = 0;
  3755. if (cap > BR_IMG_FILE_MAX)
  3756. cap = BR_IMG_FILE_MAX;
  3757. if (url[0] == '/') {
  3758. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3759. (int)cap);
  3760. if (rv < 0) {
  3761. s_copy(err, "file not found", errcap);
  3762. return -1;
  3763. }
  3764. *out = image_file_buf;
  3765. *outlen = (unsigned int)rv;
  3766. return 0;
  3767. }
  3768. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3769. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3770. if (rv == FETCH_ABORT)
  3771. return FETCH_ABORT;
  3772. if (rv < 0)
  3773. return -1;
  3774. len = (unsigned int)rv;
  3775. if (len == 0) {
  3776. s_copy(err, "empty image", errcap);
  3777. return -1;
  3778. }
  3779. *out = image_file_buf;
  3780. *outlen = len;
  3781. return 0;
  3782. }
  3783. /* Remote stylesheets are immutable enough for the current boot: keep
  3784. * successful responses under /share so a reload, a second visit or a fresh
  3785. * browser launch does not fetch the same five sheets over the network again.
  3786. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3787. static int css_cache_count;
  3788. static unsigned int css_cache_hash(const char *s)
  3789. {
  3790. unsigned int h = 2166136261u;
  3791. while (*s) {
  3792. h ^= (unsigned char)*s++;
  3793. h *= 16777619u;
  3794. }
  3795. return h;
  3796. }
  3797. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3798. {
  3799. unsigned int n = 0;
  3800. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3801. s_append_dec(out, &n, css_cache_hash(url), cap);
  3802. }
  3803. static void css_cache_clear(void)
  3804. {
  3805. struct sys_dirent d;
  3806. char path[96];
  3807. for (;;) {
  3808. int i, found = 0;
  3809. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3810. (int)&d) == 1; i++) {
  3811. unsigned int n = 0;
  3812. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3813. continue;
  3814. s_append(path, &n, "/share/", sizeof(path));
  3815. s_append(path, &n, d.name, sizeof(path));
  3816. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3817. return;
  3818. found = 1;
  3819. break;
  3820. }
  3821. if (!found)
  3822. break;
  3823. }
  3824. css_cache_count = 0;
  3825. }
  3826. static void css_cache_init(void)
  3827. {
  3828. struct sys_dirent d;
  3829. int i, count = 0;
  3830. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3831. (int)&d) == 1; i++)
  3832. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3833. count++;
  3834. if (count >= CSS_CACHE_MAX) {
  3835. css_cache_clear();
  3836. return;
  3837. }
  3838. css_cache_count = count;
  3839. }
  3840. static int css_cache_get(const char *url, unsigned char **out,
  3841. unsigned int *outlen)
  3842. {
  3843. char path[96];
  3844. int rn;
  3845. css_cache_path(url, path, sizeof(path));
  3846. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3847. (int)CSS_CACHE_FILE_MAX);
  3848. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3849. return 0;
  3850. *out = image_io_buf;
  3851. *outlen = (unsigned int)rn;
  3852. return 1;
  3853. }
  3854. static void css_cache_put(const char *url, const unsigned char *data,
  3855. unsigned int len)
  3856. {
  3857. char path[96];
  3858. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3859. len >= CSS_CACHE_FILE_MAX)
  3860. return;
  3861. css_cache_path(url, path, sizeof(path));
  3862. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3863. (int)len) >= 0)
  3864. css_cache_count++;
  3865. }
  3866. static int css_cache_has(const char *url)
  3867. {
  3868. char path[96];
  3869. struct sys_stat st;
  3870. css_cache_path(url, path, sizeof(path));
  3871. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3872. st.size < CSS_CACHE_FILE_MAX;
  3873. }
  3874. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3875. * immediately, so it does not need the page heap; this leaves the heap for
  3876. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3877. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3878. char *err, unsigned int errcap)
  3879. {
  3880. unsigned int len;
  3881. int tr = 0;
  3882. int rv;
  3883. *out = 0;
  3884. *outlen = 0;
  3885. if (url[0] == '/') {
  3886. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3887. (int)BR_CSS_MAX);
  3888. if (rv < 0) {
  3889. s_copy(err, "stylesheet not found", errcap);
  3890. return -1;
  3891. }
  3892. *out = image_io_buf;
  3893. *outlen = (unsigned int)rv;
  3894. return 0;
  3895. }
  3896. if (css_cache_get(url, out, outlen))
  3897. return 0;
  3898. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3899. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3900. &fetch_meta, &tr, err, errcap);
  3901. if (rv == FETCH_ABORT)
  3902. return FETCH_ABORT;
  3903. if (rv < 0)
  3904. return -1;
  3905. len = (unsigned int)rv;
  3906. if (len == 0) {
  3907. s_copy(err, "empty stylesheet", errcap);
  3908. return -1;
  3909. }
  3910. *out = image_io_buf;
  3911. *outlen = len;
  3912. css_cache_put(url, image_io_buf, len);
  3913. return 0;
  3914. }
  3915. static void redraw_now(void);
  3916. static char error_page[1024];
  3917. static void show_error(const char *title, const char *detail)
  3918. {
  3919. char *page = error_page;
  3920. unsigned int n = 0;
  3921. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3922. s_append(page, &n, title, sizeof(error_page));
  3923. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3924. {
  3925. const char *p = detail;
  3926. while (*p && n + 1 < sizeof(error_page)) {
  3927. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3928. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3929. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3930. else page[n++] = *p;
  3931. p++;
  3932. }
  3933. }
  3934. page[n] = '\0';
  3935. s_append(page, &n, "</p><p>", sizeof(error_page));
  3936. s_append(page, &n, page_url, sizeof(error_page));
  3937. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3938. sizeof(error_page));
  3939. br_parse(&doc, page, n);
  3940. layout_valid = 0;
  3941. preload_active = 0;
  3942. preload_pending = 0;
  3943. preload_wait = 0;
  3944. fetch_workers_cancel_busy();
  3945. s_copy(page_title, title, sizeof(page_title));
  3946. page_loading = 0;
  3947. set_status(title, 1, 0);
  3948. ngui_invalidate(&ui);
  3949. }
  3950. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3951. unsigned int node)
  3952. {
  3953. if (image_count >= BR_MAX_IMAGES)
  3954. return -1;
  3955. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3956. return -1;
  3957. doc.nodes[node].img_index = 0;
  3958. image_count = 1;
  3959. return 0;
  3960. }
  3961. static int ancestor_is(unsigned int node, unsigned int tag)
  3962. {
  3963. unsigned int p = doc.nodes[node].parent;
  3964. while (p) {
  3965. if (doc.nodes[p].tag == tag)
  3966. return 1;
  3967. p = doc.nodes[p].parent;
  3968. }
  3969. return 0;
  3970. }
  3971. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3972. * parallel but parsed in document order, so the cascade is unchanged. */
  3973. static int load_stylesheets(void)
  3974. {
  3975. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3976. static unsigned char remote[BR_MAX_SHEETS];
  3977. struct fetch_worker *slot[BR_MAX_SHEETS];
  3978. unsigned int i, n = 0, next = 0, k;
  3979. char err[64];
  3980. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3981. struct br_node *nd = &doc.nodes[i];
  3982. const char *rel, *href;
  3983. char url[BR_URL_MAX];
  3984. int dup = 0;
  3985. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3986. continue;
  3987. rel = br_rel(&doc, i);
  3988. if (!contains_ci(rel, "stylesheet"))
  3989. continue;
  3990. href = br_href(&doc, i);
  3991. if (!href[0])
  3992. continue;
  3993. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3994. continue;
  3995. for (k = 0; k < n; k++)
  3996. if (s_eq(urls[k], url)) {
  3997. dup = 1;
  3998. break;
  3999. }
  4000. if (dup)
  4001. continue;
  4002. s_copy(urls[n], url, BR_URL_MAX);
  4003. remote[n] = url[0] != '/' && !css_cache_has(url);
  4004. n++;
  4005. }
  4006. for (i = 0; i < BR_MAX_SHEETS; i++)
  4007. slot[i] = 0;
  4008. /* Start as many remote sheets as there are free workers. */
  4009. for (; next < n; next++) {
  4010. struct fetch_worker *w;
  4011. if (!remote[next])
  4012. continue;
  4013. w = fetch_worker_alloc();
  4014. if (!w)
  4015. break;
  4016. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  4017. err, sizeof(err)) != 0) {
  4018. fetch_worker_release(w);
  4019. remote[next] = 0;
  4020. continue;
  4021. }
  4022. slot[next] = w;
  4023. }
  4024. for (i = 0; i < n; i++) {
  4025. unsigned char *data = 0;
  4026. unsigned int len = 0;
  4027. int rv;
  4028. if (!remote[i]) {
  4029. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  4030. if (rv == FETCH_ABORT) {
  4031. fetch_workers_stop_all();
  4032. return FETCH_ABORT;
  4033. }
  4034. if (rv != 0 || !len)
  4035. continue;
  4036. } else {
  4037. struct fetch_worker *w = slot[i];
  4038. int tr = 0;
  4039. if (!w) {
  4040. w = fetch_worker_alloc();
  4041. if (!w) {
  4042. rv = -1;
  4043. goto css_failed;
  4044. }
  4045. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  4046. 0, 0, 0, 0, err,
  4047. sizeof(err)) != 0) {
  4048. fetch_worker_release(w);
  4049. remote[i] = 0;
  4050. if (i == next)
  4051. next++;
  4052. continue;
  4053. }
  4054. slot[i] = w;
  4055. if (i == next)
  4056. next++;
  4057. }
  4058. rv = fetch_worker_wait(w, err, sizeof(err));
  4059. if (rv == FETCH_ABORT) {
  4060. fetch_workers_stop_all();
  4061. return FETCH_ABORT;
  4062. }
  4063. if (rv == 0)
  4064. rv = fetch_worker_read_body(w, image_io_buf,
  4065. BR_CSS_MAX,
  4066. image_io_buf + BR_CSS_MAX,
  4067. BR_CSS_COMP_MAX, &tr,
  4068. err, sizeof(err));
  4069. else
  4070. rv = -1;
  4071. fetch_worker_release(w);
  4072. slot[i] = 0;
  4073. /* Refill the worker window before parsing this sheet. */
  4074. for (; next < n; next++) {
  4075. struct fetch_worker *nw;
  4076. if (!remote[next])
  4077. continue;
  4078. nw = fetch_worker_alloc();
  4079. if (!nw)
  4080. break;
  4081. if (fetch_worker_submit(nw, urls[next],
  4082. BR_CSS_MAX, 0, 0, 0, 0,
  4083. err, sizeof(err)) != 0) {
  4084. fetch_worker_release(nw);
  4085. remote[next] = 0;
  4086. continue;
  4087. }
  4088. slot[next] = nw;
  4089. }
  4090. css_failed:
  4091. if (rv <= 0) {
  4092. /* One synchronous retry: a dropped sheet leaves the
  4093. * whole page unstyled (seen intermittently on
  4094. * arstechnica's CDN). */
  4095. u_puts("[css] retry ");
  4096. u_puts(urls[i]);
  4097. u_puts(": ");
  4098. u_puts(err[0] ? err : "no worker/empty body");
  4099. u_putc('\n');
  4100. err[0] = '\0';
  4101. rv = fetch_css(urls[i], &data, &len, err,
  4102. sizeof(err));
  4103. if (rv == FETCH_ABORT) {
  4104. fetch_workers_stop_all();
  4105. return FETCH_ABORT;
  4106. }
  4107. if (rv != 0 || !len) {
  4108. u_puts("[css] failed: ");
  4109. u_puts(err);
  4110. u_putc('\n');
  4111. continue;
  4112. }
  4113. } else {
  4114. len = (unsigned int)rv;
  4115. data = image_io_buf;
  4116. css_cache_put(urls[i], data, len);
  4117. }
  4118. }
  4119. if (len) {
  4120. br_set_font_base(urls[i]);
  4121. br_parse_css_text(&doc, (const char *)data, len);
  4122. }
  4123. }
  4124. br_set_font_base(page_url);
  4125. br_parse_inline_css(&doc);
  4126. load_font_faces();
  4127. br_reset_styles(&doc);
  4128. layout_valid = 0;
  4129. return 0;
  4130. }
  4131. static void preload_begin(void)
  4132. {
  4133. preload_active = 1;
  4134. preload_pending = 0;
  4135. preload_wait = 1;
  4136. preload_max_jobs = FETCH_WORKERS;
  4137. preload_node = 0;
  4138. preload_loaded = 0;
  4139. preload_scroll = 0;
  4140. img_stat_start = u_ticks_ms();
  4141. img_stat_wall = 0;
  4142. img_stat_net = img_stat_open = img_stat_first = 0;
  4143. img_stat_io = img_stat_dec = img_stat_scale = 0;
  4144. img_stat_paint = img_stat_reflow = 0;
  4145. img_stat_bytes = 0;
  4146. img_stat_n = 0;
  4147. img_stat_log_len = 0;
  4148. if (img_stat_log[0])
  4149. img_stat_log[0] = '\0';
  4150. img_repaint_ms = 0;
  4151. img_repaint_pending = 0;
  4152. }
  4153. /* Styles are computed top-down during layout, but images inside a hidden
  4154. * menu/carousel are never visited and keep img_top == 0. Without this check
  4155. * the preloader walks the DOM in node order and spends the whole image
  4156. * budget on logos and off-canvas thumbnails the reader cannot see. */
  4157. static struct br_style base_style(void);
  4158. static int node_hidden(unsigned int node)
  4159. {
  4160. unsigned int path[32], n = 0, p = node, i;
  4161. struct br_style st, parent;
  4162. while (p && n < sizeof(path) / sizeof(path[0])) {
  4163. path[n++] = p;
  4164. p = doc.nodes[p].parent;
  4165. }
  4166. /* Node 0 is the <html> element when the page starts with one: it
  4167. * is an ancestor too. Styles are cached per node, so the chain
  4168. * must start from the same base as style_for_node(); seeding it
  4169. * with a zeroed style left <body> cached with black text and no
  4170. * line-height once an image job ran (docs.cloudron.io). */
  4171. if (!p && n && n < sizeof(path) / sizeof(path[0]) &&
  4172. doc.nodes[0].type == BR_NODE_ELEM &&
  4173. doc.nodes[0].tag == BR_TAG_HTML &&
  4174. !(doc.nodes[path[n - 1]].flags & BR_NODE_DETACHED))
  4175. path[n++] = 0;
  4176. parent = base_style();
  4177. for (i = n; i > 0; i--) {
  4178. br_style_for(&doc, path[i - 1], &parent, &st);
  4179. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  4180. st.opacity_hidden)
  4181. return 1;
  4182. parent = st;
  4183. }
  4184. return 0;
  4185. }
  4186. static struct br_style base_style(void);
  4187. static int style_width_px(const struct br_style *st, int base);
  4188. static int style_height_px(const struct br_style *st, int base);
  4189. static void style_for_node(unsigned int node, struct br_style *out)
  4190. {
  4191. unsigned int p = doc.nodes[node].parent;
  4192. struct br_style parent;
  4193. /* Parent index 0 is ambiguous: it is the <html> element when the page
  4194. * starts with one (see root_style()), but also the parent field of a
  4195. * detached subtree root. */
  4196. if (p || (node != 0 && doc.nodes[0].type == BR_NODE_ELEM &&
  4197. doc.nodes[0].tag == BR_TAG_HTML &&
  4198. !(doc.nodes[node].flags & BR_NODE_DETACHED))) {
  4199. style_for_node(p, &parent);
  4200. br_style_for(&doc, node, &parent, out);
  4201. } else {
  4202. parent = base_style();
  4203. br_style_for(&doc, node, &parent, out);
  4204. }
  4205. }
  4206. /* ---- parallel image preloading ---- *
  4207. *
  4208. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  4209. * preload_step() only starts jobs and harvests completed ones; the browser
  4210. * main loop keeps drawing between calls, instead of blocking on one fetch.
  4211. */
  4212. static int preload_active_jobs(void)
  4213. {
  4214. int i, n = 0;
  4215. for (i = 0; i < FETCH_WORKERS; i++)
  4216. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  4217. n++;
  4218. return n;
  4219. }
  4220. static void preload_job_error(struct fetch_worker *w)
  4221. {
  4222. if (w->node < doc.nnode) {
  4223. if (w->bg)
  4224. doc.nodes[w->node].bg_img_index = -2;
  4225. else
  4226. doc.nodes[w->node].img_index = -2;
  4227. image_repaint();
  4228. }
  4229. }
  4230. /* Is the image's box anywhere near the visible page? A decode below the
  4231. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  4232. * so it does not need a repaint. top/h come from the last layout; treat an
  4233. * unknown box as visible to stay safe. */
  4234. static int image_preload_visible(unsigned int node, int bg)
  4235. {
  4236. int top, h, scroll;
  4237. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  4238. return 1;
  4239. if (bg) {
  4240. top = (int)block_top[node];
  4241. h = (int)block_h[node];
  4242. } else {
  4243. top = (int)img_top[node];
  4244. h = (int)img_h[node];
  4245. }
  4246. if (!top && !h)
  4247. return 1;
  4248. scroll = (int)page_scroll.offset;
  4249. if (top > scroll + page_rect.h + 160)
  4250. return 0;
  4251. if (top + h + 160 < scroll)
  4252. return 0;
  4253. return 1;
  4254. }
  4255. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  4256. * decode_image_data applies one scale to both axes so the aspect ratio is
  4257. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  4258. * from being decoded and box-filtered to the 1000 px layout cap first. */
  4259. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  4260. {
  4261. struct br_style st;
  4262. struct br_node *nd;
  4263. unsigned int p;
  4264. int cw, w = 0, h = 0;
  4265. *out_w = *out_h = 0;
  4266. if (node >= doc.nnode)
  4267. return;
  4268. nd = &doc.nodes[node];
  4269. style_for_node(node, &st);
  4270. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4271. p = doc.nodes[node].parent;
  4272. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4273. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4274. cw = layout_boxes[p].w;
  4275. if (st.width_kind)
  4276. w = style_width_px(&st, cw);
  4277. else if (nd->width_attr)
  4278. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4279. (int)nd->width_attr;
  4280. if (st.height_kind)
  4281. h = style_height_px(&st, cw);
  4282. else if (nd->height_attr)
  4283. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4284. (int)nd->height_attr;
  4285. if (st.max_width_kind) {
  4286. int mw = st.max_width_kind == 3 ?
  4287. cw * st.max_width_calc_pct / 100 +
  4288. st.max_width_calc_px :
  4289. st.max_width_kind == 2 ?
  4290. cw * (int)st.max_width / 100 :
  4291. (int)st.max_width;
  4292. if (mw > 0 && (w == 0 || w > mw))
  4293. w = mw;
  4294. }
  4295. if (st.max_height_kind) {
  4296. int mh = st.max_height_kind == 3 ?
  4297. cw * st.max_height_calc_pct / 100 +
  4298. st.max_height_calc_px :
  4299. st.max_height_kind == 2 ?
  4300. cw * (int)st.max_height / 100 :
  4301. (int)st.max_height;
  4302. if (mh > 0 && (h == 0 || h > mh))
  4303. h = mh;
  4304. }
  4305. if (w > BR_IMG_LAYOUT_W)
  4306. w = BR_IMG_LAYOUT_W;
  4307. if (h > 4096)
  4308. h = 4096;
  4309. if (w < 0)
  4310. w = 0;
  4311. if (h < 0)
  4312. h = 0;
  4313. *out_w = w;
  4314. *out_h = h;
  4315. }
  4316. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4317. {
  4318. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4319. * same source reuses it (heise repeats one comment icon 85 times).
  4320. * Backgrounds are scaled to their box and are not shared. */
  4321. images[image_count].url_hash =
  4322. !bg && url ? script_cache_hash(url) | 1u : 0;
  4323. if (bg)
  4324. doc.nodes[node].bg_img_index = (short)image_count;
  4325. else
  4326. doc.nodes[node].img_index = (short)image_count;
  4327. image_count++;
  4328. preload_loaded++;
  4329. /* A background bitmap never changes its box, so keep the (expensive)
  4330. * measured layout and only repaint the pixels. */
  4331. if (bg)
  4332. page_cache_valid = 0;
  4333. else
  4334. layout_valid = 0;
  4335. if (image_preload_visible(node, bg))
  4336. image_repaint();
  4337. }
  4338. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4339. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4340. * on the UI thread instead of a decode. */
  4341. static int preload_store_helper(unsigned int node, int bg,
  4342. unsigned char *px, unsigned int pxlen,
  4343. unsigned int dw, unsigned int dh,
  4344. int alpha, unsigned int nw, unsigned int nh,
  4345. const char *url)
  4346. {
  4347. struct br_image *bi;
  4348. unsigned int npx;
  4349. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4350. dw > 4096 || dh > 4096) {
  4351. free(px);
  4352. return -1;
  4353. }
  4354. npx = dw * dh;
  4355. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4356. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4357. free(px);
  4358. return -1;
  4359. }
  4360. bi = &images[image_count];
  4361. bi->img.format = 0;
  4362. bi->img.w = dw;
  4363. bi->img.h = dh;
  4364. bi->img.px = (unsigned short *)px;
  4365. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4366. bi->img.flags = 0;
  4367. bi->native_w = nw ? (int)nw : (int)dw;
  4368. bi->native_h = nh ? (int)nh : (int)dh;
  4369. bi->state = 1;
  4370. image_pixels += npx;
  4371. preload_accept_image(node, bg, url);
  4372. return 0;
  4373. }
  4374. static void preload_decode(unsigned int node, int bg,
  4375. const unsigned char *data, unsigned int len,
  4376. const char *url)
  4377. {
  4378. int fit_w = 0, fit_h = 0;
  4379. if (image_count >= BR_MAX_IMAGES) {
  4380. if (bg)
  4381. doc.nodes[node].bg_img_index = -2;
  4382. else
  4383. doc.nodes[node].img_index = -2;
  4384. return;
  4385. }
  4386. if (!bg)
  4387. image_fit_size(node, &fit_w, &fit_h);
  4388. if (decode_image_data(data, len, &images[image_count],
  4389. bg && node < BR_MAX_NODES &&
  4390. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4391. bg && node < BR_MAX_NODES &&
  4392. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4393. fit_w, fit_h) == 0) {
  4394. preload_accept_image(node, bg, url);
  4395. } else {
  4396. if (bg)
  4397. doc.nodes[node].bg_img_index = -2;
  4398. else
  4399. doc.nodes[node].img_index = -2;
  4400. layout_valid = 0;
  4401. }
  4402. if (image_preload_visible(node, bg))
  4403. image_repaint();
  4404. }
  4405. /* A local file image bypasses the helpers: count its decode so a page opened
  4406. * from /share or /data still produces the same timing breakdown. */
  4407. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4408. {
  4409. img_stat_n++;
  4410. img_stat_bytes += bytes;
  4411. img_stat_io += io_ms;
  4412. if (image_count > before) {
  4413. struct br_image *bi = &images[image_count - 1];
  4414. img_stat_dec += img_last_dec_ms;
  4415. img_stat_scale += img_last_scale_ms;
  4416. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4417. unsigned int n = img_stat_log_len;
  4418. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4419. s_append_dec(img_stat_log, &n, bytes,
  4420. sizeof(img_stat_log));
  4421. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4422. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4423. sizeof(img_stat_log));
  4424. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4425. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4426. sizeof(img_stat_log));
  4427. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4428. s_append_dec(img_stat_log, &n,
  4429. (unsigned int)bi->native_w,
  4430. sizeof(img_stat_log));
  4431. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4432. s_append_dec(img_stat_log, &n,
  4433. (unsigned int)bi->native_h,
  4434. sizeof(img_stat_log));
  4435. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4436. s_append_dec(img_stat_log, &n, bi->img.w,
  4437. sizeof(img_stat_log));
  4438. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4439. s_append_dec(img_stat_log, &n, bi->img.h,
  4440. sizeof(img_stat_log));
  4441. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4442. s_append_dec(img_stat_log, &n,
  4443. bi->img.alpha ? 1u : 0u,
  4444. sizeof(img_stat_log));
  4445. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4446. img_stat_log_len = n;
  4447. }
  4448. }
  4449. }
  4450. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4451. static int preload_finish_worker(struct fetch_worker *w)
  4452. {
  4453. char err[64];
  4454. int rv, tr = 0;
  4455. unsigned int t0, io_ms;
  4456. int before;
  4457. int used_px = 0;
  4458. rv = fetch_worker_poll(w, err, sizeof(err));
  4459. if (rv < 0) {
  4460. /* A helper from an older pack does not understand the image
  4461. * decode request; retry once without it and decode in-process. */
  4462. if (w->image_job && w->dec_w && !w->dec_retried &&
  4463. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4464. 0, 0, 0, 0, w->node, w->bg,
  4465. 0, 0, err, sizeof(err)) == 0) {
  4466. w->image_job = 1;
  4467. w->dec_retried = 1;
  4468. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4469. return 0;
  4470. }
  4471. preload_job_error(w);
  4472. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4473. unsigned int n = img_stat_log_len;
  4474. char u[48];
  4475. s_copy(u, w->url, sizeof(u));
  4476. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4477. s_append(img_stat_log, &n, " error\n",
  4478. sizeof(img_stat_log));
  4479. img_stat_log_len = n;
  4480. }
  4481. img_stat_n++;
  4482. fetch_worker_release(w);
  4483. return 1;
  4484. }
  4485. if (rv == 0)
  4486. return 0;
  4487. t0 = u_ticks_ms();
  4488. rv = -1;
  4489. before = image_count;
  4490. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4491. w->m.px_len <= 8u * 1024u * 1024u) {
  4492. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4493. int pr = -1;
  4494. if (px)
  4495. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4496. (int)w->m.px_len);
  4497. if (pr == (int)w->m.px_len) {
  4498. if (preload_store_helper(w->node, w->bg, px,
  4499. w->m.px_len, w->m.dw,
  4500. w->m.dh, (int)w->m.alpha,
  4501. w->m.nw, w->m.nh,
  4502. w->url) == 0) {
  4503. rv = (int)w->m.len;
  4504. img_last_dec_ms = w->m.dec_ms;
  4505. img_last_scale_ms = 0;
  4506. used_px = 1;
  4507. } else {
  4508. px = 0; /* the helper freed it */
  4509. }
  4510. }
  4511. if (px && !(pr == (int)w->m.px_len))
  4512. free(px);
  4513. }
  4514. io_ms = u_ticks_ms() - t0;
  4515. if (rv < 0) {
  4516. t0 = u_ticks_ms();
  4517. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4518. image_comp_buf, BR_IMG_FILE_MAX,
  4519. &tr, err, sizeof(err));
  4520. io_ms += u_ticks_ms() - t0;
  4521. before = image_count;
  4522. if (rv >= 0)
  4523. preload_decode(w->node, w->bg, image_file_buf,
  4524. (unsigned int)rv, w->url);
  4525. else
  4526. preload_job_error(w);
  4527. }
  4528. img_stat_n++;
  4529. img_stat_net += w->m.total_ms;
  4530. img_stat_open += w->m.open_ms;
  4531. img_stat_first += w->m.first_ms;
  4532. img_stat_io += io_ms;
  4533. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4534. img_stat_dec += w->m.dec_ms;
  4535. if (rv >= 0 && !used_px) {
  4536. img_stat_dec += img_last_dec_ms;
  4537. img_stat_scale += img_last_scale_ms;
  4538. }
  4539. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4540. unsigned int n = img_stat_log_len;
  4541. char u[48];
  4542. s_copy(u, w->url, sizeof(u));
  4543. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4544. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4545. s_append_dec(img_stat_log, &n,
  4546. rv > 0 ? (unsigned int)rv : 0,
  4547. sizeof(img_stat_log));
  4548. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4549. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4550. sizeof(img_stat_log));
  4551. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4552. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4553. sizeof(img_stat_log));
  4554. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4555. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4556. sizeof(img_stat_log));
  4557. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4558. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4559. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4560. s_append_dec(img_stat_log, &n,
  4561. rv >= 0 ? img_last_dec_ms : 0,
  4562. sizeof(img_stat_log));
  4563. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4564. s_append_dec(img_stat_log, &n,
  4565. rv >= 0 ? img_last_scale_ms : 0,
  4566. sizeof(img_stat_log));
  4567. if (image_count > before) {
  4568. struct br_image *bi = &images[image_count - 1];
  4569. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4570. s_append_dec(img_stat_log, &n,
  4571. (unsigned int)bi->native_w,
  4572. sizeof(img_stat_log));
  4573. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4574. s_append_dec(img_stat_log, &n,
  4575. (unsigned int)bi->native_h,
  4576. sizeof(img_stat_log));
  4577. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4578. s_append_dec(img_stat_log, &n, bi->img.w,
  4579. sizeof(img_stat_log));
  4580. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4581. s_append_dec(img_stat_log, &n, bi->img.h,
  4582. sizeof(img_stat_log));
  4583. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4584. s_append_dec(img_stat_log, &n,
  4585. bi->img.alpha ? 1u : 0u,
  4586. sizeof(img_stat_log));
  4587. }
  4588. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4589. img_stat_log_len = n;
  4590. }
  4591. fetch_worker_release(w);
  4592. return 1;
  4593. }
  4594. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4595. * the number of jobs started. */
  4596. static int preload_fill_jobs(void)
  4597. {
  4598. int started = 0;
  4599. char err[64];
  4600. while (preload_active && preload_node < doc.nnode) {
  4601. unsigned int i = preload_node;
  4602. struct br_node *nd = &doc.nodes[i];
  4603. const char *src;
  4604. char url[BR_URL_MAX];
  4605. struct fetch_worker *w;
  4606. if (preload_active_jobs() >= preload_max_jobs)
  4607. break;
  4608. if (nd->type != BR_NODE_ELEM) {
  4609. preload_node++;
  4610. continue;
  4611. }
  4612. if (nd->tag != BR_TAG_IMG) {
  4613. if (nd->bg_img_index == -1) {
  4614. struct br_style bs;
  4615. style_for_node(i, &bs);
  4616. if (bs.display != BR_DISPLAY_NONE &&
  4617. !bs.vis_hidden && bs.bg_image) {
  4618. const char *bsrc =
  4619. br_bg_image_url(bs.bg_image - 1);
  4620. /* Lazy like <img>: a background box
  4621. * below the viewport (or not laid
  4622. * out yet) waits for the next scan. */
  4623. if (bsrc[0] &&
  4624. (!layout_boxes[i].valid ||
  4625. block_top[i] >
  4626. (unsigned int)(page_scroll.offset +
  4627. page_rect.h + 160))) {
  4628. preload_pending = 1;
  4629. preload_node++;
  4630. continue;
  4631. }
  4632. if (bsrc[0] &&
  4633. !starts_with(bsrc, "data:") &&
  4634. resolve_link(page_url, bsrc, url,
  4635. sizeof(url)) == 0) {
  4636. if (image_count +
  4637. preload_active_jobs() >=
  4638. BR_MAX_IMAGES) {
  4639. preload_node = doc.nnode;
  4640. break;
  4641. }
  4642. if (url[0] == '/') {
  4643. unsigned char *data = 0;
  4644. unsigned int len = 0;
  4645. unsigned int t0;
  4646. int before;
  4647. preload_node = i + 1;
  4648. before = image_count;
  4649. t0 = u_ticks_ms();
  4650. if (fetch_image(url,
  4651. BR_IMG_FILE_MAX,
  4652. &data, &len,
  4653. err,
  4654. sizeof(err)) == 0) {
  4655. preload_decode(i, 1, data, len, 0);
  4656. img_stat_local(before, len,
  4657. u_ticks_ms() - t0);
  4658. } else {
  4659. nd->bg_img_index = -2;
  4660. }
  4661. continue;
  4662. }
  4663. w = fetch_worker_alloc();
  4664. if (!w)
  4665. return started;
  4666. preload_node = i + 1;
  4667. if (fetch_worker_submit(w, url,
  4668. BR_IMG_FILE_MAX,
  4669. 0, 0, i, 1,
  4670. err,
  4671. sizeof(err)) != 0) {
  4672. nd->bg_img_index = -2;
  4673. fetch_worker_release(w);
  4674. continue;
  4675. }
  4676. w->image_job = 1;
  4677. w->deadline = u_ticks_ms() +
  4678. BR_IMG_JOB_TIMEOUT_MS;
  4679. /* in flight: rescans skip it */
  4680. nd->bg_img_index = -3;
  4681. started++;
  4682. continue;
  4683. }
  4684. }
  4685. nd->bg_img_index = -2;
  4686. }
  4687. preload_node++;
  4688. continue;
  4689. }
  4690. if (nd->img_index != -1) {
  4691. preload_node++;
  4692. continue;
  4693. }
  4694. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4695. preload_node++;
  4696. continue;
  4697. }
  4698. src = br_src(&doc, i);
  4699. if (!src[0] || starts_with(src, "data:")) {
  4700. preload_node++;
  4701. continue;
  4702. }
  4703. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4704. preload_node++;
  4705. continue;
  4706. }
  4707. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4708. preload_node = doc.nnode;
  4709. break;
  4710. }
  4711. /* Do not stop at the first below-fold image: DOM order is
  4712. * not visual order, and a footer/ad image early in the DOM
  4713. * used to hide every later article image from the loader. */
  4714. if (img_top[i] >
  4715. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4716. preload_pending = 1;
  4717. preload_node++;
  4718. continue;
  4719. }
  4720. {
  4721. unsigned int uh = script_cache_hash(url) | 1u;
  4722. int k;
  4723. for (k = 0; k < image_count; k++)
  4724. if (images[k].state == 1 &&
  4725. images[k].url_hash == uh)
  4726. break;
  4727. if (k < image_count) {
  4728. nd->img_index = (short)k;
  4729. layout_valid = 0;
  4730. preload_node = i + 1;
  4731. image_repaint();
  4732. continue;
  4733. }
  4734. }
  4735. if (url[0] == '/') {
  4736. unsigned char *data = 0;
  4737. unsigned int len = 0;
  4738. unsigned int t0;
  4739. int before;
  4740. preload_node = i + 1;
  4741. before = image_count;
  4742. t0 = u_ticks_ms();
  4743. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4744. err, sizeof(err)) == 0) {
  4745. preload_decode(i, 0, data, len, url);
  4746. img_stat_local(before, len, u_ticks_ms() - t0);
  4747. } else {
  4748. nd->img_index = -2;
  4749. }
  4750. continue;
  4751. }
  4752. w = fetch_worker_alloc();
  4753. if (!w)
  4754. return started;
  4755. preload_node = i + 1;
  4756. {
  4757. char msg[64];
  4758. unsigned int n = 0;
  4759. s_append(msg, &n, "Loading images ", sizeof(msg));
  4760. s_append_dec(msg, &n,
  4761. (unsigned int)preload_loaded + 1,
  4762. sizeof(msg));
  4763. s_append(msg, &n, "...", sizeof(msg));
  4764. set_status_quiet(msg);
  4765. image_repaint();
  4766. }
  4767. {
  4768. int fit_w = 0, fit_h = 0;
  4769. image_fit_size(i, &fit_w, &fit_h);
  4770. if (!fit_w)
  4771. fit_w = BR_IMG_LAYOUT_W;
  4772. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4773. i, 0,
  4774. (unsigned int)fit_w,
  4775. (unsigned int)fit_h,
  4776. err, sizeof(err)) != 0) {
  4777. nd->img_index = -2;
  4778. fetch_worker_release(w);
  4779. continue;
  4780. }
  4781. }
  4782. w->image_job = 1;
  4783. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4784. nd->img_index = -3; /* in flight: rescans skip it */
  4785. started++;
  4786. }
  4787. return started;
  4788. }
  4789. /* Report where the image batch spent its time: status bar for the headline,
  4790. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4791. static void img_stats_report(void)
  4792. {
  4793. char msg[80];
  4794. static char out[BR_IMG_STAT_LOG + 512];
  4795. unsigned int n = 0, o = 0;
  4796. if (!img_stat_n)
  4797. return;
  4798. img_stat_wall = img_stat_start ?
  4799. u_ticks_ms() - img_stat_start : 1;
  4800. if (!img_stat_wall)
  4801. img_stat_wall = 1;
  4802. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4803. s_append(msg, &n, "img ", sizeof(msg));
  4804. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4805. s_append(msg, &n, " ", sizeof(msg));
  4806. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4807. s_append(msg, &n, "ms net ", sizeof(msg));
  4808. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4809. s_append(msg, &n, " dec ", sizeof(msg));
  4810. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4811. s_append(msg, &n, " sc ", sizeof(msg));
  4812. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4813. s_append(msg, &n, " paint ", sizeof(msg));
  4814. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4815. /* Keep the page's phase breakdown and append the image summary when
  4816. * it fits; never hide a JS error or a truncation notice. */
  4817. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4818. unsigned int plen = s_len(post_status_text);
  4819. if (!plen) {
  4820. s_copy(post_status_text, msg, sizeof(post_status_text));
  4821. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4822. unsigned int pn = plen;
  4823. s_append(post_status_text, &pn, " | ",
  4824. sizeof(post_status_text));
  4825. s_append(post_status_text, &pn, msg,
  4826. sizeof(post_status_text));
  4827. } else {
  4828. s_copy(post_status_text, msg, sizeof(post_status_text));
  4829. }
  4830. post_status_ttl = 12000;
  4831. }
  4832. s_append(out, &o, "browser image stats\n", sizeof(out));
  4833. s_append(out, &o, "n=", sizeof(out));
  4834. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  4835. s_append(out, &o, " wall=", sizeof(out));
  4836. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  4837. s_append(out, &o, " net=", sizeof(out));
  4838. s_append_dec(out, &o, img_stat_net, sizeof(out));
  4839. s_append(out, &o, " open=", sizeof(out));
  4840. s_append_dec(out, &o, img_stat_open, sizeof(out));
  4841. s_append(out, &o, " first=", sizeof(out));
  4842. s_append_dec(out, &o, img_stat_first, sizeof(out));
  4843. s_append(out, &o, " io=", sizeof(out));
  4844. s_append_dec(out, &o, img_stat_io, sizeof(out));
  4845. s_append(out, &o, " dec=", sizeof(out));
  4846. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  4847. s_append(out, &o, " scale=", sizeof(out));
  4848. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  4849. s_append(out, &o, " paint=", sizeof(out));
  4850. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  4851. s_append(out, &o, " reflow=", sizeof(out));
  4852. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  4853. s_append(out, &o, " bytes=", sizeof(out));
  4854. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  4855. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  4856. sizeof(out));
  4857. s_append(out, &o, img_stat_log, sizeof(out));
  4858. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  4859. (int)s_len(out));
  4860. }
  4861. static void preload_step(void)
  4862. {
  4863. int i;
  4864. unsigned int t0;
  4865. if (!preload_active)
  4866. return;
  4867. if (cancel_fetch || pending_action) {
  4868. preload_active = 0;
  4869. preload_pending = 0;
  4870. fetch_workers_cancel_busy();
  4871. return;
  4872. }
  4873. preload_fill_jobs();
  4874. /* Decode completed images in a short batch instead of one per pass.
  4875. * A pass used to decode one image and then sleep 10 ms, so a page of
  4876. * small icons trickled in at the decode rate. The budget keeps a
  4877. * single huge JPEG from monopolising the UI while small images
  4878. * finish together. */
  4879. t0 = u_ticks_ms();
  4880. for (i = 0; i < FETCH_WORKERS; i++) {
  4881. if (!fetch_workers[i].busy)
  4882. continue;
  4883. if (preload_finish_worker(&fetch_workers[i]) &&
  4884. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  4885. break;
  4886. }
  4887. if (preload_active && preload_node >= doc.nnode &&
  4888. preload_active_jobs() == 0) {
  4889. preload_active = 0;
  4890. if (preload_pending)
  4891. preload_scroll = page_scroll.offset;
  4892. else
  4893. preload_pending = 0;
  4894. /* Keep the now idle helpers and their connections; a later
  4895. * navigation reuses them. They exit after ten idle seconds,
  4896. * and losing window focus stops them at once. */
  4897. if (img_repaint_pending) {
  4898. img_repaint_pending = 0;
  4899. ngui_invalidate(&ui);
  4900. }
  4901. img_stats_report();
  4902. set_status(post_status_text, post_status_error, post_status_ttl);
  4903. ngui_invalidate(&ui);
  4904. }
  4905. }
  4906. /* Set by navigate() when it turned a typed bare host into https://; the next
  4907. * load_page() consumes it and may retry over http. */
  4908. static int nav_https_upgraded;
  4909. /* Errors that mean "https is not served here" rather than "the site is
  4910. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  4911. static int https_fallback_error(int e)
  4912. {
  4913. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  4914. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  4915. e == UHTTP_ERR_RESET;
  4916. }
  4917. static void history_push(const char *url)
  4918. {
  4919. if (!url || !url[0])
  4920. return;
  4921. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  4922. s_eq(history[hist_pos], url))
  4923. return;
  4924. if (hist_len > 0 && hist_pos + 1 < hist_len)
  4925. hist_len = hist_pos + 1;
  4926. if (hist_len < BR_HISTORY) {
  4927. s_copy(history[hist_len], url, BR_URL_MAX);
  4928. hist_pos = hist_len;
  4929. hist_len++;
  4930. } else {
  4931. int i;
  4932. for (i = 1; i < BR_HISTORY; i++)
  4933. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4934. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4935. hist_pos = BR_HISTORY - 1;
  4936. }
  4937. }
  4938. static void load_page(const char *url, int local, int push)
  4939. {
  4940. unsigned char *body = 0;
  4941. unsigned int len = 0;
  4942. int truncated = 0;
  4943. struct img_info image_info;
  4944. char ctype[64];
  4945. char final[BR_URL_MAX];
  4946. char err[80];
  4947. const char *detail = 0;
  4948. const char *post = pending_post_is ? pending_post : 0;
  4949. unsigned int post_len = pending_post_len;
  4950. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4951. /* Phase timings for the status line: where a slow load spends it. */
  4952. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4953. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4954. int upgraded = nav_https_upgraded;
  4955. int retried = 0;
  4956. int rv;
  4957. nav_https_upgraded = 0;
  4958. final[0] = '\0';
  4959. pending_post_len = 0;
  4960. pending_post_is = 0;
  4961. cancel_fetch = 0;
  4962. preload_active = 0;
  4963. preload_pending = 0;
  4964. fetch_workers_prepare_nav(url);
  4965. js_browser_stop();
  4966. js_last_status[0] = '\0';
  4967. js_last_error = 0;
  4968. heap_clear();
  4969. image_reset();
  4970. form_reset_state();
  4971. layout_valid = 0;
  4972. page_scroll.offset = 0;
  4973. page_scroll.dragging = 0;
  4974. page_title[0] = '\0';
  4975. page_loading = 1;
  4976. page_is_local = local;
  4977. s_copy(page_url, url, sizeof(page_url));
  4978. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4979. url_in.len = s_len(url_in.text);
  4980. url_in.cursor = url_in.len;
  4981. url_in.scroll = 0;
  4982. ngui_set_focus(&ui, 0);
  4983. if (final[0])
  4984. final[0] = '\0';
  4985. if (push)
  4986. history_push(url);
  4987. set_status("Loading...", 0, 0);
  4988. ngui_invalidate(&ui);
  4989. /* heap_clear() detaches the fonts, so attach them again before the
  4990. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4991. if (heap_start() != 0) {
  4992. show_error("Out of memory", "Cannot allocate the page buffer");
  4993. return;
  4994. }
  4995. br_parse_plain(&doc, "", 0); /* blank while loading */
  4996. ngui_font_attach(&ui);
  4997. redraw_now();
  4998. browser_rules_alloc();
  4999. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5000. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  5001. &truncated, post, post_len);
  5002. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  5003. fetch_last_error == UHTTP_ERR_DNS) {
  5004. /* A busy previous page can leave the receiver ring full just
  5005. * long enough to lose a DNS reply. Tear the old helpers down
  5006. * and try once more before giving up. */
  5007. retried = 1;
  5008. fetch_workers_stop_all();
  5009. u_sleep_ms(500);
  5010. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  5011. sizeof(ctype), final, sizeof(final), err,
  5012. sizeof(err), &truncated, post, post_len);
  5013. }
  5014. if (rv == FETCH_ABORT)
  5015. return;
  5016. t_fetch = u_ticks_ms() - t_start;
  5017. /* Capture the page timing before CSS/script/image fetches overwrite the
  5018. * shared fetch_meta block. */
  5019. if (rv == 0 && !local) {
  5020. page_open_ms = fetch_meta.open_ms;
  5021. page_first_ms = fetch_meta.first_ms;
  5022. page_total_ms = fetch_meta.total_ms;
  5023. }
  5024. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  5025. https_fallback_error(fetch_last_error)) {
  5026. char http_url[BR_URL_MAX];
  5027. unsigned int n = 0;
  5028. s_append(http_url, &n, "http://", sizeof(http_url));
  5029. s_append(http_url, &n, url + 8, sizeof(http_url));
  5030. /* Replace the https entry instead of adding a second one. */
  5031. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  5032. s_eq(history[hist_pos], url))
  5033. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  5034. load_page(http_url, 0, 0);
  5035. return;
  5036. }
  5037. if (rv != 0) {
  5038. detail = err;
  5039. show_error("Cannot load this page", detail);
  5040. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5041. url_in.len = s_len(url_in.text);
  5042. url_in.cursor = url_in.len;
  5043. url_in.scroll = 0;
  5044. return;
  5045. }
  5046. if (!local)
  5047. origin_cache_learn(url, final[0] ? final : url);
  5048. page_is_local = local;
  5049. if (final[0]) {
  5050. s_copy(page_url, final, sizeof(page_url));
  5051. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5052. url_in.len = s_len(url_in.text);
  5053. url_in.cursor = url_in.len;
  5054. url_in.scroll = 0;
  5055. }
  5056. if (contains_ci(ctype, "text/plain")) {
  5057. br_parse_plain(&doc, (const char *)body, len);
  5058. } else if (contains_ci(ctype, "image/") ||
  5059. (!contains_ci(ctype, "text/html") &&
  5060. img_sniff(body, len, &image_info) == 0)) {
  5061. unsigned int node = br_parse_image_doc(&doc, page_url);
  5062. if (node)
  5063. decode_direct_image(body, len, node);
  5064. s_copy(page_title, "Image", sizeof(page_title));
  5065. } else {
  5066. br_set_viewport(ui.w);
  5067. t_mark = u_ticks_ms();
  5068. br_parse(&doc, (const char *)body, len);
  5069. t_parse = u_ticks_ms() - t_mark;
  5070. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  5071. sizeof(page_title));
  5072. t_mark = u_ticks_ms();
  5073. if (load_stylesheets() == FETCH_ABORT)
  5074. return;
  5075. t_css = u_ticks_ms() - t_mark;
  5076. if (pending_action)
  5077. return;
  5078. }
  5079. preload_begin();
  5080. page_loading = 0;
  5081. hist_visit(page_url, page_title);
  5082. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5083. url_in.len = s_len(url_in.text);
  5084. url_in.cursor = url_in.len;
  5085. url_in.scroll = 0;
  5086. ngui_set_focus(&ui, 0);
  5087. /* Paint the parsed page before fetching/running scripts. A slow
  5088. * remote <script src> then does not hide the page behind the loading
  5089. * screen; the fetch helper pumps this UI while it waits. */
  5090. set_status("Loading scripts...", 0, 0);
  5091. t_mark = u_ticks_ms();
  5092. redraw_now();
  5093. t_paint = u_ticks_ms() - t_mark;
  5094. /* Start one image download before the scripts. The other workers
  5095. * fetch the external script bodies in parallel, and the remaining
  5096. * images start as soon as the script phase ends. */
  5097. preload_max_jobs = 1;
  5098. preload_fill_jobs();
  5099. preload_wait = 0;
  5100. t_mark = u_ticks_ms();
  5101. run_page_scripts();
  5102. t_js = u_ticks_ms() - t_mark;
  5103. preload_max_jobs = FETCH_WORKERS;
  5104. if (pending_action)
  5105. return;
  5106. post_status_text[0] = '\0';
  5107. post_status_error = 0;
  5108. post_status_ttl = 0;
  5109. if (js_last_status[0]) {
  5110. s_copy(post_status_text, js_last_status,
  5111. sizeof(post_status_text));
  5112. post_status_error = js_last_error;
  5113. post_status_ttl = 8000;
  5114. } else if (truncated) {
  5115. s_copy(post_status_text, "Page truncated at the buffer limit",
  5116. sizeof(post_status_text));
  5117. post_status_ttl = 6000;
  5118. } else if (doc.truncated) {
  5119. s_copy(post_status_text, "Page truncated by the parser",
  5120. sizeof(post_status_text));
  5121. post_status_ttl = 6000;
  5122. } else if (page_total_ms) {
  5123. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  5124. * paint 220, js 1750" -- the phases of this load. */
  5125. unsigned int n = 0;
  5126. static const char *const names[] = {
  5127. ", parse ", ", css ", ", paint ", ", js "
  5128. };
  5129. unsigned int vals[4];
  5130. int k;
  5131. vals[0] = t_parse;
  5132. vals[1] = t_css;
  5133. vals[2] = t_paint;
  5134. vals[3] = t_js;
  5135. (void)page_first_ms;
  5136. if (starts_with(page_url, "https://"))
  5137. s_append(post_status_text, &n,
  5138. "HTTPS (not verified), ",
  5139. sizeof(post_status_text));
  5140. s_append(post_status_text, &n, "Loaded in ",
  5141. sizeof(post_status_text));
  5142. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  5143. sizeof(post_status_text));
  5144. s_append(post_status_text, &n, " ms: page ",
  5145. sizeof(post_status_text));
  5146. s_append_dec(post_status_text, &n, t_fetch,
  5147. sizeof(post_status_text));
  5148. s_append(post_status_text, &n, " (headers ",
  5149. sizeof(post_status_text));
  5150. s_append_dec(post_status_text, &n, page_open_ms,
  5151. sizeof(post_status_text));
  5152. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  5153. for (k = 0; k < 4; k++) {
  5154. s_append(post_status_text, &n, names[k],
  5155. sizeof(post_status_text));
  5156. s_append_dec(post_status_text, &n, vals[k],
  5157. sizeof(post_status_text));
  5158. }
  5159. post_status_ttl = 12000;
  5160. } else if (starts_with(page_url, "https://")) {
  5161. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  5162. sizeof(post_status_text));
  5163. post_status_ttl = 6000;
  5164. }
  5165. set_status(post_status_text, post_status_error, post_status_ttl);
  5166. ngui_invalidate(&ui);
  5167. }
  5168. static void load_home(int push)
  5169. {
  5170. pending_post_len = 0;
  5171. pending_post_is = 0;
  5172. cancel_fetch = 0;
  5173. preload_active = 0;
  5174. preload_pending = 0;
  5175. js_browser_stop();
  5176. js_last_status[0] = '\0';
  5177. js_last_error = 0;
  5178. heap_clear();
  5179. image_reset();
  5180. form_reset_state();
  5181. layout_valid = 0;
  5182. page_scroll.offset = 0;
  5183. page_scroll.dragging = 0;
  5184. page_loading = 1;
  5185. page_is_local = 0;
  5186. s_copy(page_url, "about:home", sizeof(page_url));
  5187. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5188. url_in.len = s_len(url_in.text);
  5189. url_in.cursor = url_in.len;
  5190. url_in.scroll = 0;
  5191. ngui_set_focus(&ui, 0);
  5192. if (push)
  5193. history_push(page_url);
  5194. ngui_invalidate(&ui);
  5195. /* See load_page(): reattach the fonts before the first redraw. */
  5196. if (heap_start() != 0) {
  5197. show_error("Out of memory", "Cannot allocate the browser heap");
  5198. return;
  5199. }
  5200. br_parse_plain(&doc, "", 0);
  5201. ngui_font_attach(&ui);
  5202. redraw_now();
  5203. browser_rules_alloc();
  5204. {
  5205. static const char home[] =
  5206. "<html><head><title>NebOS Browser</title><style>"
  5207. "body { margin: 10px; color: #e4e6f0; }"
  5208. "h1 { color: #7fb0ff; }"
  5209. ".box { background-color: #262b3a; margin: 12px; "
  5210. "padding: 10px; }"
  5211. "a { color: #7fb0ff; }"
  5212. "pre { background-color: #32384a; }"
  5213. "</style></head><body>"
  5214. "<h1>NebOS Browser</h1>"
  5215. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  5216. "shared HTTP client and the image library.</p>"
  5217. "<div class=\"box\"><b>Try:</b>"
  5218. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  5219. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  5220. "<li><a href=\"/floppy1/JS.HTM\">/"
  5221. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  5222. "<li><a href=\"http://10.0.2.2:8000/\">"
  5223. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  5224. "<li><a href=\"https://example.com/\">"
  5225. "https://example.com/</a> (TLS, not verified)</li>"
  5226. "</ul></div>"
  5227. "<p>Type a URL in the bar above. Esc closes the "
  5228. "window, Ctrl+L focuses the address bar.</p>"
  5229. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  5230. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  5231. "</body></html>";
  5232. br_set_viewport(ui.w);
  5233. br_parse(&doc, home, sizeof(home) - 1);
  5234. br_parse_inline_css(&doc);
  5235. br_reset_styles(&doc);
  5236. s_copy(page_title, doc.title, sizeof(page_title));
  5237. }
  5238. post_status_text[0] = '\0';
  5239. post_status_error = 0;
  5240. post_status_ttl = 0;
  5241. page_loading = 0;
  5242. set_status("", 0, 0);
  5243. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  5244. url_in.len = s_len(url_in.text);
  5245. url_in.cursor = url_in.len;
  5246. url_in.scroll = 0;
  5247. ngui_set_focus(&ui, 0);
  5248. ngui_invalidate(&ui);
  5249. }
  5250. /* Extensions the browser opens from the local filesystem. A dotted input
  5251. * with one of these still resolves relative to the cwd. */
  5252. static int local_file_ext(const char *s)
  5253. {
  5254. static const char *const exts[] = {
  5255. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  5256. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  5257. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  5258. "cfg", "conf", 0
  5259. };
  5260. unsigned int i = 0, start = 0, len = 0, e;
  5261. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5262. s[i] != '#') {
  5263. if (s[i] == '.') {
  5264. start = i + 1;
  5265. len = 0;
  5266. } else if (start) {
  5267. len++;
  5268. }
  5269. i++;
  5270. }
  5271. if (!len)
  5272. return 0;
  5273. for (e = 0; exts[e]; e++) {
  5274. const char *x = exts[e];
  5275. unsigned int xn = s_len(x), k;
  5276. if (xn != len)
  5277. continue;
  5278. for (k = 0; k < len; k++) {
  5279. char a = s[start + k];
  5280. if (a >= 'A' && a <= 'Z')
  5281. a = (char)(a - 'A' + 'a');
  5282. if (a != x[k])
  5283. break;
  5284. }
  5285. if (k == len)
  5286. return 1;
  5287. }
  5288. return 0;
  5289. }
  5290. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5291. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5292. * Enter to the first network request. */
  5293. static int looks_like_host(const char *s)
  5294. {
  5295. unsigned int i = 0;
  5296. int dot = 0;
  5297. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5298. s[i] != ':') {
  5299. char c = s[i];
  5300. if (c == '.') {
  5301. dot = 1;
  5302. } else if (!((c >= 'a' && c <= 'z') ||
  5303. (c >= 'A' && c <= 'Z') ||
  5304. (c >= '0' && c <= '9') ||
  5305. c == '-' || c == '_')) {
  5306. return 0;
  5307. }
  5308. i++;
  5309. }
  5310. return dot && i > 0 && !local_file_ext(s);
  5311. }
  5312. static void load_remote(const char *url, int push)
  5313. {
  5314. char canon[BR_URL_MAX];
  5315. s_copy(canon, url, sizeof(canon));
  5316. origin_cache_apply(canon, sizeof(canon));
  5317. load_page(canon, 0, push);
  5318. }
  5319. static void navigate(const char *input, int push)
  5320. {
  5321. char target[BR_URL_MAX];
  5322. char *t;
  5323. if (!input)
  5324. return;
  5325. s_copy(target, input, sizeof(target));
  5326. t = trim(target);
  5327. if (!t[0])
  5328. return;
  5329. if (s_eq(t, "about:home")) {
  5330. load_home(push);
  5331. return;
  5332. }
  5333. if (starts_with(t, "file://")) {
  5334. make_abs_local(t + 7, target, sizeof(target));
  5335. load_page(target, 1, push);
  5336. return;
  5337. }
  5338. if (is_http(t)) {
  5339. load_remote(t, push);
  5340. return;
  5341. }
  5342. if (t[0] == '/') {
  5343. make_abs_local(t, target, sizeof(target));
  5344. load_page(target, 1, push);
  5345. return;
  5346. }
  5347. if (!looks_like_host(t)) {
  5348. struct sys_stat st;
  5349. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5350. make_abs_local(t, target, sizeof(target));
  5351. load_page(target, 1, push);
  5352. return;
  5353. }
  5354. }
  5355. {
  5356. /* A typed bare host tries https first: nearly every site
  5357. * redirects http -> https anyway, and that hop costs a whole
  5358. * extra connection. load_page() falls back to http when the
  5359. * https connection itself fails. */
  5360. char with_scheme[BR_URL_MAX];
  5361. unsigned int n = 0;
  5362. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5363. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5364. nav_https_upgraded = 1;
  5365. load_remote(with_scheme, push);
  5366. }
  5367. }
  5368. /* ---- layout ---- */
  5369. static struct ufont_face *style_face(const struct br_style *st)
  5370. {
  5371. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5372. return font_faces[st->font_face - 1];
  5373. return 0;
  5374. }
  5375. static struct ufont_face *run_face(const struct lay_run *r)
  5376. {
  5377. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5378. return font_faces[r->font_face - 1];
  5379. return 0;
  5380. }
  5381. static unsigned int face_text_width(struct ngui *gui,
  5382. const struct br_style *st,
  5383. const char *s, unsigned int n)
  5384. {
  5385. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5386. st->bold, st->italic, st->mono);
  5387. }
  5388. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5389. {
  5390. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5391. st->mono);
  5392. }
  5393. static unsigned int run_text_width(struct ngui *gui,
  5394. const struct lay_run *r,
  5395. const char *s, unsigned int n)
  5396. {
  5397. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5398. r->bold, r->italic, r->mono);
  5399. }
  5400. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5401. {
  5402. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5403. r->mono);
  5404. }
  5405. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5406. {
  5407. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5408. }
  5409. static struct br_style base_style(void)
  5410. {
  5411. struct br_style s = { 0 };
  5412. s.color = ui.theme.text;
  5413. s.bg = ui.theme.bg;
  5414. s.has_bg = 0;
  5415. for (int i = 0; i < 4; i++) {
  5416. s.border_c[i] = 0;
  5417. s.border_w[i] = 0;
  5418. s.border_s[i] = BR_BORDER_SOLID;
  5419. }
  5420. s.font_px = 16;
  5421. s.bold = 0;
  5422. s.italic = 0;
  5423. s.mono = 0;
  5424. s.underline = 0;
  5425. s.strike = 0;
  5426. s.overline = 0;
  5427. s.align = BR_ALIGN_LEFT;
  5428. s.display = BR_DISPLAY_BLOCK;
  5429. s.no_bullet = 0;
  5430. s.list_style = BR_LIST_AUTO;
  5431. s.uppercase = 0;
  5432. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5433. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5434. s.width = s.max_width = s.min_width = 0;
  5435. s.height = s.min_height = s.max_height = 0;
  5436. s.box_sizing = 0;
  5437. s.ml_auto = s.mr_auto = 0;
  5438. s.line_h_pct = 0;
  5439. s.line_h_px = 0;
  5440. s.mt = s.mb = s.ml = s.mr = 0;
  5441. s.pt = s.pb = s.pl = s.pr = 0;
  5442. return s;
  5443. }
  5444. /* The style node 0's children inherit. Node 0 is the first parsed node:
  5445. * a minified page that starts `<!doctype html><html ...>` makes it the
  5446. * <html> element itself, and the layout walks only its children, so its
  5447. * own cascade (html { color; font } -- Docusaurus/Infima put the page
  5448. * colour and font there) used to be skipped and the theme defaults showed
  5449. * through. Only inherited properties are taken: the root's box (margins,
  5450. * display, background) is not a container style for its children here. */
  5451. static struct br_style root_style(void)
  5452. {
  5453. struct br_style base = base_style(), st;
  5454. if (!doc.nnode || doc.nodes[doc.root].type != BR_NODE_ELEM ||
  5455. doc.nodes[doc.root].tag != BR_TAG_HTML)
  5456. return base;
  5457. br_style_for(&doc, doc.root, &base, &st);
  5458. base.color = st.color;
  5459. base.font_px = st.font_px;
  5460. base.bold = st.bold;
  5461. base.italic = st.italic;
  5462. base.mono = st.mono;
  5463. base.font_face = st.font_face;
  5464. base.align = st.align;
  5465. base.line_h_pct = st.line_h_pct;
  5466. base.line_h_px = st.line_h_px;
  5467. base.nowrap = st.nowrap;
  5468. base.uppercase = st.uppercase;
  5469. base.cursor = st.cursor;
  5470. base.vis_hidden = st.vis_hidden;
  5471. base.fill_mode = st.fill_mode;
  5472. base.fill = st.fill;
  5473. base.stroke_mode = st.stroke_mode;
  5474. base.stroke = st.stroke;
  5475. base.stroke_w = st.stroke_w;
  5476. base.fill_evenodd = st.fill_evenodd;
  5477. return base;
  5478. }
  5479. /* Resolve a margin/padding raw value. Percentages use the containing
  5480. * block width for all four sides, as CSS specifies. */
  5481. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5482. {
  5483. if (unit == 1)
  5484. return base * v / 10000;
  5485. if (unit == 2)
  5486. return st->font_px * v / 100;
  5487. if (unit == 3)
  5488. return (int)br_root_font_px() * v / 100;
  5489. if (unit == 4)
  5490. return 0;
  5491. return v;
  5492. }
  5493. static int mp_px(const struct br_style *st, int side, int base)
  5494. {
  5495. int raw;
  5496. switch (side) {
  5497. case 0: raw = st->mt; break;
  5498. case 1: raw = st->mr; break;
  5499. case 2: raw = st->mb; break;
  5500. case 3: raw = st->ml; break;
  5501. case 4: raw = st->pt; break;
  5502. case 5: raw = st->pr; break;
  5503. case 6: raw = st->pb; break;
  5504. default: raw = st->pl; break;
  5505. }
  5506. if (st->mp_unit[side] == 5)
  5507. return base * raw / 100 + st->mp_calc_px[side];
  5508. return css_mp_px(st, raw, st->mp_unit[side], base);
  5509. }
  5510. static int style_width_px(const struct br_style *st, int base)
  5511. {
  5512. if (st->width_kind == 1)
  5513. return st->width;
  5514. if (st->width_kind == 2)
  5515. return base * (int)st->width / 100;
  5516. if (st->width_kind == 3)
  5517. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5518. return 0;
  5519. }
  5520. static int style_height_px(const struct br_style *st, int base)
  5521. {
  5522. if (st->height_kind == 1)
  5523. return st->height;
  5524. if (st->height_kind == 2)
  5525. return base * (int)st->height / 100;
  5526. if (st->height_kind == 3)
  5527. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5528. return 0;
  5529. }
  5530. static int css_size(unsigned char kind, int val, int base)
  5531. {
  5532. if (kind == 1)
  5533. return val;
  5534. if (kind == 2)
  5535. return base * val / 100;
  5536. return -1;
  5537. }
  5538. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5539. int thick, int horizontal, unsigned short color,
  5540. unsigned char style)
  5541. {
  5542. int pos;
  5543. if (len <= 0 || thick <= 0)
  5544. return;
  5545. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5546. if (horizontal)
  5547. ngui_fill_rect(ui, (struct ngui_rect){
  5548. x, y, len, thick}, color);
  5549. else
  5550. ngui_fill_rect(ui, (struct ngui_rect){
  5551. x, y, thick, len}, color);
  5552. return;
  5553. }
  5554. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5555. int seg = len - pos;
  5556. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5557. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5558. if (horizontal)
  5559. ngui_fill_rect(ui, (struct ngui_rect){
  5560. x + pos, y, seg, thick}, color);
  5561. else
  5562. ngui_fill_rect(ui, (struct ngui_rect){
  5563. x, y + pos, thick, seg}, color);
  5564. }
  5565. }
  5566. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5567. const struct br_style *st)
  5568. {
  5569. int top = st->border_w[0], right = st->border_w[1];
  5570. int bottom = st->border_w[2], left = st->border_w[3];
  5571. if (r.w <= 0 || r.h <= 0)
  5572. return;
  5573. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5574. int i;
  5575. for (i = 0; i < 4; i++)
  5576. if (st->border_w[i] && !st->border_t[i]) {
  5577. ngui_fill_rect(ui, r, st->border_c[i]);
  5578. break;
  5579. }
  5580. return;
  5581. }
  5582. if (top && !st->border_t[0])
  5583. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5584. st->border_c[0], st->border_s[0]);
  5585. if (bottom && !st->border_t[2])
  5586. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5587. st->border_c[2], st->border_s[2]);
  5588. if (left && !st->border_t[3])
  5589. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5590. left, 0, st->border_c[3], st->border_s[3]);
  5591. if (right && !st->border_t[1])
  5592. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5593. r.h - top - bottom, right, 0,
  5594. st->border_c[1], st->border_s[1]);
  5595. }
  5596. static void transform_origin(const struct br_style *st, int w, int h,
  5597. int *ox, int *oy)
  5598. {
  5599. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5600. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5601. }
  5602. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5603. unsigned int a)
  5604. {
  5605. unsigned int dr, dg, db, sr, sg, sb;
  5606. if (a >= 255)
  5607. return s;
  5608. dr = (d >> 11) & 31;
  5609. dg = (d >> 5) & 63;
  5610. db = d & 31;
  5611. sr = (s >> 11) & 31;
  5612. sg = (s >> 5) & 63;
  5613. sb = s & 31;
  5614. dr = (dr * (255 - a) + sr * a) / 255;
  5615. dg = (dg * (255 - a) + sg * a) / 255;
  5616. db = (db * (255 - a) + sb * a) / 255;
  5617. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5618. }
  5619. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5620. * transforms the element's own background box; text and descendants keep
  5621. * their layout (documented approximation). */
  5622. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5623. unsigned short color,
  5624. const struct br_style *st)
  5625. {
  5626. double sx = st->scale_x / 100.0;
  5627. double sy = st->scale_y / 100.0;
  5628. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5629. double c = cos(th), sn = sin(th);
  5630. int ox, oy, minx, miny, maxx, maxy, x, y;
  5631. double ax, ay;
  5632. double px[4], py[4];
  5633. int cx1, cy1, cx2, cy2, i;
  5634. if (sx == 0)
  5635. sx = 0.01;
  5636. if (sy == 0)
  5637. sy = 0.01;
  5638. transform_origin(st, box.w, box.h, &ox, &oy);
  5639. ax = box.x + ox;
  5640. ay = box.y + oy;
  5641. px[0] = -ox; py[0] = -oy;
  5642. px[1] = box.w - ox; py[1] = -oy;
  5643. px[2] = box.w - ox; py[2] = box.h - oy;
  5644. px[3] = -ox; py[3] = box.h - oy;
  5645. minx = miny = 1000000;
  5646. maxx = maxy = -1000000;
  5647. for (i = 0; i < 4; i++) {
  5648. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5649. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5650. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5651. if (dx < minx) minx = dx;
  5652. if (dx > maxx) maxx = dx;
  5653. if (dy < miny) miny = dy;
  5654. if (dy > maxy) maxy = dy;
  5655. }
  5656. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5657. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5658. cx2 = page_rect.x + page_rect.w - 12;
  5659. cy2 = page_rect.y + page_rect.h;
  5660. if (cx2 > gui->w) cx2 = gui->w;
  5661. if (cy2 > gui->h) cy2 = gui->h;
  5662. if (minx < cx1) minx = cx1;
  5663. if (miny < cy1) miny = cy1;
  5664. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5665. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5666. for (y = miny; y <= maxy; y++) {
  5667. for (x = minx; x <= maxx; x++) {
  5668. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5669. double rx = dx * c + dy * sn;
  5670. double ry = -dx * sn + dy * c;
  5671. double bx = rx / sx + ox;
  5672. double by = ry / sy + oy;
  5673. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5674. gui->px[y * gui->w + x] = color;
  5675. }
  5676. }
  5677. }
  5678. static void draw_image_transformed(struct ngui *gui,
  5679. const struct img_image *im,
  5680. int x, int y, int w, int h,
  5681. int sx100, int sy100, int rot100,
  5682. int origin_x, int origin_y,
  5683. int origin_x_kind, int origin_y_kind)
  5684. {
  5685. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5686. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5687. double c = cos(th), sn = sin(th);
  5688. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5689. double ax, ay;
  5690. double bx[4], by[4];
  5691. int cx1, cy1, cx2, cy2;
  5692. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5693. return;
  5694. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5695. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5696. ax = x + ox;
  5697. ay = y + oy;
  5698. bx[0] = -ox; by[0] = -oy;
  5699. bx[1] = w - ox; by[1] = -oy;
  5700. bx[2] = w - ox; by[2] = h - oy;
  5701. bx[3] = -ox; by[3] = h - oy;
  5702. minx = miny = 1000000;
  5703. maxx = maxy = -1000000;
  5704. for (i = 0; i < 4; i++) {
  5705. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5706. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5707. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5708. if (dx < minx) minx = dx;
  5709. if (dx > maxx) maxx = dx;
  5710. if (dy < miny) miny = dy;
  5711. if (dy > maxy) maxy = dy;
  5712. }
  5713. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5714. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5715. cx2 = page_rect.x + page_rect.w - 12;
  5716. cy2 = page_rect.y + page_rect.h;
  5717. if (cx2 > gui->w) cx2 = gui->w;
  5718. if (cy2 > gui->h) cy2 = gui->h;
  5719. if (minx < cx1) minx = cx1;
  5720. if (miny < cy1) miny = cy1;
  5721. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5722. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5723. for (py = miny; py <= maxy; py++) {
  5724. for (px = minx; px <= maxx; px++) {
  5725. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5726. double rx = dx * c + dy * sn;
  5727. double ry = -dx * sn + dy * c;
  5728. double fx = rx / sx + ox;
  5729. double fy = ry / sy + oy;
  5730. int ix, iy;
  5731. unsigned int si, a;
  5732. unsigned short src;
  5733. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5734. continue;
  5735. ix = (int)(fx * (double)im->w / w);
  5736. iy = (int)(fy * (double)im->h / h);
  5737. if (ix < 0 || ix >= (int)im->w ||
  5738. iy < 0 || iy >= (int)im->h)
  5739. continue;
  5740. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5741. src = im->px[si];
  5742. a = im->alpha ? im->alpha[si] : 255;
  5743. gui->px[py * gui->w + px] =
  5744. a >= 255 ? src :
  5745. blend_rgb565(gui->px[py * gui->w + px],
  5746. src, a);
  5747. }
  5748. }
  5749. }
  5750. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5751. unsigned int node, const struct br_style *st);
  5752. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5753. * first and every pixel outside a corner's arc is restored afterwards. */
  5754. #define BG_ROUND_MAX 64
  5755. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5756. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5757. unsigned int node, const struct br_style *st,
  5758. int rtl, int rtr, int rbr, int rbl)
  5759. {
  5760. struct ngui *ui = l->ui;
  5761. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5762. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5763. if (ui->nclip > 0)
  5764. clip = ui->clip[ui->nclip - 1];
  5765. for (c = 0; c < 4; c++) {
  5766. if (r[c] > BG_ROUND_MAX)
  5767. r[c] = BG_ROUND_MAX;
  5768. if (r[c] > box.w / 2)
  5769. r[c] = box.w / 2;
  5770. if (r[c] > box.h / 2)
  5771. r[c] = box.h / 2;
  5772. }
  5773. for (c = 0; c < 4; c++) {
  5774. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5775. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5776. for (dy = 0; dy < r[c]; dy++)
  5777. for (dx = 0; dx < r[c]; dx++) {
  5778. int px = ox + dx, py = oy + dy;
  5779. if (px >= clip.x && py >= clip.y &&
  5780. px < clip.x + clip.w && py < clip.y + clip.h)
  5781. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5782. ui->px[py * ui->w + px];
  5783. }
  5784. }
  5785. draw_bg_image(l, box, node, st);
  5786. for (c = 0; c < 4; c++) {
  5787. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5788. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5789. /* arc centre, in corner-square coordinates */
  5790. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5791. int cy = (c >= 2) ? 0 : r[c];
  5792. for (dy = 0; dy < r[c]; dy++)
  5793. for (dx = 0; dx < r[c]; dx++) {
  5794. int px = ox + dx, py = oy + dy;
  5795. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5796. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5797. continue;
  5798. if (px >= clip.x && py >= clip.y &&
  5799. px < clip.x + clip.w && py < clip.y + clip.h)
  5800. ui->px[py * ui->w + px] =
  5801. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5802. }
  5803. }
  5804. }
  5805. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5806. unsigned int node, const struct br_style *st)
  5807. {
  5808. struct br_image *bi;
  5809. struct img_blit b;
  5810. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5811. unsigned int scale = 65536;
  5812. int legacy, tiles = 0, rows = 0;
  5813. int cx1, cy1, cx2, cy2;
  5814. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5815. return;
  5816. if (doc.nodes[node].bg_img_index < 0 ||
  5817. doc.nodes[node].bg_img_index >= image_count)
  5818. return;
  5819. bi = &images[doc.nodes[node].bg_img_index];
  5820. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5821. return;
  5822. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5823. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5824. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5825. if (legacy) {
  5826. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5827. tw = box.w;
  5828. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5829. x = box.x;
  5830. y = box.y;
  5831. rep_x = rep_y = 0;
  5832. } else {
  5833. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5834. unsigned int sx = ((unsigned int)box.w << 16) /
  5835. bi->img.w;
  5836. unsigned int sy = ((unsigned int)box.h << 16) /
  5837. bi->img.h;
  5838. scale = st->bg_size_kind == 3 ?
  5839. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  5840. } else if (st->bg_size_kind == 1 ||
  5841. st->bg_size_kind == 2) {
  5842. int w = st->bg_size_w;
  5843. int h = st->bg_size_h;
  5844. if (st->bg_size_kind == 2) {
  5845. if (w)
  5846. w = box.w * w / 100;
  5847. if (h)
  5848. h = box.h * h / 100;
  5849. }
  5850. if (w)
  5851. scale = ((unsigned int)w << 16) / bi->img.w;
  5852. else if (h)
  5853. scale = ((unsigned int)h << 16) / bi->img.h;
  5854. }
  5855. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  5856. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5857. if (tw < 1)
  5858. tw = 1;
  5859. if (th < 1)
  5860. th = 1;
  5861. posx = st->bg_pos_x_kind == 1 ?
  5862. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  5863. posy = st->bg_pos_y_kind == 1 ?
  5864. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  5865. x = box.x + posx;
  5866. y = box.y + posy;
  5867. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  5868. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  5869. if (rep_x) {
  5870. int m = (x - box.x) % tw;
  5871. if (m > 0)
  5872. m -= tw;
  5873. x = box.x + m;
  5874. }
  5875. if (rep_y) {
  5876. int m = (y - box.y) % th;
  5877. if (m > 0)
  5878. m -= th;
  5879. y = box.y + m;
  5880. }
  5881. }
  5882. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  5883. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  5884. cx2 = box.x + box.w;
  5885. cy2 = box.y + box.h;
  5886. if (cx2 > page_rect.x + page_rect.w - 12)
  5887. cx2 = page_rect.x + page_rect.w - 12;
  5888. if (cy2 > page_rect.y + page_rect.h)
  5889. cy2 = page_rect.y + page_rect.h;
  5890. if (cx1 >= cx2 || cy1 >= cy2)
  5891. return;
  5892. b.dst = l->ui->px;
  5893. b.dst_w = l->ui->w;
  5894. b.dst_h = l->ui->h;
  5895. b.clip_x = cx1;
  5896. b.clip_y = cy1;
  5897. b.clip_w = cx2 - cx1;
  5898. b.clip_h = cy2 - cy1;
  5899. b.bg = ui.theme.bg;
  5900. b.bg2 = ui.theme.bg;
  5901. b.dst_a = 0;
  5902. {
  5903. struct img_image *src = image_display_get(bi, tw, th);
  5904. int row_x;
  5905. if (!src)
  5906. src = &bi->img;
  5907. b.scale = ((unsigned int)tw << 16) / src->w;
  5908. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  5909. row_x = x;
  5910. for (;;) {
  5911. for (;;) {
  5912. b.x = x;
  5913. b.y = y;
  5914. img_draw(src, &b);
  5915. if (!rep_x || ++tiles > 512)
  5916. break;
  5917. x += tw;
  5918. if (x >= box.x + box.w)
  5919. break;
  5920. }
  5921. if (!rep_y || ++rows > 64)
  5922. break;
  5923. y += th;
  5924. if (y >= box.y + box.h)
  5925. break;
  5926. x = row_x;
  5927. }
  5928. }
  5929. }
  5930. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5931. int *out_w, int *out_h);
  5932. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5933. const struct br_style *st, int x, int y, int w,
  5934. int h);
  5935. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  5936. * RUN_SVG an inline <svg> icon (its node in off). */
  5937. #define RUN_SVG (-3)
  5938. static int run_width(const struct lay_run *r)
  5939. {
  5940. if (r->img >= 0)
  5941. return r->iw;
  5942. if (r->img == -2 || r->img == RUN_SVG)
  5943. return r->iw;
  5944. return (int)r->w;
  5945. }
  5946. static void start_line(struct lay *l, const struct br_style *st)
  5947. {
  5948. (void)st;
  5949. if (l->nruns == 0) {
  5950. l->line_y = l->y;
  5951. l->line_h = 0;
  5952. }
  5953. l->line_left = l->left;
  5954. l->line_right = l->right;
  5955. if (l->float_active && l->line_y < l->float_bottom) {
  5956. if (l->float_left > l->line_left)
  5957. l->line_left = l->float_left;
  5958. if (l->float_right < l->line_right)
  5959. l->line_right = l->float_right;
  5960. }
  5961. if (l->line_right < l->line_left + 8)
  5962. l->line_right = l->line_left + 8;
  5963. l->line_x = l->line_left;
  5964. l->run_x = l->line_left;
  5965. }
  5966. static void flush_line(struct lay *l)
  5967. {
  5968. int total, x, i, vis;
  5969. if (!l->nruns && l->line_x == l->line_left) {
  5970. l->line_h = 0;
  5971. return;
  5972. }
  5973. total = l->line_x - l->line_left;
  5974. x = l->line_left;
  5975. vis = 1;
  5976. if (l->draw) {
  5977. int lh = l->line_h ? l->line_h : 16;
  5978. vis = l->line_y + lh >= page_rect.y &&
  5979. l->line_y <= page_rect.y + page_rect.h;
  5980. }
  5981. if (l->align == BR_ALIGN_CENTER)
  5982. x += (l->line_right - l->line_left - total) / 2;
  5983. else if (l->align == BR_ALIGN_RIGHT)
  5984. x = l->line_right - total;
  5985. if (x < l->line_left)
  5986. x = l->line_left;
  5987. for (i = 0; i < l->nruns; i++) {
  5988. struct lay_run *r = &l->runs[i];
  5989. int w = run_width(r);
  5990. int ry = l->line_y + r->dy;
  5991. x += r->gap;
  5992. if (l->draw && vis) {
  5993. if (r->form) {
  5994. unsigned int node = r->form - 1;
  5995. struct form_state *fs = form_get(node, 1);
  5996. int hh = r->ih ? r->ih : 20;
  5997. int focused = form_focus == node;
  5998. int disabled = r->form_disabled;
  5999. unsigned short bg = l->ui->theme.panel_alt;
  6000. unsigned short fg = disabled ? 0x8410 : r->color;
  6001. struct ngui_rect box = {x, ry, w, hh};
  6002. if (r->form_kind == FORM_CHECKBOX ||
  6003. r->form_kind == FORM_RADIO) {
  6004. ngui_fill_rect(l->ui, box, bg);
  6005. ngui_frame(l->ui, box,
  6006. focused ? l->ui->theme.accent :
  6007. l->ui->theme.border);
  6008. if (fs && fs->checked) {
  6009. struct ngui_rect dot = {
  6010. x + 4, ry + 4,
  6011. w > 8 ? w - 8 : 1,
  6012. hh > 8 ? hh - 8 : 1
  6013. };
  6014. if (r->form_kind == FORM_RADIO)
  6015. ngui_fill_round_rect(
  6016. l->ui, dot, 4,
  6017. 4, 4, 4,
  6018. l->ui->theme.accent);
  6019. else
  6020. ngui_fill_rect(l->ui,
  6021. dot,
  6022. l->ui->theme.accent);
  6023. }
  6024. } else {
  6025. int editable =
  6026. r->form_kind == FORM_TEXT ||
  6027. r->form_kind == FORM_PASSWORD ||
  6028. r->form_kind == FORM_TEXTAREA;
  6029. int scroll = 0;
  6030. /* Editable fields draw the live value
  6031. * (r->lit is a short copy). */
  6032. static char shown[FORM_VALUE_MAX + 1];
  6033. const char *txt = r->lit;
  6034. unsigned int tl = s_len(r->lit);
  6035. if (editable && fs && fs->len) {
  6036. unsigned int k;
  6037. if (r->form_kind == FORM_PASSWORD) {
  6038. for (k = 0; k < fs->len; k++)
  6039. shown[k] = '*';
  6040. shown[k] = '\0';
  6041. txt = shown;
  6042. } else {
  6043. txt = fs->value;
  6044. }
  6045. tl = fs->len;
  6046. }
  6047. struct br_style fst;
  6048. int author, tx = x + 6, pr = 6;
  6049. style_for_node(node, &fst);
  6050. author = form_author_styled(&fst);
  6051. if (author) {
  6052. /* The page styled the control:
  6053. * its background, border, radius
  6054. * and text colour. */
  6055. form_paint_author(l->ui, box, &fst,
  6056. focused);
  6057. tx = x + fst.border_w[3] +
  6058. mp_px(&fst, 7, w);
  6059. pr = fst.border_w[1] +
  6060. mp_px(&fst, 5, w);
  6061. if (tx < x + 2 && !editable)
  6062. tx = x + 2;
  6063. if (!disabled)
  6064. fg = editable && fs &&
  6065. !fs->len ?
  6066. 0x8410 : fst.color;
  6067. if (!editable) {
  6068. int tw0 = (int)
  6069. run_text_width(l->ui,
  6070. r, txt, tl);
  6071. tx = x + (w - tw0) / 2;
  6072. }
  6073. } else {
  6074. /* The box is drawn in theme colours, so
  6075. * the text is too: the page's CSS colour
  6076. * (dark on a light page) would vanish on
  6077. * the dark field. */
  6078. if (!disabled)
  6079. fg = editable && fs && !fs->len ?
  6080. l->ui->theme.text_dim :
  6081. l->ui->theme.text;
  6082. ngui_fill_rect(l->ui, box, bg);
  6083. ngui_frame(l->ui, box,
  6084. focused ? l->ui->theme.accent :
  6085. l->ui->theme.border);
  6086. }
  6087. /* A value wider than the field shows its
  6088. * tail (where typing happens). */
  6089. if (editable && fs && fs->len &&
  6090. w > (tx - x) + pr) {
  6091. int tw = (int)run_text_width(l->ui,
  6092. r, txt, tl);
  6093. int room = w - (tx - x) - pr;
  6094. if (tw > room)
  6095. scroll = tw - room;
  6096. }
  6097. ngui_push_clip(l->ui, (struct ngui_rect){
  6098. x + 1, ry + 1,
  6099. w > 2 ? w - 2 : 1,
  6100. hh > 2 ? hh - 2 : 1 });
  6101. ngui_text_px_face(l->ui, run_face(r),
  6102. tx - scroll,
  6103. ry + (hh - r->font_px) / 2 - 1,
  6104. txt, tl, fg, r->font_px,
  6105. r->bold, r->italic, r->mono);
  6106. if (focused && fs && editable) {
  6107. int cw = 0;
  6108. if (fs->len && fs->caret)
  6109. cw = (int)run_text_width(
  6110. l->ui, r, txt,
  6111. fs->caret < fs->len ?
  6112. fs->caret : fs->len);
  6113. ngui_fill_rect(l->ui,
  6114. (struct ngui_rect){
  6115. tx + cw - scroll,
  6116. ry + 4, 1,
  6117. hh > 8 ? hh - 8 : 1
  6118. },
  6119. l->ui->theme.accent);
  6120. }
  6121. ngui_pop_clip(l->ui);
  6122. if (r->form_kind == FORM_SELECT) {
  6123. ngui_text_px(l->ui, x + w - 12,
  6124. ry + 2, "v", 1, fg,
  6125. r->font_px, 0, 0, 0);
  6126. }
  6127. }
  6128. } else if (r->img == RUN_SVG) {
  6129. struct br_style sst;
  6130. style_for_node(r->off, &sst);
  6131. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  6132. r->ih);
  6133. } else if (r->img == -2) {
  6134. int hh = r->ih ? r->ih : 20;
  6135. ngui_fill_rect(l->ui,
  6136. (struct ngui_rect){x, ry, w, hh},
  6137. l->ui->theme.panel_alt);
  6138. ngui_frame(l->ui,
  6139. (struct ngui_rect){x, ry, w, hh},
  6140. l->ui->theme.border);
  6141. ngui_text_px_face(l->ui, run_face(r),
  6142. x + 6, ry + 2, r->lit,
  6143. s_len(r->lit), r->color,
  6144. r->font_px, r->bold, r->italic,
  6145. r->mono);
  6146. } else if (r->img >= 0) {
  6147. struct br_image *bi = &images[r->img];
  6148. if (bi->state == 1 && r->transform_scale) {
  6149. draw_image_transformed(l->ui, &bi->img,
  6150. x, ry, r->iw, r->ih,
  6151. r->scale_x, r->scale_y,
  6152. r->rotate_x100, r->origin_x,
  6153. r->origin_y, r->origin_x_kind,
  6154. r->origin_y_kind);
  6155. } else if (bi->state == 1) {
  6156. struct img_image *src =
  6157. image_display_get(bi, r->iw, r->ih);
  6158. struct img_blit b;
  6159. if (!src)
  6160. src = &bi->img;
  6161. b.dst = l->ui->px;
  6162. b.dst_w = l->ui->w;
  6163. b.dst_h = l->ui->h;
  6164. b.clip_x = page_rect.x;
  6165. b.clip_y = page_rect.y;
  6166. b.clip_w = page_rect.w - 12;
  6167. b.clip_h = page_rect.h;
  6168. b.x = x;
  6169. b.y = ry;
  6170. b.scale = ((unsigned int)r->iw << 16) /
  6171. src->w;
  6172. b.bg = ui.theme.bg;
  6173. b.bg2 = ui.theme.bg;
  6174. b.dst_a = 0;
  6175. b.flags = src->alpha ?
  6176. IMG_BLIT_OVER_DST : 0;
  6177. img_draw(src, &b);
  6178. }
  6179. } else {
  6180. const char *s = r->has_lit ? r->lit :
  6181. doc.text + r->off;
  6182. unsigned int n = r->has_lit ? s_len(r->lit) :
  6183. r->len;
  6184. ngui_text_px_face(l->ui, run_face(r), x, ry,
  6185. s, n, r->color, r->font_px,
  6186. r->bold, r->italic, r->mono);
  6187. if (r->underline)
  6188. ngui_fill_rect(l->ui,
  6189. (struct ngui_rect){x,
  6190. ry + run_ascent(l->ui, r) + 2,
  6191. w, 1}, r->color);
  6192. if (r->strike)
  6193. ngui_fill_rect(l->ui,
  6194. (struct ngui_rect){x,
  6195. ry + run_ascent(l->ui, r) -
  6196. (r->font_px > 3 ?
  6197. r->font_px / 3 : 1),
  6198. w, 1}, r->color);
  6199. if (r->overline)
  6200. ngui_fill_rect(l->ui,
  6201. (struct ngui_rect){x, ry,
  6202. w, 1}, r->color);
  6203. }
  6204. if (r->form || r->href) {
  6205. if (nhits < HIT_MAX) {
  6206. struct hit *h = &hits[nhits];
  6207. unsigned int target = r->form ?
  6208. r->form - 1 : r->href;
  6209. int hh = (r->form || r->img >= 0 ||
  6210. r->img == RUN_SVG) ?
  6211. r->ih :
  6212. run_line_height(l->ui, r);
  6213. int merge = nhits > 0 &&
  6214. hits[nhits - 1].node == target &&
  6215. hits[nhits - 1].y == ry &&
  6216. hits[nhits - 1].h == hh &&
  6217. x <= hits[nhits - 1].x +
  6218. hits[nhits - 1].w + 2;
  6219. if (merge) {
  6220. struct hit *p = &hits[nhits - 1];
  6221. int end = x + w;
  6222. if (end > p->x + p->w)
  6223. p->w = end - p->x;
  6224. } else {
  6225. h->x = x;
  6226. h->y = ry;
  6227. h->w = w;
  6228. h->h = hh;
  6229. h->node = (unsigned short)target;
  6230. nhits++;
  6231. }
  6232. }
  6233. }
  6234. }
  6235. x += w;
  6236. }
  6237. l->y += l->line_h + 2;
  6238. if (l->float_active && l->y >= l->float_bottom)
  6239. l->float_active = 0;
  6240. l->nruns = 0;
  6241. l->line_x = l->left;
  6242. l->run_x = l->left;
  6243. l->line_left = l->left;
  6244. l->line_right = l->right;
  6245. l->line_h = 0;
  6246. l->space_pending = 0;
  6247. }
  6248. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  6249. const struct br_style *st, unsigned short href,
  6250. const char *lit)
  6251. {
  6252. unsigned int n = lit ? s_len(lit) : len;
  6253. const char *tp = lit ? lit : doc.text + off;
  6254. int w = (int)face_text_width(l->ui, st, tp, n);
  6255. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6256. flush_line(l);
  6257. if (l->nruns == 0) {
  6258. l->line_y = l->y;
  6259. l->line_h = 0;
  6260. start_line(l, st);
  6261. }
  6262. {
  6263. struct lay_run *r = &l->runs[l->nruns++];
  6264. int gap = l->line_x - l->run_x;
  6265. if (gap < 0)
  6266. gap = 0;
  6267. r->gap = (unsigned short)gap;
  6268. r->off = off;
  6269. r->len = len;
  6270. r->color = st->color;
  6271. r->href = href;
  6272. r->dy = 0;
  6273. r->has_lit = 0;
  6274. r->form = 0;
  6275. r->form_kind = 0;
  6276. r->form_disabled = 0;
  6277. r->lit[0] = '\0';
  6278. if (lit && lit[0]) {
  6279. unsigned int i;
  6280. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  6281. r->lit[i] = lit[i];
  6282. r->lit[i] = '\0';
  6283. r->has_lit = 1;
  6284. }
  6285. r->img = -1;
  6286. r->iw = r->ih = 0;
  6287. r->font_px = st->font_px;
  6288. r->bold = st->bold;
  6289. r->italic = st->italic;
  6290. r->mono = st->mono;
  6291. r->font_face = st->font_face;
  6292. /* A control with its own background is a button, not body copy;
  6293. * an inherited link underline would strike through the fill. */
  6294. r->underline = st->underline && !st->has_bg;
  6295. r->strike = st->strike && !st->has_bg;
  6296. r->overline = st->overline && !st->has_bg;
  6297. r->w = (unsigned short)w;
  6298. if (r->has_lit)
  6299. r->w = (unsigned short)run_text_width(
  6300. l->ui, r, r->lit, s_len(r->lit));
  6301. w = r->w;
  6302. }
  6303. l->line_x += w;
  6304. l->run_x = l->line_x;
  6305. {
  6306. int lh = face_line_height(l->ui, st);
  6307. if (st->line_h_px)
  6308. lh = st->line_h_px;
  6309. else if (st->line_h_pct)
  6310. lh = st->font_px * st->line_h_pct / 100;
  6311. if (lh < face_line_height(l->ui, st))
  6312. lh = face_line_height(l->ui, st);
  6313. if (l->line_h < lh)
  6314. l->line_h = lh;
  6315. }
  6316. }
  6317. static void add_image_run(struct lay *l, unsigned int node,
  6318. const struct br_style *st, unsigned short href)
  6319. {
  6320. struct br_image *bi = 0;
  6321. int idx = doc.nodes[node].img_index;
  6322. int dw, dh, maxw;
  6323. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  6324. bi = &images[idx];
  6325. if (l->nruns == 0)
  6326. start_line(l, st);
  6327. if (l->space_pending &&
  6328. (l->nruns > 0 || l->line_x > l->line_left)) {
  6329. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6330. if (l->line_x + sp <= l->line_right)
  6331. l->line_x += sp;
  6332. }
  6333. l->space_pending = 0;
  6334. if (!bi) {
  6335. const char *alt = br_alt(&doc, node);
  6336. struct br_style gs = *st;
  6337. char tmp[96];
  6338. unsigned int n = 0;
  6339. int w;
  6340. gs.color = BR_GRAY;
  6341. gs.underline = 0;
  6342. s_append(tmp, &n, "[", sizeof(tmp));
  6343. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6344. s_append(tmp, &n, "]", sizeof(tmp));
  6345. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6346. if (l->line_x + w > l->line_right &&
  6347. (l->nruns > 0 || l->line_x > l->line_left))
  6348. flush_line(l);
  6349. add_run(l, 0, 0, &gs, href, tmp);
  6350. if (!l->draw) {
  6351. int t = l->line_y < 0 ? 0 : l->line_y;
  6352. int hh = face_line_height(l->ui, &gs);
  6353. if (t > 65535)
  6354. t = 65535;
  6355. if (hh > 65535)
  6356. hh = 65535;
  6357. img_top[node] = (unsigned short)t;
  6358. img_h[node] = (unsigned short)hh;
  6359. }
  6360. return;
  6361. }
  6362. maxw = l->line_right - l->line_left;
  6363. if (maxw < 8)
  6364. maxw = 8;
  6365. {
  6366. int iw = bi->native_w, ih = bi->native_h;
  6367. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6368. if (iw <= 0 || ih <= 0) {
  6369. iw = (int)bi->img.w;
  6370. ih = (int)bi->img.h;
  6371. }
  6372. dw = iw;
  6373. dh = ih;
  6374. if (doc.nodes[node].width_attr) {
  6375. int want = doc.nodes[node].width_attr;
  6376. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6377. have_w = 1;
  6378. }
  6379. if (doc.nodes[node].height_attr) {
  6380. int want = doc.nodes[node].height_attr;
  6381. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6382. have_h = 1;
  6383. }
  6384. if (have_w && !have_h)
  6385. dh = ih ? ih * dw / iw : 0;
  6386. if (have_h && !have_w)
  6387. dw = iw ? iw * dh / ih : 0;
  6388. if (st->width_kind) {
  6389. css_w = 1;
  6390. if (st->width_kind == 3)
  6391. dw = maxw * st->width_calc_pct / 100 +
  6392. st->width_calc_px;
  6393. else
  6394. dw = st->width_kind == 2 ?
  6395. maxw * (int)st->width / 100 :
  6396. (int)st->width;
  6397. }
  6398. /* Percentage heights resolve against the containing block's
  6399. * definite height (Docusaurus' logo: `.navbar__logo { height:
  6400. * 2rem }` holding an `img { height: 100% }`), and are auto
  6401. * when it has none; they used to use the width. */
  6402. if (st->height_kind == 1 ||
  6403. ((st->height_kind == 2 || st->height_kind == 3) &&
  6404. l->cb_h > 0)) {
  6405. css_h = 1;
  6406. if (st->height_kind == 3)
  6407. dh = l->cb_h * st->height_calc_pct / 100 +
  6408. st->height_calc_px;
  6409. else
  6410. dh = st->height_kind == 2 ?
  6411. l->cb_h * (int)st->height / 100 :
  6412. (int)st->height;
  6413. }
  6414. if (css_w && !css_h)
  6415. dh = ih ? ih * dw / iw : 0;
  6416. if (css_h && !css_w)
  6417. dw = iw ? iw * dh / ih : 0;
  6418. if (st->max_width_kind) {
  6419. int mw = st->max_width_kind == 3 ?
  6420. maxw * st->max_width_calc_pct / 100 +
  6421. st->max_width_calc_px :
  6422. st->max_width_kind == 2 ?
  6423. maxw * (int)st->max_width / 100 :
  6424. (int)st->max_width;
  6425. if (mw > 0 && dw > mw) {
  6426. dh = iw ? ih * mw / iw : 0;
  6427. dw = mw;
  6428. }
  6429. }
  6430. }
  6431. if (dw < 8)
  6432. dw = 8;
  6433. if (dh < 8)
  6434. dh = 8;
  6435. if (dw > maxw) {
  6436. dh = dw ? dh * maxw / dw : dh;
  6437. dw = maxw;
  6438. }
  6439. if (!l->draw) {
  6440. int t = l->line_y < 0 ? 0 : l->line_y;
  6441. if (t > 65535)
  6442. t = 65535;
  6443. if (dh > 65535)
  6444. dh = 65535;
  6445. img_top[node] = (unsigned short)t;
  6446. img_h[node] = (unsigned short)dh;
  6447. }
  6448. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6449. l->line_x > l->line_left))
  6450. flush_line(l);
  6451. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6452. flush_line(l);
  6453. if (l->nruns == 0) {
  6454. l->line_y = l->y;
  6455. l->line_h = 0;
  6456. start_line(l, st);
  6457. }
  6458. {
  6459. struct lay_run *r = &l->runs[l->nruns++];
  6460. int gap = l->line_x - l->run_x;
  6461. if (gap < 0)
  6462. gap = 0;
  6463. r->gap = (unsigned short)gap;
  6464. r->off = 0;
  6465. r->len = 0;
  6466. r->color = 0;
  6467. r->href = href;
  6468. r->form = 0;
  6469. r->form_kind = 0;
  6470. r->form_disabled = 0;
  6471. /* Inline replaced elements honour their vertical margins; this
  6472. * is how Bootstrap's negative logo margins centre the wordmark. */
  6473. {
  6474. int idy = mp_px(st, 0, l->right - l->left);
  6475. if (idy < -2048)
  6476. idy = -2048;
  6477. if (idy > 2048)
  6478. idy = 2048;
  6479. r->dy = (signed short)idy;
  6480. }
  6481. r->has_lit = 0;
  6482. r->lit[0] = '\0';
  6483. r->img = (short)idx;
  6484. r->iw = (unsigned short)dw;
  6485. r->ih = (unsigned short)dh;
  6486. r->w = (unsigned short)dw;
  6487. r->font_px = st->font_px;
  6488. r->bold = st->bold;
  6489. r->italic = st->italic;
  6490. r->mono = st->mono;
  6491. r->font_face = st->font_face;
  6492. r->transform_scale = st->transform_scale;
  6493. r->scale_x = st->scale_x;
  6494. r->scale_y = st->scale_y;
  6495. r->rotate_x100 = st->rotate_x100;
  6496. r->origin_x = st->origin_x;
  6497. r->origin_y = st->origin_y;
  6498. r->origin_x_kind = st->origin_x_kind;
  6499. r->origin_y_kind = st->origin_y_kind;
  6500. r->underline = 0;
  6501. }
  6502. if (node < BR_MAX_NODES) {
  6503. layout_boxes[node].x = l->line_x;
  6504. layout_boxes[node].y = l->line_y +
  6505. mp_px(st, 0, l->right - l->left);
  6506. layout_boxes[node].w = dw;
  6507. layout_boxes[node].h = dh;
  6508. layout_boxes[node].valid = 1;
  6509. }
  6510. l->line_x += dw;
  6511. l->run_x = l->line_x;
  6512. if (l->line_h < dh)
  6513. l->line_h = dh;
  6514. }
  6515. /* An inline (or inline-block) <svg> is a replaced element in the text
  6516. * line, like an <img>: comment bubbles and arrows sit next to their label
  6517. * instead of starting a block of their own. */
  6518. static void add_svg_run(struct lay *l, unsigned int node,
  6519. const struct br_style *st, unsigned short href)
  6520. {
  6521. struct lay_run *r;
  6522. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6523. if (lw < 8)
  6524. lw = 8;
  6525. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6526. if (cw < 1)
  6527. cw = 1;
  6528. svg_size(node, st, cw, &dw, &dh);
  6529. if (dw > lw)
  6530. dw = lw;
  6531. ml = mp_px(st, 3, lw);
  6532. mr = mp_px(st, 1, lw);
  6533. if (ml < 0)
  6534. ml = 0;
  6535. if (mr < 0)
  6536. mr = 0;
  6537. if (l->line_x + ml + dw > l->line_right &&
  6538. (l->nruns > 0 || l->line_x > l->line_left))
  6539. flush_line(l);
  6540. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6541. flush_line(l);
  6542. if (l->nruns == 0) {
  6543. l->line_y = l->y;
  6544. l->line_h = 0;
  6545. start_line(l, st);
  6546. }
  6547. l->line_x += ml;
  6548. r = &l->runs[l->nruns++];
  6549. memset(r, 0, sizeof(*r));
  6550. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6551. l->line_x - l->run_x : 0);
  6552. r->off = node;
  6553. r->color = st->color;
  6554. r->href = href;
  6555. r->img = RUN_SVG;
  6556. r->iw = (unsigned short)dw;
  6557. r->ih = (unsigned short)dh;
  6558. r->w = (unsigned short)dw;
  6559. r->font_px = st->font_px;
  6560. if (node < BR_MAX_NODES) {
  6561. layout_boxes[node].x = l->line_x;
  6562. layout_boxes[node].y = l->line_y;
  6563. layout_boxes[node].w = dw;
  6564. layout_boxes[node].h = dh;
  6565. layout_boxes[node].valid = 1;
  6566. }
  6567. l->line_x += dw + mr;
  6568. l->run_x = l->line_x;
  6569. if (l->line_h < dh)
  6570. l->line_h = dh;
  6571. }
  6572. static int text_width(struct lay *l, const char *s, unsigned int n,
  6573. const struct br_style *st)
  6574. {
  6575. return (int)face_text_width(l->ui, st, s, n);
  6576. }
  6577. /* Longest prefix that fits in maxw, at least one byte. */
  6578. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6579. const struct br_style *st, int maxw)
  6580. {
  6581. unsigned int take = 0;
  6582. while (take < n) {
  6583. if (text_width(l, s, take + 1, st) > maxw)
  6584. break;
  6585. take++;
  6586. }
  6587. return take ? take : 1;
  6588. }
  6589. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6590. unsigned int n, unsigned int base,
  6591. const struct br_style *st, unsigned short href)
  6592. {
  6593. int avail;
  6594. int w = text_width(l, s + start, n, st);
  6595. unsigned int off = start;
  6596. if (l->nruns == 0)
  6597. start_line(l, st);
  6598. avail = l->line_right - l->line_left;
  6599. if (st->nowrap) {
  6600. if (n)
  6601. add_run(l, base + start,
  6602. (unsigned short)n, st, href, 0);
  6603. return;
  6604. }
  6605. /* A padded/bordered one-word button can be a few pixels wider than
  6606. * the content box; keep it on one line instead of splitting it. */
  6607. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6608. add_run(l, base + start,
  6609. (unsigned short)n, st, href, 0);
  6610. return;
  6611. }
  6612. if (l->line_x + w > l->line_right &&
  6613. (l->nruns > 0 || l->line_x > l->line_left)) {
  6614. flush_line(l);
  6615. start_line(l, st);
  6616. avail = l->line_right - l->line_left;
  6617. }
  6618. if (w <= avail) {
  6619. if (n)
  6620. add_run(l, base + start,
  6621. (unsigned short)n, st, href, 0);
  6622. return;
  6623. }
  6624. while (n > 0) {
  6625. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6626. add_run(l, base + off,
  6627. (unsigned short)take, st, href, 0);
  6628. off += take;
  6629. n -= take;
  6630. if (n) {
  6631. flush_line(l);
  6632. start_line(l, st);
  6633. avail = l->line_right - l->line_left;
  6634. }
  6635. }
  6636. }
  6637. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6638. const struct br_style *st, unsigned short href, int pre)
  6639. {
  6640. unsigned int i = 0;
  6641. unsigned int base;
  6642. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6643. if (!s || !len)
  6644. return;
  6645. if (space_w <= 0)
  6646. space_w = 8;
  6647. if (l->nruns == 0)
  6648. start_line(l, st);
  6649. base = (unsigned int)(s - doc.text);
  6650. if (st->uppercase) {
  6651. char *p = (char *)s;
  6652. unsigned int j;
  6653. for (j = 0; j < len; j++)
  6654. if (p[j] >= 'a' && p[j] <= 'z')
  6655. p[j] = (char)(p[j] - 'a' + 'A');
  6656. }
  6657. if (pre) {
  6658. while (i < len) {
  6659. unsigned int start;
  6660. if (s[i] == '\n') {
  6661. flush_line(l);
  6662. start_line(l, st);
  6663. i++;
  6664. continue;
  6665. }
  6666. if (s[i] == ' ') {
  6667. if (l->line_x + space_w > l->line_right &&
  6668. (l->nruns > 0 || l->line_x > l->line_left)) {
  6669. flush_line(l);
  6670. start_line(l, st);
  6671. } else {
  6672. l->line_x += space_w;
  6673. }
  6674. i++;
  6675. continue;
  6676. }
  6677. start = i;
  6678. while (i < len && s[i] != ' ' && s[i] != '\n')
  6679. i++;
  6680. emit_word(l, s, start, i - start, base, st, href);
  6681. }
  6682. return;
  6683. }
  6684. while (i < len) {
  6685. unsigned int start, n;
  6686. if (s[i] == ' ') {
  6687. l->space_pending = 1;
  6688. i++;
  6689. continue;
  6690. }
  6691. start = i;
  6692. while (i < len && s[i] != ' ')
  6693. i++;
  6694. n = i - start;
  6695. if (l->space_pending &&
  6696. (l->nruns > 0 || l->line_x > l->line_left)) {
  6697. if (st->nowrap ||
  6698. l->line_x + space_w <= l->line_right)
  6699. l->line_x += space_w;
  6700. }
  6701. l->space_pending = 0;
  6702. emit_word(l, s, start, n, base, st, href);
  6703. }
  6704. }
  6705. static int list_index(unsigned int parent, unsigned int node)
  6706. {
  6707. unsigned int n = 0, i;
  6708. for (i = doc.nodes[parent].first; i && i != node;
  6709. i = doc.nodes[i].next)
  6710. if (doc.nodes[i].tag == BR_TAG_LI)
  6711. n++;
  6712. return (int)n + 1;
  6713. }
  6714. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6715. unsigned int cap)
  6716. {
  6717. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6718. 50, 40, 10, 9, 5, 4, 1 };
  6719. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6720. "l", "xl", "x", "ix", "v", "iv", "i" };
  6721. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6722. "L", "XL", "X", "IX", "V", "IV", "I" };
  6723. unsigned int i;
  6724. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6725. while (v >= val[i] && *n + 1 < cap) {
  6726. const char *s = upper ? up[i] : lo[i];
  6727. while (*s && *n + 1 < cap)
  6728. m[(*n)++] = *s++;
  6729. v -= val[i];
  6730. }
  6731. }
  6732. }
  6733. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6734. {
  6735. unsigned int n = 0;
  6736. if (style == BR_LIST_DISC) {
  6737. m[n++] = '-';
  6738. } else if (style == BR_LIST_CIRCLE) {
  6739. m[n++] = 'o';
  6740. } else if (style == BR_LIST_SQUARE) {
  6741. m[n++] = '+';
  6742. } else if (style == BR_LIST_LOWER_ALPHA ||
  6743. style == BR_LIST_UPPER_ALPHA) {
  6744. if (idx >= 1 && idx <= 26)
  6745. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6746. 'A' : 'a') + idx - 1);
  6747. else
  6748. m[n++] = '?';
  6749. m[n++] = '.';
  6750. } else if (style == BR_LIST_LOWER_ROMAN ||
  6751. style == BR_LIST_UPPER_ROMAN) {
  6752. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6753. if (n + 1 < cap)
  6754. m[n++] = '.';
  6755. } else {
  6756. s_append_dec(m, &n, (unsigned int)idx, cap);
  6757. if (n + 1 < cap)
  6758. m[n++] = '.';
  6759. }
  6760. m[n] = '\0';
  6761. }
  6762. /* A control the page styled itself (background, border or radius in author
  6763. * CSS -- `background:transparent;border:none` counts) is painted with that
  6764. * style, sized from its padding/height and keeps the page's text colour.
  6765. * Unstyled controls keep the ngui theme look. */
  6766. static int form_author_styled(const struct br_style *st)
  6767. {
  6768. int i;
  6769. if (st->bg_set)
  6770. return 1;
  6771. for (i = 0; i < 4; i++)
  6772. if (st->border_w[i] || st->radius[i])
  6773. return 1;
  6774. return 0;
  6775. }
  6776. /* Set by the layout when the control is stretched to its line: a flex item
  6777. * (its box width was assigned by the flex row) or a child of a flex column,
  6778. * whose default align-items: stretch makes inputs full width. */
  6779. static int form_fill_line;
  6780. static void add_form_run(struct lay *l, unsigned int node,
  6781. const struct br_style *st, unsigned short href)
  6782. {
  6783. struct form_state *fs = form_get(node, 1);
  6784. char shown[FORM_VALUE_MAX + 1];
  6785. char opt[64];
  6786. const char *text = "";
  6787. struct lay_run *r;
  6788. int kind = form_kind_of(node);
  6789. int disabled = form_disabled(node);
  6790. int author = form_author_styled(st);
  6791. int tw, w = 120, h = 20, i, line_w, pad_x, pad_y;
  6792. int ml = 0, mr = 0, mt = 0, mb = 0;
  6793. if (!fs)
  6794. return;
  6795. if (l->nruns == 0)
  6796. start_line(l, st);
  6797. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6798. text = "";
  6799. w = 16;
  6800. h = 16;
  6801. } else if (kind == FORM_SELECT) {
  6802. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6803. s_copy(opt, "Select", sizeof(opt));
  6804. text = opt;
  6805. w = 120;
  6806. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6807. kind == FORM_RESET) {
  6808. if (fs->len)
  6809. text = fs->value;
  6810. else if (doc.nodes[node].tag == BR_TAG_BUTTON)
  6811. /* A <button>'s label is its content: an empty one
  6812. * (Docusaurus' sidebar caret, drawn by a CSS
  6813. * ::before icon) shows none. Only <input> buttons
  6814. * get the UA's default label. */
  6815. text = "";
  6816. else
  6817. text = kind == FORM_SUBMIT ? "Submit" :
  6818. kind == FORM_RESET ? "Reset" : "Button";
  6819. } else if (kind == FORM_PASSWORD) {
  6820. for (i = 0; i < fs->len; i++)
  6821. shown[i] = '*';
  6822. shown[fs->len] = '\0';
  6823. text = fs->len ? shown : br_placeholder(&doc, node);
  6824. } else {
  6825. if (fs->len)
  6826. text = fs->value;
  6827. else
  6828. text = br_placeholder(&doc, node);
  6829. if (kind == FORM_TEXTAREA) {
  6830. w = 180;
  6831. h = 40;
  6832. }
  6833. }
  6834. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  6835. line_w = l->line_right - l->line_left;
  6836. pad_x = mp_px(st, 7, line_w) + mp_px(st, 5, line_w) +
  6837. st->border_w[1] + st->border_w[3];
  6838. pad_y = mp_px(st, 4, line_w) + mp_px(st, 6, line_w) +
  6839. st->border_w[0] + st->border_w[2];
  6840. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  6841. /* Buttons are border-box in every UA stylesheet: an
  6842. * explicit width/height is the whole box. */
  6843. if (author || pad_x) {
  6844. w = tw + pad_x;
  6845. } else {
  6846. w = tw + 18;
  6847. if (w < 64)
  6848. w = 64;
  6849. }
  6850. if (st->width_kind)
  6851. w = style_width_px(st, line_w);
  6852. if (st->min_width_kind == 1 && w < (int)st->min_width)
  6853. w = st->min_width;
  6854. if (st->height_kind == 1)
  6855. h = st->height;
  6856. else if (author)
  6857. h = st->font_px + 6 + pad_y;
  6858. else
  6859. h = 22;
  6860. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  6861. kind == FORM_TEXTAREA) {
  6862. int fill = form_fill_line || st->display == BR_DISPLAY_BLOCK ||
  6863. st->display == BR_DISPLAY_FLEX;
  6864. int boxed = st->box_sizing ? 0 : pad_x;
  6865. if (st->width_kind)
  6866. w = style_width_px(st, line_w) + boxed;
  6867. else if (fill)
  6868. w = line_w - (l->line_x - l->line_left);
  6869. else
  6870. w = kind == FORM_TEXTAREA ? 180 : 120;
  6871. if (kind == FORM_TEXTAREA) {
  6872. const char *ra = br_find_attr(&doc, node, "rows");
  6873. int rows = 0;
  6874. int lh = st->line_h_px ? st->line_h_px :
  6875. st->font_px * 5 / 4;
  6876. while (ra && *ra >= '0' && *ra <= '9')
  6877. rows = rows * 10 + (*ra++ - '0');
  6878. if (rows < 1 || rows > 40)
  6879. rows = 2;
  6880. h = author ? rows * lh + pad_y : 40;
  6881. } else if (author) {
  6882. h = st->font_px + 8 + pad_y;
  6883. } else if (st->font_px + 8 > h) {
  6884. /* Taller fields for large text (min-height/padding
  6885. * on login pages): keep the box around the glyphs. */
  6886. h = st->font_px + 8;
  6887. }
  6888. if (st->height_kind == 1)
  6889. h = st->height + (st->box_sizing ? 0 : pad_y);
  6890. if (st->min_height_kind == 1 && h < (int)st->min_height)
  6891. h = st->min_height;
  6892. } else if (kind == FORM_SELECT) {
  6893. w = st->width_kind == 1 ? st->width : 120;
  6894. }
  6895. if (author) {
  6896. /* Inline margins (Google's `margin:11px 4px` between its
  6897. * two submit buttons). */
  6898. ml = mp_px(st, 3, line_w);
  6899. mr = mp_px(st, 1, line_w);
  6900. mt = mp_px(st, 0, line_w);
  6901. mb = mp_px(st, 2, line_w);
  6902. if (ml < 0 || ml > 64) ml = 0;
  6903. if (mr < 0 || mr > 64) mr = 0;
  6904. if (mt < 0 || mt > 64) mt = 0;
  6905. if (mb < 0 || mb > 64) mb = 0;
  6906. }
  6907. if (w > line_w - ml - mr)
  6908. w = line_w - ml - mr;
  6909. if (w < 8)
  6910. w = 8;
  6911. if (h > 400)
  6912. h = 400;
  6913. if (l->line_x + ml + w > l->line_right &&
  6914. (l->nruns > 0 || l->line_x > l->line_left))
  6915. flush_line(l);
  6916. if (l->nruns >= 96)
  6917. return;
  6918. if (l->nruns == 0) {
  6919. l->line_y = l->y;
  6920. l->line_h = 0;
  6921. start_line(l, st);
  6922. }
  6923. l->line_x += ml;
  6924. r = &l->runs[l->nruns++];
  6925. r->gap = (unsigned short)(l->line_x - l->run_x);
  6926. r->off = r->len = 0;
  6927. r->color = st->color;
  6928. r->href = href;
  6929. r->dy = (signed short)mt;
  6930. r->has_lit = 1;
  6931. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  6932. r->lit[i] = text[i];
  6933. r->lit[i] = '\0';
  6934. r->img = -2;
  6935. r->iw = (unsigned short)w;
  6936. r->ih = (unsigned short)h;
  6937. r->w = (unsigned short)w;
  6938. r->font_px = st->font_px;
  6939. r->bold = st->bold;
  6940. r->italic = st->italic;
  6941. r->mono = st->mono;
  6942. r->font_face = st->font_face;
  6943. r->underline = 0;
  6944. r->form = node + 1;
  6945. r->form_kind = (unsigned char)kind;
  6946. r->form_disabled = (unsigned char)disabled;
  6947. if (node < BR_MAX_NODES) {
  6948. layout_boxes[node].x = l->line_x;
  6949. layout_boxes[node].y = l->line_y + mt;
  6950. layout_boxes[node].w = w;
  6951. layout_boxes[node].h = h;
  6952. layout_boxes[node].valid = 1;
  6953. }
  6954. l->line_x += w;
  6955. l->run_x = l->line_x;
  6956. l->line_x += mr;
  6957. if (l->line_h < h + mt + mb)
  6958. l->line_h = h + mt + mb;
  6959. }
  6960. /* Background, border and corner radius of an author-styled control, the
  6961. * same decoration rules as a block box. */
  6962. static void form_paint_author(struct ngui *ui, struct ngui_rect box,
  6963. const struct br_style *st, int focused)
  6964. {
  6965. int rtl = css_radius(st, 0, box.w, box.h);
  6966. int rtr = css_radius(st, 1, box.w, box.h);
  6967. int rbr = css_radius(st, 2, box.w, box.h);
  6968. int rbl = css_radius(st, 3, box.w, box.h);
  6969. int bw = st->border_t[0] ? 0 : st->border_w[0];
  6970. (void)focused;
  6971. if (box.w <= 0 || box.h <= 0)
  6972. return;
  6973. if (rtl || rtr || rbr || rbl) {
  6974. if (bw > 0 && st->has_bg && st->border_c[0] != st->bg &&
  6975. box.w > bw * 2 && box.h > bw * 2) {
  6976. struct ngui_rect in = { box.x + bw, box.y + bw,
  6977. box.w - bw * 2,
  6978. box.h - bw * 2 };
  6979. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6980. st->border_c[0]);
  6981. ngui_fill_round_rect(ui, in,
  6982. rtl > bw ? rtl - bw : 0,
  6983. rtr > bw ? rtr - bw : 0,
  6984. rbr > bw ? rbr - bw : 0,
  6985. rbl > bw ? rbl - bw : 0, st->bg);
  6986. } else if (st->has_bg) {
  6987. ngui_fill_round_rect(ui, box, rtl, rtr, rbr, rbl,
  6988. st->bg);
  6989. } else if (bw > 0) {
  6990. ngui_frame_round(ui, box, rtl, rtr, rbr, rbl, bw,
  6991. st->border_c[0]);
  6992. }
  6993. return;
  6994. }
  6995. if (st->has_bg)
  6996. ngui_fill_rect(ui, box, st->bg);
  6997. if (st->border_w[0] || st->border_w[1] || st->border_w[2] ||
  6998. st->border_w[3])
  6999. draw_border_box(ui, box, st);
  7000. }
  7001. /* A poster wrapper is absolutely positioned over the media slot; the
  7002. * measured height of its picture is normally added back to the flow. When a
  7003. * loading-skeleton sibling already reserves that slot, adding both doubles
  7004. * the media height and pushes the article text a full screen down. */
  7005. static int has_skeleton_sibling(unsigned int node)
  7006. {
  7007. unsigned int p = doc.nodes[node].parent, c;
  7008. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  7009. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  7010. continue;
  7011. if (doc.nodes[c].class_off &&
  7012. contains_ci(doc.attrs + doc.nodes[c].class_off,
  7013. "skeleton"))
  7014. return 1;
  7015. }
  7016. return 0;
  7017. }
  7018. static void layout_children(struct lay *l, unsigned int parent,
  7019. const struct br_style *pst, int depth,
  7020. unsigned short link);
  7021. static void layout_flex_children(struct lay *l, unsigned int parent,
  7022. const struct br_style *pst, int depth,
  7023. unsigned short link);
  7024. static void layout_grid_children(struct lay *l, unsigned int parent,
  7025. const struct br_style *pst, int depth,
  7026. unsigned short link);
  7027. static void layout_grid_auto(struct lay *l, unsigned int parent,
  7028. const struct br_style *pst, int depth,
  7029. unsigned short link);
  7030. static int flex_item_width(struct lay *l, unsigned int n,
  7031. const struct br_style *cs, int avail);
  7032. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  7033. const struct br_style *pst, int depth,
  7034. unsigned short link);
  7035. static void layout_table_row(struct lay *l, unsigned int row,
  7036. const struct br_style *pst, int depth,
  7037. unsigned short link);
  7038. static int table_has_rowspan(unsigned int table);
  7039. static void layout_table(struct lay *l, unsigned int table,
  7040. const struct br_style *st, int depth,
  7041. unsigned short link);
  7042. /* A flex container whose items are only inline spans is usually just a
  7043. * heading/icon pair. Our flex row positions such items without emitting
  7044. * their inline text in some deep page contexts; normal inline flow renders
  7045. * the same content correctly. */
  7046. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  7047. {
  7048. unsigned int c;
  7049. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  7050. struct br_node *nd = &doc.nodes[c];
  7051. struct br_style cs;
  7052. if (nd->type == BR_NODE_TEXT)
  7053. continue;
  7054. br_style_for(&doc, c, pst, &cs);
  7055. if (cs.display == BR_DISPLAY_NONE)
  7056. continue;
  7057. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  7058. cs.width_kind || cs.has_bg ||
  7059. cs.border_w[0] || cs.border_w[1] ||
  7060. cs.border_w[2] || cs.border_w[3] ||
  7061. nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG)
  7062. return 1;
  7063. }
  7064. return 0;
  7065. }
  7066. static int css_radius(const struct br_style *st, int corner,
  7067. int w, int h)
  7068. {
  7069. int r = st->radius[corner];
  7070. if (r <= 0)
  7071. return 0;
  7072. if (r > w / 2)
  7073. r = w / 2;
  7074. if (r > h / 2)
  7075. r = h / 2;
  7076. return r;
  7077. }
  7078. /* ---- inline SVG ----
  7079. *
  7080. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  7081. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  7082. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  7083. * opacity and solid paint; a gradient paints the average of its stops) and
  7084. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  7085. #define SVG_CACHE_MAX 48
  7086. #define SVG_CACHE_PIXELS (640 * 1024)
  7087. #define SVG_MAX_POINTS 24576
  7088. struct svg_cache_ent {
  7089. unsigned int node;
  7090. int w, h;
  7091. unsigned short *px;
  7092. unsigned char *a;
  7093. unsigned int stamp;
  7094. };
  7095. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  7096. static unsigned int svg_cache_pixels, svg_cache_clock;
  7097. static struct svgr svg_geom;
  7098. static void *svg_geom_buf;
  7099. /* Current viewport in user units: percentage lengths resolve against it
  7100. * (the viewBox size, not the device pixels). */
  7101. static double svg_vp_w = 300, svg_vp_h = 150;
  7102. /* The layers live in the page heap: forget them before heap_reset(). */
  7103. static void svg_cache_clear(void)
  7104. {
  7105. memset(svg_cache, 0, sizeof(svg_cache));
  7106. svg_cache_pixels = 0;
  7107. svg_geom_buf = 0;
  7108. }
  7109. static int svg_name_is(const char *a, const char *b)
  7110. {
  7111. while (*a && *b) {
  7112. char x = *a, y = *b;
  7113. if (x >= 'A' && x <= 'Z')
  7114. x = (char)(x - 'A' + 'a');
  7115. if (x != y)
  7116. return 0;
  7117. a++;
  7118. b++;
  7119. }
  7120. return *a == *b;
  7121. }
  7122. static const char *svg_elem_name(unsigned int node)
  7123. {
  7124. const struct br_node *nd = &doc.nodes[node];
  7125. if (nd->name_off)
  7126. return doc.attrs + nd->name_off;
  7127. return br_tag_name(nd->tag);
  7128. }
  7129. /* A numeric attribute; a percentage resolves against `base`. */
  7130. static double svg_attr_num(unsigned int node, const char *name, double def,
  7131. double base)
  7132. {
  7133. const char *v = br_find_attr(&doc, node, name);
  7134. const char *p = v;
  7135. int ok = 0;
  7136. double x;
  7137. if (!v)
  7138. return def;
  7139. x = svgr_num(&p, &ok);
  7140. if (!ok)
  7141. return def;
  7142. if (*p == '%')
  7143. x = x * base / 100.0;
  7144. return x;
  7145. }
  7146. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  7147. static int svg_viewbox4(unsigned int node, double vb[4])
  7148. {
  7149. const char *v = br_find_attr(&doc, node, "viewbox");
  7150. const char *p = v;
  7151. int i, ok = 1;
  7152. if (!v)
  7153. return 0;
  7154. for (i = 0; i < 4 && ok; i++)
  7155. vb[i] = svgr_num(&p, &ok);
  7156. return ok && vb[2] > 0 && vb[3] > 0;
  7157. }
  7158. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  7159. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  7160. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  7161. double w, double h, double m[6])
  7162. {
  7163. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  7164. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  7165. int ax = 1, ay = 1;
  7166. if (par && contains_ci(par, "none")) {
  7167. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  7168. m[4] = -vb[0] * sx;
  7169. m[5] = -vb[1] * sy;
  7170. return;
  7171. }
  7172. if (par) {
  7173. if (contains_ci(par, "xmin"))
  7174. ax = 0;
  7175. else if (contains_ci(par, "xmax"))
  7176. ax = 2;
  7177. if (contains_ci(par, "ymin"))
  7178. ay = 0;
  7179. else if (contains_ci(par, "ymax"))
  7180. ay = 2;
  7181. }
  7182. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  7183. (sx < sy ? sx : sy);
  7184. tx = (w - vb[2] * s) * ax / 2.0;
  7185. ty = (h - vb[3] * s) * ay / 2.0;
  7186. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  7187. m[4] = tx - vb[0] * s;
  7188. m[5] = ty - vb[1] * s;
  7189. }
  7190. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  7191. * the paint attribute, then average the gradient's stops. */
  7192. static int svg_url_paint(unsigned int node, const char *attr,
  7193. unsigned short *color, unsigned int *alpha)
  7194. {
  7195. const char *v = 0, *h;
  7196. char id[64];
  7197. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  7198. for (k = 0; node && k < 32 && !v; k++) {
  7199. v = br_find_attr(&doc, node, attr);
  7200. if (!v) {
  7201. const char *style = br_find_attr(&doc, node, "style");
  7202. if (style && contains_ci(style, "url(#"))
  7203. v = strstr(style, "url(#");
  7204. }
  7205. if (v && !contains_ci(v, "url("))
  7206. v = 0;
  7207. node = doc.nodes[node].parent;
  7208. }
  7209. if (!v || !(h = strstr(v, "#")))
  7210. return 0;
  7211. h++;
  7212. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  7213. id[n++] = *h++;
  7214. id[n] = '\0';
  7215. g = br_find_id(&doc, id);
  7216. /* Follow href chains (a gradient that only references another one's
  7217. * stops), at most a few hops. */
  7218. for (k = 0; g && k < 4; k++) {
  7219. unsigned int gi = g - 1;
  7220. const char *ref;
  7221. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  7222. const char *nm, *sc, *so;
  7223. unsigned short col = 0;
  7224. double op = 1;
  7225. if (doc.nodes[c].type != BR_NODE_ELEM)
  7226. continue;
  7227. nm = svg_elem_name(c);
  7228. if (!svg_name_is(nm, "stop"))
  7229. continue;
  7230. sc = br_find_attr(&doc, c, "stop-color");
  7231. so = br_find_attr(&doc, c, "stop-opacity");
  7232. {
  7233. const char *st = br_find_attr(&doc, c, "style");
  7234. const char *q;
  7235. if (st && (q = strstr(st, "stop-color:")) != 0)
  7236. sc = q + 11;
  7237. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  7238. so = q + 13;
  7239. }
  7240. if (sc) {
  7241. unsigned int L = 0;
  7242. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  7243. L++;
  7244. if (!br_parse_color(sc, L, &col))
  7245. col = 0;
  7246. }
  7247. if (so) {
  7248. const char *p = so;
  7249. int ok = 0;
  7250. double x = svgr_num(&p, &ok);
  7251. if (ok)
  7252. op = x < 0 ? 0 : x > 1 ? 1 : x;
  7253. }
  7254. sr += (col >> 11) & 31;
  7255. sg += (col >> 5) & 63;
  7256. sb += col & 31;
  7257. sa += (unsigned int)(op * 255);
  7258. cnt++;
  7259. }
  7260. if (cnt)
  7261. break;
  7262. ref = br_find_attr(&doc, gi, "href");
  7263. if (!ref)
  7264. ref = br_find_attr(&doc, gi, "xlink:href");
  7265. if (!ref || ref[0] != '#')
  7266. break;
  7267. g = br_find_id(&doc, ref + 1);
  7268. }
  7269. if (!cnt)
  7270. return 0;
  7271. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  7272. (sb / cnt));
  7273. *alpha = sa / cnt;
  7274. return 1;
  7275. }
  7276. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  7277. unsigned short *color, unsigned int *alpha)
  7278. {
  7279. int mode = fill ? st->fill_mode : st->stroke_mode;
  7280. const char *op = br_find_attr(&doc, node,
  7281. fill ? "fill-opacity" : "stroke-opacity");
  7282. *alpha = 255;
  7283. switch (mode) {
  7284. case BR_PAINT_UNSET:
  7285. if (!fill)
  7286. return 0;
  7287. *color = 0;
  7288. break;
  7289. case BR_PAINT_COLOR:
  7290. *color = fill ? st->fill : st->stroke;
  7291. break;
  7292. case BR_PAINT_CURRENT:
  7293. *color = st->color;
  7294. break;
  7295. case BR_PAINT_URL:
  7296. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  7297. alpha))
  7298. return 0;
  7299. break;
  7300. default:
  7301. return 0;
  7302. }
  7303. if (op) {
  7304. const char *p = op;
  7305. int ok = 0;
  7306. double x = svgr_num(&p, &ok);
  7307. if (ok)
  7308. *alpha = (unsigned int)(*alpha *
  7309. (x < 0 ? 0 : x > 1 ? 1 : x));
  7310. }
  7311. return *alpha > 0;
  7312. }
  7313. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7314. const double m[6], const struct br_style *pst,
  7315. unsigned int alpha, int depth);
  7316. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  7317. const double m[6], const struct br_style *st,
  7318. unsigned int alpha, int depth)
  7319. {
  7320. unsigned int c;
  7321. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  7322. if (doc.nodes[c].type == BR_NODE_ELEM)
  7323. svg_draw_node(L, c, m, st, alpha, depth + 1);
  7324. }
  7325. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  7326. const double pm[6], const struct br_style *pst,
  7327. unsigned int alpha, int depth)
  7328. {
  7329. struct br_style st;
  7330. const char *nm = svg_elem_name(node);
  7331. const char *tf;
  7332. double m[6];
  7333. unsigned short color;
  7334. unsigned int pa;
  7335. int shape = 0, fillable = 1;
  7336. if (depth > 24 || !nm)
  7337. return;
  7338. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  7339. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  7340. svg_name_is(nm, "lineargradient") ||
  7341. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  7342. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  7343. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  7344. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  7345. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  7346. svg_name_is(nm, "foreignobject"))
  7347. return;
  7348. br_style_for(&doc, node, pst, &st);
  7349. if (st.display == BR_DISPLAY_NONE)
  7350. return;
  7351. memcpy(m, pm, sizeof(m));
  7352. tf = br_find_attr(&doc, node, "transform");
  7353. if (tf)
  7354. svgr_transform(m, tf);
  7355. {
  7356. const char *op = br_find_attr(&doc, node, "opacity");
  7357. if (op) {
  7358. const char *p = op;
  7359. int ok = 0;
  7360. double x = svgr_num(&p, &ok);
  7361. if (ok)
  7362. alpha = (unsigned int)(alpha *
  7363. (x < 0 ? 0 :
  7364. x > 1 ? 1 : x));
  7365. }
  7366. }
  7367. if (!alpha)
  7368. return;
  7369. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  7370. svg_name_is(nm, "switch")) {
  7371. svg_draw_children(L, node, m, &st, alpha, depth);
  7372. return;
  7373. }
  7374. if (svg_name_is(nm, "svg")) {
  7375. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  7376. y = svg_attr_num(node, "y", 0, 0);
  7377. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7378. t[4] = x;
  7379. t[5] = y;
  7380. svgr_mat_mul(m, m, t);
  7381. double ow = svg_vp_w, oh = svg_vp_h;
  7382. if (svg_viewbox4(node, vb)) {
  7383. double w = svg_attr_num(node, "width", vb[2], ow);
  7384. double h = svg_attr_num(node, "height", vb[3], oh);
  7385. double vm[6];
  7386. svg_viewport_matrix(node, vb, w, h, vm);
  7387. svgr_mat_mul(m, m, vm);
  7388. svg_vp_w = vb[2];
  7389. svg_vp_h = vb[3];
  7390. }
  7391. svg_draw_children(L, node, m, &st, alpha, depth);
  7392. svg_vp_w = ow;
  7393. svg_vp_h = oh;
  7394. return;
  7395. }
  7396. if (svg_name_is(nm, "use")) {
  7397. const char *ref = br_find_attr(&doc, node, "href");
  7398. unsigned int tgt;
  7399. double t[6] = { 1, 0, 0, 1, 0, 0 };
  7400. if (!ref)
  7401. ref = br_find_attr(&doc, node, "xlink:href");
  7402. if (!ref || ref[0] != '#')
  7403. return;
  7404. tgt = br_find_id(&doc, ref + 1);
  7405. if (!tgt || tgt - 1 == node)
  7406. return;
  7407. tgt--;
  7408. t[4] = svg_attr_num(node, "x", 0, 0);
  7409. t[5] = svg_attr_num(node, "y", 0, 0);
  7410. svgr_mat_mul(m, m, t);
  7411. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  7412. double vb[4];
  7413. double ow = svg_vp_w, oh = svg_vp_h;
  7414. if (svg_viewbox4(tgt, vb)) {
  7415. double w = svg_attr_num(node, "width", vb[2],
  7416. ow);
  7417. double h = svg_attr_num(node, "height", vb[3],
  7418. oh);
  7419. double vm[6];
  7420. svg_viewport_matrix(tgt, vb, w, h, vm);
  7421. svgr_mat_mul(m, m, vm);
  7422. svg_vp_w = vb[2];
  7423. svg_vp_h = vb[3];
  7424. }
  7425. svg_draw_children(L, tgt, m, &st, alpha, depth);
  7426. svg_vp_w = ow;
  7427. svg_vp_h = oh;
  7428. } else {
  7429. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  7430. }
  7431. return;
  7432. }
  7433. svgr_reset(&svg_geom, m);
  7434. if (svg_name_is(nm, "path")) {
  7435. const char *d = br_find_attr(&doc, node, "d");
  7436. if (d) {
  7437. svgr_path(&svg_geom, d);
  7438. shape = 1;
  7439. }
  7440. } else if (svg_name_is(nm, "rect")) {
  7441. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  7442. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  7443. double rx = svg_attr_num(node, "rx", -1, w);
  7444. double ry = svg_attr_num(node, "ry", -1, h);
  7445. if (rx < 0)
  7446. rx = ry < 0 ? 0 : ry;
  7447. if (ry < 0)
  7448. ry = rx;
  7449. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7450. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7451. shape = 1;
  7452. } else if (svg_name_is(nm, "circle")) {
  7453. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7454. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7455. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7456. shape = 1;
  7457. } else if (svg_name_is(nm, "ellipse")) {
  7458. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7459. svg_attr_num(node, "cy", 0, svg_vp_h),
  7460. svg_attr_num(node, "rx", 0, svg_vp_w),
  7461. svg_attr_num(node, "ry", 0, svg_vp_h));
  7462. shape = 1;
  7463. } else if (svg_name_is(nm, "line")) {
  7464. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7465. svg_attr_num(node, "y1", 0, svg_vp_h));
  7466. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7467. svg_attr_num(node, "y2", 0, svg_vp_h));
  7468. shape = 1;
  7469. fillable = 0;
  7470. } else if (svg_name_is(nm, "polyline") ||
  7471. svg_name_is(nm, "polygon")) {
  7472. const char *pts = br_find_attr(&doc, node, "points");
  7473. if (pts) {
  7474. svgr_points(&svg_geom, pts,
  7475. svg_name_is(nm, "polygon"));
  7476. shape = 1;
  7477. }
  7478. }
  7479. if (!shape)
  7480. return;
  7481. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7482. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7483. st.fill_evenodd);
  7484. if (svg_paint(node, &st, 0, &color, &pa)) {
  7485. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7486. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7487. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7488. }
  7489. }
  7490. /* <text> elements: drawn straight onto the page every frame (the glyph
  7491. * renderer targets the ngui canvas, not a layer). x/y map through the
  7492. * accumulated transform; the font size scales with it. */
  7493. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7494. const double pm[6], const struct br_style *pst,
  7495. int ox, int oy, int depth)
  7496. {
  7497. unsigned int c;
  7498. if (depth > 24)
  7499. return;
  7500. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7501. struct br_style st;
  7502. const char *nm, *tf;
  7503. double m[6];
  7504. if (doc.nodes[c].type != BR_NODE_ELEM)
  7505. continue;
  7506. nm = svg_elem_name(c);
  7507. if (!nm || svg_name_is(nm, "defs") ||
  7508. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7509. svg_name_is(nm, "clippath"))
  7510. continue;
  7511. br_style_for(&doc, c, pst, &st);
  7512. if (st.display == BR_DISPLAY_NONE)
  7513. continue;
  7514. memcpy(m, pm, sizeof(m));
  7515. tf = br_find_attr(&doc, c, "transform");
  7516. if (tf)
  7517. svgr_transform(m, tf);
  7518. if (svg_name_is(nm, "text")) {
  7519. unsigned int t = doc.nodes[c].first;
  7520. const char *s;
  7521. unsigned int n, tw;
  7522. double x = svg_attr_num(c, "x", 0, 0),
  7523. y = svg_attr_num(c, "y", 0, 0);
  7524. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7525. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7526. int tx, ty, anchor;
  7527. unsigned short col;
  7528. unsigned int pa;
  7529. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7530. continue;
  7531. if (px < 6)
  7532. px = 6;
  7533. if (px > 72)
  7534. px = 72;
  7535. if (!svg_paint(c, &st, 1, &col, &pa))
  7536. continue;
  7537. s = doc.text + doc.nodes[t].text_off;
  7538. n = doc.nodes[t].text_len;
  7539. st.font_px = (unsigned char)px;
  7540. tw = face_text_width(ui, &st, s, n);
  7541. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7542. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7543. ngui_text_ascent_face(ui, style_face(&st), px,
  7544. st.mono);
  7545. anchor = st.align;
  7546. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7547. anchor = BR_ALIGN_CENTER;
  7548. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7549. anchor = BR_ALIGN_RIGHT;
  7550. if (anchor == BR_ALIGN_CENTER)
  7551. tx -= (int)tw / 2;
  7552. else if (anchor == BR_ALIGN_RIGHT)
  7553. tx -= (int)tw;
  7554. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7555. col, px, st.bold, st.italic,
  7556. st.mono);
  7557. } else {
  7558. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7559. }
  7560. }
  7561. }
  7562. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7563. {
  7564. double vb[4];
  7565. if (svg_viewbox4(node, vb)) {
  7566. svg_viewport_matrix(node, vb, w, h, m);
  7567. } else {
  7568. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7569. }
  7570. }
  7571. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7572. const struct br_style *st)
  7573. {
  7574. struct svg_cache_ent *e = 0;
  7575. struct svgr_layer L;
  7576. double m[6];
  7577. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7578. svg_cache_clock++;
  7579. for (i = 0; i < SVG_CACHE_MAX; i++)
  7580. if (svg_cache[i].px && svg_cache[i].node == node &&
  7581. svg_cache[i].w == w && svg_cache[i].h == h) {
  7582. svg_cache[i].stamp = svg_cache_clock;
  7583. return &svg_cache[i];
  7584. }
  7585. if (need > SVG_CACHE_PIXELS)
  7586. return 0;
  7587. /* Evict least recently used layers until this one fits. */
  7588. for (;;) {
  7589. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7590. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7591. if (!svg_cache[i].px) {
  7592. if (!free_slot)
  7593. free_slot = &svg_cache[i];
  7594. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7595. lru = &svg_cache[i];
  7596. }
  7597. }
  7598. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7599. e = free_slot;
  7600. break;
  7601. }
  7602. if (!lru)
  7603. return 0;
  7604. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7605. free(lru->px);
  7606. free(lru->a);
  7607. memset(lru, 0, sizeof(*lru));
  7608. }
  7609. if (!svg_geom_buf) {
  7610. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7611. if (!svg_geom_buf)
  7612. return 0;
  7613. }
  7614. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7615. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7616. e->a = (unsigned char *)calloc(need, 1);
  7617. if (!e->px || !e->a) {
  7618. free(e->px);
  7619. free(e->a);
  7620. memset(e, 0, sizeof(*e));
  7621. return 0;
  7622. }
  7623. e->node = node;
  7624. e->w = w;
  7625. e->h = h;
  7626. e->stamp = svg_cache_clock;
  7627. svg_cache_pixels += need;
  7628. L.px = e->px;
  7629. L.a = e->a;
  7630. L.w = w;
  7631. L.h = h;
  7632. svg_root_matrix(node, w, h, m);
  7633. {
  7634. double vb[4];
  7635. if (svg_viewbox4(node, vb)) {
  7636. svg_vp_w = vb[2];
  7637. svg_vp_h = vb[3];
  7638. } else {
  7639. svg_vp_w = w;
  7640. svg_vp_h = h;
  7641. }
  7642. }
  7643. svg_draw_children(&L, node, m, st, 255, 0);
  7644. return e;
  7645. }
  7646. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7647. *
  7648. * The markup is parsed into a detached subtree of the page document and
  7649. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7650. * bitmap, which then behaves like any decoded image. currentColor is
  7651. * black (an image has no inherited text colour); <text> is not drawn. */
  7652. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7653. {
  7654. unsigned int i = 0;
  7655. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7656. i = 3;
  7657. while (i < len) {
  7658. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7659. d[i] == '\r' || d[i] == '\n'))
  7660. i++;
  7661. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7662. return 1;
  7663. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7664. i += 4;
  7665. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7666. i++;
  7667. i += 3;
  7668. continue;
  7669. }
  7670. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7671. while (i < len && d[i] != '>')
  7672. i++;
  7673. i++;
  7674. continue;
  7675. }
  7676. return 0;
  7677. }
  7678. return 0;
  7679. }
  7680. static int svg_len_attr(unsigned int node, const char *name)
  7681. {
  7682. const char *v = br_find_attr(&doc, node, name);
  7683. int n = 0, any = 0;
  7684. if (!v)
  7685. return 0;
  7686. while (*v == ' ')
  7687. v++;
  7688. while (*v >= '0' && *v <= '9') {
  7689. n = n * 10 + (*v++ - '0');
  7690. any = 1;
  7691. }
  7692. if (*v == '.')
  7693. while (*++v >= '0' && *v <= '9')
  7694. ;
  7695. if (!any || *v == '%')
  7696. return 0;
  7697. return n;
  7698. }
  7699. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7700. struct br_image *bi, int box_w, int box_h)
  7701. {
  7702. unsigned int holder, svg = 0, c, need, i;
  7703. struct br_style base = base_style(), st;
  7704. struct svgr_layer L;
  7705. double vb[4], m[6];
  7706. int w, h, have_vb, nat_w, nat_h;
  7707. holder = br_create_element(&doc, "div", 3);
  7708. if (!holder) {
  7709. s_copy(bi->err, "page is full", sizeof(bi->err));
  7710. return -1;
  7711. }
  7712. holder--;
  7713. br_set_inner_html(&doc, holder, (const char *)data, len);
  7714. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7715. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7716. doc.nodes[c].tag == BR_TAG_SVG) {
  7717. svg = c;
  7718. break;
  7719. }
  7720. if (!svg) {
  7721. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7722. return -1;
  7723. }
  7724. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7725. w = svg_len_attr(svg, "width");
  7726. h = svg_len_attr(svg, "height");
  7727. if (box_w > 0 && box_h > 0) {
  7728. w = box_w;
  7729. h = box_h;
  7730. } else if (!w && !h) {
  7731. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7732. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7733. } else if (!w) {
  7734. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7735. } else if (!h) {
  7736. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7737. }
  7738. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7739. * so CSS scaling stays crisp. */
  7740. nat_w = w;
  7741. nat_h = h;
  7742. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7743. w *= 2;
  7744. h *= 2;
  7745. }
  7746. if (w > BR_IMG_LAYOUT_W) {
  7747. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7748. w = BR_IMG_LAYOUT_W;
  7749. }
  7750. if (h > 2048)
  7751. h = 2048;
  7752. if (w < 1)
  7753. w = 1;
  7754. if (h < 1)
  7755. h = 1;
  7756. need = (unsigned int)w * (unsigned int)h;
  7757. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7758. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7759. return -1;
  7760. }
  7761. if (!svg_geom_buf) {
  7762. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7763. if (!svg_geom_buf) {
  7764. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7765. return -1;
  7766. }
  7767. }
  7768. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7769. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7770. L.a = (unsigned char *)calloc(need, 1);
  7771. if (!L.px || !L.a) {
  7772. free(L.px);
  7773. free(L.a);
  7774. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7775. return -1;
  7776. }
  7777. for (i = 0; i < need; i++)
  7778. L.px[i] = 0xFFFF;
  7779. L.w = w;
  7780. L.h = h;
  7781. base.color = 0x0000;
  7782. br_style_for(&doc, svg, &base, &st);
  7783. svg_root_matrix(svg, w, h, m);
  7784. svg_vp_w = have_vb ? vb[2] : w;
  7785. svg_vp_h = have_vb ? vb[3] : h;
  7786. svg_draw_children(&L, svg, m, &st, 255, 0);
  7787. bi->native_w = nat_w;
  7788. bi->native_h = nat_h;
  7789. bi->img.format = 0;
  7790. bi->img.w = (unsigned int)w;
  7791. bi->img.h = (unsigned int)h;
  7792. bi->img.px = L.px;
  7793. bi->img.alpha = L.a;
  7794. bi->img.flags = 0;
  7795. bi->state = 1;
  7796. image_pixels += need;
  7797. return 0;
  7798. }
  7799. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  7800. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  7801. int *out_w, int *out_h)
  7802. {
  7803. double vb[4];
  7804. int has_vb = svg_viewbox4(node, vb);
  7805. double aw = svg_attr_num(node, "width", -1, cw);
  7806. double ah = svg_attr_num(node, "height", -1, 0);
  7807. int w, h;
  7808. if (st->width_kind)
  7809. w = cw;
  7810. else if (aw > 0)
  7811. w = (int)(aw + 0.5);
  7812. else if (st->height_kind == 1 && has_vb)
  7813. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  7814. else if (ah > 0 && has_vb)
  7815. w = (int)(ah * vb[2] / vb[3] + 0.5);
  7816. else if (has_vb)
  7817. w = cw;
  7818. else
  7819. w = 300;
  7820. if (st->max_width_kind == 1 && w > st->max_width)
  7821. w = st->max_width;
  7822. if (w > cw && cw > 0 && !(aw > 0))
  7823. w = cw;
  7824. if (w < 1)
  7825. w = 1;
  7826. if (w > 2000)
  7827. w = 2000;
  7828. if (st->height_kind == 1)
  7829. h = st->height;
  7830. else if (ah > 0)
  7831. h = (int)(ah + 0.5);
  7832. else if (has_vb)
  7833. h = (int)(w * vb[3] / vb[2] + 0.5);
  7834. else
  7835. h = 150;
  7836. if (h < 1)
  7837. h = 1;
  7838. if (h > 1400)
  7839. h = 1400;
  7840. *out_w = w;
  7841. *out_h = h;
  7842. }
  7843. static void svg_paint_box(struct ngui *ui, unsigned int node,
  7844. const struct br_style *st, int x, int y, int w, int h)
  7845. {
  7846. struct svg_cache_ent *e;
  7847. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  7848. int cx0, cy0, cx1, cy1, px, py;
  7849. double m[6];
  7850. if (ui->nclip > 0)
  7851. clip = ui->clip[ui->nclip - 1];
  7852. cx0 = r.x > clip.x ? r.x : clip.x;
  7853. cy0 = r.y > clip.y ? r.y : clip.y;
  7854. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  7855. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  7856. if (cx0 >= cx1 || cy0 >= cy1)
  7857. return;
  7858. e = svg_layer(node, w, h, st);
  7859. if (e) {
  7860. for (py = cy0; py < cy1; py++) {
  7861. unsigned int srow = (unsigned int)(py - y) *
  7862. (unsigned int)w;
  7863. unsigned short *dst = ui->px + py * ui->w;
  7864. for (px = cx0; px < cx1; px++) {
  7865. unsigned int si = srow + (unsigned int)(px - x);
  7866. unsigned int a = e->a[si];
  7867. if (!a)
  7868. continue;
  7869. dst[px] = a >= 255 ? e->px[si] :
  7870. blend_rgb565(dst[px], e->px[si], a);
  7871. }
  7872. }
  7873. }
  7874. svg_root_matrix(node, w, h, m);
  7875. ngui_push_clip(ui, r);
  7876. svg_draw_text(ui, node, m, st, x, y, 0);
  7877. ngui_pop_clip(ui);
  7878. }
  7879. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  7880. * keep using add_image_run(); this covers the CSS `position:absolute;
  7881. * width:100%` poster pattern used by news sites. */
  7882. static void image_block_size(unsigned int node, const struct br_style *st,
  7883. int cbw, int *out_w, int *out_h)
  7884. {
  7885. struct br_node *nd = &doc.nodes[node];
  7886. int idx = nd->img_index;
  7887. int iw = 0, ih = 0, w, h, aw, ah;
  7888. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7889. iw = (int)images[idx].img.w;
  7890. ih = (int)images[idx].img.h;
  7891. if (iw <= 0 || ih <= 0) {
  7892. iw = (int)images[idx].native_w;
  7893. ih = (int)images[idx].native_h;
  7894. }
  7895. }
  7896. if (st->width_kind)
  7897. w = style_width_px(st, cbw);
  7898. else if (nd->width_attr)
  7899. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  7900. (int)nd->width_attr;
  7901. else if (nd->height_attr && !nd->height_pct && iw && ih)
  7902. w = iw * (int)nd->height_attr / ih;
  7903. else if (iw)
  7904. w = iw;
  7905. else
  7906. w = 64;
  7907. /* max-width/min-width against the containing block: Tailwind's
  7908. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  7909. * 300x300 thumbnail to its 75 px avatar box. */
  7910. if (st->max_width_kind) {
  7911. int mw = st->max_width_kind == 3 ?
  7912. cbw * st->max_width_calc_pct / 100 +
  7913. st->max_width_calc_px :
  7914. st->max_width_kind == 2 ?
  7915. cbw * (int)st->max_width / 100 : (int)st->max_width;
  7916. if (mw > 0 && w > mw)
  7917. w = mw;
  7918. }
  7919. if (st->min_width_kind) {
  7920. int mn = st->min_width_kind == 3 ?
  7921. cbw * st->min_width_calc_pct / 100 +
  7922. st->min_width_calc_px :
  7923. st->min_width_kind == 2 ?
  7924. cbw * (int)st->min_width / 100 : (int)st->min_width;
  7925. if (mn > w)
  7926. w = mn;
  7927. }
  7928. if (w < 8)
  7929. w = 8;
  7930. if (cbw > 0 && w > cbw)
  7931. w = cbw;
  7932. /* Without a CSS height the attributes (or the bitmap) only give the
  7933. * aspect ratio: a width clamped by max-width scales the height too,
  7934. * instead of letterboxing the image into its attribute height. */
  7935. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  7936. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  7937. if (st->height_kind)
  7938. h = style_height_px(st, cbw);
  7939. else if (aw > 0 && ah > 0)
  7940. h = w * ah / aw;
  7941. else if (nd->height_attr)
  7942. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  7943. (int)nd->height_attr;
  7944. else
  7945. h = 64;
  7946. if (h < 8)
  7947. h = 8;
  7948. *out_w = w;
  7949. *out_h = h;
  7950. }
  7951. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  7952. int dw, int dh)
  7953. {
  7954. int idx = doc.nodes[node].img_index;
  7955. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7956. struct img_image *src = image_display_get(&images[idx], dw, dh);
  7957. struct img_blit b;
  7958. if (!src)
  7959. src = &images[idx].img;
  7960. b.dst = l->ui->px;
  7961. b.dst_w = l->ui->w;
  7962. b.dst_h = l->ui->h;
  7963. b.clip_x = page_rect.x;
  7964. b.clip_y = page_rect.y;
  7965. b.clip_w = page_rect.w - 12;
  7966. b.clip_h = page_rect.h;
  7967. b.x = x;
  7968. b.y = y;
  7969. b.scale = ((unsigned int)dw << 16) / src->w;
  7970. b.bg = ui.theme.bg;
  7971. b.bg2 = ui.theme.bg;
  7972. b.dst_a = 0;
  7973. /* OVER_DST is only needed for an alpha source; an opaque one can
  7974. * take img_draw's 1:1 copy path. */
  7975. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  7976. img_draw(src, &b);
  7977. } else if (l->draw) {
  7978. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  7979. 0xD69A);
  7980. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  7981. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  7982. }
  7983. }
  7984. static void layout_block(struct lay *l, unsigned int node,
  7985. const struct br_style *st, int depth,
  7986. unsigned short link)
  7987. {
  7988. int old_left = l->left, old_right = l->right, old_align = l->align;
  7989. int parent_cb_h = l->cb_h;
  7990. int saved_parent_top = l->parent_top;
  7991. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  7992. int saved_cb_top = l->cb_top;
  7993. int top, l0, r0;
  7994. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  7995. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  7996. int deco_w, deco_h, content_w, content_h, box_h;
  7997. int img_dh = 0;
  7998. int definite_w = 0;
  7999. int normal_top = 0;
  8000. int rel_dx = 0, rel_dy = 0;
  8001. int clip_pushed = 0;
  8002. struct ngui_rect clip_rect;
  8003. /* A DOM level costs about two depth units (layout_block ->
  8004. * layout_children), so 48 covers a ~24-level page. Real news pages
  8005. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  8006. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  8007. return;
  8008. flow_y = l->y;
  8009. flow_left = l->left;
  8010. flow_right = l->right;
  8011. positioned = st->pos == 1 || st->pos == 2;
  8012. relative = st->pos == 3;
  8013. sticky = st->pos == 4;
  8014. shifted = relative || sticky || st->transform_set;
  8015. if (positioned) {
  8016. int def_w = st->width_kind == 1 ? st->width : -1;
  8017. if (st->pos == 2) {
  8018. int avail_w = page_rect.w - 12;
  8019. if (st->right_set && def_w >= 0)
  8020. l->left = page_rect.x + avail_w - st->right -
  8021. def_w;
  8022. else
  8023. l->left = page_rect.x +
  8024. (st->left_set ? st->left : 0);
  8025. l->right = def_w >= 0 ? l->left + def_w :
  8026. page_rect.x + avail_w;
  8027. if (st->bottom_set && st->height_kind)
  8028. l->y = page_rect.y + page_rect.h -
  8029. st->bottom -
  8030. style_height_px(st, page_rect.w);
  8031. else
  8032. l->y = page_rect.y +
  8033. (st->top_set ? st->top : 0);
  8034. } else {
  8035. int left = flow_left + (st->left_set ? st->left : 0);
  8036. unsigned int parent = doc.nodes[node].parent;
  8037. if (st->right_set && def_w >= 0)
  8038. left = flow_right - st->right - def_w;
  8039. l->left = left;
  8040. l->right = def_w >= 0 ? left + def_w :
  8041. flow_right +
  8042. (st->left_set ? st->left : 0);
  8043. l->y = flow_y + (st->top_set ? st->top : 0);
  8044. if (st->bottom_set && st->height_kind &&
  8045. parent < BR_MAX_NODES && block_h[parent] > 0)
  8046. l->y = flow_y + block_h[parent] - st->bottom -
  8047. style_height_px(st, old_right - old_left);
  8048. }
  8049. /* `left: 100%` parks a box (Docusaurus' "Skip to main
  8050. * content" link) past the containing block's right edge
  8051. * until it is focused. An auto width then has no room: it
  8052. * used to collapse to 8 px and wrap one word per line into a
  8053. * tall column painted over the page. Lay it out at the
  8054. * containing block's width so it stays one line and
  8055. * overflows (off-screen) like in a real browser. */
  8056. if (def_w < 0 && l->right - l->left < 8) {
  8057. int avail = st->pos == 2 ? page_rect.w - 12 :
  8058. flow_right - flow_left;
  8059. l->right = l->left + (avail > 8 ? avail : 8);
  8060. }
  8061. old_left = l->left;
  8062. old_right = l->right;
  8063. } else if (relative) {
  8064. rel_dx = st->left_set ? st->left :
  8065. (st->right_set ? -st->right : 0);
  8066. rel_dy = st->top_set ? st->top :
  8067. (st->bottom_set ? -st->bottom : 0);
  8068. }
  8069. if (st->transform_set) {
  8070. rel_dx += st->tx;
  8071. rel_dy += st->ty;
  8072. }
  8073. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  8074. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  8075. doc.nodes[node].tag == BR_TAG_SELECT ||
  8076. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  8077. !button_has_elements(node)) {
  8078. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  8079. s_eq(br_type(&doc, node), "hidden"))
  8080. return;
  8081. /* Reached as a block-level box (a flex item): the control
  8082. * fills the box the caller assigned, and its line is flushed
  8083. * here; flex layout resets the run list for the next item, so
  8084. * a queued run would never be drawn. */
  8085. form_fill_line = 1;
  8086. add_form_run(l, node, st, link);
  8087. form_fill_line = 0;
  8088. flush_line(l);
  8089. return;
  8090. }
  8091. flush_line(l);
  8092. cbw = old_right - old_left;
  8093. if (cbw < 8)
  8094. cbw = 8;
  8095. l->y += mp_px(st, 0, cbw);
  8096. top = l->y;
  8097. ml = mp_px(st, 3, cbw);
  8098. mr = mp_px(st, 1, cbw);
  8099. bl = st->border_w[3];
  8100. br = st->border_w[1];
  8101. pl = mp_px(st, 7, cbw);
  8102. pr = mp_px(st, 5, cbw);
  8103. bt = st->border_w[0];
  8104. bb = st->border_w[2];
  8105. pt = mp_px(st, 4, cbw);
  8106. pb = mp_px(st, 6, cbw);
  8107. deco_w = bl + br + pl + pr;
  8108. deco_h = bt + bb + pt + pb;
  8109. if (st->width_kind) {
  8110. int w;
  8111. if (st->width_kind == 3)
  8112. w = cbw * st->width_calc_pct / 100 +
  8113. st->width_calc_px;
  8114. else
  8115. w = css_size(st->width_kind, st->width, cbw);
  8116. if (w < 0)
  8117. w = 0;
  8118. content_w = st->box_sizing ? w - deco_w : w;
  8119. definite_w = 1;
  8120. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  8121. doc.nodes[node].tag == BR_TAG_TD ||
  8122. doc.nodes[node].tag == BR_TAG_TH) &&
  8123. doc.nodes[node].width_attr) {
  8124. /* Legacy table/cell width attributes: percentages resolve
  8125. * against the containing block, bare numbers are pixels. */
  8126. int w = doc.nodes[node].width_pct ?
  8127. cbw * doc.nodes[node].width_attr / 100 :
  8128. doc.nodes[node].width_attr;
  8129. if (w < 0)
  8130. w = 0;
  8131. content_w = st->box_sizing ? w - deco_w : w;
  8132. definite_w = 1;
  8133. } else {
  8134. content_w = cbw - ml - mr - deco_w;
  8135. }
  8136. if (content_w < 0)
  8137. content_w = 0;
  8138. if (st->max_width_kind) {
  8139. int mw = st->max_width_kind == 3 ?
  8140. cbw * st->max_width_calc_pct / 100 +
  8141. st->max_width_calc_px :
  8142. css_size(st->max_width_kind, st->max_width, cbw);
  8143. int max_box = st->box_sizing ? mw : mw + deco_w;
  8144. /* A clamped auto width is used as the width, so auto
  8145. * margins share the rest (Google's 688 px search box). */
  8146. if (content_w + deco_w > max_box) {
  8147. content_w = max_box - deco_w;
  8148. definite_w = 1;
  8149. }
  8150. }
  8151. if (st->min_width_kind) {
  8152. int mw = st->min_width_kind == 3 ?
  8153. cbw * st->min_width_calc_pct / 100 +
  8154. st->min_width_calc_px :
  8155. css_size(st->min_width_kind, st->min_width, cbw);
  8156. int min_box = st->box_sizing ? mw : mw + deco_w;
  8157. if (content_w + deco_w < min_box) {
  8158. content_w = min_box - deco_w;
  8159. definite_w = 1;
  8160. }
  8161. }
  8162. if (content_w < 8)
  8163. content_w = 8;
  8164. if (definite_w) {
  8165. int free_w = cbw - ml - mr - deco_w - content_w;
  8166. if (free_w < 0)
  8167. free_w = 0;
  8168. if (st->ml_auto && st->mr_auto) {
  8169. ml = free_w / 2;
  8170. mr = free_w - ml;
  8171. } else if (st->ml_auto) {
  8172. ml = free_w;
  8173. } else if (st->mr_auto) {
  8174. mr = free_w;
  8175. }
  8176. }
  8177. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8178. int iw, ih;
  8179. image_block_size(node, st, cbw, &iw, &ih);
  8180. content_w = iw;
  8181. img_dh = ih;
  8182. }
  8183. l0 = old_left + ml;
  8184. r0 = l0 + deco_w + content_w;
  8185. if (r0 < l0 + 8)
  8186. r0 = l0 + 8;
  8187. normal_top = top;
  8188. if (sticky) {
  8189. if (st->top_set) {
  8190. int stick = page_rect.y + 4 + st->top;
  8191. if (normal_top < stick)
  8192. rel_dy += stick - normal_top;
  8193. } else if (st->bottom_set && block_h[node]) {
  8194. int stick = page_rect.y + page_rect.h - st->bottom -
  8195. block_h[node];
  8196. if (normal_top > stick)
  8197. rel_dy += stick - normal_top;
  8198. }
  8199. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  8200. block_h[doc.nodes[node].parent]) {
  8201. unsigned int p = doc.nodes[node].parent;
  8202. int ptop = l->parent_top;
  8203. int pbottom = ptop + block_h[p];
  8204. int eh = block_h[node];
  8205. int moved_top = normal_top + rel_dy;
  8206. int moved_bottom = moved_top + eh;
  8207. if (moved_bottom > pbottom)
  8208. rel_dy -= moved_bottom - pbottom;
  8209. moved_top = normal_top + rel_dy;
  8210. if (moved_top < ptop)
  8211. rel_dy += ptop - moved_top;
  8212. }
  8213. }
  8214. if (shifted && l->draw) {
  8215. top += rel_dy;
  8216. l0 += rel_dx;
  8217. r0 += rel_dx;
  8218. }
  8219. l->parent_top = top;
  8220. if (st->pos != 0) {
  8221. /* Positioned boxes establish the containing block for their
  8222. * absolutely positioned descendants. */
  8223. l->cb_left = l0;
  8224. l->cb_right = r0;
  8225. l->cb_top = top;
  8226. }
  8227. if (l->draw && block_h[node] &&
  8228. top < page_rect.y + page_rect.h &&
  8229. top + block_h[node] > page_rect.y) {
  8230. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  8231. int rtl = css_radius(st, 0, box.w, box.h);
  8232. int rtr = css_radius(st, 1, box.w, box.h);
  8233. int rbr = css_radius(st, 2, box.w, box.h);
  8234. int rbl = css_radius(st, 3, box.w, box.h);
  8235. if (st->transform_scale) {
  8236. if (st->has_bg)
  8237. fill_transformed_rect(l->ui, box, st->bg, st);
  8238. } else if (rtl || rtr || rbr || rbl) {
  8239. if (st->has_bg) {
  8240. int bw = st->border_w[0];
  8241. if (bw > 0 && !st->border_t[0] &&
  8242. st->border_c[0] != st->bg &&
  8243. box.w > bw * 2 && box.h > bw * 2) {
  8244. struct ngui_rect inner = {
  8245. box.x + bw, box.y + bw,
  8246. box.w - bw * 2, box.h - bw * 2
  8247. };
  8248. int itl = rtl > bw ? rtl - bw : 0;
  8249. int itr = rtr > bw ? rtr - bw : 0;
  8250. int ibr = rbr > bw ? rbr - bw : 0;
  8251. int ibl = rbl > bw ? rbl - bw : 0;
  8252. ngui_fill_round_rect(l->ui, box, rtl,
  8253. rtr, rbr, rbl,
  8254. st->border_c[0]);
  8255. ngui_fill_round_rect(l->ui, inner,
  8256. itl, itr, ibr,
  8257. ibl, st->bg);
  8258. } else {
  8259. ngui_fill_round_rect(l->ui, box, rtl,
  8260. rtr, rbr, rbl,
  8261. st->bg);
  8262. }
  8263. } else if (st->border_w[0] && !st->border_t[0]) {
  8264. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  8265. rbl, st->border_w[0],
  8266. st->border_c[0]);
  8267. }
  8268. /* Rounded boxes paint their background image too
  8269. * (app icons are rounded squares), kept inside the
  8270. * corner arcs. */
  8271. if (st->bg_image)
  8272. draw_bg_image_round(l, box, node, st, rtl, rtr,
  8273. rbr, rbl);
  8274. } else {
  8275. if (st->has_bg)
  8276. ngui_fill_rect(l->ui, box, st->bg);
  8277. if (st->bg_image)
  8278. draw_bg_image(l, box, node, st);
  8279. if (st->border_w[0] || st->border_w[1] ||
  8280. st->border_w[2] || st->border_w[3])
  8281. draw_border_box(l->ui, box, st);
  8282. }
  8283. }
  8284. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  8285. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  8286. content_w, img_dh);
  8287. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  8288. l->ui && l->ui->nclip < 4) {
  8289. clip_rect.x = l0 + bl;
  8290. clip_rect.y = top + bt;
  8291. clip_rect.w = (r0 - l0) - bl - br;
  8292. clip_rect.h = (int)block_h[node] - bt - bb;
  8293. if (clip_rect.w > 0 && clip_rect.h > 0) {
  8294. ngui_push_clip(l->ui, clip_rect);
  8295. clip_pushed = 1;
  8296. }
  8297. }
  8298. l->left = l0 + bl + pl;
  8299. l->right = l->left + content_w;
  8300. if (l->right < l->left + 8)
  8301. l->right = l->left + 8;
  8302. l->align = st->align;
  8303. l->line_left = l->left;
  8304. l->line_right = l->right;
  8305. l->y = top + bt + pt;
  8306. if (doc.nodes[node].tag == BR_TAG_HR) {
  8307. if (l->draw)
  8308. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  8309. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  8310. l->y += 8;
  8311. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  8312. int vw = l->right - l->left;
  8313. int vh;
  8314. if (doc.nodes[node].width_pct)
  8315. vw = vw * doc.nodes[node].width_attr / 100;
  8316. else if (doc.nodes[node].width_attr)
  8317. vw = doc.nodes[node].width_attr;
  8318. if (vw > l->right - l->left)
  8319. vw = l->right - l->left;
  8320. if (vw < 8)
  8321. vw = 8;
  8322. vh = vw * 9 / 16;
  8323. if (vh > 240)
  8324. vh = 240;
  8325. if (vh < 80)
  8326. vh = 80;
  8327. if (l->draw) {
  8328. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  8329. vw, vh}, 0xD69A);
  8330. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  8331. vw, vh}, 0x8410);
  8332. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  8333. 0x4208);
  8334. }
  8335. l->y += vh + 4;
  8336. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  8337. int dw, dh, cw = l->right - l->left;
  8338. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  8339. if (l->draw && l->y < page_rect.y + page_rect.h &&
  8340. l->y + dh > page_rect.y)
  8341. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  8342. l->y += dh;
  8343. } else {
  8344. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  8345. !st->no_bullet) {
  8346. char *m = li_marker[node];
  8347. if (!m[0]) {
  8348. unsigned int parent = doc.nodes[node].parent;
  8349. int style = st->list_style;
  8350. int idx = parent ? list_index(parent, node) : 1;
  8351. if (style == BR_LIST_AUTO)
  8352. style = (parent &&
  8353. doc.nodes[parent].tag ==
  8354. BR_TAG_OL) ?
  8355. BR_LIST_DECIMAL : BR_LIST_DISC;
  8356. list_marker_text(m, sizeof(li_marker[node]),
  8357. style, idx);
  8358. }
  8359. if (l->draw && m[0]) {
  8360. int mw = (int)ngui_text_width_ui(l->ui, m);
  8361. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  8362. st->color);
  8363. }
  8364. }
  8365. /* This box's definite content height, for its children's
  8366. * percentage heights. */
  8367. if (doc.nodes[node].tag == BR_TAG_HTML ||
  8368. doc.nodes[node].tag == BR_TAG_BODY)
  8369. l->cb_h = layout_view_h;
  8370. else if (st->height_kind == 1)
  8371. l->cb_h = (int)st->height -
  8372. (st->box_sizing ? deco_h : 0);
  8373. else if (st->height_kind == 2 && parent_cb_h > 0)
  8374. l->cb_h = parent_cb_h * (int)st->height / 100 -
  8375. (st->box_sizing ? deco_h : 0);
  8376. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  8377. l->cb_h = content_w * (int)st->aspect_h /
  8378. (int)st->aspect_w;
  8379. else
  8380. l->cb_h = 0;
  8381. if (l->cb_h < 0)
  8382. l->cb_h = 0;
  8383. if (doc.nodes[node].tag == BR_TAG_TR)
  8384. layout_table_row(l, node, st, depth + 1, link);
  8385. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  8386. table_has_rowspan(node))
  8387. layout_table(l, node, st, depth + 1, link);
  8388. else if (st->grid_auto)
  8389. layout_grid_auto(l, node, st, depth + 1, link);
  8390. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  8391. st->grid_gap > 0)
  8392. layout_grid_children(l, node, st, depth + 1, link);
  8393. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  8394. flex_wants_row(node, st))
  8395. layout_flex_children(l, node, st, depth + 1, link);
  8396. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  8397. st->align_items == 1) {
  8398. /* align-items: center in a column: the items' lines
  8399. * (an app card's icon and label) are centred; a child
  8400. * with its own text-align keeps it. */
  8401. struct br_style cst = *st;
  8402. cst.align = BR_ALIGN_CENTER;
  8403. l->align = BR_ALIGN_CENTER;
  8404. layout_children(l, node, &cst, depth + 1, link);
  8405. } else
  8406. layout_children(l, node, st, depth + 1, link);
  8407. l->cb_h = parent_cb_h;
  8408. }
  8409. flush_line(l);
  8410. if (clip_pushed)
  8411. ngui_pop_clip(l->ui);
  8412. if (l->float_active) {
  8413. if (l->y < l->float_bottom)
  8414. l->y = l->float_bottom;
  8415. l->float_active = 0;
  8416. }
  8417. if (doc.nodes[node].tag == BR_TAG_IMG) {
  8418. content_h = img_dh;
  8419. } else if (st->height_kind == 2 &&
  8420. doc.nodes[node].tag != BR_TAG_HTML &&
  8421. doc.nodes[node].tag != BR_TAG_BODY) {
  8422. /* A percentage of the containing block's definite height, or
  8423. * auto when it has none (it used to resolve against the
  8424. * width). The result is a minimum: without scrollable inner
  8425. * boxes, an app shell's height:100%; overflow:hidden column
  8426. * would otherwise clip everything past the first screen. */
  8427. int auto_h = l->y - (top + bt + pt);
  8428. content_h = parent_cb_h > 0 ?
  8429. parent_cb_h * (int)st->height / 100 -
  8430. (st->box_sizing ? deco_h : 0) : 0;
  8431. if (content_h < auto_h)
  8432. content_h = auto_h;
  8433. } else if (st->height_kind &&
  8434. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8435. doc.nodes[node].tag == BR_TAG_BODY) &&
  8436. st->height_kind == 2)) {
  8437. content_h = style_height_px(st, cbw);
  8438. if (st->box_sizing)
  8439. content_h -= deco_h;
  8440. } else {
  8441. /* Percentage heights on html/body resolve against the
  8442. * viewport, but their content still defines the document
  8443. * scroll height. Treating them as auto avoids collapsing
  8444. * the measured page to the containing block width. */
  8445. content_h = l->y - (top + bt + pt);
  8446. /* aspect-ratio: the preferred height of an auto-height box
  8447. * (Tailwind aspect-video image frames); content can still
  8448. * make it taller, as with min-height: auto. */
  8449. if (st->aspect_w && st->aspect_h && content_w > 0) {
  8450. int ah = content_w * (int)st->aspect_h /
  8451. (int)st->aspect_w;
  8452. if (content_h < ah)
  8453. content_h = ah;
  8454. }
  8455. }
  8456. if (content_h < 0)
  8457. content_h = 0;
  8458. if (st->max_height_kind) {
  8459. int mh = st->max_height_kind == 3 ?
  8460. cbw * st->max_height_calc_pct / 100 +
  8461. st->max_height_calc_px :
  8462. css_size(st->max_height_kind, st->max_height, cbw);
  8463. int max_box = st->box_sizing ? mh : mh + deco_h;
  8464. if (content_h + deco_h > max_box)
  8465. content_h = max_box - deco_h;
  8466. }
  8467. if (st->min_height_kind &&
  8468. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8469. doc.nodes[node].tag == BR_TAG_BODY) &&
  8470. st->min_height_kind == 2)) {
  8471. int mh = st->min_height_kind == 3 ?
  8472. cbw * st->min_height_calc_pct / 100 +
  8473. st->min_height_calc_px :
  8474. css_size(st->min_height_kind, st->min_height, cbw);
  8475. int min_box = st->box_sizing ? mh : mh + deco_h;
  8476. if (content_h + deco_h < min_box)
  8477. content_h = min_box - deco_h;
  8478. }
  8479. if (content_h < 0)
  8480. content_h = 0;
  8481. box_h = deco_h + content_h;
  8482. if (box_h < 0)
  8483. box_h = 0;
  8484. l->y = (shifted ? normal_top : top) + box_h;
  8485. if (node < BR_MAX_NODES) {
  8486. layout_boxes[node].x = l0;
  8487. layout_boxes[node].y = top;
  8488. layout_boxes[node].w = r0 - l0;
  8489. layout_boxes[node].h = box_h;
  8490. layout_boxes[node].valid = r0 > l0;
  8491. }
  8492. l->left = old_left;
  8493. l->right = old_right;
  8494. l->align = old_align;
  8495. l->y += mp_px(st, 2, cbw);
  8496. if (!l->draw) {
  8497. if (box_h > 65535)
  8498. box_h = 65535;
  8499. block_h[node] = (unsigned short)box_h;
  8500. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8501. top > 65535 ? 65535 : top);
  8502. }
  8503. if (positioned) {
  8504. l->y = flow_y;
  8505. l->left = flow_left;
  8506. l->right = flow_right;
  8507. }
  8508. l->parent_top = saved_parent_top;
  8509. l->cb_left = saved_cb_left;
  8510. l->cb_right = saved_cb_right;
  8511. l->cb_top = saved_cb_top;
  8512. }
  8513. static int text_node_blank(const struct br_node *nd)
  8514. {
  8515. const char *t = doc.text + nd->text_off;
  8516. unsigned int i;
  8517. for (i = 0; i < nd->text_len; i++)
  8518. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8519. t[i] != '\r')
  8520. return 0;
  8521. return 1;
  8522. }
  8523. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8524. * text/image widths in the subtree, plus padding and margins. This keeps
  8525. * Bootstrap's floated nav items on one line instead of giving each the whole
  8526. * row. */
  8527. static int text_space(char c)
  8528. {
  8529. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8530. }
  8531. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8532. const struct br_style *pst, int depth, int base)
  8533. {
  8534. unsigned int c;
  8535. int line_w = 0, max_w = 0;
  8536. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8537. if (depth > 32)
  8538. return 0;
  8539. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8540. struct br_node *nd = &doc.nodes[c];
  8541. struct br_style cs;
  8542. if (nd->type == BR_NODE_TEXT) {
  8543. const char *t = doc.text + nd->text_off;
  8544. unsigned int tn = nd->text_len;
  8545. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8546. line_w += (int)face_text_width(ui, pst, t, tn);
  8547. } else {
  8548. unsigned int ti = 0;
  8549. int first = 1;
  8550. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8551. int sp = (int)face_text_width(ui, pst, " ", 1);
  8552. while (ti < tn) {
  8553. unsigned int ts;
  8554. while (ti < tn && text_space(t[ti]))
  8555. ti++;
  8556. ts = ti;
  8557. while (ti < tn && !text_space(t[ti]))
  8558. ti++;
  8559. if (ti == ts)
  8560. break;
  8561. if (!first || lead)
  8562. line_w += sp;
  8563. lead = 0;
  8564. line_w += (int)face_text_width(ui, pst,
  8565. t + ts, ti - ts);
  8566. first = 0;
  8567. }
  8568. }
  8569. continue;
  8570. }
  8571. br_style_for(&doc, c, pst, &cs);
  8572. if (cs.display == BR_DISPLAY_NONE)
  8573. continue;
  8574. if (nd->tag == BR_TAG_BR) {
  8575. if (line_w > max_w)
  8576. max_w = line_w;
  8577. line_w = 0;
  8578. continue;
  8579. }
  8580. if (nd->tag == BR_TAG_IMG) {
  8581. /* Measure the image as layout will draw it: a CSS or
  8582. * attribute height keeps the intrinsic aspect ratio, and
  8583. * a CSS width overrides the native pixel width. Bootstrap
  8584. * sizes the Cloudron logo with height:40px only. */
  8585. int idx = nd->img_index;
  8586. int iw = 0, ih = 0;
  8587. if (idx >= 0 && idx < image_count &&
  8588. images[idx].state == 1) {
  8589. iw = (int)images[idx].native_w;
  8590. ih = (int)images[idx].native_h;
  8591. if (iw <= 0 || ih <= 0) {
  8592. iw = (int)images[idx].img.w;
  8593. ih = (int)images[idx].img.h;
  8594. }
  8595. }
  8596. if (cs.width_kind) {
  8597. int ww = style_width_px(&cs, base);
  8598. line_w += ww > 0 ? ww : 64;
  8599. } else if (nd->width_attr) {
  8600. line_w += nd->width_attr;
  8601. } else if (nd->height_attr && iw && ih) {
  8602. line_w += iw * (int)nd->height_attr / ih;
  8603. } else if (cs.height_kind && iw && ih) {
  8604. /* A percentage height needs the parent's
  8605. * definite height (the logo's 2rem box), as in
  8606. * add_image_run(); otherwise it is auto. */
  8607. int hh = cs.height_kind == 1 ?
  8608. style_height_px(&cs, base) :
  8609. cs.height_kind == 2 &&
  8610. pst->height_kind == 1 ?
  8611. (int)pst->height * (int)cs.height / 100 :
  8612. 0;
  8613. line_w += hh > 0 ? iw * hh / ih : iw;
  8614. } else if (iw) {
  8615. line_w += iw;
  8616. } else {
  8617. line_w += 64;
  8618. }
  8619. continue;
  8620. }
  8621. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8622. nd->tag == BR_TAG_TEXTAREA) &&
  8623. !s_eq(br_type(&doc, c), "hidden")) {
  8624. /* Form controls are replaced: CSS width applies even
  8625. * when they are inline (add_form_run's sizes). */
  8626. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8627. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8628. if (s_eq(br_type(&doc, c), "checkbox") ||
  8629. s_eq(br_type(&doc, c), "radio"))
  8630. fw = 16;
  8631. line_w += (fw > 0 ? fw : 120) +
  8632. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8633. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8634. continue;
  8635. }
  8636. if (nd->tag == BR_TAG_SVG) {
  8637. /* A replaced element: its own size, like add_svg_run()
  8638. * (its path children have no width). */
  8639. int sw, sh, sb = cs.width_kind ?
  8640. style_width_px(&cs, base) : base;
  8641. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8642. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8643. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8644. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8645. line_w += sw;
  8646. } else {
  8647. if (line_w > max_w)
  8648. max_w = line_w;
  8649. line_w = 0;
  8650. if (sw > max_w)
  8651. max_w = sw;
  8652. }
  8653. continue;
  8654. }
  8655. {
  8656. int cw = mp_px(&cs, 7, base) +
  8657. mp_px(&cs, 5, base) +
  8658. mp_px(&cs, 3, base) +
  8659. mp_px(&cs, 1, base) +
  8660. cs.border_w[1] + cs.border_w[3];
  8661. /* width/height do not apply to non-replaced inline
  8662. * boxes. The tagesschau home label is an inline span
  8663. * with width:1px for the mobile icon-only header; using
  8664. * that width made the whole subnav collapse to a
  8665. * one-character column. */
  8666. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8667. cw += cs.width_kind == 1 ? cs.width :
  8668. style_width_px(&cs, base);
  8669. else
  8670. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8671. base);
  8672. if (flex_row || cs.float_left ||
  8673. cs.display == BR_DISPLAY_INLINE ||
  8674. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8675. line_w += cw;
  8676. } else {
  8677. if (line_w > max_w)
  8678. max_w = line_w;
  8679. line_w = 0;
  8680. if (cw > max_w)
  8681. max_w = cw;
  8682. }
  8683. }
  8684. if (line_w > 4096 || max_w > 4096)
  8685. break;
  8686. }
  8687. return line_w > max_w ? line_w : max_w;
  8688. }
  8689. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8690. * the main user: .row > .col-md-* with float:left and a percentage width.
  8691. * Each column is laid out with its own left/right edge and the row advances
  8692. * to the tallest column. Returns the first child not consumed. */
  8693. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8694. const struct br_style *pst, int depth,
  8695. unsigned short link)
  8696. {
  8697. unsigned int n = first;
  8698. int row_left = l->left, row_right = l->right;
  8699. int row_top, row_bottom, xl, xr, any = 0;
  8700. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8701. flush_line(l);
  8702. row_top = l->y;
  8703. row_bottom = l->y;
  8704. fl_bottom = row_top;
  8705. xl = row_left;
  8706. xr = row_right;
  8707. while (n) {
  8708. struct br_node *nd = &doc.nodes[n];
  8709. struct br_style cs;
  8710. unsigned short lk = link;
  8711. int colw, right;
  8712. if (nd->type == BR_NODE_TEXT) {
  8713. if (text_node_blank(nd)) {
  8714. n = nd->next;
  8715. continue;
  8716. }
  8717. break;
  8718. }
  8719. br_style_for(&doc, n, pst, &cs);
  8720. if (cs.display == BR_DISPLAY_NONE) {
  8721. n = nd->next;
  8722. continue;
  8723. }
  8724. /* A float blockifies its box: Bootstrap floats inline
  8725. * anchors too (the navbar brand and its text links), and
  8726. * their padding must be honoured. */
  8727. if (!cs.float_left)
  8728. break;
  8729. if (nd->tag == BR_TAG_A && nd->href_off)
  8730. lk = (unsigned short)n;
  8731. right = cs.float_left == 2;
  8732. if (cs.width_kind == 1 || cs.width_kind == 2 ||
  8733. cs.width_kind == 3) {
  8734. /* The column is the margin box: `width` is the
  8735. * content (or, with border-box, the border) box,
  8736. * and layout_block() takes margins, padding and
  8737. * borders back out of the column. A 200px float
  8738. * with margin-right:20px used to get 180px of
  8739. * content. */
  8740. int base = row_right - row_left;
  8741. colw = cs.width_kind == 1 ? (int)cs.width :
  8742. style_width_px(&cs, base);
  8743. colw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8744. if (!cs.box_sizing)
  8745. colw += mp_px(&cs, 7, base) +
  8746. mp_px(&cs, 5, base) +
  8747. cs.border_w[1] + cs.border_w[3];
  8748. } else {
  8749. int base = row_right - row_left;
  8750. /* Shrink-to-fit outer width: borders too (Google's
  8751. * 1px-bordered "Anmelden" pill wrapped otherwise). */
  8752. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8753. mp_px(&cs, 7, base) +
  8754. mp_px(&cs, 5, base) +
  8755. mp_px(&cs, 3, base) +
  8756. mp_px(&cs, 1, base) +
  8757. cs.border_w[1] + cs.border_w[3];
  8758. if (colw < 8)
  8759. colw = 8;
  8760. }
  8761. if (colw < 8)
  8762. colw = 8;
  8763. if (colw > row_right - row_left)
  8764. colw = row_right - row_left;
  8765. /* The float column width is already resolved. */
  8766. cs.width_kind = 0;
  8767. cs.max_width_kind = 0;
  8768. if (right) {
  8769. if (any && xr - colw < xl) {
  8770. row_top = row_bottom;
  8771. row_bottom = row_top;
  8772. xl = row_left;
  8773. xr = row_right;
  8774. }
  8775. if (xr - colw < xl)
  8776. colw = xr - xl;
  8777. if (colw < 8)
  8778. colw = 8;
  8779. l->left = xr - colw;
  8780. if (l->left < row_left)
  8781. l->left = row_left;
  8782. l->right = xr;
  8783. xr = l->left;
  8784. if (xr < fl_right)
  8785. fl_right = xr;
  8786. } else {
  8787. if (any && xl + colw > xr) {
  8788. row_top = row_bottom;
  8789. row_bottom = row_top;
  8790. xl = row_left;
  8791. xr = row_right;
  8792. }
  8793. l->left = xl;
  8794. l->right = xl + colw;
  8795. xl += colw;
  8796. if (xl > fl_left)
  8797. fl_left = xl;
  8798. }
  8799. if (l->right < l->left + 8)
  8800. l->right = l->left + 8;
  8801. l->y = row_top;
  8802. l->line_x = l->left;
  8803. l->run_x = l->left;
  8804. l->line_y = l->y;
  8805. l->line_h = 0;
  8806. l->nruns = 0;
  8807. l->space_pending = 0;
  8808. l->align = cs.align;
  8809. layout_block(l, n, &cs, depth + 1, lk);
  8810. if (l->y > row_bottom)
  8811. row_bottom = l->y;
  8812. if (l->y > fl_bottom)
  8813. fl_bottom = l->y;
  8814. any = 1;
  8815. n = nd->next;
  8816. }
  8817. l->left = row_left;
  8818. l->right = row_right;
  8819. if (n && any) {
  8820. struct br_node *nd = &doc.nodes[n];
  8821. int inline_next = 0;
  8822. if (nd->type == BR_NODE_TEXT) {
  8823. inline_next = 1;
  8824. } else if (nd->type == BR_NODE_ELEM) {
  8825. struct br_style cs;
  8826. br_style_for(&doc, n, pst, &cs);
  8827. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  8828. cs.display != BR_DISPLAY_NONE &&
  8829. !br_tag_is_block(nd->tag);
  8830. }
  8831. if (inline_next) {
  8832. if (l->float_active) {
  8833. if (l->float_left > fl_left)
  8834. fl_left = l->float_left;
  8835. if (l->float_right < fl_right)
  8836. fl_right = l->float_right;
  8837. if (l->float_bottom > fl_bottom)
  8838. fl_bottom = l->float_bottom;
  8839. }
  8840. l->float_active = 1;
  8841. l->float_left = fl_left;
  8842. l->float_right = fl_right;
  8843. l->float_bottom = fl_bottom;
  8844. l->y = row_top;
  8845. } else {
  8846. l->float_active = 0;
  8847. l->y = row_bottom;
  8848. }
  8849. } else {
  8850. l->float_active = 0;
  8851. l->y = row_bottom;
  8852. }
  8853. l->line_x = l->left;
  8854. l->run_x = l->left;
  8855. l->line_left = l->left;
  8856. l->line_right = l->right;
  8857. l->line_y = l->y;
  8858. l->line_h = 0;
  8859. l->nruns = 0;
  8860. l->space_pending = 0;
  8861. return n;
  8862. }
  8863. static int flex_item_width(struct lay *l, unsigned int n,
  8864. const struct br_style *cs, int avail)
  8865. {
  8866. struct br_node *nd = &doc.nodes[n];
  8867. (void)l;
  8868. int w;
  8869. if (cs->width_kind == 2 || cs->width_kind == 3)
  8870. w = style_width_px(cs, avail);
  8871. else if (cs->width_kind == 1)
  8872. w = (int)cs->width;
  8873. else if (nd->tag == BR_TAG_IMG) {
  8874. int idx = nd->img_index;
  8875. if (idx >= 0 && idx < image_count &&
  8876. images[idx].state == 1)
  8877. w = (int)images[idx].img.w;
  8878. else if (nd->width_attr)
  8879. w = (int)nd->width_attr;
  8880. else
  8881. w = 64;
  8882. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8883. nd->tag == BR_TAG_TEXTAREA) {
  8884. /* A control has no content to measure: its default size
  8885. * (a search field in a filter bar). */
  8886. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  8887. } else {
  8888. w = intrinsic_width(l->ui, n, cs, 0, avail);
  8889. }
  8890. /* Explicit widths are content-box sizes; the flex item's outer width
  8891. * must include padding, borders and margins. */
  8892. w += mp_px(cs, 7, avail);
  8893. w += mp_px(cs, 5, avail);
  8894. w += mp_px(cs, 3, avail);
  8895. w += mp_px(cs, 1, avail);
  8896. w += cs->border_w[1] + cs->border_w[3];
  8897. if (w < 24)
  8898. w = 24;
  8899. if (w > avail)
  8900. w = avail;
  8901. return w;
  8902. }
  8903. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8904. int depth);
  8905. /* An inline child of a text-only inline-block: the same test minus the
  8906. * display check (an inline <span> may have padding/background in CSS, but
  8907. * the inline path paints those for spans anyway). */
  8908. static int inline_block_flows_inline(unsigned int node,
  8909. const struct br_style *cs, int depth)
  8910. {
  8911. unsigned int c;
  8912. if (depth > 3 || cs->pos)
  8913. return 0;
  8914. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8915. const struct br_node *nd = &doc.nodes[c];
  8916. struct br_style ch;
  8917. if (nd->type != BR_NODE_ELEM)
  8918. continue;
  8919. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8920. br_tag_is_block(nd->tag))
  8921. return 0;
  8922. br_style_for(&doc, c, cs, &ch);
  8923. if (ch.display == BR_DISPLAY_NONE)
  8924. continue;
  8925. if (ch.display != BR_DISPLAY_INLINE ||
  8926. !inline_block_flows_inline(c, &ch, depth + 1))
  8927. return 0;
  8928. }
  8929. return 1;
  8930. }
  8931. /* An inline-block that is only text in a line (a <time> in a byline, a
  8932. * label) with no box of its own -- no size, background, border or padding
  8933. * -- lays out exactly like an inline element, so it stays in the text line
  8934. * instead of ending it. Boxes with any of those keep the row path. */
  8935. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8936. int depth)
  8937. {
  8938. unsigned int c;
  8939. int i;
  8940. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  8941. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  8942. cs->pos || depth > 3)
  8943. return 0;
  8944. for (i = 0; i < 4; i++)
  8945. if (cs->border_w[i])
  8946. return 0;
  8947. for (i = 4; i < 8; i++)
  8948. if (mp_px(cs, i, 0) > 0)
  8949. return 0;
  8950. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8951. const struct br_node *nd = &doc.nodes[c];
  8952. struct br_style ch;
  8953. if (nd->type != BR_NODE_ELEM)
  8954. continue;
  8955. if (nd->tag == BR_TAG_SVG) {
  8956. /* An icon box (Docusaurus' admonition heading:
  8957. * `<span inline-block><svg/></span>Note`): the SVG
  8958. * is an inline replaced run, so the box can stay in
  8959. * the text line. */
  8960. br_style_for(&doc, c, cs, &ch);
  8961. if (ch.display == BR_DISPLAY_NONE ||
  8962. ch.display == BR_DISPLAY_INLINE ||
  8963. ch.display == BR_DISPLAY_INLINE_BLOCK)
  8964. continue;
  8965. return 0;
  8966. }
  8967. if (nd->tag == BR_TAG_IMG || br_tag_is_block(nd->tag))
  8968. return 0;
  8969. br_style_for(&doc, c, cs, &ch);
  8970. if (ch.display == BR_DISPLAY_NONE)
  8971. continue;
  8972. if (ch.display != BR_DISPLAY_INLINE ||
  8973. !inline_block_flows_inline(c, &ch, depth + 1))
  8974. return 0;
  8975. }
  8976. return 1;
  8977. }
  8978. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  8979. * on one line, not one full-width block each. Place intrinsic widths from
  8980. * left to right and wrap when the row is full. */
  8981. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8982. const struct br_style *pst, int depth,
  8983. unsigned short link)
  8984. {
  8985. unsigned int n = first;
  8986. int row_left = l->left, row_right = l->right;
  8987. int avail = row_right - row_left;
  8988. int x = row_left, y = l->y, row_h = 0, any = 0;
  8989. /* Each box sets l->align from its own style; the text after the row
  8990. * must keep the container's (a centred .fa-fw icon centred the menu
  8991. * label that followed it). */
  8992. unsigned char row_align = l->align;
  8993. flush_line(l);
  8994. y = l->y;
  8995. while (n) {
  8996. struct br_node *nd = &doc.nodes[n];
  8997. struct br_style cs;
  8998. unsigned short lk = link;
  8999. int colw, h;
  9000. if (nd->type == BR_NODE_TEXT) {
  9001. if (!text_node_blank(nd))
  9002. break;
  9003. if (any)
  9004. x += 4;
  9005. n = nd->next;
  9006. continue;
  9007. }
  9008. br_style_for(&doc, n, pst, &cs);
  9009. if (cs.display == BR_DISPLAY_NONE) {
  9010. n = nd->next;
  9011. continue;
  9012. }
  9013. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  9014. break;
  9015. if (nd->tag == BR_TAG_A && nd->href_off)
  9016. lk = (unsigned short)n;
  9017. colw = flex_item_width(l, n, &cs, avail);
  9018. /* A few pixels of slack keep a single long token (boot.S)
  9019. * from wrapping at the exact content width. */
  9020. colw += 8;
  9021. if (colw > avail)
  9022. colw = avail;
  9023. cs.width_kind = 0;
  9024. cs.max_width_kind = 0;
  9025. if (any && x + colw > row_right) {
  9026. y += row_h + 2;
  9027. x = row_left;
  9028. row_h = 0;
  9029. any = 0;
  9030. }
  9031. if (any && x > row_left)
  9032. x += 4;
  9033. l->left = x;
  9034. l->right = x + colw;
  9035. if (l->right < l->left + 8)
  9036. l->right = l->left + 8;
  9037. l->y = y;
  9038. l->line_x = l->left;
  9039. l->run_x = l->left;
  9040. l->line_y = l->y;
  9041. l->line_h = 0;
  9042. l->nruns = 0;
  9043. l->space_pending = 0;
  9044. l->align = cs.align;
  9045. layout_block(l, n, &cs, depth + 1, lk);
  9046. h = l->y - y;
  9047. if (h > row_h)
  9048. row_h = h;
  9049. x += colw;
  9050. any = 1;
  9051. n = nd->next;
  9052. }
  9053. if (any)
  9054. y += row_h;
  9055. l->left = row_left;
  9056. l->right = row_right;
  9057. l->align = row_align;
  9058. l->y = y;
  9059. l->line_x = l->left;
  9060. l->run_x = l->left;
  9061. l->line_y = l->y;
  9062. l->line_h = 0;
  9063. l->nruns = 0;
  9064. l->space_pending = 0;
  9065. return n;
  9066. }
  9067. struct flex_item {
  9068. unsigned int node;
  9069. unsigned short link;
  9070. int w;
  9071. };
  9072. /* An item's min-width/max-width as outer (margin-box) widths in the flex
  9073. * row, or -1 when unset. Percentages and calc() resolve against the
  9074. * container width. */
  9075. static int flex_limit_w(const struct br_style *cs, int which_max, int avail)
  9076. {
  9077. unsigned char kind = which_max ? cs->max_width_kind :
  9078. cs->min_width_kind;
  9079. int w;
  9080. if (kind == 3)
  9081. w = which_max ?
  9082. avail * cs->max_width_calc_pct / 100 +
  9083. cs->max_width_calc_px :
  9084. avail * cs->min_width_calc_pct / 100 +
  9085. cs->min_width_calc_px;
  9086. else
  9087. w = css_size(kind, which_max ? cs->max_width : cs->min_width,
  9088. avail);
  9089. if (w < 0)
  9090. return -1;
  9091. if (!cs->box_sizing)
  9092. w += mp_px(cs, 7, avail) + mp_px(cs, 5, avail) +
  9093. cs->border_w[1] + cs->border_w[3];
  9094. return w + mp_px(cs, 3, avail) + mp_px(cs, 1, avail);
  9095. }
  9096. static int flex_clamp_w(const struct br_style *cs, int w, int avail)
  9097. {
  9098. int mx = flex_limit_w(cs, 1, avail), mn = flex_limit_w(cs, 0, avail);
  9099. if (mx >= 0 && w > mx)
  9100. w = mx;
  9101. if (mn >= 0 && w < mn)
  9102. w = mn;
  9103. return w;
  9104. }
  9105. static void layout_flex_children(struct lay *l, unsigned int parent,
  9106. const struct br_style *pst, int depth,
  9107. unsigned short link)
  9108. {
  9109. struct flex_item it[32];
  9110. unsigned int c;
  9111. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  9112. int grow_need = 0; /* growing items at their content width */
  9113. int row_left = l->left, row_right = l->right;
  9114. int avail = row_right - row_left;
  9115. int idx, row_top;
  9116. unsigned char row_align = l->align;
  9117. if (avail < 8 || depth > 48) {
  9118. layout_children(l, parent, pst, depth, link);
  9119. return;
  9120. }
  9121. /* If direct text is not just whitespace, normal block flow handles it
  9122. * better than pretending it is a flex item. */
  9123. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9124. struct br_node *nd = &doc.nodes[c];
  9125. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9126. layout_children(l, parent, pst, depth, link);
  9127. return;
  9128. }
  9129. }
  9130. for (c = doc.nodes[parent].first;
  9131. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  9132. c = doc.nodes[c].next) {
  9133. struct br_node *nd = &doc.nodes[c];
  9134. struct br_style cs;
  9135. if (nd->type == BR_NODE_TEXT)
  9136. continue;
  9137. br_style_for(&doc, c, pst, &cs);
  9138. if (cs.display == BR_DISPLAY_NONE)
  9139. continue;
  9140. it[nitem].node = c;
  9141. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  9142. (unsigned short)c : link;
  9143. it[nitem].w = 0;
  9144. if (cs.flex_grow && !cs.width_kind) {
  9145. grow_count++;
  9146. grow_need += flex_item_width(l, c, &cs, avail);
  9147. } else
  9148. fixed += flex_clamp_w(&cs,
  9149. flex_item_width(l, c, &cs, avail),
  9150. avail);
  9151. nitem++;
  9152. }
  9153. /* A narrow container (an icon row sized to its content, Google's
  9154. * mic + lens buttons) is still a row when its items fit; only a
  9155. * narrow one that would overflow or squeeze growing items falls
  9156. * back to block flow. */
  9157. if (avail < 160 && fixed + grow_need > avail) {
  9158. layout_children(l, parent, pst, depth, link);
  9159. return;
  9160. }
  9161. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  9162. /* A growing item capped by max-width (Docusaurus' doc column,
  9163. * `max-width: 75%`; its main container, `calc(100% - 300px)`)
  9164. * keeps its cap and leaves the rest of the free space to the other
  9165. * growing items. */
  9166. if (grow_count) {
  9167. int pass, capped[32] = { 0 };
  9168. for (pass = 0; pass < nitem; pass++) {
  9169. int changed = 0;
  9170. for (idx = 0; idx < nitem; idx++) {
  9171. struct br_style cs;
  9172. int lim;
  9173. if (capped[idx])
  9174. continue;
  9175. br_style_for(&doc, it[idx].node, pst, &cs);
  9176. if (!cs.flex_grow || cs.width_kind)
  9177. continue;
  9178. lim = flex_clamp_w(&cs, grow_w, avail);
  9179. if (lim == grow_w)
  9180. continue;
  9181. capped[idx] = lim + 1;
  9182. fixed += lim;
  9183. grow_count--;
  9184. changed = 1;
  9185. }
  9186. if (!changed || !grow_count)
  9187. break;
  9188. grow_w = (avail - fixed) / grow_count;
  9189. }
  9190. for (idx = 0; idx < nitem; idx++)
  9191. it[idx].w = capped[idx] ? capped[idx] - 1 : 0;
  9192. }
  9193. if (grow_w < 96 && avail >= 160)
  9194. grow_w = 96;
  9195. for (idx = 0; idx < nitem; idx++) {
  9196. struct br_style cs;
  9197. if (it[idx].w)
  9198. continue; /* capped growing item */
  9199. br_style_for(&doc, it[idx].node, pst, &cs);
  9200. if (cs.flex_grow && !cs.width_kind)
  9201. it[idx].w = grow_w;
  9202. else
  9203. it[idx].w = flex_clamp_w(&cs,
  9204. flex_item_width(l,
  9205. it[idx].node,
  9206. &cs, avail),
  9207. avail);
  9208. if (it[idx].w > avail)
  9209. it[idx].w = avail;
  9210. if (it[idx].w < 8)
  9211. it[idx].w = 8;
  9212. }
  9213. row_top = l->y;
  9214. idx = 0;
  9215. while (idx < nitem) {
  9216. int start = idx, count = 0, row_w = 0;
  9217. int free_w, x, extra = 0, row_h = 0, k;
  9218. while (idx < nitem) {
  9219. int add = it[idx].w + (count ? gap : 0);
  9220. /* CSS default is nowrap; only flex-wrap: wrap (1)
  9221. * starts a new row. */
  9222. if (count && pst->flex_wrap == 1 &&
  9223. row_w + add > avail)
  9224. break;
  9225. row_w += add;
  9226. count++;
  9227. idx++;
  9228. }
  9229. if (!count) {
  9230. count = 1;
  9231. row_w = it[start].w;
  9232. idx = start + 1;
  9233. }
  9234. free_w = avail - row_w;
  9235. if (free_w < 0)
  9236. free_w = 0;
  9237. x = row_left;
  9238. if (pst->justify == 1) {
  9239. x += free_w / 2;
  9240. } else if (pst->justify == 2) {
  9241. x += free_w;
  9242. } else if (pst->justify == 3) {
  9243. extra = count > 1 ? free_w / (count - 1) : 0;
  9244. } else if (pst->justify == 4) {
  9245. extra = count ? free_w / count : 0;
  9246. x += extra / 2;
  9247. } else if (pst->justify == 5) {
  9248. extra = count ? free_w / (count + 1) : 0;
  9249. x += extra;
  9250. }
  9251. for (k = 0; k < count; k++) {
  9252. int node = (int)it[start + k].node;
  9253. int h = block_h[node];
  9254. if (h > row_h)
  9255. row_h = h;
  9256. }
  9257. if (pst->height_kind) {
  9258. int hh = style_height_px(pst, avail);
  9259. if (hh > row_h)
  9260. row_h = hh;
  9261. }
  9262. for (k = 0; k < count; k++) {
  9263. struct br_style cs;
  9264. int node = (int)it[start + k].node;
  9265. int yoff = 0;
  9266. br_style_for(&doc, node, pst, &cs);
  9267. cs.width_kind = 0;
  9268. cs.max_width_kind = 0;
  9269. {
  9270. int ai = cs.align_self ? cs.align_self - 1 :
  9271. pst->align_items;
  9272. if (l->draw && ai && row_h > block_h[node]) {
  9273. if (ai == 1)
  9274. yoff = (row_h -
  9275. block_h[node]) / 2;
  9276. else if (ai == 2)
  9277. yoff = row_h - block_h[node];
  9278. }
  9279. }
  9280. l->left = x;
  9281. l->right = x + it[start + k].w;
  9282. if (l->right < l->left + 8)
  9283. l->right = l->left + 8;
  9284. l->y = row_top + yoff;
  9285. l->line_x = l->left;
  9286. l->run_x = l->left;
  9287. l->line_y = l->y;
  9288. l->line_h = 0;
  9289. l->nruns = 0;
  9290. l->space_pending = 0;
  9291. l->align = cs.align;
  9292. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  9293. if (!l->draw) {
  9294. int h = l->y - row_top;
  9295. if (h > row_h)
  9296. row_h = h;
  9297. }
  9298. x += it[start + k].w;
  9299. if (k + 1 < count)
  9300. x += gap + extra;
  9301. }
  9302. row_top += row_h;
  9303. }
  9304. l->left = row_left;
  9305. l->right = row_right;
  9306. l->align = row_align;
  9307. l->y = row_top;
  9308. l->line_x = l->left;
  9309. l->run_x = l->left;
  9310. l->line_y = l->y;
  9311. l->line_h = 0;
  9312. l->nruns = 0;
  9313. l->space_pending = 0;
  9314. }
  9315. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  9316. * plus the grid-area hints used by site shells (site notice/footer full
  9317. * width, column-start left, page-content right). Anything more elaborate
  9318. * falls back to normal block flow. */
  9319. static int grid_track_width(unsigned char kind, unsigned short val,
  9320. int avail, int other)
  9321. {
  9322. if (kind == 2)
  9323. return avail * (int)val / 100;
  9324. if (kind == 1)
  9325. return val;
  9326. return other;
  9327. }
  9328. static void layout_grid_children(struct lay *l, unsigned int parent,
  9329. const struct br_style *pst, int depth,
  9330. unsigned short link)
  9331. {
  9332. unsigned int n;
  9333. int row_left = l->left, row_right = l->right;
  9334. int avail = row_right - row_left;
  9335. int gap = pst->grid_gap;
  9336. int track_total = avail - gap;
  9337. int col0, col1, x0, x1;
  9338. int row_y, row_bottom, have_left = 0, have_right = 0;
  9339. unsigned int c;
  9340. if (avail < 32 || depth > 48)
  9341. return;
  9342. if (track_total < 16)
  9343. track_total = 16;
  9344. col0 = grid_track_width((unsigned char)(pst->width_kind),
  9345. pst->width, track_total, 0);
  9346. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  9347. pst->max_width, track_total, 0);
  9348. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  9349. int w0 = pst->width ? pst->width : 1;
  9350. int w1 = pst->max_width ? pst->max_width : 1;
  9351. col0 = track_total * w0 / (w0 + w1);
  9352. col1 = track_total - col0;
  9353. } else if (pst->width_kind == 3) {
  9354. col0 = track_total - col1;
  9355. if (col0 < 24)
  9356. col0 = 24;
  9357. } else if (pst->max_width_kind == 3) {
  9358. col1 = track_total - col0;
  9359. if (col1 < 24)
  9360. col1 = 24;
  9361. }
  9362. if (col0 < 24)
  9363. col0 = 24;
  9364. if (col1 < 24)
  9365. col1 = 24;
  9366. if (col0 + col1 > track_total) {
  9367. col1 = track_total - col0;
  9368. if (col1 < 24)
  9369. col1 = 24;
  9370. }
  9371. x0 = row_left;
  9372. x1 = row_left + col0 + gap;
  9373. /* Direct text makes a grid ambiguous; use block flow instead. */
  9374. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9375. struct br_node *nd = &doc.nodes[c];
  9376. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9377. layout_children(l, parent, pst, depth, link);
  9378. return;
  9379. }
  9380. }
  9381. row_y = row_bottom = l->y;
  9382. n = doc.nodes[parent].first;
  9383. while (n) {
  9384. struct br_node *nd = &doc.nodes[n];
  9385. struct br_style cs;
  9386. unsigned short lk = link;
  9387. int slot, x, w;
  9388. if (nd->type == BR_NODE_TEXT) {
  9389. n = nd->next;
  9390. continue;
  9391. }
  9392. br_style_for(&doc, n, pst, &cs);
  9393. if (cs.display == BR_DISPLAY_NONE) {
  9394. n = nd->next;
  9395. continue;
  9396. }
  9397. if (nd->tag == BR_TAG_A && nd->href_off)
  9398. lk = (unsigned short)n;
  9399. slot = cs.grid_slot;
  9400. if (!slot) {
  9401. if (!have_left)
  9402. slot = 2;
  9403. else if (!have_right)
  9404. slot = 3;
  9405. else
  9406. slot = 2;
  9407. }
  9408. if (slot == 1) {
  9409. if (have_left || have_right) {
  9410. row_y = row_bottom;
  9411. have_left = have_right = 0;
  9412. }
  9413. x = row_left;
  9414. w = avail;
  9415. } else if (slot == 2) {
  9416. if (have_left) {
  9417. row_y = row_bottom;
  9418. have_left = have_right = 0;
  9419. }
  9420. x = x0;
  9421. w = col0;
  9422. have_left = 1;
  9423. } else {
  9424. if (have_right) {
  9425. row_y = row_bottom;
  9426. have_left = have_right = 0;
  9427. }
  9428. x = x1;
  9429. w = col1;
  9430. have_right = 1;
  9431. }
  9432. cs.width_kind = 0;
  9433. cs.max_width_kind = 0;
  9434. l->left = x;
  9435. l->right = x + w;
  9436. if (l->right < l->left + 8)
  9437. l->right = l->left + 8;
  9438. l->y = row_y;
  9439. l->line_x = l->left;
  9440. l->run_x = l->left;
  9441. l->line_y = l->y;
  9442. l->line_h = 0;
  9443. l->nruns = 0;
  9444. l->space_pending = 0;
  9445. l->align = cs.align;
  9446. layout_block(l, n, &cs, depth + 1, lk);
  9447. if (l->y > row_bottom)
  9448. row_bottom = l->y;
  9449. n = nd->next;
  9450. }
  9451. l->left = row_left;
  9452. l->right = row_right;
  9453. l->y = row_bottom;
  9454. l->line_x = l->left;
  9455. l->run_x = l->left;
  9456. l->line_y = l->y;
  9457. l->line_h = 0;
  9458. l->nruns = 0;
  9459. l->space_pending = 0;
  9460. }
  9461. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  9462. * capped at four. Used by the project docs' card grids. A fixed
  9463. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  9464. static void layout_grid_auto(struct lay *l, unsigned int parent,
  9465. const struct br_style *pst, int depth,
  9466. unsigned short link)
  9467. {
  9468. unsigned int n, c;
  9469. int row_left = l->left, row_right = l->right;
  9470. int avail = row_right - row_left;
  9471. int gap = pst->grid_gap;
  9472. int minw = pst->width_kind == 1 ? pst->width : 200;
  9473. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  9474. if (avail < 32 || depth > 48) {
  9475. layout_children(l, parent, pst, depth, link);
  9476. return;
  9477. }
  9478. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  9479. struct br_node *nd = &doc.nodes[c];
  9480. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  9481. layout_children(l, parent, pst, depth, link);
  9482. return;
  9483. }
  9484. }
  9485. if (minw < 80)
  9486. minw = 80;
  9487. ncols = (avail + gap) / (minw + gap);
  9488. if (ncols < 1)
  9489. ncols = 1;
  9490. if (ncols > 4)
  9491. ncols = 4;
  9492. if (pst->grid_auto > BR_GRID_FIXED) {
  9493. /* grid-template-columns: repeat(N, 1fr) */
  9494. ncols = pst->grid_auto - BR_GRID_FIXED;
  9495. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  9496. ncols--;
  9497. }
  9498. colw = (avail - gap * (ncols - 1)) / ncols;
  9499. if (colw < 24)
  9500. colw = 24;
  9501. x = row_left;
  9502. n = doc.nodes[parent].first;
  9503. while (n) {
  9504. struct br_node *nd = &doc.nodes[n];
  9505. struct br_style cs;
  9506. unsigned short lk = link;
  9507. int h;
  9508. if (nd->type == BR_NODE_TEXT) {
  9509. n = nd->next;
  9510. continue;
  9511. }
  9512. br_style_for(&doc, n, pst, &cs);
  9513. if (cs.display == BR_DISPLAY_NONE) {
  9514. n = nd->next;
  9515. continue;
  9516. }
  9517. if (nd->tag == BR_TAG_A && nd->href_off)
  9518. lk = (unsigned short)n;
  9519. cs.width_kind = 0;
  9520. cs.max_width_kind = 0;
  9521. l->left = x;
  9522. l->right = x + colw;
  9523. if (l->right < l->left + 8)
  9524. l->right = l->left + 8;
  9525. l->y = y;
  9526. l->line_x = l->left;
  9527. l->run_x = l->left;
  9528. l->line_y = l->y;
  9529. l->line_h = 0;
  9530. l->nruns = 0;
  9531. l->space_pending = 0;
  9532. l->align = cs.align;
  9533. layout_block(l, n, &cs, depth + 1, lk);
  9534. h = l->y - y;
  9535. if (h > row_h)
  9536. row_h = h;
  9537. col++;
  9538. n = nd->next;
  9539. if (col == ncols) {
  9540. y += row_h + gap;
  9541. x = row_left;
  9542. row_h = 0;
  9543. col = 0;
  9544. } else {
  9545. x += colw + gap;
  9546. }
  9547. }
  9548. if (col)
  9549. y += row_h;
  9550. else if (y > start_y)
  9551. y -= gap;
  9552. l->left = row_left;
  9553. l->right = row_right;
  9554. l->y = y;
  9555. l->line_x = l->left;
  9556. l->run_x = l->left;
  9557. l->line_y = l->y;
  9558. l->line_h = 0;
  9559. l->nruns = 0;
  9560. l->space_pending = 0;
  9561. }
  9562. /* Column widths are the widest cell in each column across every row, so all
  9563. * rows line up. The table model is still deliberately basic: no colspan,
  9564. * border-collapse or percentage columns. */
  9565. static void table_columns(struct lay *l, unsigned int table,
  9566. const struct br_style *pst, int avail,
  9567. int *raw, int maxcols, int *out_cols,
  9568. int *out_total)
  9569. {
  9570. unsigned int r, c;
  9571. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  9572. int fixed[12];
  9573. for (c = 0; c < (unsigned int)maxcols; c++) {
  9574. raw[c] = 0;
  9575. fixed[c] = 0;
  9576. }
  9577. /* Intrinsic widths of single-column cells. */
  9578. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9579. struct br_node *rn = &doc.nodes[r];
  9580. int col = 0;
  9581. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9582. continue;
  9583. for (c = rn->first; c; c = doc.nodes[c].next) {
  9584. struct br_node *cn = &doc.nodes[c];
  9585. struct br_style cs;
  9586. int w, span;
  9587. if (cn->type != BR_NODE_ELEM ||
  9588. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9589. continue;
  9590. span = cn->colspan ? cn->colspan : 1;
  9591. br_style_for(&doc, c, pst, &cs);
  9592. if (cs.display == BR_DISPLAY_NONE)
  9593. continue;
  9594. if (col + span > maxcols)
  9595. span = maxcols - col;
  9596. if (span < 1)
  9597. break;
  9598. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9599. mp_px(&cs, 7, avail) +
  9600. mp_px(&cs, 5, avail) +
  9601. mp_px(&cs, 3, avail) +
  9602. mp_px(&cs, 1, avail) +
  9603. cs.border_w[0] + cs.border_w[1] +
  9604. cs.border_w[2] + cs.border_w[3];
  9605. if (w < 24)
  9606. w = 24;
  9607. if (span == 1) {
  9608. if (w > raw[col])
  9609. raw[col] = w;
  9610. }
  9611. if (col + span > cols)
  9612. cols = col + span;
  9613. col += span;
  9614. }
  9615. }
  9616. /* A colspan cell only has to be as wide as the sum of its columns. */
  9617. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9618. struct br_node *rn = &doc.nodes[r];
  9619. int col = 0;
  9620. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9621. continue;
  9622. for (c = rn->first; c; c = doc.nodes[c].next) {
  9623. struct br_node *cn = &doc.nodes[c];
  9624. struct br_style cs;
  9625. int span, w, sum, i;
  9626. if (cn->type != BR_NODE_ELEM ||
  9627. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9628. continue;
  9629. span = cn->colspan ? cn->colspan : 1;
  9630. if (col + span > maxcols)
  9631. span = maxcols - col;
  9632. if (span < 1)
  9633. break;
  9634. if (span > 1) {
  9635. br_style_for(&doc, c, pst, &cs);
  9636. if (cs.display != BR_DISPLAY_NONE) {
  9637. w = intrinsic_width(l->ui, c, &cs,
  9638. 0, avail) +
  9639. mp_px(&cs, 7, avail) +
  9640. mp_px(&cs, 5, avail) +
  9641. mp_px(&cs, 3, avail) +
  9642. mp_px(&cs, 1, avail) +
  9643. cs.border_w[0] + cs.border_w[1] +
  9644. cs.border_w[2] + cs.border_w[3];
  9645. sum = 0;
  9646. for (i = 0; i < span; i++)
  9647. sum += raw[col + i];
  9648. if (w > sum)
  9649. raw[col + span - 1] += w - sum;
  9650. }
  9651. }
  9652. col += span;
  9653. }
  9654. }
  9655. /* Explicit and percentage widths override intrinsic widths. */
  9656. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9657. struct br_node *rn = &doc.nodes[r];
  9658. int col = 0;
  9659. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9660. continue;
  9661. for (c = rn->first; c; c = doc.nodes[c].next) {
  9662. struct br_node *cn = &doc.nodes[c];
  9663. struct br_style cs;
  9664. int span;
  9665. if (cn->type != BR_NODE_ELEM ||
  9666. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9667. continue;
  9668. span = cn->colspan ? cn->colspan : 1;
  9669. if (col + span > maxcols)
  9670. span = maxcols - col;
  9671. if (span < 1)
  9672. break;
  9673. if (span == 1) {
  9674. br_style_for(&doc, c, pst, &cs);
  9675. if (cs.display != BR_DISPLAY_NONE) {
  9676. if (cs.width_kind == 1) {
  9677. raw[col] = cs.width;
  9678. fixed[col] = 1;
  9679. } else if (cs.width_kind == 2 ||
  9680. cs.width_kind == 3) {
  9681. raw[col] = style_width_px(&cs,
  9682. avail);
  9683. fixed[col] = 1;
  9684. }
  9685. }
  9686. }
  9687. col += span;
  9688. }
  9689. }
  9690. for (c = 0; c < (unsigned int)cols; c++) {
  9691. if (raw[c] < 8)
  9692. raw[c] = 8;
  9693. total += raw[c];
  9694. if (fixed[c])
  9695. fixed_sum += raw[c];
  9696. else {
  9697. free_raw += raw[c];
  9698. free_cols++;
  9699. }
  9700. }
  9701. if (fixed_sum > 0 && fixed_sum < avail) {
  9702. int free_avail = avail - fixed_sum;
  9703. int i;
  9704. if (free_raw > 0) {
  9705. for (i = 0; i < cols; i++)
  9706. if (!fixed[i])
  9707. raw[i] = free_avail * raw[i] /
  9708. free_raw;
  9709. } else if (free_cols > 0) {
  9710. for (i = 0; i < cols; i++)
  9711. if (!fixed[i])
  9712. raw[i] = free_avail / free_cols;
  9713. }
  9714. total = 0;
  9715. for (i = 0; i < cols; i++)
  9716. total += raw[i];
  9717. } else if (total < avail && total > 0) {
  9718. int i;
  9719. for (i = 0; i < cols; i++)
  9720. raw[i] = raw[i] * avail / total;
  9721. total = 0;
  9722. for (i = 0; i < cols; i++)
  9723. total += raw[i];
  9724. }
  9725. *out_cols = cols;
  9726. *out_total = total;
  9727. }
  9728. static void layout_table_row(struct lay *l, unsigned int row,
  9729. const struct br_style *pst, int depth,
  9730. unsigned short link)
  9731. {
  9732. unsigned int n, cell[12];
  9733. int raw[12], colstart[12], colspan[12];
  9734. int prefix[13];
  9735. int ncell = 0, total = 0, cols = 0, col = 0;
  9736. int row_left = l->left, row_right = l->right;
  9737. int avail = row_right - row_left;
  9738. int y = l->y, bottom = l->y;
  9739. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9740. struct br_node *nd = &doc.nodes[n];
  9741. struct br_style cs;
  9742. int span;
  9743. if (nd->type == BR_NODE_TEXT) {
  9744. if (text_node_blank(nd))
  9745. continue;
  9746. layout_children(l, row, pst, depth, link);
  9747. return;
  9748. }
  9749. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  9750. layout_children(l, row, pst, depth, link);
  9751. return;
  9752. }
  9753. br_style_for(&doc, n, pst, &cs);
  9754. if (cs.display == BR_DISPLAY_NONE)
  9755. continue;
  9756. if (ncell >= 12) {
  9757. layout_children(l, row, pst, depth, link);
  9758. return;
  9759. }
  9760. span = nd->colspan ? nd->colspan : 1;
  9761. if (span > 12 - col)
  9762. span = 12 - col;
  9763. if (span < 1)
  9764. continue;
  9765. cell[ncell] = n;
  9766. colstart[ncell] = col;
  9767. colspan[ncell] = span;
  9768. col += span;
  9769. ncell++;
  9770. }
  9771. if (ncell < 1 || avail < 32) {
  9772. layout_children(l, row, pst, depth, link);
  9773. return;
  9774. }
  9775. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  9776. &total);
  9777. if (cols < 2 || total <= 0) {
  9778. int c;
  9779. total = 0;
  9780. for (c = 0; c < ncell; c++) {
  9781. struct br_style cs;
  9782. br_style_for(&doc, cell[c], pst, &cs);
  9783. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  9784. avail) +
  9785. mp_px(&cs, 7, avail) +
  9786. mp_px(&cs, 5, avail) +
  9787. mp_px(&cs, 3, avail) +
  9788. mp_px(&cs, 1, avail);
  9789. if (raw[c] < 24)
  9790. raw[c] = 24;
  9791. total += raw[c];
  9792. }
  9793. /* A one-column table still has to fill its own width; the
  9794. * intrinsic fallback above otherwise leaves the cell at its
  9795. * text width (HN's outer table and nested story table). */
  9796. if (total > 0 && total < avail) {
  9797. int c;
  9798. for (c = 0; c < ncell; c++)
  9799. raw[c] = raw[c] * avail / total;
  9800. total = avail;
  9801. }
  9802. }
  9803. prefix[0] = row_left;
  9804. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  9805. prefix[n + 1] = prefix[n] + raw[n];
  9806. for (n = 0; n < (unsigned int)ncell; n++) {
  9807. struct br_style cs;
  9808. int start = colstart[n];
  9809. int end = start + colspan[n];
  9810. int w;
  9811. if (end > cols)
  9812. end = cols;
  9813. if (start >= cols)
  9814. continue;
  9815. w = prefix[end] - prefix[start];
  9816. br_style_for(&doc, cell[n], pst, &cs);
  9817. /* The column width already reflects the cell's width property. */
  9818. cs.width_kind = 0;
  9819. cs.max_width_kind = 0;
  9820. if (w < 24)
  9821. w = 24;
  9822. if (w < 8)
  9823. w = 8;
  9824. l->left = prefix[start];
  9825. l->right = l->left + w;
  9826. l->y = y;
  9827. l->line_x = l->left;
  9828. l->run_x = l->left;
  9829. l->line_y = l->y;
  9830. l->line_h = 0;
  9831. l->nruns = 0;
  9832. l->space_pending = 0;
  9833. l->align = cs.align;
  9834. layout_block(l, cell[n], &cs, depth + 1, link);
  9835. if (l->y > bottom)
  9836. bottom = l->y;
  9837. }
  9838. l->left = row_left;
  9839. l->right = row_right;
  9840. l->y = bottom;
  9841. l->line_x = l->left;
  9842. l->run_x = l->left;
  9843. l->line_y = l->y;
  9844. l->line_h = 0;
  9845. l->nruns = 0;
  9846. l->space_pending = 0;
  9847. }
  9848. #define TBL_MAX_ROWS 32
  9849. #define TBL_MAX_COLS 12
  9850. #define TBL_MAX_CELLS 128
  9851. struct tbl_cell {
  9852. unsigned int node;
  9853. unsigned char row, col, rowspan, colspan;
  9854. int height;
  9855. };
  9856. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  9857. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  9858. static int table_active;
  9859. static int table_has_rowspan(unsigned int table)
  9860. {
  9861. unsigned int r, c;
  9862. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9863. struct br_node *rn = &doc.nodes[r];
  9864. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9865. continue;
  9866. for (c = rn->first; c; c = doc.nodes[c].next) {
  9867. struct br_node *cn = &doc.nodes[c];
  9868. if (cn->type == BR_NODE_ELEM &&
  9869. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  9870. cn->rowspan > 1)
  9871. return 1;
  9872. }
  9873. }
  9874. return 0;
  9875. }
  9876. static void table_cell_style(unsigned int row, unsigned int cell,
  9877. const struct br_style *st, struct br_style *out)
  9878. {
  9879. struct br_style trs;
  9880. br_style_for(&doc, row, st, &trs);
  9881. br_style_for(&doc, cell, &trs, out);
  9882. }
  9883. /* Tables that use rowspan need row heights before anything is painted. This
  9884. * path builds a small occupancy grid, measures the natural cell heights, then
  9885. * lays every cell out at its row/column position. Tables without rowspan
  9886. * keep the lighter per-row path in layout_table_row(). */
  9887. static void layout_table(struct lay *l, unsigned int table,
  9888. const struct br_style *st, int depth,
  9889. unsigned short link)
  9890. {
  9891. unsigned int rows[TBL_MAX_ROWS];
  9892. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  9893. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  9894. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  9895. int free_raw = 0, free_cols = 0;
  9896. int table_left = l->left, table_right = l->right;
  9897. int top = l->y, avail = table_right - table_left;
  9898. unsigned int r, c;
  9899. int i, rr, cc;
  9900. if (depth > 48 || table_active) {
  9901. layout_children(l, table, st, depth, link);
  9902. return;
  9903. }
  9904. table_active = 1;
  9905. for (r = doc.nodes[table].first;
  9906. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  9907. struct br_node *rn = &doc.nodes[r];
  9908. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  9909. rows[nrows++] = r;
  9910. }
  9911. if (!nrows) {
  9912. table_active = 0;
  9913. layout_children(l, table, st, depth, link);
  9914. return;
  9915. }
  9916. for (rr = 0; rr < nrows; rr++)
  9917. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  9918. tbl_at[rr][cc] = 0;
  9919. for (rr = 0; rr < nrows; rr++) {
  9920. int col = 0;
  9921. for (c = doc.nodes[rows[rr]].first; c;
  9922. c = doc.nodes[c].next) {
  9923. struct br_node *cn = &doc.nodes[c];
  9924. struct br_style cs;
  9925. int rs, csn;
  9926. if (cn->type != BR_NODE_ELEM ||
  9927. (cn->tag != BR_TAG_TD &&
  9928. cn->tag != BR_TAG_TH))
  9929. continue;
  9930. table_cell_style(rows[rr], c, st, &cs);
  9931. if (cs.display == BR_DISPLAY_NONE)
  9932. continue;
  9933. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  9934. col++;
  9935. if (col >= TBL_MAX_COLS)
  9936. break;
  9937. rs = cn->rowspan ? cn->rowspan : 1;
  9938. csn = cn->colspan ? cn->colspan : 1;
  9939. if (rr + rs > nrows)
  9940. rs = nrows - rr;
  9941. if (col + csn > TBL_MAX_COLS)
  9942. csn = TBL_MAX_COLS - col;
  9943. if (rs < 1 || csn < 1)
  9944. continue;
  9945. if (ncells >= TBL_MAX_CELLS)
  9946. break;
  9947. tbl_cells[ncells].node = c;
  9948. tbl_cells[ncells].row = (unsigned char)rr;
  9949. tbl_cells[ncells].col = (unsigned char)col;
  9950. tbl_cells[ncells].rowspan = (unsigned char)rs;
  9951. tbl_cells[ncells].colspan = (unsigned char)csn;
  9952. tbl_cells[ncells].height = 0;
  9953. for (i = rr; i < rr + rs; i++)
  9954. for (int j = col; j < col + csn; j++)
  9955. tbl_at[i][j] =
  9956. (unsigned short)(ncells + 1);
  9957. ncells++;
  9958. col += csn;
  9959. if (col > cols)
  9960. cols = col;
  9961. }
  9962. }
  9963. if (!ncells || cols < 1) {
  9964. table_active = 0;
  9965. layout_children(l, table, st, depth, link);
  9966. return;
  9967. }
  9968. for (i = 0; i < cols; i++) {
  9969. raw[i] = 0;
  9970. fixed[i] = 0;
  9971. }
  9972. /* Intrinsic widths of single-column cells. */
  9973. for (i = 0; i < ncells; i++) {
  9974. struct br_style cs;
  9975. int w;
  9976. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9977. st, &cs);
  9978. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9979. mp_px(&cs, 7, avail) +
  9980. mp_px(&cs, 5, avail) +
  9981. mp_px(&cs, 3, avail) +
  9982. mp_px(&cs, 1, avail) +
  9983. cs.border_w[0] + cs.border_w[1] +
  9984. cs.border_w[2] + cs.border_w[3];
  9985. if (w < 24)
  9986. w = 24;
  9987. if (tbl_cells[i].colspan == 1) {
  9988. int col = tbl_cells[i].col;
  9989. if (w > raw[col])
  9990. raw[col] = w;
  9991. }
  9992. }
  9993. /* A spanning cell only needs the sum of its columns to be large
  9994. * enough; put the deficit in the last column. */
  9995. for (i = 0; i < ncells; i++) {
  9996. struct br_style cs;
  9997. int w, sum, col, span;
  9998. if (tbl_cells[i].colspan < 2)
  9999. continue;
  10000. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10001. st, &cs);
  10002. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  10003. mp_px(&cs, 7, avail) +
  10004. mp_px(&cs, 5, avail) +
  10005. mp_px(&cs, 3, avail) +
  10006. mp_px(&cs, 1, avail) +
  10007. cs.border_w[0] + cs.border_w[1] +
  10008. cs.border_w[2] + cs.border_w[3];
  10009. col = tbl_cells[i].col;
  10010. span = tbl_cells[i].colspan;
  10011. sum = 0;
  10012. for (int j = 0; j < span; j++)
  10013. sum += raw[col + j];
  10014. if (w > sum)
  10015. raw[col + span - 1] += w - sum;
  10016. }
  10017. /* Explicit/percentage widths, as in table_columns(). */
  10018. for (i = 0; i < ncells; i++) {
  10019. struct br_style cs;
  10020. int col;
  10021. if (tbl_cells[i].colspan != 1)
  10022. continue;
  10023. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10024. st, &cs);
  10025. col = tbl_cells[i].col;
  10026. if (cs.width_kind == 1) {
  10027. raw[col] = cs.width;
  10028. fixed[col] = 1;
  10029. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  10030. raw[col] = style_width_px(&cs, avail);
  10031. fixed[col] = 1;
  10032. }
  10033. }
  10034. for (i = 0; i < cols; i++) {
  10035. if (raw[i] < 8)
  10036. raw[i] = 8;
  10037. total += raw[i];
  10038. if (fixed[i])
  10039. fixed_sum += raw[i];
  10040. else {
  10041. free_raw += raw[i];
  10042. free_cols++;
  10043. }
  10044. }
  10045. if (fixed_sum > 0 && fixed_sum < avail) {
  10046. int free_avail = avail - fixed_sum;
  10047. if (free_raw > 0) {
  10048. for (i = 0; i < cols; i++)
  10049. if (!fixed[i])
  10050. raw[i] = free_avail * raw[i] /
  10051. free_raw;
  10052. } else if (free_cols > 0) {
  10053. for (i = 0; i < cols; i++)
  10054. if (!fixed[i])
  10055. raw[i] = free_avail / free_cols;
  10056. }
  10057. } else if (total < avail && total > 0) {
  10058. for (i = 0; i < cols; i++)
  10059. raw[i] = raw[i] * avail / total;
  10060. }
  10061. prefix[0] = table_left;
  10062. for (i = 0; i < cols; i++)
  10063. prefix[i + 1] = prefix[i] + raw[i];
  10064. /* Measure natural cell heights with the column widths. */
  10065. for (i = 0; i < ncells; i++) {
  10066. struct br_style cs;
  10067. int col = tbl_cells[i].col;
  10068. int span = tbl_cells[i].colspan;
  10069. int w = prefix[col + span] - prefix[col];
  10070. int sl = l->left, sr = l->right, sy = l->y;
  10071. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10072. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10073. int sal = l->align, sdraw = l->draw;
  10074. struct ngui *sui = l->ui;
  10075. if (w < 8)
  10076. w = 8;
  10077. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  10078. st, &cs);
  10079. cs.width_kind = 0;
  10080. cs.max_width_kind = 0;
  10081. l->draw = 0;
  10082. l->ui = 0;
  10083. l->left = prefix[col];
  10084. l->right = l->left + w;
  10085. l->y = 0;
  10086. l->line_x = l->left;
  10087. l->run_x = l->left;
  10088. l->line_y = 0;
  10089. l->line_h = 0;
  10090. l->nruns = 0;
  10091. l->space_pending = 0;
  10092. l->align = cs.align;
  10093. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10094. tbl_cells[i].height = block_h[tbl_cells[i].node];
  10095. l->left = sl;
  10096. l->right = sr;
  10097. l->y = sy;
  10098. l->line_x = slx;
  10099. l->run_x = srx;
  10100. l->line_y = sly;
  10101. l->line_h = slh;
  10102. l->nruns = snr;
  10103. l->space_pending = ssp;
  10104. l->align = sal;
  10105. l->draw = sdraw;
  10106. l->ui = sui;
  10107. }
  10108. for (i = 0; i < nrows; i++)
  10109. rowh[i] = 0;
  10110. for (i = 0; i < ncells; i++) {
  10111. int row = tbl_cells[i].row;
  10112. if (tbl_cells[i].rowspan == 1) {
  10113. if (tbl_cells[i].height > rowh[row])
  10114. rowh[row] = tbl_cells[i].height;
  10115. }
  10116. }
  10117. for (i = 0; i < ncells; i++) {
  10118. int row = tbl_cells[i].row;
  10119. int span = tbl_cells[i].rowspan;
  10120. int sum = 0;
  10121. if (span < 2)
  10122. continue;
  10123. for (int j = 0; j < span; j++)
  10124. sum += rowh[row + j];
  10125. if (sum < tbl_cells[i].height)
  10126. rowh[row + span - 1] +=
  10127. tbl_cells[i].height - sum;
  10128. }
  10129. for (i = 0; i < nrows; i++)
  10130. if (rowh[i] < 8)
  10131. rowh[i] = 8;
  10132. rowy[0] = top;
  10133. for (i = 1; i < nrows; i++)
  10134. rowy[i] = rowy[i - 1] + rowh[i - 1];
  10135. if (!l->draw) {
  10136. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10137. table_active = 0;
  10138. return;
  10139. }
  10140. for (i = 0; i < ncells; i++) {
  10141. struct br_style cs;
  10142. int col = tbl_cells[i].col;
  10143. int span = tbl_cells[i].colspan;
  10144. int row = tbl_cells[i].row;
  10145. int rspan = tbl_cells[i].rowspan;
  10146. int w = prefix[col + span] - prefix[col];
  10147. int h = 0;
  10148. int sl = l->left, sr = l->right, sy = l->y;
  10149. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  10150. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  10151. int sal = l->align;
  10152. int deco;
  10153. for (int j = 0; j < rspan; j++)
  10154. h += rowh[row + j];
  10155. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  10156. cs.width_kind = 0;
  10157. cs.max_width_kind = 0;
  10158. cs.box_sizing = 0;
  10159. deco = mp_px(&cs, 4, avail) +
  10160. mp_px(&cs, 6, avail) +
  10161. cs.border_w[0] + cs.border_w[2];
  10162. cs.height_kind = 1;
  10163. cs.height = h > deco ? h - deco : 0;
  10164. /* The block painter reads block_h[] from the measure pass; make
  10165. * the table cell fill its row/rowspan, not just its content. */
  10166. if (h > 0 && h < 65536)
  10167. block_h[tbl_cells[i].node] = (unsigned short)h;
  10168. l->left = prefix[col];
  10169. l->right = l->left + w;
  10170. l->y = rowy[row];
  10171. l->line_x = l->left;
  10172. l->run_x = l->left;
  10173. l->line_y = l->y;
  10174. l->line_h = 0;
  10175. l->nruns = 0;
  10176. l->space_pending = 0;
  10177. l->align = cs.align;
  10178. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  10179. l->left = sl;
  10180. l->right = sr;
  10181. l->y = sy;
  10182. l->line_x = slx;
  10183. l->run_x = srx;
  10184. l->line_y = sly;
  10185. l->line_h = slh;
  10186. l->nruns = snr;
  10187. l->space_pending = ssp;
  10188. l->align = sal;
  10189. }
  10190. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  10191. table_active = 0;
  10192. }
  10193. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  10194. * flow so they sit above it, like CSS painting order. Their flow origin is
  10195. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  10196. struct br_deferred {
  10197. unsigned int node;
  10198. int flow_y, flow_left, flow_right;
  10199. int parent_top; /* the parent box top, for sticky clamping */
  10200. unsigned short link;
  10201. signed short z_index;
  10202. unsigned char z_set;
  10203. unsigned int order;
  10204. };
  10205. /* Positioned boxes painted after the flow. News front pages have one or two
  10206. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  10207. * old 16 entries the rest fell back into the flow, so a hero image landed
  10208. * below its padding-top aspect box instead of on top of it. */
  10209. #define BR_MAX_DEFERRED 256
  10210. static struct br_deferred deferred[BR_MAX_DEFERRED];
  10211. static int ndeferred;
  10212. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  10213. * element's line. A block-level pseudo-element gets its own line; its box
  10214. * (margins, padding, background) is not drawn. */
  10215. static void emit_pseudo(struct lay *l, unsigned int node,
  10216. const struct br_style *st, int pe, unsigned short link)
  10217. {
  10218. char buf[160];
  10219. struct br_style ps;
  10220. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  10221. unsigned int i = 0;
  10222. int block, space_w;
  10223. if (!n)
  10224. return;
  10225. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  10226. if (block)
  10227. flush_line(l);
  10228. if (ps.uppercase)
  10229. for (i = 0; i < n; i++)
  10230. if (buf[i] >= 'a' && buf[i] <= 'z')
  10231. buf[i] = (char)(buf[i] - 'a' + 'A');
  10232. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  10233. if (space_w <= 0)
  10234. space_w = 8;
  10235. i = 0;
  10236. while (i < n) {
  10237. char word[28];
  10238. unsigned int k = 0;
  10239. int w;
  10240. if (buf[i] == ' ') {
  10241. l->space_pending = 1;
  10242. i++;
  10243. continue;
  10244. }
  10245. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  10246. word[k++] = buf[i++];
  10247. word[k] = '\0';
  10248. if (l->space_pending &&
  10249. (l->nruns > 0 || l->line_x > l->line_left) &&
  10250. l->line_x + space_w <= l->line_right)
  10251. l->line_x += space_w;
  10252. l->space_pending = 0;
  10253. w = (int)face_text_width(l->ui, &ps, word, k);
  10254. if (l->line_x + w > l->line_right &&
  10255. (l->nruns > 0 || l->line_x > l->line_left))
  10256. flush_line(l);
  10257. add_run(l, 0, 0, &ps, link, word);
  10258. }
  10259. if (block)
  10260. flush_line(l);
  10261. }
  10262. static void layout_children(struct lay *l, unsigned int parent,
  10263. const struct br_style *pst, int depth,
  10264. unsigned short link)
  10265. {
  10266. unsigned int n;
  10267. if (depth > 48)
  10268. return;
  10269. emit_pseudo(l, parent, pst, 1, link);
  10270. n = doc.nodes[parent].first;
  10271. while (n) {
  10272. struct br_node *nd = &doc.nodes[n];
  10273. struct br_style cs;
  10274. unsigned short lk = link;
  10275. if (nd->type == BR_NODE_TEXT) {
  10276. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  10277. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  10278. n = nd->next;
  10279. continue;
  10280. }
  10281. br_style_for(&doc, n, pst, &cs);
  10282. if (cs.display == BR_DISPLAY_NONE) {
  10283. n = nd->next;
  10284. continue;
  10285. }
  10286. if (cs.clear && l->float_active) {
  10287. flush_line(l);
  10288. if (l->y < l->float_bottom)
  10289. l->y = l->float_bottom;
  10290. l->float_active = 0;
  10291. l->line_x = l->left;
  10292. l->run_x = l->left;
  10293. l->line_left = l->left;
  10294. l->line_right = l->right;
  10295. l->line_y = l->y;
  10296. l->line_h = 0;
  10297. l->nruns = 0;
  10298. l->space_pending = 0;
  10299. }
  10300. if (nd->tag == BR_TAG_A && nd->href_off)
  10301. lk = (unsigned short)n;
  10302. if (cs.pos == 1 || cs.pos == 2 ||
  10303. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  10304. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  10305. ndeferred < BR_MAX_DEFERRED) {
  10306. /* Relative or sticky z-index (a sticky site
  10307. * header): measure and advance the flow without
  10308. * painting, then paint it in the deferred
  10309. * (stacked) pass, above the content after it. */
  10310. int fy = l->y, fl = l->left, fr = l->right;
  10311. int save_draw = l->draw;
  10312. l->draw = 0;
  10313. layout_block(l, n, &cs, depth + 1, lk);
  10314. l->draw = save_draw;
  10315. deferred[ndeferred].node = n;
  10316. deferred[ndeferred].parent_top = l->parent_top;
  10317. deferred[ndeferred].flow_y = fy;
  10318. deferred[ndeferred].flow_left = fl;
  10319. deferred[ndeferred].flow_right = fr;
  10320. deferred[ndeferred].link = lk;
  10321. deferred[ndeferred].z_index = cs.z_index;
  10322. deferred[ndeferred].z_set = cs.z_set;
  10323. deferred[ndeferred].order = (unsigned int)ndeferred;
  10324. ndeferred++;
  10325. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  10326. deferred[ndeferred].node = n;
  10327. deferred[ndeferred].parent_top = l->parent_top;
  10328. deferred[ndeferred].flow_y =
  10329. cs.pos == 1 ? l->cb_top : l->y;
  10330. deferred[ndeferred].flow_left =
  10331. cs.pos == 1 ? l->cb_left : l->left;
  10332. deferred[ndeferred].flow_right =
  10333. cs.pos == 1 ? l->cb_right : l->right;
  10334. deferred[ndeferred].link = lk;
  10335. deferred[ndeferred].z_index = cs.z_index;
  10336. deferred[ndeferred].z_set = cs.z_set;
  10337. deferred[ndeferred].order = (unsigned int)ndeferred;
  10338. ndeferred++;
  10339. } else if (l->draw && cs.pos == 1) {
  10340. /* Deferred list full: paint in place, but still
  10341. * against the containing block, not the flow. */
  10342. int fy = l->y, fl = l->left, fr = l->right;
  10343. l->y = l->cb_top;
  10344. l->left = l->cb_left;
  10345. l->right = l->cb_right;
  10346. layout_block(l, n, &cs, depth + 1, lk);
  10347. l->y = fy;
  10348. l->left = fl;
  10349. l->right = fr;
  10350. } else {
  10351. layout_block(l, n, &cs, depth + 1, lk);
  10352. }
  10353. if (cs.pos == 1 && block_h[n] &&
  10354. doc.nodes[n].class_off) {
  10355. const char *cl = doc.attrs +
  10356. doc.nodes[n].class_off;
  10357. if ((contains_ci(cl, "poster-wrapper") ||
  10358. contains_ci(cl, "ts-picture")) &&
  10359. !has_skeleton_sibling(n))
  10360. l->y += block_h[n];
  10361. }
  10362. n = nd->next;
  10363. continue;
  10364. }
  10365. if (nd->tag == BR_TAG_BR) {
  10366. flush_line(l);
  10367. n = nd->next;
  10368. continue;
  10369. }
  10370. if (nd->tag == BR_TAG_HR) {
  10371. flush_line(l);
  10372. if (l->draw)
  10373. ngui_fill_rect(l->ui,
  10374. (struct ngui_rect){l->left, l->y + 2,
  10375. l->right - l->left, 1}, BR_GRAY);
  10376. l->y += 8;
  10377. n = nd->next;
  10378. continue;
  10379. }
  10380. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  10381. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  10382. !button_has_elements(n)) {
  10383. if (!(nd->tag == BR_TAG_INPUT &&
  10384. s_eq(br_type(&doc, n), "hidden"))) {
  10385. form_fill_line = pst->display ==
  10386. BR_DISPLAY_FLEX &&
  10387. pst->flex_col;
  10388. add_form_run(l, n, &cs, lk);
  10389. form_fill_line = 0;
  10390. }
  10391. n = nd->next;
  10392. continue;
  10393. }
  10394. if (nd->tag == BR_TAG_IMG) {
  10395. add_image_run(l, n, &cs, lk);
  10396. n = nd->next;
  10397. continue;
  10398. }
  10399. if (nd->tag == BR_TAG_SVG &&
  10400. (cs.display == BR_DISPLAY_INLINE ||
  10401. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  10402. !cs.float_left) {
  10403. add_svg_run(l, n, &cs, lk);
  10404. n = nd->next;
  10405. continue;
  10406. }
  10407. if (nd->tag == BR_TAG_VIDEO) {
  10408. layout_block(l, n, &cs, depth + 1, lk);
  10409. n = nd->next;
  10410. continue;
  10411. }
  10412. if (cs.float_left) {
  10413. n = layout_float_group(l, n, pst, depth, lk);
  10414. continue;
  10415. }
  10416. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  10417. inline_block_flows(n, &cs, 0)) {
  10418. layout_children(l, n, &cs, depth + 1, lk);
  10419. n = nd->next;
  10420. continue;
  10421. }
  10422. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  10423. n = layout_inline_blocks(l, n, pst, depth, link);
  10424. continue;
  10425. }
  10426. /* A flex container is block-level like any block box even when
  10427. * the element is an inline tag such as <a> (a link card with
  10428. * display:flex is common on news sites). Without the block box
  10429. * its children were laid out in the parent flow with a 0x0 box
  10430. * of their own. */
  10431. /* inline-flex around inline content only ("| mehr" link
  10432. * tails, icon+label pills) stays in the text line. */
  10433. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  10434. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  10435. !flex_wants_row(n, &cs)) {
  10436. layout_children(l, n, &cs, depth + 1, lk);
  10437. } else if (cs.display == BR_DISPLAY_BLOCK ||
  10438. cs.display == BR_DISPLAY_FLEX ||
  10439. br_tag_is_block(nd->tag))
  10440. layout_block(l, n, &cs, depth + 1, lk);
  10441. else {
  10442. layout_children(l, n, &cs, depth + 1, lk);
  10443. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  10444. l->space_pending = 1;
  10445. }
  10446. n = nd->next;
  10447. }
  10448. emit_pseudo(l, parent, pst, 2, link);
  10449. }
  10450. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  10451. * runs and a recursive page can otherwise overflow the stack. */
  10452. static struct lay layout_state;
  10453. static int measure_page(int left, int right)
  10454. {
  10455. struct lay *l = &layout_state;
  10456. struct br_style base = base_style();
  10457. unsigned int i;
  10458. for (i = 0; i < BR_MAX_NODES; i++) {
  10459. block_h[i] = 0;
  10460. img_top[i] = 0;
  10461. block_top[i] = 0;
  10462. img_h[i] = 0;
  10463. layout_boxes[i].valid = 0;
  10464. }
  10465. memset(li_marker, 0, sizeof(li_marker));
  10466. l->draw = 0;
  10467. l->ui = &ui;
  10468. l->left = left;
  10469. l->right = right;
  10470. l->y = 0;
  10471. l->line_x = left;
  10472. l->run_x = left;
  10473. l->line_left = left;
  10474. l->line_right = right;
  10475. l->line_y = 0;
  10476. l->line_h = 0;
  10477. l->align = BR_ALIGN_LEFT;
  10478. l->cb_h = layout_view_h;
  10479. l->float_active = 0;
  10480. l->parent_top = 0;
  10481. l->cb_left = left;
  10482. l->cb_right = right;
  10483. l->cb_top = 0;
  10484. l->depth = 0;
  10485. l->nruns = 0;
  10486. l->space_pending = 0;
  10487. base = root_style();
  10488. layout_children(l, doc.root, &base, 0, 0);
  10489. return l->y + 8;
  10490. }
  10491. static int deferred_cmp(const struct br_deferred *a,
  10492. const struct br_deferred *b)
  10493. {
  10494. int az = a->z_set ? a->z_index : 0;
  10495. int bz = b->z_set ? b->z_index : 0;
  10496. if (az != bz)
  10497. return az < bz ? -1 : 1;
  10498. if (a->order != b->order)
  10499. return a->order < b->order ? -1 : 1;
  10500. return 0;
  10501. }
  10502. static void sort_deferred(void)
  10503. {
  10504. int i;
  10505. for (i = 1; i < ndeferred; i++) {
  10506. struct br_deferred key = deferred[i];
  10507. int j = i;
  10508. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  10509. deferred[j] = deferred[j - 1];
  10510. j--;
  10511. }
  10512. deferred[j] = key;
  10513. }
  10514. }
  10515. static void render_page(int left, int right, int y0)
  10516. {
  10517. struct lay *l = &layout_state;
  10518. struct br_style base = base_style();
  10519. l->draw = 1;
  10520. l->ui = &ui;
  10521. l->left = left;
  10522. l->right = right;
  10523. l->y = y0;
  10524. l->line_x = left;
  10525. l->run_x = left;
  10526. l->line_left = left;
  10527. l->line_right = right;
  10528. l->line_y = y0;
  10529. l->line_h = 0;
  10530. l->align = BR_ALIGN_LEFT;
  10531. l->cb_h = layout_view_h;
  10532. l->float_active = 0;
  10533. l->parent_top = 0;
  10534. l->cb_left = left;
  10535. l->cb_right = right;
  10536. l->cb_top = y0;
  10537. l->depth = 0;
  10538. l->nruns = 0;
  10539. l->space_pending = 0;
  10540. nhits = 0;
  10541. ndeferred = 0;
  10542. base = root_style();
  10543. layout_children(l, doc.root, &base, 0, 0);
  10544. sort_deferred();
  10545. {
  10546. int i;
  10547. for (i = 0; i < ndeferred; i++) {
  10548. struct br_style st;
  10549. br_style_for(&doc, deferred[i].node, &base, &st);
  10550. if (st.display == BR_DISPLAY_NONE)
  10551. continue;
  10552. l->draw = 1;
  10553. l->left = deferred[i].flow_left;
  10554. l->right = deferred[i].flow_right;
  10555. l->y = deferred[i].flow_y;
  10556. l->parent_top = deferred[i].parent_top;
  10557. l->line_x = l->left;
  10558. l->run_x = l->left;
  10559. l->line_y = l->y;
  10560. l->line_h = 0;
  10561. l->nruns = 0;
  10562. l->space_pending = 0;
  10563. l->align = st.align;
  10564. if (st.pos == 2 && block_h[deferred[i].node]) {
  10565. struct ngui_rect clip;
  10566. int ch = block_h[deferred[i].node] + 24;
  10567. int pr = page_rect.x + page_rect.w - 12;
  10568. int x0 = page_rect.x, x1 = pr;
  10569. /* The background pre-fill spans the box's own
  10570. * columns, not the whole page: Docusaurus parks
  10571. * a white "Skip to main content" link at
  10572. * `left: 100%` with a z-index above the navbar,
  10573. * and a full-width fill painted over the bar. */
  10574. if (st.left_set)
  10575. x0 = page_rect.x + st.left;
  10576. if (st.width_kind == 1) {
  10577. if (st.right_set && !st.left_set)
  10578. x0 = pr - st.right - st.width;
  10579. x1 = x0 + st.width;
  10580. } else if (st.right_set) {
  10581. x1 = pr - st.right;
  10582. }
  10583. if (x0 >= pr || x1 <= page_rect.x)
  10584. continue; /* entirely off-screen */
  10585. if (x0 < page_rect.x)
  10586. x0 = page_rect.x;
  10587. if (x1 > pr)
  10588. x1 = pr;
  10589. clip.x = x0;
  10590. clip.y = page_rect.y;
  10591. clip.w = x1 - x0;
  10592. if (ch > page_rect.h)
  10593. ch = page_rect.h;
  10594. clip.h = ch;
  10595. ngui_push_clip(&ui, clip);
  10596. if (st.has_bg)
  10597. ngui_fill_rect(&ui, clip, st.bg);
  10598. layout_block(l, deferred[i].node, &st, 0,
  10599. deferred[i].link);
  10600. ngui_pop_clip(&ui);
  10601. } else {
  10602. layout_block(l, deferred[i].node, &st, 0,
  10603. deferred[i].link);
  10604. }
  10605. }
  10606. }
  10607. }
  10608. /* ---- UI ---- */
  10609. static int find_hit(int x, int y)
  10610. {
  10611. int i;
  10612. for (i = nhits - 1; i >= 0; i--) {
  10613. struct hit *h = &hits[i];
  10614. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10615. y < h->y + h->h)
  10616. return (int)h->node;
  10617. }
  10618. return 0;
  10619. }
  10620. /* ---- URL-bar autocomplete ----
  10621. *
  10622. * While the address bar has the focus a dropdown lists up to SUG_MAX
  10623. * history entries. An empty bar (a fresh focus, Ctrl+L) shows the most
  10624. * visited/recent sites; typing ranks prefix matches of the URL (with or
  10625. * without the scheme and "www.") above substring matches of the URL, then
  10626. * of the title, and adds visit count and recency. Typing at the end of the
  10627. * text also completes inline to the next '/' of the best prefix match
  10628. * ("clo" -> "cloudron.io/"), with the added part selected so the next
  10629. * keystroke replaces it; Enter on that text opens the history URL it came
  10630. * from (scheme included). Up/Down preview a row in the bar, Delete on a
  10631. * highlighted row forgets it, Esc closes the list (a second Esc leaves the
  10632. * bar), and a click on a row opens it. */
  10633. #define SUG_MAX 6
  10634. #define SUG_ROW_H 36
  10635. static int sug_idx[SUG_MAX];
  10636. static int sug_n, sug_sel = -1, sug_open;
  10637. static char sug_typed[NGUI_INPUT_MAX]; /* what the user typed */
  10638. static char sug_restore[NGUI_INPUT_MAX]; /* bar text before a preview */
  10639. static char ac_text[NGUI_INPUT_MAX]; /* bar text of the inline completion */
  10640. static char ac_url[HIST_URL_MAX]; /* the history URL it stands for */
  10641. static struct ngui_rect url_rect, sug_rect;
  10642. static int url_had_focus;
  10643. static char lc(char c)
  10644. {
  10645. return c >= 'A' && c <= 'Z' ? (char)(c - 'A' + 'a') : c;
  10646. }
  10647. static int prefix_ci(const char *s, const char *p) /* p is lower case */
  10648. {
  10649. for (; *p; s++, p++)
  10650. if (lc(*s) != *p)
  10651. return 0;
  10652. return 1;
  10653. }
  10654. static unsigned int url_scheme_len(const char *url)
  10655. {
  10656. if (starts_with(url, "https://"))
  10657. return 8;
  10658. if (starts_with(url, "http://"))
  10659. return 7;
  10660. return 0;
  10661. }
  10662. /* Offset in `url` where the lower-case text `t` matches as a prefix: the
  10663. * whole URL, the URL without its scheme, or without scheme and "www.". */
  10664. static int hist_prefix_at(const char *url, const char *t)
  10665. {
  10666. unsigned int s = url_scheme_len(url);
  10667. if (prefix_ci(url, t))
  10668. return 0;
  10669. if (s && prefix_ci(url + s, t))
  10670. return (int)s;
  10671. if (starts_with(url + s, "www.") && prefix_ci(url + s + 4, t))
  10672. return (int)s + 4;
  10673. return -1;
  10674. }
  10675. static int hist_score(const struct hist_ent *e, const char *t,
  10676. unsigned int next)
  10677. {
  10678. unsigned int age = next - e->stamp;
  10679. int sc, at;
  10680. if (!t[0]) {
  10681. sc = 0;
  10682. } else if ((at = hist_prefix_at(e->url, t)) >= 0) {
  10683. /* Shorter rests first: "cloudron.io/" before its subpages. */
  10684. int rest = (int)s_len(e->url + at);
  10685. sc = 4000 - (rest > 400 ? 400 : rest);
  10686. } else if (contains_ci(e->url, t)) {
  10687. sc = 1000;
  10688. } else if (contains_ci(e->title, t)) {
  10689. sc = 600;
  10690. } else {
  10691. return -1;
  10692. }
  10693. sc += (int)(e->visits > 50 ? 50 : e->visits) * 20;
  10694. sc += age >= 500 ? 0 : (int)(500 - age);
  10695. return sc;
  10696. }
  10697. static void sug_lower(char *t, unsigned int cap)
  10698. {
  10699. unsigned int k;
  10700. for (k = 0; sug_typed[k] && k + 1 < cap; k++)
  10701. t[k] = lc(sug_typed[k]);
  10702. t[k] = '\0';
  10703. }
  10704. static void sug_refresh(void)
  10705. {
  10706. char t[NGUI_INPUT_MAX];
  10707. int sc[SUG_MAX], i, j;
  10708. unsigned int next = hist_next_stamp();
  10709. sug_lower(t, sizeof(t));
  10710. sug_n = 0;
  10711. for (i = 0; i < hist_n; i++) {
  10712. int s = hist_score(&hist_tab[i], t, next);
  10713. if (s < 0)
  10714. continue;
  10715. j = sug_n;
  10716. if (j == SUG_MAX) {
  10717. if (sc[SUG_MAX - 1] >= s)
  10718. continue;
  10719. j = SUG_MAX - 1;
  10720. }
  10721. while (j > 0 && sc[j - 1] < s) {
  10722. sc[j] = sc[j - 1];
  10723. sug_idx[j] = sug_idx[j - 1];
  10724. j--;
  10725. }
  10726. sc[j] = s;
  10727. sug_idx[j] = i;
  10728. if (sug_n < SUG_MAX)
  10729. sug_n++;
  10730. }
  10731. if (sug_sel >= sug_n)
  10732. sug_sel = -1;
  10733. }
  10734. /* Complete the typed text inline to the next '/' of the best prefix match. */
  10735. static void sug_inline(void)
  10736. {
  10737. char t[NGUI_INPUT_MAX];
  10738. const char *url, *rest;
  10739. unsigned int L, start, end, hs, tn, n = 0;
  10740. unsigned int next = hist_next_stamp();
  10741. int i, best = -1, best_sc = -1, at = 0;
  10742. sug_lower(t, sizeof(t));
  10743. L = s_len(t);
  10744. if (!L)
  10745. return;
  10746. for (i = 0; i < hist_n; i++) {
  10747. int a = hist_prefix_at(hist_tab[i].url, t), s;
  10748. if (a < 0)
  10749. continue;
  10750. s = hist_score(&hist_tab[i], t, next);
  10751. if (s > best_sc) {
  10752. best_sc = s;
  10753. best = i;
  10754. at = a;
  10755. }
  10756. }
  10757. if (best < 0)
  10758. return;
  10759. url = hist_tab[best].url;
  10760. rest = url + at;
  10761. /* Typing the scheme ("htt") completes past "https://", not to it. */
  10762. hs = at == 0 ? url_scheme_len(url) : 0;
  10763. start = L > hs ? L : hs;
  10764. end = start;
  10765. while (rest[end] && rest[end] != '/')
  10766. end++;
  10767. if (rest[end] == '/')
  10768. end++;
  10769. tn = s_len(sug_typed);
  10770. if (end <= L || tn + (end - L) + 1 >= NGUI_INPUT_MAX)
  10771. return;
  10772. s_append(ac_text, &n, sug_typed, sizeof(ac_text));
  10773. for (; L < end && n + 1 < sizeof(ac_text); L++)
  10774. ac_text[n++] = rest[L];
  10775. ac_text[n] = '\0';
  10776. s_copy(ac_url, url, (unsigned int)at + end + 1);
  10777. ngui_input_set(&url_in, ac_text);
  10778. url_in.anchor = tn; /* select the completed part */
  10779. }
  10780. static void sug_close(void)
  10781. {
  10782. sug_open = 0;
  10783. sug_sel = -1;
  10784. ac_text[0] = '\0';
  10785. }
  10786. static int sug_visible(void)
  10787. {
  10788. return sug_open && sug_n > 0 && ngui_focus(&ui) == ID_URL;
  10789. }
  10790. /* Returns whether the bar has the focus; a fresh focus (a click, Ctrl+L, the
  10791. * start page) lists the top sites until something is typed. */
  10792. static int sug_focus_check(void)
  10793. {
  10794. int focused = ngui_focus(&ui) == ID_URL;
  10795. if (focused && !url_had_focus) {
  10796. sug_typed[0] = '\0';
  10797. sug_close();
  10798. sug_open = 1;
  10799. sug_refresh();
  10800. }
  10801. url_had_focus = focused;
  10802. return focused;
  10803. }
  10804. static void url_submit(unsigned int *action)
  10805. {
  10806. if (ac_text[0] && s_eq(url_in.text, ac_text))
  10807. s_copy(click_url, ac_url, sizeof(click_url));
  10808. *action |= ACT_NAV;
  10809. sug_close();
  10810. }
  10811. /* The bar text changed through typing or editing. */
  10812. static void sug_changed(void)
  10813. {
  10814. unsigned int pl = s_len(sug_typed);
  10815. int grew = url_in.len > pl && url_in.cursor == url_in.len &&
  10816. !memcmp(url_in.text, sug_typed, pl);
  10817. s_copy(sug_typed, url_in.text, sizeof(sug_typed));
  10818. ac_text[0] = '\0';
  10819. sug_sel = -1;
  10820. sug_open = 1;
  10821. sug_refresh();
  10822. if (grew)
  10823. sug_inline();
  10824. }
  10825. /* Keys for the list, taken off the queue before the text field sees them.
  10826. * Only a leading run is handled; the rest goes to the field. */
  10827. static void sug_keys(void)
  10828. {
  10829. int k;
  10830. while ((k = ngui_key_peek(&ui)) != 0) {
  10831. if ((k == NGUI_KEY_DOWN || k == NGUI_KEY_UP) && sug_n) {
  10832. ngui_key(&ui);
  10833. if (!sug_open) {
  10834. sug_open = 1;
  10835. continue;
  10836. }
  10837. if (sug_sel < 0)
  10838. s_copy(sug_restore, url_in.text,
  10839. sizeof(sug_restore));
  10840. if (k == NGUI_KEY_DOWN)
  10841. sug_sel = sug_sel + 1 < sug_n ? sug_sel + 1 : -1;
  10842. else
  10843. sug_sel = sug_sel < 0 ? sug_n - 1 : sug_sel - 1;
  10844. ngui_input_set(&url_in, sug_sel >= 0 ?
  10845. hist_tab[sug_idx[sug_sel]].url :
  10846. sug_restore);
  10847. } else if (k == NGUI_KEY_ESC && sug_visible()) {
  10848. ngui_key(&ui);
  10849. if (sug_sel >= 0)
  10850. ngui_input_set(&url_in, sug_restore);
  10851. else if (ac_text[0] && s_eq(url_in.text, ac_text))
  10852. ngui_input_set(&url_in, sug_typed);
  10853. sug_close();
  10854. } else if (k == NGUI_KEY_DELETE && sug_visible() &&
  10855. sug_sel >= 0) {
  10856. ngui_key(&ui);
  10857. hist_forget(sug_idx[sug_sel]);
  10858. ngui_input_set(&url_in, sug_restore);
  10859. sug_sel = -1;
  10860. sug_refresh();
  10861. } else {
  10862. break;
  10863. }
  10864. }
  10865. }
  10866. /* A press on a row of last frame's list opens it; any press on the list is
  10867. * swallowed so the page underneath does not see it. */
  10868. static void sug_click(unsigned int *action)
  10869. {
  10870. int row;
  10871. if (!(ui.pressed & 1) || !sug_rect.w ||
  10872. !ngui_rect_contains(&sug_rect, ui.press_x, ui.press_y))
  10873. return;
  10874. row = (ui.press_y - sug_rect.y - 1) / SUG_ROW_H;
  10875. if (row >= 0 && row < sug_n) {
  10876. s_copy(click_url, hist_tab[sug_idx[row]].url,
  10877. sizeof(click_url));
  10878. *action |= ACT_NAV;
  10879. sug_close();
  10880. }
  10881. ui.pressed = 0;
  10882. }
  10883. static void draw_suggest(struct ngui_rect page)
  10884. {
  10885. struct ngui_rect r;
  10886. int i, rows = sug_n, hover = -1;
  10887. r.x = url_rect.x;
  10888. r.y = url_rect.y + url_rect.h + 1;
  10889. r.w = url_rect.w < 320 ? 320 : url_rect.w;
  10890. if (r.x + r.w > ui.w - 2)
  10891. r.w = ui.w - 2 - r.x;
  10892. while (rows > 0 && r.y + rows * SUG_ROW_H + 2 > page.y + page.h)
  10893. rows--;
  10894. if (rows <= 0 || r.w < 60) {
  10895. sug_rect.w = 0;
  10896. return;
  10897. }
  10898. r.h = rows * SUG_ROW_H + 2;
  10899. sug_rect = r;
  10900. if (ui.inside && ngui_rect_contains(&r, ui.mouse_x, ui.mouse_y)) {
  10901. hover = (ui.mouse_y - r.y - 1) / SUG_ROW_H;
  10902. ngui_set_cursor(&ui, CURSOR_POINTER);
  10903. }
  10904. ngui_fill_rect(&ui, r, ui.theme.border);
  10905. for (i = 0; i < rows; i++) {
  10906. const struct hist_ent *e = &hist_tab[sug_idx[i]];
  10907. struct ngui_rect rr = {r.x + 1, r.y + 1 + i * SUG_ROW_H,
  10908. r.w - 2, SUG_ROW_H};
  10909. struct ngui_rect tr = {rr.x + 8, rr.y, rr.w - 16, rr.h};
  10910. unsigned short bg = i == sug_sel ? ui.theme.selection :
  10911. i == hover ? ui.theme.panel_alt :
  10912. ui.theme.panel;
  10913. ngui_fill_rect(&ui, rr, bg);
  10914. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 2,
  10915. e->title[0] ? e->title : e->url,
  10916. ui.theme.text);
  10917. ngui_text_ellipsis(&ui, tr, tr.x, rr.y + 18, e->url,
  10918. i == sug_sel ? ui.theme.text :
  10919. ui.theme.text_dim);
  10920. }
  10921. }
  10922. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  10923. {
  10924. int x = r.x + 4, y = r.y + 4, h = 22;
  10925. int compact = r.w < 560;
  10926. int go_w = r.w < 420 ? 32 : 42;
  10927. int in_x, in_w, res;
  10928. ngui_fill_rect(&ui, r, ui.theme.panel);
  10929. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  10930. ui.theme.border);
  10931. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  10932. NGUI_ICON_CHEVRON_LEFT))
  10933. *action |= ACT_BACK;
  10934. x += 32;
  10935. if (!compact) {
  10936. if (ngui_icon_button(&ui, ID_FORWARD,
  10937. (struct ngui_rect){x, y, 28, h},
  10938. NGUI_ICON_CHEVRON_RIGHT))
  10939. *action |= ACT_FORWARD;
  10940. x += 32;
  10941. }
  10942. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  10943. NGUI_ICON_REFRESH))
  10944. *action |= ACT_RELOAD;
  10945. x += 32;
  10946. if (!compact) {
  10947. if (ngui_icon_button(&ui, ID_HOME,
  10948. (struct ngui_rect){x, y, 28, h},
  10949. NGUI_ICON_HOME))
  10950. *action |= ACT_HOME;
  10951. x += 32;
  10952. }
  10953. in_x = x + 2;
  10954. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  10955. if (in_w < 60)
  10956. in_w = 60;
  10957. url_rect = (struct ngui_rect){in_x, y, in_w, h};
  10958. if (sug_focus_check())
  10959. sug_keys();
  10960. res = ngui_text_input(&ui, ID_URL, url_rect, &url_in);
  10961. sug_focus_check(); /* a click into the bar focuses it here */
  10962. if (res & NGUI_INPUT_CHANGED)
  10963. sug_changed();
  10964. if (res & NGUI_INPUT_SUBMIT)
  10965. url_submit(action);
  10966. if (res & NGUI_INPUT_CANCEL)
  10967. ngui_set_focus(&ui, 0);
  10968. if (ngui_button(&ui, ID_GO,
  10969. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  10970. "Go"))
  10971. url_submit(action);
  10972. if (!sug_focus_check())
  10973. sug_close();
  10974. }
  10975. static int page_hover_node(void)
  10976. {
  10977. if (!ui.inside)
  10978. return 0;
  10979. if (ui.mouse_x < page_rect.x ||
  10980. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  10981. ui.mouse_y < page_rect.y ||
  10982. ui.mouse_y >= page_rect.y + page_rect.h)
  10983. return 0;
  10984. return find_hit(ui.mouse_x, ui.mouse_y);
  10985. }
  10986. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  10987. {
  10988. int x, y, w = page.w, h = page.h;
  10989. if (!src || w <= 0 || h <= 0)
  10990. return;
  10991. for (y = 0; y < h; y++) {
  10992. unsigned short *s = src + (page.y + y) * sw + page.x;
  10993. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  10994. for (x = 0; x + 1 < w; x += 2) {
  10995. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  10996. }
  10997. if (x < w)
  10998. d[x] = s[x];
  10999. }
  11000. }
  11001. static void draw_page(struct ngui_rect page)
  11002. {
  11003. int left, right, ch;
  11004. int old_panel, old_dim;
  11005. unsigned short *saved_px;
  11006. unsigned short page_bg = ui.theme.bg;
  11007. int saved_w, saved_h, use_buf;
  11008. unsigned int t0 = u_ticks_ms();
  11009. page_rect = page;
  11010. {
  11011. unsigned int root = doc.nnode > 1 ?
  11012. br_find_tag(&doc, BR_TAG_HTML) : 0;
  11013. unsigned int body = doc.nnode > 1 ?
  11014. br_find_tag(&doc, BR_TAG_BODY) : 0;
  11015. struct br_style bs;
  11016. int bg_found = 0;
  11017. if (root) {
  11018. style_for_node(root - 1, &bs);
  11019. if (bs.has_bg) {
  11020. page_bg = bs.bg;
  11021. bg_found = 1;
  11022. }
  11023. }
  11024. if (body) {
  11025. style_for_node(body - 1, &bs);
  11026. if (bs.has_bg) {
  11027. page_bg = bs.bg;
  11028. bg_found = 1;
  11029. }
  11030. }
  11031. /* No canvas colour, but the author made the text dark
  11032. * (Infima's light theme: `--ifm-background-color:
  11033. * transparent` on html, #1c1e21 text): the page expects the
  11034. * white canvas of a normal browser, and dark text on the
  11035. * dark default canvas is unreadable. */
  11036. if (!bg_found && (body || root) && bs.color != ui.theme.text) {
  11037. unsigned int c = bs.color;
  11038. unsigned int lum = ((c >> 11) & 31) * 8 * 299 +
  11039. ((c >> 5) & 63) * 4 * 587 +
  11040. (c & 31) * 8 * 114;
  11041. if (lum < 100 * 1000)
  11042. page_bg = 0xFFFF;
  11043. }
  11044. }
  11045. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  11046. page_cache_valid && layout_valid &&
  11047. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  11048. !(ui.scroll_y &&
  11049. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  11050. page_scroll.offset == page_cache_scroll &&
  11051. page_cache_nnode == doc.nnode &&
  11052. page_cache_x == page.x && page_cache_y == page.y &&
  11053. page_cache_w == page.w && page_cache_h == page.h) {
  11054. blit_page(page, page_backbuf, pagebuf_w);
  11055. if (img_stat_n)
  11056. img_stat_paint += u_ticks_ms() - t0;
  11057. return;
  11058. }
  11059. ngui_fill_rect(&ui, page, page_bg);
  11060. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  11061. const char *s = page_loading ? "Loading..." : "No page";
  11062. int w = (int)ngui_text_width_ui(&ui, s);
  11063. ngui_text(&ui, page.x + (page.w - w) / 2,
  11064. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  11065. page_scroll.content_h = 0;
  11066. page_scroll.view_h = page.h;
  11067. page_cache_valid = 0;
  11068. return;
  11069. }
  11070. if (page.w < 40 || page.h < 40) {
  11071. page_cache_valid = 0;
  11072. return;
  11073. }
  11074. saved_px = ui.px;
  11075. saved_w = ui.w;
  11076. saved_h = ui.h;
  11077. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  11078. if (use_buf) {
  11079. ui.px = page_backbuf;
  11080. ui.w = pagebuf_w;
  11081. ui.h = pagebuf_h;
  11082. ngui_fill_rect(&ui, page, page_bg);
  11083. }
  11084. left = page.x + 8;
  11085. right = page.x + page.w - 16;
  11086. if (!layout_valid || left != layout_left || right != layout_right ||
  11087. layout_nnode != doc.nnode) {
  11088. unsigned int tm = u_ticks_ms();
  11089. layout_view_h = page.h - 8;
  11090. layout_content_h = measure_page(left, right);
  11091. if (img_stat_n)
  11092. img_stat_reflow += u_ticks_ms() - tm;
  11093. layout_valid = 1;
  11094. layout_left = left;
  11095. layout_right = right;
  11096. layout_nnode = doc.nnode;
  11097. /* Scripts that measured before any layout (offsetWidth on
  11098. * mount) get a resize event once real boxes exist, and again
  11099. * whenever the page width changes. */
  11100. if (js_browser_active() && right - left != resize_sent_w)
  11101. resize_pending = 1;
  11102. }
  11103. ch = layout_content_h;
  11104. page_scroll.content_h = ch;
  11105. page_scroll.view_h = page.h;
  11106. t0 = u_ticks_ms();
  11107. ngui_scroll_begin(&ui, page, &page_scroll);
  11108. ngui_scroll_wheel(&ui, page, &page_scroll);
  11109. render_page(left, right, page.y + 4 - page_scroll.offset);
  11110. old_panel = ui.theme.panel_alt;
  11111. old_dim = ui.theme.text_dim;
  11112. ui.theme.panel_alt = 0xC618;
  11113. ui.theme.text_dim = 0x8410;
  11114. ngui_scroll_end(&ui, page, &page_scroll);
  11115. ui.theme.panel_alt = old_panel;
  11116. ui.theme.text_dim = old_dim;
  11117. if (use_buf) {
  11118. ui.px = saved_px;
  11119. ui.w = saved_w;
  11120. ui.h = saved_h;
  11121. blit_page(page, page_backbuf, pagebuf_w);
  11122. page_cache_valid = 1;
  11123. page_cache_scroll = page_scroll.offset;
  11124. page_cache_nnode = doc.nnode;
  11125. page_cache_x = page.x;
  11126. page_cache_y = page.y;
  11127. page_cache_w = page.w;
  11128. page_cache_h = page.h;
  11129. } else {
  11130. page_cache_valid = 0;
  11131. }
  11132. if (img_stat_n)
  11133. img_stat_paint += u_ticks_ms() - t0;
  11134. }
  11135. static void draw_status(struct ngui_rect r)
  11136. {
  11137. static char msg[BR_URL_MAX + 32]; /* leaf: off the 128 KB stack */
  11138. unsigned int n = 0;
  11139. int hover = page_hover_node();
  11140. unsigned short color;
  11141. const char *kind;
  11142. ngui_fill_rect(&ui, r, ui.theme.panel);
  11143. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  11144. ui.theme.border);
  11145. if (hover) {
  11146. const char *href = br_href(&doc, (unsigned int)hover);
  11147. char url[BR_URL_MAX];
  11148. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  11149. s_append(msg, &n, "Link: ", sizeof(msg));
  11150. s_append(msg, &n, url, sizeof(msg));
  11151. } else {
  11152. s_copy(msg, "Link", sizeof(msg));
  11153. }
  11154. color = ui.theme.accent;
  11155. } else if (status_text[0]) {
  11156. s_copy(msg, status_text, sizeof(msg));
  11157. color = status_error ? ui.theme.error : ui.theme.text;
  11158. } else if (page_title[0]) {
  11159. s_copy(msg, page_title, sizeof(msg));
  11160. color = ui.theme.text;
  11161. } else {
  11162. s_copy(msg, "Ready", sizeof(msg));
  11163. color = ui.theme.text_dim;
  11164. }
  11165. kind = s_eq(page_url, "about:home") ? "HOME" :
  11166. page_is_local ? "FILE" :
  11167. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  11168. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  11169. {
  11170. int kw = (int)ngui_text_width_ui(&ui, kind);
  11171. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  11172. ui.theme.text_dim);
  11173. }
  11174. }
  11175. /* Mouse cursor over the page: the hovered node's CSS `cursor` (inherited);
  11176. * for `auto`, a hand over links, the I-beam over text fields, and the
  11177. * progress arrow anywhere on the page while it is still loading. The
  11178. * toolbar's URL field sets its own I-beam through ngui. */
  11179. static void page_cursor(void)
  11180. {
  11181. int hover = page_hover_node();
  11182. struct br_style st;
  11183. if (!hover) {
  11184. if (page_loading && ui.inside &&
  11185. ngui_rect_contains(&page_rect, ui.mouse_x, ui.mouse_y))
  11186. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11187. return;
  11188. }
  11189. style_for_node((unsigned int)hover, &st);
  11190. if (st.cursor != BR_CURSOR_AUTO) {
  11191. ngui_set_cursor(&ui, (int)st.cursor - 1);
  11192. return;
  11193. }
  11194. if (br_href(&doc, (unsigned int)hover)) {
  11195. ngui_set_cursor(&ui, CURSOR_POINTER);
  11196. return;
  11197. }
  11198. if (form_is_control((unsigned int)hover)) {
  11199. int k = form_kind_of((unsigned int)hover);
  11200. if (form_disabled((unsigned int)hover))
  11201. ngui_set_cursor(&ui, CURSOR_DEFAULT);
  11202. else if (k == FORM_TEXT || k == FORM_PASSWORD ||
  11203. k == FORM_TEXTAREA)
  11204. ngui_set_cursor(&ui, CURSOR_TEXT);
  11205. return;
  11206. }
  11207. if (page_loading)
  11208. ngui_set_cursor(&ui, CURSOR_PROGRESS);
  11209. }
  11210. static void draw(unsigned int *action)
  11211. {
  11212. struct ngui_rect r = {0, 0, ui.w, ui.h};
  11213. struct ngui_rect toolbar, status, page;
  11214. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  11215. status = ngui_cut_bottom(&r, BR_STATUS_H);
  11216. page = r;
  11217. if (sug_visible())
  11218. sug_click(action);
  11219. draw_toolbar(toolbar, action);
  11220. draw_page(page);
  11221. draw_status(status);
  11222. page_cursor();
  11223. if (sug_visible())
  11224. draw_suggest(page);
  11225. else
  11226. sug_rect.w = 0;
  11227. }
  11228. static void redraw_now(void)
  11229. {
  11230. unsigned int action = 0;
  11231. ngui_begin(&ui);
  11232. draw(&action);
  11233. ngui_end(&ui);
  11234. }
  11235. static void handle_keys(unsigned int *action)
  11236. {
  11237. int k, scrolled = 0;
  11238. if (form_focus >= doc.nnode)
  11239. form_focus = 0;
  11240. if (form_focus && !ngui_focus(&ui)) {
  11241. while ((k = ngui_key(&ui)) != 0)
  11242. form_key(k);
  11243. return;
  11244. }
  11245. /* Batch queued page keys: a slow full-page render must not make a
  11246. * held Page Down advance only once every few frames. */
  11247. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  11248. scrolled++;
  11249. if (scrolled)
  11250. ngui_invalidate(&ui);
  11251. if (ngui_focus(&ui))
  11252. return;
  11253. while ((k = ngui_key(&ui)) != 0) {
  11254. switch (k) {
  11255. case NGUI_KEY_ESC:
  11256. *action |= ACT_CLOSE;
  11257. break;
  11258. case NGUI_KEY_TAB:
  11259. case 0x0C: /* Ctrl+L */
  11260. ngui_set_focus(&ui, ID_URL);
  11261. break;
  11262. case 0x12: /* Ctrl+R */
  11263. *action |= ACT_RELOAD;
  11264. break;
  11265. case NGUI_KEY_BACKSPACE:
  11266. *action |= ACT_BACK;
  11267. break;
  11268. case NGUI_KEY_UP:
  11269. ngui_scroll_to(&page_scroll,
  11270. page_scroll.offset - 24);
  11271. ngui_invalidate(&ui);
  11272. break;
  11273. case NGUI_KEY_DOWN:
  11274. ngui_scroll_to(&page_scroll,
  11275. page_scroll.offset + 24);
  11276. ngui_invalidate(&ui);
  11277. break;
  11278. case NGUI_KEY_HOME:
  11279. ngui_scroll_to(&page_scroll, 0);
  11280. ngui_invalidate(&ui);
  11281. break;
  11282. case NGUI_KEY_END:
  11283. ngui_scroll_to(&page_scroll,
  11284. page_scroll.content_h -
  11285. page_scroll.view_h);
  11286. ngui_invalidate(&ui);
  11287. break;
  11288. default:
  11289. break;
  11290. }
  11291. }
  11292. }
  11293. static unsigned int form_ancestor(unsigned int node)
  11294. {
  11295. unsigned int p = node;
  11296. while (p && p < doc.nnode) {
  11297. if (doc.nodes[p].tag == BR_TAG_FORM &&
  11298. doc.nodes[p].type == BR_NODE_ELEM)
  11299. return p;
  11300. p = doc.nodes[p].parent;
  11301. }
  11302. return 0;
  11303. }
  11304. static int form_descendant(unsigned int node, unsigned int form)
  11305. {
  11306. unsigned int p = node;
  11307. while (p && p < doc.nnode) {
  11308. if (p == form)
  11309. return 1;
  11310. p = doc.nodes[p].parent;
  11311. }
  11312. return 0;
  11313. }
  11314. static void form_reset_form(unsigned int form)
  11315. {
  11316. unsigned int i;
  11317. for (i = 0; i < FORM_MAX; i++)
  11318. if (form_states[i].used &&
  11319. form_descendant(form_states[i].node, form))
  11320. form_states[i].used = 0;
  11321. form_focus = 0;
  11322. }
  11323. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  11324. const char *s)
  11325. {
  11326. static const char hex[] = "0123456789ABCDEF";
  11327. while (s && *s && *n + 1 < cap) {
  11328. unsigned char c = (unsigned char)*s++;
  11329. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  11330. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  11331. c == '.' || c == '~') {
  11332. dst[(*n)++] = (char)c;
  11333. } else if (c == ' ') {
  11334. dst[(*n)++] = '+';
  11335. } else if (*n + 3 < cap) {
  11336. dst[(*n)++] = '%';
  11337. dst[(*n)++] = hex[c >> 4];
  11338. dst[(*n)++] = hex[c & 15];
  11339. }
  11340. }
  11341. dst[*n] = '\0';
  11342. }
  11343. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  11344. const char *name, const char *value, int *first)
  11345. {
  11346. if (!name || !name[0])
  11347. return;
  11348. if (!*first && *n + 1 < cap)
  11349. dst[(*n)++] = '&';
  11350. *first = 0;
  11351. form_url_append(dst, n, cap, name);
  11352. if (*n + 1 < cap)
  11353. dst[(*n)++] = '=';
  11354. form_url_append(dst, n, cap, value ? value : "");
  11355. dst[*n] = '\0';
  11356. }
  11357. static int form_submit_form(unsigned int node, int fire_event)
  11358. {
  11359. unsigned int form = form_ancestor(node);
  11360. char action[BR_URL_MAX], query[2048];
  11361. unsigned int qn = 0, i;
  11362. int first = 1, is_post = 0;
  11363. const char *a, *method;
  11364. if (!form)
  11365. return 0;
  11366. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  11367. return 0;
  11368. method = br_find_attr(&doc, form, "method");
  11369. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  11370. is_post = 1;
  11371. a = br_find_attr(&doc, form, "action");
  11372. if (a && a[0]) {
  11373. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  11374. return 0;
  11375. } else {
  11376. s_copy(action, page_url, sizeof(action));
  11377. }
  11378. query[0] = '\0';
  11379. for (i = 0; i < doc.nnode; i++) {
  11380. struct br_node *nd = &doc.nodes[i];
  11381. struct form_state *fs;
  11382. const char *name;
  11383. const char *value = "";
  11384. if (nd->type != BR_NODE_ELEM || i == form ||
  11385. !form_descendant(i, form))
  11386. continue;
  11387. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  11388. nd->tag != BR_TAG_SELECT)
  11389. continue;
  11390. if (form_disabled(i))
  11391. continue;
  11392. name = br_find_attr(&doc, i, "name");
  11393. if (!name || !name[0])
  11394. continue;
  11395. fs = form_get(i, 1);
  11396. if (!fs)
  11397. continue;
  11398. if (nd->tag == BR_TAG_SELECT) {
  11399. char opt[64];
  11400. if (!form_option_text(i, fs->selected, opt,
  11401. sizeof(opt)))
  11402. s_copy(opt, "", sizeof(opt));
  11403. value = opt;
  11404. {
  11405. unsigned int c, oi = 0;
  11406. for (c = nd->first; c;
  11407. c = doc.nodes[c].next) {
  11408. if (doc.nodes[c].type != BR_NODE_ELEM ||
  11409. doc.nodes[c].tag != BR_TAG_OPTION)
  11410. continue;
  11411. if (oi == fs->selected) {
  11412. const char *v =
  11413. br_value(&doc, c);
  11414. if (v && v[0])
  11415. value = v;
  11416. break;
  11417. }
  11418. oi++;
  11419. }
  11420. }
  11421. } else if (nd->tag == BR_TAG_INPUT) {
  11422. int kind = form_kind_of(i);
  11423. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11424. if (!fs->checked)
  11425. continue;
  11426. value = br_value(&doc, i);
  11427. if (!value || !value[0])
  11428. value = "on";
  11429. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  11430. kind == FORM_BUTTON) {
  11431. if (i != node)
  11432. continue;
  11433. value = fs->value;
  11434. } else {
  11435. value = fs->value;
  11436. }
  11437. } else {
  11438. value = fs->value;
  11439. }
  11440. form_add_param(query, &qn, sizeof(query), name, value, &first);
  11441. }
  11442. if (is_post) {
  11443. if (action[0] == '/') {
  11444. set_status("POST forms need an HTTP action URL", 1, 4000);
  11445. ngui_invalidate(&ui);
  11446. return 0;
  11447. }
  11448. if (qn >= sizeof(pending_post))
  11449. qn = sizeof(pending_post) - 1;
  11450. if (qn)
  11451. memcpy(pending_post, query, qn);
  11452. pending_post[qn] = '\0';
  11453. pending_post_len = qn;
  11454. pending_post_is = 1;
  11455. } else {
  11456. pending_post_len = 0;
  11457. pending_post_is = 0;
  11458. if (qn) {
  11459. unsigned int an = s_len(action);
  11460. if (an + qn + 2 < sizeof(action)) {
  11461. action[an++] = strchr(action, '?') ? '&' : '?';
  11462. action[an] = '\0';
  11463. s_copy(action + an, query,
  11464. sizeof(action) - an);
  11465. }
  11466. }
  11467. }
  11468. s_copy(pending_url, action, sizeof(pending_url));
  11469. pending_action |= ACT_NAV;
  11470. cancel_fetch = 1;
  11471. ngui_invalidate(&ui);
  11472. return 1;
  11473. }
  11474. static void form_reset_event(unsigned int form)
  11475. {
  11476. if (form && !js_browser_event(form, "reset", 1, 1))
  11477. return;
  11478. if (form)
  11479. form_reset_form(form);
  11480. else
  11481. form_reset_state();
  11482. form_dirty = 0;
  11483. layout_valid = 0;
  11484. ngui_invalidate(&ui);
  11485. }
  11486. static void form_blur(void)
  11487. {
  11488. unsigned int node = form_focus;
  11489. form_focus = 0;
  11490. if (node && form_dirty) {
  11491. form_dirty = 0;
  11492. js_browser_event(node, "change", 1, 0);
  11493. }
  11494. }
  11495. static void form_click(unsigned int node)
  11496. {
  11497. struct form_state *fs;
  11498. int kind, changed = 0;
  11499. if (!form_is_control(node) || form_disabled(node))
  11500. return;
  11501. if (form_focus != node)
  11502. form_blur();
  11503. if (!js_browser_event(node, "click", 1, 1))
  11504. return;
  11505. fs = form_get(node, 1);
  11506. if (!fs)
  11507. return;
  11508. kind = form_kind_of(node);
  11509. form_focus = node;
  11510. form_dirty = 0;
  11511. if (kind == FORM_CHECKBOX) {
  11512. fs->checked = !fs->checked;
  11513. changed = 1;
  11514. } else if (kind == FORM_RADIO) {
  11515. const char *name = br_find_attr(&doc, node, "name");
  11516. unsigned int i;
  11517. fs->checked = 1;
  11518. changed = 1;
  11519. if (name) {
  11520. for (i = 0; i < FORM_MAX; i++) {
  11521. struct form_state *o = &form_states[i];
  11522. if (!o->used || o->node == node)
  11523. continue;
  11524. if (form_kind_of(o->node) == FORM_RADIO) {
  11525. const char *on = br_find_attr(&doc,
  11526. o->node,
  11527. "name");
  11528. if (on && s_eq(on, name))
  11529. o->checked = 0;
  11530. }
  11531. }
  11532. }
  11533. } else if (kind == FORM_SELECT) {
  11534. unsigned int n = form_option_count(node);
  11535. if (n) {
  11536. fs->selected = (unsigned char)
  11537. ((fs->selected + 1) % n);
  11538. changed = 1;
  11539. }
  11540. } else if (kind == FORM_SUBMIT) {
  11541. form_submit_form(node, 1);
  11542. return;
  11543. } else if (kind == FORM_RESET) {
  11544. form_reset_event(form_ancestor(node));
  11545. return;
  11546. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  11547. kind == FORM_TEXTAREA) {
  11548. fs->caret = fs->len;
  11549. }
  11550. if (changed) {
  11551. js_browser_event(node, "input", 1, 0);
  11552. js_browser_event(node, "change", 1, 0);
  11553. }
  11554. layout_valid = 0;
  11555. ngui_invalidate(&ui);
  11556. }
  11557. static void form_focus_next(void)
  11558. {
  11559. unsigned int start = form_focus ? form_focus + 1 : 0;
  11560. unsigned int i;
  11561. form_blur();
  11562. for (i = start; i < doc.nnode; i++) {
  11563. if (form_is_control(i) && !form_disabled(i) &&
  11564. !s_eq(br_type(&doc, i), "hidden")) {
  11565. form_focus = i;
  11566. layout_valid = 0;
  11567. ngui_invalidate(&ui);
  11568. return;
  11569. }
  11570. }
  11571. form_focus = 0;
  11572. layout_valid = 0;
  11573. ngui_invalidate(&ui);
  11574. }
  11575. static void form_key(int k)
  11576. {
  11577. struct form_state *fs;
  11578. int kind;
  11579. if (!form_focus || form_focus >= doc.nnode) {
  11580. form_focus = 0;
  11581. return;
  11582. }
  11583. fs = form_get(form_focus, 1);
  11584. if (!fs || form_disabled(form_focus))
  11585. return;
  11586. kind = form_kind_of(form_focus);
  11587. if (kind == FORM_SELECT) {
  11588. unsigned int n = form_option_count(form_focus);
  11589. int changed = 0;
  11590. if (k == NGUI_KEY_UP && n) {
  11591. fs->selected = (unsigned char)
  11592. ((fs->selected + n - 1) % n);
  11593. changed = 1;
  11594. } else if (k == NGUI_KEY_DOWN && n) {
  11595. fs->selected = (unsigned char)
  11596. ((fs->selected + 1) % n);
  11597. changed = 1;
  11598. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11599. form_blur();
  11600. layout_valid = 0;
  11601. ngui_invalidate(&ui);
  11602. return;
  11603. } else {
  11604. return;
  11605. }
  11606. if (changed) {
  11607. js_browser_event(form_focus, "input", 1, 0);
  11608. js_browser_event(form_focus, "change", 1, 0);
  11609. }
  11610. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  11611. if (k == ' ') {
  11612. form_click(form_focus);
  11613. return;
  11614. }
  11615. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  11616. form_blur();
  11617. layout_valid = 0;
  11618. ngui_invalidate(&ui);
  11619. }
  11620. return;
  11621. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  11622. kind == FORM_RESET) {
  11623. if (k == NGUI_KEY_ESC) {
  11624. form_blur();
  11625. layout_valid = 0;
  11626. ngui_invalidate(&ui);
  11627. } else if (k == '\r' || k == '\n' || k == ' ') {
  11628. form_click(form_focus);
  11629. }
  11630. return;
  11631. } else if (k == NGUI_KEY_TAB) {
  11632. form_focus_next();
  11633. return;
  11634. } else if (k == NGUI_KEY_ESC) {
  11635. form_blur();
  11636. layout_valid = 0;
  11637. ngui_invalidate(&ui);
  11638. return;
  11639. } else if (k == '\r' || k == '\n') {
  11640. unsigned int node = form_focus;
  11641. form_blur();
  11642. if (form_ancestor(node))
  11643. form_submit_form(node, 1);
  11644. layout_valid = 0;
  11645. ngui_invalidate(&ui);
  11646. return;
  11647. } else if (k == NGUI_KEY_BACKSPACE) {
  11648. if (fs->caret) {
  11649. unsigned int i = --fs->caret;
  11650. for (; i < fs->len; i++)
  11651. fs->value[i] = fs->value[i + 1];
  11652. if (fs->len)
  11653. fs->len--;
  11654. form_dirty = 1;
  11655. js_browser_event(form_focus, "input", 1, 0);
  11656. }
  11657. } else if (k == NGUI_KEY_DELETE) {
  11658. if (fs->caret < fs->len) {
  11659. unsigned int i;
  11660. for (i = fs->caret; i < fs->len; i++)
  11661. fs->value[i] = fs->value[i + 1];
  11662. fs->len--;
  11663. form_dirty = 1;
  11664. js_browser_event(form_focus, "input", 1, 0);
  11665. }
  11666. } else if (k == NGUI_KEY_LEFT) {
  11667. if (fs->caret)
  11668. fs->caret--;
  11669. } else if (k == NGUI_KEY_RIGHT) {
  11670. if (fs->caret < fs->len)
  11671. fs->caret++;
  11672. } else if (k == NGUI_KEY_HOME) {
  11673. fs->caret = 0;
  11674. } else if (k == NGUI_KEY_END) {
  11675. fs->caret = fs->len;
  11676. } else if (k >= 32 && k < 127) {
  11677. if (fs->len < FORM_VALUE_MAX) {
  11678. unsigned int i;
  11679. for (i = fs->len; i > fs->caret; i--)
  11680. fs->value[i] = fs->value[i - 1];
  11681. fs->value[fs->caret++] = (char)k;
  11682. fs->len++;
  11683. form_dirty = 1;
  11684. js_browser_event(form_focus, "input", 1, 0);
  11685. }
  11686. } else {
  11687. return;
  11688. }
  11689. fs->value[fs->len] = '\0';
  11690. layout_valid = 0;
  11691. ngui_invalidate(&ui);
  11692. }
  11693. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  11694. * a same-document navigation: update the URL and fire hashchange. Returns
  11695. * 1 when handled. */
  11696. static int link_fragment_nav(unsigned int node)
  11697. {
  11698. const char *href = br_href(&doc, node);
  11699. char url[BR_URL_MAX];
  11700. unsigned int n = 0;
  11701. if (!href || !href[0] || !js_browser_active())
  11702. return 0;
  11703. if (href[0] == '#') {
  11704. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  11705. url[n] = page_url[n];
  11706. n++;
  11707. }
  11708. url[n] = '\0';
  11709. s_append(url, &n, href, sizeof(url));
  11710. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  11711. return 0;
  11712. }
  11713. if (!same_doc_fragment(url))
  11714. return href[0] == '#';
  11715. page_set_fragment(url, 1);
  11716. js_browser_hashchange();
  11717. return 1;
  11718. }
  11719. /* The innermost laid-out box under a screen point: the smallest valid box
  11720. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  11721. * Used to deliver clicks to elements that are neither links nor controls
  11722. * (a Vue <div role="button">, a card with a click listener). */
  11723. static unsigned int find_box_hit(int x, int y)
  11724. {
  11725. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  11726. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  11727. const struct br_layout_box *b = &layout_boxes[i];
  11728. unsigned int area;
  11729. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  11730. x < b->x || y < b->y || x >= b->x + b->w ||
  11731. y >= b->y + b->h)
  11732. continue;
  11733. area = (unsigned int)b->w * (unsigned int)b->h;
  11734. if (area <= best_area) {
  11735. best = i;
  11736. best_area = area;
  11737. }
  11738. }
  11739. return best;
  11740. }
  11741. static void handle_page_click(unsigned int *action)
  11742. {
  11743. int node;
  11744. char url[BR_URL_MAX];
  11745. if (!ui.pressed)
  11746. return;
  11747. if (ui.press_x < page_rect.x ||
  11748. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  11749. ui.press_y < page_rect.y ||
  11750. ui.press_y >= page_rect.y + page_rect.h)
  11751. return;
  11752. node = find_hit(ui.press_x, ui.press_y);
  11753. if (!node) {
  11754. unsigned int box;
  11755. if (!js_browser_active())
  11756. return;
  11757. box = find_box_hit(ui.press_x, ui.press_y);
  11758. if (box) {
  11759. form_blur();
  11760. js_browser_event(box, "click", 1, 1);
  11761. }
  11762. return;
  11763. }
  11764. if (form_is_control((unsigned int)node)) {
  11765. form_click((unsigned int)node);
  11766. return;
  11767. }
  11768. form_blur();
  11769. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  11770. return;
  11771. if (link_fragment_nav((unsigned int)node))
  11772. return;
  11773. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  11774. sizeof(url)) != 0)
  11775. return;
  11776. s_copy(click_url, url, sizeof(click_url));
  11777. *action |= ACT_NAV;
  11778. }
  11779. void _start(const char *arg)
  11780. {
  11781. struct win_info wi;
  11782. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  11783. u_win_create(960, 640, "Browser", &wi) != 0 &&
  11784. u_win_create(780, 540, "Browser", &wi) != 0) {
  11785. u_puts("browser: no graphics window\n");
  11786. u_exit(1);
  11787. }
  11788. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  11789. url_in.placeholder = "http://...";
  11790. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  11791. ui.theme.accent);
  11792. br_set_viewport(wi.width);
  11793. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  11794. s_copy(cwd, "/", sizeof(cwd));
  11795. heap_clear();
  11796. origin_cache_load();
  11797. css_cache_init();
  11798. script_cache_init();
  11799. persist_restore();
  11800. hist_load();
  11801. page_scroll.offset = 0;
  11802. page_scroll.content_h = 0;
  11803. if (arg && arg[0]) {
  11804. navigate(arg, 1);
  11805. } else {
  11806. load_home(1);
  11807. /* Start ready to type: keep the home page, but leave the address
  11808. * bar empty instead of showing "about:home". */
  11809. ngui_input_set(&url_in, "");
  11810. ngui_set_focus(&ui, ID_URL);
  11811. }
  11812. for (;;) {
  11813. unsigned int action = 0;
  11814. unsigned int now;
  11815. click_url[0] = '\0';
  11816. if (pending_action) {
  11817. action |= pending_action & ACT_WAIT_NAV;
  11818. if (pending_url[0])
  11819. s_copy(click_url, pending_url, sizeof(click_url));
  11820. pending_action = 0;
  11821. pending_url[0] = '\0';
  11822. cancel_fetch = 0;
  11823. } else if (preload_active) {
  11824. if (preload_wait)
  11825. preload_wait = 0;
  11826. else
  11827. preload_step();
  11828. } else if ((preload_pending &&
  11829. page_scroll.offset != preload_scroll) ||
  11830. (preload_rescan && layout_valid)) {
  11831. preload_scroll = page_scroll.offset;
  11832. preload_rescan = 0;
  11833. preload_pending = 0;
  11834. preload_node = 0;
  11835. preload_active = 1;
  11836. }
  11837. js_browser_tick();
  11838. if (resize_pending && !pending_action) {
  11839. resize_pending = 0;
  11840. resize_sent_w = layout_right - layout_left;
  11841. js_browser_window_event("resize");
  11842. }
  11843. persist_tick();
  11844. if (pending_action)
  11845. continue;
  11846. now = u_ticks_ms();
  11847. if (status_until && (int)(now - status_until) >= 0) {
  11848. status_text[0] = '\0';
  11849. status_until = 0;
  11850. status_error = 0;
  11851. ngui_invalidate(&ui);
  11852. }
  11853. if (!ngui_begin(&ui)) {
  11854. /* A queued navigation (e.g. Enter in the URL bar during
  11855. * a slow fetch) must be handled even when this frame
  11856. * needs no redraw. */
  11857. if (!action) {
  11858. fetch_workers_stop_if_unfocused();
  11859. u_sleep_ms(10);
  11860. continue;
  11861. }
  11862. } else {
  11863. draw(&action);
  11864. handle_keys(&action);
  11865. handle_page_click(&action);
  11866. ngui_end(&ui);
  11867. }
  11868. if (action & ACT_NAV) {
  11869. if (click_url[0]) {
  11870. navigate(click_url, 1);
  11871. click_url[0] = '\0';
  11872. } else {
  11873. navigate(url_in.text, 1);
  11874. }
  11875. }
  11876. if (action & ACT_BACK) {
  11877. if (hist_pos > 0) {
  11878. hist_pos--;
  11879. if (same_doc_fragment(history[hist_pos])) {
  11880. page_set_fragment(history[hist_pos], 0);
  11881. js_browser_hashchange();
  11882. } else {
  11883. navigate(history[hist_pos], 0);
  11884. }
  11885. }
  11886. }
  11887. if (action & ACT_FORWARD) {
  11888. if (hist_pos + 1 < hist_len) {
  11889. hist_pos++;
  11890. if (same_doc_fragment(history[hist_pos])) {
  11891. page_set_fragment(history[hist_pos], 0);
  11892. js_browser_hashchange();
  11893. } else {
  11894. navigate(history[hist_pos], 0);
  11895. }
  11896. }
  11897. }
  11898. if (action & ACT_RELOAD) {
  11899. if (s_eq(page_url, "about:home"))
  11900. load_home(0);
  11901. else
  11902. navigate(page_url, 0);
  11903. }
  11904. if (action & ACT_HOME)
  11905. load_home(1);
  11906. if (action & ACT_CLOSE)
  11907. quit = 1;
  11908. if (quit)
  11909. break;
  11910. if (pending_action)
  11911. continue;
  11912. fetch_workers_stop_if_unfocused();
  11913. u_sleep_ms(10);
  11914. }
  11915. fetch_workers_stop_all();
  11916. u_win_close();
  11917. u_exit(0);
  11918. }