browser.c 309 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935193619371938193919401941194219431944194519461947194819491950195119521953195419551956195719581959196019611962196319641965196619671968196919701971197219731974197519761977197819791980198119821983198419851986198719881989199019911992199319941995199619971998199920002001200220032004200520062007200820092010201120122013201420152016201720182019202020212022202320242025202620272028202920302031203220332034203520362037203820392040204120422043204420452046204720482049205020512052205320542055205620572058205920602061206220632064206520662067206820692070207120722073207420752076207720782079208020812082208320842085208620872088208920902091209220932094209520962097209820992100210121022103210421052106210721082109211021112112211321142115211621172118211921202121212221232124212521262127212821292130213121322133213421352136213721382139214021412142214321442145214621472148214921502151215221532154215521562157215821592160216121622163216421652166216721682169217021712172217321742175217621772178217921802181218221832184218521862187218821892190219121922193219421952196219721982199220022012202220322042205220622072208220922102211221222132214221522162217221822192220222122222223222422252226222722282229223022312232223322342235223622372238223922402241224222432244224522462247224822492250225122522253225422552256225722582259226022612262226322642265226622672268226922702271227222732274227522762277227822792280228122822283228422852286228722882289229022912292229322942295229622972298229923002301230223032304230523062307230823092310231123122313231423152316231723182319232023212322232323242325232623272328232923302331233223332334233523362337233823392340234123422343234423452346234723482349235023512352235323542355235623572358235923602361236223632364236523662367236823692370237123722373237423752376237723782379238023812382238323842385238623872388238923902391239223932394239523962397239823992400240124022403240424052406240724082409241024112412241324142415241624172418241924202421242224232424242524262427242824292430243124322433243424352436243724382439244024412442244324442445244624472448244924502451245224532454245524562457245824592460246124622463246424652466246724682469247024712472247324742475247624772478247924802481248224832484248524862487248824892490249124922493249424952496249724982499250025012502250325042505250625072508250925102511251225132514251525162517251825192520252125222523252425252526252725282529253025312532253325342535253625372538253925402541254225432544254525462547254825492550255125522553255425552556255725582559256025612562256325642565256625672568256925702571257225732574257525762577257825792580258125822583258425852586258725882589259025912592259325942595259625972598259926002601260226032604260526062607260826092610261126122613261426152616261726182619262026212622262326242625262626272628262926302631263226332634263526362637263826392640264126422643264426452646264726482649265026512652265326542655265626572658265926602661266226632664266526662667266826692670267126722673267426752676267726782679268026812682268326842685268626872688268926902691269226932694269526962697269826992700270127022703270427052706270727082709271027112712271327142715271627172718271927202721272227232724272527262727272827292730273127322733273427352736273727382739274027412742274327442745274627472748274927502751275227532754275527562757275827592760276127622763276427652766276727682769277027712772277327742775277627772778277927802781278227832784278527862787278827892790279127922793279427952796279727982799280028012802280328042805280628072808280928102811281228132814281528162817281828192820282128222823282428252826282728282829283028312832283328342835283628372838283928402841284228432844284528462847284828492850285128522853285428552856285728582859286028612862286328642865286628672868286928702871287228732874287528762877287828792880288128822883288428852886288728882889289028912892289328942895289628972898289929002901290229032904290529062907290829092910291129122913291429152916291729182919292029212922292329242925292629272928292929302931293229332934293529362937293829392940294129422943294429452946294729482949295029512952295329542955295629572958295929602961296229632964296529662967296829692970297129722973297429752976297729782979298029812982298329842985298629872988298929902991299229932994299529962997299829993000300130023003300430053006300730083009301030113012301330143015301630173018301930203021302230233024302530263027302830293030303130323033303430353036303730383039304030413042304330443045304630473048304930503051305230533054305530563057305830593060306130623063306430653066306730683069307030713072307330743075307630773078307930803081308230833084308530863087308830893090309130923093309430953096309730983099310031013102310331043105310631073108310931103111311231133114311531163117311831193120312131223123312431253126312731283129313031313132313331343135313631373138313931403141314231433144314531463147314831493150315131523153315431553156315731583159316031613162316331643165316631673168316931703171317231733174317531763177317831793180318131823183318431853186318731883189319031913192319331943195319631973198319932003201320232033204320532063207320832093210321132123213321432153216321732183219322032213222322332243225322632273228322932303231323232333234323532363237323832393240324132423243324432453246324732483249325032513252325332543255325632573258325932603261326232633264326532663267326832693270327132723273327432753276327732783279328032813282328332843285328632873288328932903291329232933294329532963297329832993300330133023303330433053306330733083309331033113312331333143315331633173318331933203321332233233324332533263327332833293330333133323333333433353336333733383339334033413342334333443345334633473348334933503351335233533354335533563357335833593360336133623363336433653366336733683369337033713372337333743375337633773378337933803381338233833384338533863387338833893390339133923393339433953396339733983399340034013402340334043405340634073408340934103411341234133414341534163417341834193420342134223423342434253426342734283429343034313432343334343435343634373438343934403441344234433444344534463447344834493450345134523453345434553456345734583459346034613462346334643465346634673468346934703471347234733474347534763477347834793480348134823483348434853486348734883489349034913492349334943495349634973498349935003501350235033504350535063507350835093510351135123513351435153516351735183519352035213522352335243525352635273528352935303531353235333534353535363537353835393540354135423543354435453546354735483549355035513552355335543555355635573558355935603561356235633564356535663567356835693570357135723573357435753576357735783579358035813582358335843585358635873588358935903591359235933594359535963597359835993600360136023603360436053606360736083609361036113612361336143615361636173618361936203621362236233624362536263627362836293630363136323633363436353636363736383639364036413642364336443645364636473648364936503651365236533654365536563657365836593660366136623663366436653666366736683669367036713672367336743675367636773678367936803681368236833684368536863687368836893690369136923693369436953696369736983699370037013702370337043705370637073708370937103711371237133714371537163717371837193720372137223723372437253726372737283729373037313732373337343735373637373738373937403741374237433744374537463747374837493750375137523753375437553756375737583759376037613762376337643765376637673768376937703771377237733774377537763777377837793780378137823783378437853786378737883789379037913792379337943795379637973798379938003801380238033804380538063807380838093810381138123813381438153816381738183819382038213822382338243825382638273828382938303831383238333834383538363837383838393840384138423843384438453846384738483849385038513852385338543855385638573858385938603861386238633864386538663867386838693870387138723873387438753876387738783879388038813882388338843885388638873888388938903891389238933894389538963897389838993900390139023903390439053906390739083909391039113912391339143915391639173918391939203921392239233924392539263927392839293930393139323933393439353936393739383939394039413942394339443945394639473948394939503951395239533954395539563957395839593960396139623963396439653966396739683969397039713972397339743975397639773978397939803981398239833984398539863987398839893990399139923993399439953996399739983999400040014002400340044005400640074008400940104011401240134014401540164017401840194020402140224023402440254026402740284029403040314032403340344035403640374038403940404041404240434044404540464047404840494050405140524053405440554056405740584059406040614062406340644065406640674068406940704071407240734074407540764077407840794080408140824083408440854086408740884089409040914092409340944095409640974098409941004101410241034104410541064107410841094110411141124113411441154116411741184119412041214122412341244125412641274128412941304131413241334134413541364137413841394140414141424143414441454146414741484149415041514152415341544155415641574158415941604161416241634164416541664167416841694170417141724173417441754176417741784179418041814182418341844185418641874188418941904191419241934194419541964197419841994200420142024203420442054206420742084209421042114212421342144215421642174218421942204221422242234224422542264227422842294230423142324233423442354236423742384239424042414242424342444245424642474248424942504251425242534254425542564257425842594260426142624263426442654266426742684269427042714272427342744275427642774278427942804281428242834284428542864287428842894290429142924293429442954296429742984299430043014302430343044305430643074308430943104311431243134314431543164317431843194320432143224323432443254326432743284329433043314332433343344335433643374338433943404341434243434344434543464347434843494350435143524353435443554356435743584359436043614362436343644365436643674368436943704371437243734374437543764377437843794380438143824383438443854386438743884389439043914392439343944395439643974398439944004401440244034404440544064407440844094410441144124413441444154416441744184419442044214422442344244425442644274428442944304431443244334434443544364437443844394440444144424443444444454446444744484449445044514452445344544455445644574458445944604461446244634464446544664467446844694470447144724473447444754476447744784479448044814482448344844485448644874488448944904491449244934494449544964497449844994500450145024503450445054506450745084509451045114512451345144515451645174518451945204521452245234524452545264527452845294530453145324533453445354536453745384539454045414542454345444545454645474548454945504551455245534554455545564557455845594560456145624563456445654566456745684569457045714572457345744575457645774578457945804581458245834584458545864587458845894590459145924593459445954596459745984599460046014602460346044605460646074608460946104611461246134614461546164617461846194620462146224623462446254626462746284629463046314632463346344635463646374638463946404641464246434644464546464647464846494650465146524653465446554656465746584659466046614662466346644665466646674668466946704671467246734674467546764677467846794680468146824683468446854686468746884689469046914692469346944695469646974698469947004701470247034704470547064707470847094710471147124713471447154716471747184719472047214722472347244725472647274728472947304731473247334734473547364737473847394740474147424743474447454746474747484749475047514752475347544755475647574758475947604761476247634764476547664767476847694770477147724773477447754776477747784779478047814782478347844785478647874788478947904791479247934794479547964797479847994800480148024803480448054806480748084809481048114812481348144815481648174818481948204821482248234824482548264827482848294830483148324833483448354836483748384839484048414842484348444845484648474848484948504851485248534854485548564857485848594860486148624863486448654866486748684869487048714872487348744875487648774878487948804881488248834884488548864887488848894890489148924893489448954896489748984899490049014902490349044905490649074908490949104911491249134914491549164917491849194920492149224923492449254926492749284929493049314932493349344935493649374938493949404941494249434944494549464947494849494950495149524953495449554956495749584959496049614962496349644965496649674968496949704971497249734974497549764977497849794980498149824983498449854986498749884989499049914992499349944995499649974998499950005001500250035004500550065007500850095010501150125013501450155016501750185019502050215022502350245025502650275028502950305031503250335034503550365037503850395040504150425043504450455046504750485049505050515052505350545055505650575058505950605061506250635064506550665067506850695070507150725073507450755076507750785079508050815082508350845085508650875088508950905091509250935094509550965097509850995100510151025103510451055106510751085109511051115112511351145115511651175118511951205121512251235124512551265127512851295130513151325133513451355136513751385139514051415142514351445145514651475148514951505151515251535154515551565157515851595160516151625163516451655166516751685169517051715172517351745175517651775178517951805181518251835184518551865187518851895190519151925193519451955196519751985199520052015202520352045205520652075208520952105211521252135214521552165217521852195220522152225223522452255226522752285229523052315232523352345235523652375238523952405241524252435244524552465247524852495250525152525253525452555256525752585259526052615262526352645265526652675268526952705271527252735274527552765277527852795280528152825283528452855286528752885289529052915292529352945295529652975298529953005301530253035304530553065307530853095310531153125313531453155316531753185319532053215322532353245325532653275328532953305331533253335334533553365337533853395340534153425343534453455346534753485349535053515352535353545355535653575358535953605361536253635364536553665367536853695370537153725373537453755376537753785379538053815382538353845385538653875388538953905391539253935394539553965397539853995400540154025403540454055406540754085409541054115412541354145415541654175418541954205421542254235424542554265427542854295430543154325433543454355436543754385439544054415442544354445445544654475448544954505451545254535454545554565457545854595460546154625463546454655466546754685469547054715472547354745475547654775478547954805481548254835484548554865487548854895490549154925493549454955496549754985499550055015502550355045505550655075508550955105511551255135514551555165517551855195520552155225523552455255526552755285529553055315532553355345535553655375538553955405541554255435544554555465547554855495550555155525553555455555556555755585559556055615562556355645565556655675568556955705571557255735574557555765577557855795580558155825583558455855586558755885589559055915592559355945595559655975598559956005601560256035604560556065607560856095610561156125613561456155616561756185619562056215622562356245625562656275628562956305631563256335634563556365637563856395640564156425643564456455646564756485649565056515652565356545655565656575658565956605661566256635664566556665667566856695670567156725673567456755676567756785679568056815682568356845685568656875688568956905691569256935694569556965697569856995700570157025703570457055706570757085709571057115712571357145715571657175718571957205721572257235724572557265727572857295730573157325733573457355736573757385739574057415742574357445745574657475748574957505751575257535754575557565757575857595760576157625763576457655766576757685769577057715772577357745775577657775778577957805781578257835784578557865787578857895790579157925793579457955796579757985799580058015802580358045805580658075808580958105811581258135814581558165817581858195820582158225823582458255826582758285829583058315832583358345835583658375838583958405841584258435844584558465847584858495850585158525853585458555856585758585859586058615862586358645865586658675868586958705871587258735874587558765877587858795880588158825883588458855886588758885889589058915892589358945895589658975898589959005901590259035904590559065907590859095910591159125913591459155916591759185919592059215922592359245925592659275928592959305931593259335934593559365937593859395940594159425943594459455946594759485949595059515952595359545955595659575958595959605961596259635964596559665967596859695970597159725973597459755976597759785979598059815982598359845985598659875988598959905991599259935994599559965997599859996000600160026003600460056006600760086009601060116012601360146015601660176018601960206021602260236024602560266027602860296030603160326033603460356036603760386039604060416042604360446045604660476048604960506051605260536054605560566057605860596060606160626063606460656066606760686069607060716072607360746075607660776078607960806081608260836084608560866087608860896090609160926093609460956096609760986099610061016102610361046105610661076108610961106111611261136114611561166117611861196120612161226123612461256126612761286129613061316132613361346135613661376138613961406141614261436144614561466147614861496150615161526153615461556156615761586159616061616162616361646165616661676168616961706171617261736174617561766177617861796180618161826183618461856186618761886189619061916192619361946195619661976198619962006201620262036204620562066207620862096210621162126213621462156216621762186219622062216222622362246225622662276228622962306231623262336234623562366237623862396240624162426243624462456246624762486249625062516252625362546255625662576258625962606261626262636264626562666267626862696270627162726273627462756276627762786279628062816282628362846285628662876288628962906291629262936294629562966297629862996300630163026303630463056306630763086309631063116312631363146315631663176318631963206321632263236324632563266327632863296330633163326333633463356336633763386339634063416342634363446345634663476348634963506351635263536354635563566357635863596360636163626363636463656366636763686369637063716372637363746375637663776378637963806381638263836384638563866387638863896390639163926393639463956396639763986399640064016402640364046405640664076408640964106411641264136414641564166417641864196420642164226423642464256426642764286429643064316432643364346435643664376438643964406441644264436444644564466447644864496450645164526453645464556456645764586459646064616462646364646465646664676468646964706471647264736474647564766477647864796480648164826483648464856486648764886489649064916492649364946495649664976498649965006501650265036504650565066507650865096510651165126513651465156516651765186519652065216522652365246525652665276528652965306531653265336534653565366537653865396540654165426543654465456546654765486549655065516552655365546555655665576558655965606561656265636564656565666567656865696570657165726573657465756576657765786579658065816582658365846585658665876588658965906591659265936594659565966597659865996600660166026603660466056606660766086609661066116612661366146615661666176618661966206621662266236624662566266627662866296630663166326633663466356636663766386639664066416642664366446645664666476648664966506651665266536654665566566657665866596660666166626663666466656666666766686669667066716672667366746675667666776678667966806681668266836684668566866687668866896690669166926693669466956696669766986699670067016702670367046705670667076708670967106711671267136714671567166717671867196720672167226723672467256726672767286729673067316732673367346735673667376738673967406741674267436744674567466747674867496750675167526753675467556756675767586759676067616762676367646765676667676768676967706771677267736774677567766777677867796780678167826783678467856786678767886789679067916792679367946795679667976798679968006801680268036804680568066807680868096810681168126813681468156816681768186819682068216822682368246825682668276828682968306831683268336834683568366837683868396840684168426843684468456846684768486849685068516852685368546855685668576858685968606861686268636864686568666867686868696870687168726873687468756876687768786879688068816882688368846885688668876888688968906891689268936894689568966897689868996900690169026903690469056906690769086909691069116912691369146915691669176918691969206921692269236924692569266927692869296930693169326933693469356936693769386939694069416942694369446945694669476948694969506951695269536954695569566957695869596960696169626963696469656966696769686969697069716972697369746975697669776978697969806981698269836984698569866987698869896990699169926993699469956996699769986999700070017002700370047005700670077008700970107011701270137014701570167017701870197020702170227023702470257026702770287029703070317032703370347035703670377038703970407041704270437044704570467047704870497050705170527053705470557056705770587059706070617062706370647065706670677068706970707071707270737074707570767077707870797080708170827083708470857086708770887089709070917092709370947095709670977098709971007101710271037104710571067107710871097110711171127113711471157116711771187119712071217122712371247125712671277128712971307131713271337134713571367137713871397140714171427143714471457146714771487149715071517152715371547155715671577158715971607161716271637164716571667167716871697170717171727173717471757176717771787179718071817182718371847185718671877188718971907191719271937194719571967197719871997200720172027203720472057206720772087209721072117212721372147215721672177218721972207221722272237224722572267227722872297230723172327233723472357236723772387239724072417242724372447245724672477248724972507251725272537254725572567257725872597260726172627263726472657266726772687269727072717272727372747275727672777278727972807281728272837284728572867287728872897290729172927293729472957296729772987299730073017302730373047305730673077308730973107311731273137314731573167317731873197320732173227323732473257326732773287329733073317332733373347335733673377338733973407341734273437344734573467347734873497350735173527353735473557356735773587359736073617362736373647365736673677368736973707371737273737374737573767377737873797380738173827383738473857386738773887389739073917392739373947395739673977398739974007401740274037404740574067407740874097410741174127413741474157416741774187419742074217422742374247425742674277428742974307431743274337434743574367437743874397440744174427443744474457446744774487449745074517452745374547455745674577458745974607461746274637464746574667467746874697470747174727473747474757476747774787479748074817482748374847485748674877488748974907491749274937494749574967497749874997500750175027503750475057506750775087509751075117512751375147515751675177518751975207521752275237524752575267527752875297530753175327533753475357536753775387539754075417542754375447545754675477548754975507551755275537554755575567557755875597560756175627563756475657566756775687569757075717572757375747575757675777578757975807581758275837584758575867587758875897590759175927593759475957596759775987599760076017602760376047605760676077608760976107611761276137614761576167617761876197620762176227623762476257626762776287629763076317632763376347635763676377638763976407641764276437644764576467647764876497650765176527653765476557656765776587659766076617662766376647665766676677668766976707671767276737674767576767677767876797680768176827683768476857686768776887689769076917692769376947695769676977698769977007701770277037704770577067707770877097710771177127713771477157716771777187719772077217722772377247725772677277728772977307731773277337734773577367737773877397740774177427743774477457746774777487749775077517752775377547755775677577758775977607761776277637764776577667767776877697770777177727773777477757776777777787779778077817782778377847785778677877788778977907791779277937794779577967797779877997800780178027803780478057806780778087809781078117812781378147815781678177818781978207821782278237824782578267827782878297830783178327833783478357836783778387839784078417842784378447845784678477848784978507851785278537854785578567857785878597860786178627863786478657866786778687869787078717872787378747875787678777878787978807881788278837884788578867887788878897890789178927893789478957896789778987899790079017902790379047905790679077908790979107911791279137914791579167917791879197920792179227923792479257926792779287929793079317932793379347935793679377938793979407941794279437944794579467947794879497950795179527953795479557956795779587959796079617962796379647965796679677968796979707971797279737974797579767977797879797980798179827983798479857986798779887989799079917992799379947995799679977998799980008001800280038004800580068007800880098010801180128013801480158016801780188019802080218022802380248025802680278028802980308031803280338034803580368037803880398040804180428043804480458046804780488049805080518052805380548055805680578058805980608061806280638064806580668067806880698070807180728073807480758076807780788079808080818082808380848085808680878088808980908091809280938094809580968097809880998100810181028103810481058106810781088109811081118112811381148115811681178118811981208121812281238124812581268127812881298130813181328133813481358136813781388139814081418142814381448145814681478148814981508151815281538154815581568157815881598160816181628163816481658166816781688169817081718172817381748175817681778178817981808181818281838184818581868187818881898190819181928193819481958196819781988199820082018202820382048205820682078208820982108211821282138214821582168217821882198220822182228223822482258226822782288229823082318232823382348235823682378238823982408241824282438244824582468247824882498250825182528253825482558256825782588259826082618262826382648265826682678268826982708271827282738274827582768277827882798280828182828283828482858286828782888289829082918292829382948295829682978298829983008301830283038304830583068307830883098310831183128313831483158316831783188319832083218322832383248325832683278328832983308331833283338334833583368337833883398340834183428343834483458346834783488349835083518352835383548355835683578358835983608361836283638364836583668367836883698370837183728373837483758376837783788379838083818382838383848385838683878388838983908391839283938394839583968397839883998400840184028403840484058406840784088409841084118412841384148415841684178418841984208421842284238424842584268427842884298430843184328433843484358436843784388439844084418442844384448445844684478448844984508451845284538454845584568457845884598460846184628463846484658466846784688469847084718472847384748475847684778478847984808481848284838484848584868487848884898490849184928493849484958496849784988499850085018502850385048505850685078508850985108511851285138514851585168517851885198520852185228523852485258526852785288529853085318532853385348535853685378538853985408541854285438544854585468547854885498550855185528553855485558556855785588559856085618562856385648565856685678568856985708571857285738574857585768577857885798580858185828583858485858586858785888589859085918592859385948595859685978598859986008601860286038604860586068607860886098610861186128613861486158616861786188619862086218622862386248625862686278628862986308631863286338634863586368637863886398640864186428643864486458646864786488649865086518652865386548655865686578658865986608661866286638664866586668667866886698670867186728673867486758676867786788679868086818682868386848685868686878688868986908691869286938694869586968697869886998700870187028703870487058706870787088709871087118712871387148715871687178718871987208721872287238724872587268727872887298730873187328733873487358736873787388739874087418742874387448745874687478748874987508751875287538754875587568757875887598760876187628763876487658766876787688769877087718772877387748775877687778778877987808781878287838784878587868787878887898790879187928793879487958796879787988799880088018802880388048805880688078808880988108811881288138814881588168817881888198820882188228823882488258826882788288829883088318832883388348835883688378838883988408841884288438844884588468847884888498850885188528853885488558856885788588859886088618862886388648865886688678868886988708871887288738874887588768877887888798880888188828883888488858886888788888889889088918892889388948895889688978898889989008901890289038904890589068907890889098910891189128913891489158916891789188919892089218922892389248925892689278928892989308931893289338934893589368937893889398940894189428943894489458946894789488949895089518952895389548955895689578958895989608961896289638964896589668967896889698970897189728973897489758976897789788979898089818982898389848985898689878988898989908991899289938994899589968997899889999000900190029003900490059006900790089009901090119012901390149015901690179018901990209021902290239024902590269027902890299030903190329033903490359036903790389039904090419042904390449045904690479048904990509051905290539054905590569057905890599060906190629063906490659066906790689069907090719072907390749075907690779078907990809081908290839084908590869087908890899090909190929093909490959096909790989099910091019102910391049105910691079108910991109111911291139114911591169117911891199120912191229123912491259126912791289129913091319132913391349135913691379138913991409141914291439144914591469147914891499150915191529153915491559156915791589159916091619162916391649165916691679168916991709171917291739174917591769177917891799180918191829183918491859186918791889189919091919192919391949195919691979198919992009201920292039204920592069207920892099210921192129213921492159216921792189219922092219222922392249225922692279228922992309231923292339234923592369237923892399240924192429243924492459246924792489249925092519252925392549255925692579258925992609261926292639264926592669267926892699270927192729273927492759276927792789279928092819282928392849285928692879288928992909291929292939294929592969297929892999300930193029303930493059306930793089309931093119312931393149315931693179318931993209321932293239324932593269327932893299330933193329333933493359336933793389339934093419342934393449345934693479348934993509351935293539354935593569357935893599360936193629363936493659366936793689369937093719372937393749375937693779378937993809381938293839384938593869387938893899390939193929393939493959396939793989399940094019402940394049405940694079408940994109411941294139414941594169417941894199420942194229423942494259426942794289429943094319432943394349435943694379438943994409441944294439444944594469447944894499450945194529453945494559456945794589459946094619462946394649465946694679468946994709471947294739474947594769477947894799480948194829483948494859486948794889489949094919492949394949495949694979498949995009501950295039504950595069507950895099510951195129513951495159516951795189519952095219522952395249525952695279528952995309531953295339534953595369537953895399540954195429543954495459546954795489549955095519552955395549555955695579558955995609561956295639564956595669567956895699570957195729573957495759576957795789579958095819582958395849585958695879588958995909591959295939594959595969597959895999600960196029603960496059606960796089609961096119612961396149615961696179618961996209621962296239624962596269627962896299630963196329633963496359636963796389639964096419642964396449645964696479648964996509651965296539654965596569657965896599660966196629663966496659666966796689669967096719672967396749675967696779678967996809681968296839684968596869687968896899690969196929693969496959696969796989699970097019702970397049705970697079708970997109711971297139714971597169717971897199720972197229723972497259726972797289729973097319732973397349735973697379738973997409741974297439744974597469747974897499750975197529753975497559756975797589759976097619762976397649765976697679768976997709771977297739774977597769777977897799780978197829783978497859786978797889789979097919792979397949795979697979798979998009801980298039804980598069807980898099810981198129813981498159816981798189819982098219822982398249825982698279828982998309831983298339834983598369837983898399840984198429843984498459846984798489849985098519852985398549855985698579858985998609861986298639864986598669867986898699870987198729873987498759876987798789879988098819882988398849885988698879888988998909891989298939894989598969897989898999900990199029903990499059906990799089909991099119912991399149915991699179918991999209921992299239924992599269927992899299930993199329933993499359936993799389939994099419942994399449945994699479948994999509951995299539954995599569957995899599960996199629963996499659966996799689969997099719972997399749975997699779978997999809981998299839984998599869987998899899990999199929993999499959996999799989999100001000110002100031000410005100061000710008100091001010011100121001310014100151001610017100181001910020100211002210023100241002510026100271002810029100301003110032100331003410035100361003710038100391004010041100421004310044100451004610047100481004910050100511005210053100541005510056100571005810059100601006110062100631006410065100661006710068100691007010071100721007310074100751007610077100781007910080100811008210083100841008510086100871008810089100901009110092100931009410095100961009710098100991010010101101021010310104101051010610107101081010910110101111011210113101141011510116101171011810119101201012110122101231012410125101261012710128101291013010131101321013310134101351013610137101381013910140101411014210143101441014510146101471014810149101501015110152101531015410155101561015710158101591016010161101621016310164101651016610167101681016910170101711017210173101741017510176101771017810179101801018110182101831018410185101861018710188101891019010191101921019310194101951019610197101981019910200102011020210203102041020510206102071020810209102101021110212102131021410215102161021710218102191022010221102221022310224102251022610227102281022910230102311023210233102341023510236102371023810239102401024110242102431024410245102461024710248102491025010251102521025310254102551025610257102581025910260102611026210263102641026510266102671026810269102701027110272102731027410275102761027710278102791028010281102821028310284102851028610287102881028910290102911029210293102941029510296102971029810299103001030110302103031030410305103061030710308103091031010311103121031310314103151031610317103181031910320103211032210323103241032510326103271032810329103301033110332103331033410335103361033710338103391034010341103421034310344103451034610347103481034910350103511035210353103541035510356103571035810359103601036110362103631036410365103661036710368103691037010371103721037310374103751037610377103781037910380103811038210383103841038510386103871038810389103901039110392103931039410395103961039710398103991040010401104021040310404104051040610407104081040910410104111041210413104141041510416104171041810419104201042110422104231042410425104261042710428104291043010431104321043310434104351043610437104381043910440104411044210443104441044510446104471044810449104501045110452104531045410455104561045710458104591046010461104621046310464104651046610467104681046910470104711047210473104741047510476104771047810479104801048110482104831048410485104861048710488104891049010491104921049310494104951049610497104981049910500105011050210503105041050510506105071050810509105101051110512105131051410515105161051710518105191052010521105221052310524105251052610527105281052910530105311053210533105341053510536105371053810539105401054110542105431054410545105461054710548105491055010551105521055310554105551055610557105581055910560105611056210563105641056510566105671056810569105701057110572105731057410575105761057710578105791058010581105821058310584105851058610587105881058910590105911059210593105941059510596105971059810599106001060110602106031060410605106061060710608106091061010611106121061310614106151061610617106181061910620106211062210623106241062510626106271062810629106301063110632106331063410635106361063710638106391064010641106421064310644106451064610647106481064910650106511065210653106541065510656106571065810659106601066110662106631066410665106661066710668106691067010671106721067310674106751067610677106781067910680106811068210683106841068510686106871068810689106901069110692106931069410695106961069710698106991070010701107021070310704107051070610707107081070910710107111071210713107141071510716107171071810719107201072110722107231072410725107261072710728107291073010731107321073310734107351073610737107381073910740107411074210743107441074510746107471074810749107501075110752107531075410755107561075710758107591076010761107621076310764107651076610767107681076910770107711077210773107741077510776107771077810779107801078110782107831078410785107861078710788107891079010791107921079310794107951079610797107981079910800108011080210803108041080510806108071080810809108101081110812108131081410815108161081710818108191082010821108221082310824108251082610827108281082910830108311083210833108341083510836108371083810839108401084110842108431084410845108461084710848108491085010851108521085310854108551085610857108581085910860108611086210863108641086510866108671086810869108701087110872108731087410875108761087710878108791088010881108821088310884108851088610887108881088910890108911089210893108941089510896108971089810899109001090110902109031090410905109061090710908109091091010911109121091310914109151091610917109181091910920109211092210923109241092510926109271092810929109301093110932109331093410935109361093710938109391094010941109421094310944109451094610947109481094910950109511095210953109541095510956109571095810959109601096110962109631096410965109661096710968109691097010971109721097310974109751097610977109781097910980109811098210983109841098510986109871098810989109901099110992109931099410995109961099710998109991100011001110021100311004110051100611007110081100911010110111101211013110141101511016110171101811019110201102111022110231102411025110261102711028110291103011031110321103311034110351103611037110381103911040110411104211043110441104511046110471104811049110501105111052110531105411055110561105711058110591106011061110621106311064110651106611067110681106911070110711107211073110741107511076110771107811079110801108111082110831108411085110861108711088110891109011091110921109311094110951109611097110981109911100111011110211103111041110511106111071110811109111101111111112111131111411115111161111711118111191112011121111221112311124111251112611127111281112911130111311113211133111341113511136111371113811139111401114111142111431114411145111461114711148111491115011151111521115311154111551115611157111581115911160111611116211163111641116511166111671116811169111701117111172111731117411175111761117711178111791118011181111821118311184111851118611187111881118911190111911119211193111941119511196111971119811199112001120111202112031120411205112061120711208112091121011211112121121311214112151121611217112181121911220112211122211223112241122511226112271122811229112301123111232112331123411235112361123711238112391124011241112421124311244112451124611247112481124911250112511125211253112541125511256112571125811259112601126111262112631126411265112661126711268112691127011271112721127311274112751127611277112781127911280112811128211283112841128511286112871128811289112901129111292112931129411295112961129711298112991130011301113021130311304113051130611307113081130911310113111131211313113141131511316113171131811319113201132111322113231132411325113261132711328113291133011331113321133311334113351133611337113381133911340113411134211343113441134511346113471134811349113501135111352113531135411355113561135711358113591136011361113621136311364113651136611367113681136911370113711137211373113741137511376113771137811379113801138111382113831138411385113861138711388113891139011391113921139311394113951139611397113981139911400114011140211403114041140511406114071140811409114101141111412114131141411415114161141711418114191142011421114221142311424114251142611427114281142911430114311143211433114341143511436114371143811439114401144111442114431144411445114461144711448114491145011451114521145311454114551145611457114581145911460114611146211463114641146511466114671146811469114701147111472114731147411475114761147711478114791148011481114821148311484114851148611487114881148911490114911149211493114941149511496114971149811499115001150111502115031150411505115061150711508115091151011511115121151311514115151151611517115181151911520115211152211523115241152511526115271152811529115301153111532115331153411535115361153711538115391154011541115421154311544115451154611547115481154911550115511155211553115541155511556115571155811559115601156111562115631156411565115661156711568115691157011571115721157311574115751157611577115781157911580115811158211583115841158511586115871158811589115901159111592115931159411595115961159711598115991160011601116021160311604116051160611607116081160911610116111161211613116141161511616116171161811619116201162111622116231162411625116261162711628116291163011631116321163311634116351163611637116381163911640116411164211643116441164511646116471164811649116501165111652116531165411655116561165711658116591166011661116621166311664116651166611667116681166911670116711167211673116741167511676116771167811679116801168111682116831168411685116861168711688116891169011691116921169311694116951169611697116981169911700117011170211703117041170511706117071170811709117101171111712117131171411715117161171711718117191172011721117221172311724117251172611727117281172911730117311173211733117341173511736117371173811739117401174111742117431174411745117461174711748117491175011751117521175311754117551175611757117581175911760117611176211763117641176511766117671176811769117701177111772117731177411775117761177711778117791178011781117821178311784117851178611787117881178911790117911179211793117941179511796117971179811799118001180111802118031180411805118061180711808118091181011811118121181311814118151181611817118181181911820118211182211823118241182511826
  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 512
  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_disabled(unsigned int node)
  283. {
  284. struct br_node *n = &doc.nodes[node];
  285. if (n->attr_flags & BR_ATTR_DISABLED)
  286. return 1;
  287. return br_find_attr(&doc, node, "disabled") != 0;
  288. }
  289. static int form_kind_of(unsigned int node)
  290. {
  291. const char *type = br_type(&doc, node);
  292. if (doc.nodes[node].tag == BR_TAG_TEXTAREA)
  293. return FORM_TEXTAREA;
  294. if (doc.nodes[node].tag == BR_TAG_SELECT)
  295. return FORM_SELECT;
  296. if (doc.nodes[node].tag == BR_TAG_BUTTON) {
  297. if (s_eq(type, "reset"))
  298. return FORM_RESET;
  299. if (s_eq(type, "button"))
  300. return FORM_BUTTON;
  301. return FORM_SUBMIT;
  302. }
  303. if (s_eq(type, "password"))
  304. return FORM_PASSWORD;
  305. if (s_eq(type, "checkbox"))
  306. return FORM_CHECKBOX;
  307. if (s_eq(type, "radio"))
  308. return FORM_RADIO;
  309. if (s_eq(type, "submit"))
  310. return FORM_SUBMIT;
  311. if (s_eq(type, "reset"))
  312. return FORM_RESET;
  313. if (s_eq(type, "button"))
  314. return FORM_BUTTON;
  315. return FORM_TEXT;
  316. }
  317. static unsigned int form_option_count(unsigned int node)
  318. {
  319. unsigned int c, n = 0;
  320. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  321. if (doc.nodes[c].type == BR_NODE_ELEM &&
  322. doc.nodes[c].tag == BR_TAG_OPTION)
  323. n++;
  324. return n;
  325. }
  326. static unsigned int form_option_selected(unsigned int node)
  327. {
  328. unsigned int c, i = 0;
  329. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  330. if (doc.nodes[c].type != BR_NODE_ELEM ||
  331. doc.nodes[c].tag != BR_TAG_OPTION)
  332. continue;
  333. if (br_find_attr(&doc, c, "selected"))
  334. return i;
  335. i++;
  336. }
  337. return 0;
  338. }
  339. static unsigned int form_option_text(unsigned int node, unsigned int idx,
  340. char *out, unsigned int cap)
  341. {
  342. unsigned int c, i = 0;
  343. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  344. if (doc.nodes[c].type != BR_NODE_ELEM ||
  345. doc.nodes[c].tag != BR_TAG_OPTION)
  346. continue;
  347. if (i == idx)
  348. return br_text_content(&doc, c, out, cap);
  349. i++;
  350. }
  351. return 0;
  352. }
  353. static struct form_state *form_get(unsigned int node, int create)
  354. {
  355. struct form_state *slot = 0;
  356. unsigned int i;
  357. for (i = 0; i < FORM_MAX; i++) {
  358. if (form_states[i].used) {
  359. if (form_states[i].node == node)
  360. return &form_states[i];
  361. } else if (!slot) {
  362. slot = &form_states[i];
  363. }
  364. }
  365. if (!create || !slot)
  366. return 0;
  367. slot->node = node;
  368. slot->len = 0;
  369. slot->caret = 0;
  370. slot->checked = br_find_attr(&doc, node, "checked") != 0;
  371. slot->selected = form_option_selected(node);
  372. slot->used = 1;
  373. {
  374. unsigned int n = 0;
  375. if (doc.nodes[node].tag == BR_TAG_TEXTAREA) {
  376. n = br_text_content(&doc, node, slot->value,
  377. FORM_VALUE_MAX + 1);
  378. } else {
  379. const char *v = br_value(&doc, node);
  380. if (v) {
  381. n = s_len(v);
  382. if (n > FORM_VALUE_MAX)
  383. n = FORM_VALUE_MAX;
  384. for (unsigned int j = 0; j < n; j++)
  385. slot->value[j] = v[j];
  386. }
  387. if (doc.nodes[node].tag == BR_TAG_BUTTON && n == 0)
  388. n = br_text_content(&doc, node, slot->value,
  389. FORM_VALUE_MAX + 1);
  390. }
  391. if (n > FORM_VALUE_MAX)
  392. n = FORM_VALUE_MAX;
  393. slot->value[n] = '\0';
  394. slot->len = (unsigned char)n;
  395. slot->caret = (unsigned char)n;
  396. }
  397. return slot;
  398. }
  399. static void form_reset_state(void)
  400. {
  401. unsigned int i;
  402. for (i = 0; i < FORM_MAX; i++)
  403. form_states[i].used = 0;
  404. form_focus = 0;
  405. }
  406. /* A <button> with element content (an icon <svg>/<img>, a <span> label)
  407. * is laid out like a normal element so that content shows; only a text or
  408. * empty button is drawn as a native control. Clicks still reach it
  409. * through the box hit test. */
  410. static int button_has_elements(unsigned int node)
  411. {
  412. unsigned int c;
  413. if (node >= doc.nnode || doc.nodes[node].tag != BR_TAG_BUTTON)
  414. return 0;
  415. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  416. if (doc.nodes[c].type == BR_NODE_ELEM)
  417. return 1;
  418. return 0;
  419. }
  420. static int form_is_control(unsigned int node)
  421. {
  422. unsigned int tag;
  423. if (node >= doc.nnode || doc.nodes[node].type != BR_NODE_ELEM)
  424. return 0;
  425. tag = doc.nodes[node].tag;
  426. return tag == BR_TAG_INPUT || tag == BR_TAG_TEXTAREA ||
  427. tag == BR_TAG_SELECT ||
  428. (tag == BR_TAG_BUTTON && !button_has_elements(node));
  429. }
  430. #define HIT_MAX 96
  431. static struct hit hits[HIT_MAX];
  432. static int nhits;
  433. static unsigned short block_h[BR_MAX_NODES];
  434. /* Measure-pass top of each block, in the same document coordinates as
  435. * img_top[] (layout_boxes[] is rewritten in screen coordinates by every
  436. * paint, so it cannot drive the lazy background loader). */
  437. static unsigned short block_top[BR_MAX_NODES];
  438. static char li_marker[BR_MAX_NODES][12];
  439. /* one connection object; the browser fetches one resource at a time */
  440. /* ---- tiny strings ---- */
  441. static unsigned int s_len(const char *s)
  442. {
  443. unsigned int n = 0;
  444. while (s && s[n])
  445. n++;
  446. return n;
  447. }
  448. static void s_copy(char *d, const char *s, unsigned int cap)
  449. {
  450. unsigned int i = 0;
  451. if (!cap)
  452. return;
  453. while (s && s[i] && i + 1 < cap) {
  454. d[i] = s[i];
  455. i++;
  456. }
  457. d[i] = '\0';
  458. }
  459. static void s_append(char *d, unsigned int *n, const char *s, unsigned int cap)
  460. {
  461. while (s && *s && *n + 1 < cap)
  462. d[(*n)++] = *s++;
  463. d[*n] = '\0';
  464. }
  465. static void s_append_dec(char *d, unsigned int *n, unsigned int v,
  466. unsigned int cap)
  467. {
  468. char tmp[12];
  469. unsigned int i = 0, j;
  470. do {
  471. tmp[i++] = (char)('0' + v % 10);
  472. v /= 10;
  473. } while (v && i < sizeof(tmp));
  474. for (j = 0; j < i && *n + 1 < cap; j++)
  475. d[(*n)++] = tmp[i - 1 - j];
  476. d[*n] = '\0';
  477. }
  478. static int s_eq(const char *a, const char *b)
  479. {
  480. while (*a && *b) {
  481. if (*a != *b)
  482. return 0;
  483. a++;
  484. b++;
  485. }
  486. return *a == *b;
  487. }
  488. static int starts_with(const char *s, const char *p)
  489. {
  490. unsigned int i = 0;
  491. while (p[i]) {
  492. if (s[i] != p[i])
  493. return 0;
  494. i++;
  495. }
  496. return 1;
  497. }
  498. static int contains_ci(const char *s, const char *p)
  499. {
  500. unsigned int i, j;
  501. for (i = 0; s[i]; i++) {
  502. for (j = 0; p[j]; j++) {
  503. char a = s[i + j];
  504. if (a >= 'A' && a <= 'Z')
  505. a = (char)(a - 'A' + 'a');
  506. if (a != p[j])
  507. break;
  508. }
  509. if (!p[j])
  510. return 1;
  511. }
  512. return 0;
  513. }
  514. static char *trim(char *s)
  515. {
  516. unsigned int n;
  517. while (*s == ' ' || *s == '\t' || *s == '\r' || *s == '\n')
  518. s++;
  519. n = s_len(s);
  520. while (n && (s[n - 1] == ' ' || s[n - 1] == '\t' ||
  521. s[n - 1] == '\r' || s[n - 1] == '\n'))
  522. s[--n] = '\0';
  523. return s;
  524. }
  525. /* ---- per-process heap ---- */
  526. static int heap_start(void)
  527. {
  528. image_io_buf = (unsigned char *)malloc(2u * BR_IMG_FILE_MAX);
  529. if (!image_io_buf)
  530. return -1;
  531. page_backbuf = (unsigned short *)malloc(
  532. (unsigned int)ui.w * (unsigned int)ui.h * 2u);
  533. pagebuf_w = page_backbuf ? ui.w : 0;
  534. pagebuf_h = page_backbuf ? ui.h : 0;
  535. page_cache_valid = 0;
  536. return 0;
  537. }
  538. static void heap_clear(void)
  539. {
  540. memset(font_faces, 0, sizeof(font_faces));
  541. ngui_font_detach(&ui);
  542. svg_cache_clear();
  543. decode_arena = 0; /* lives in the page heap too */
  544. decode_arena_size = 0;
  545. heap_reset();
  546. /* The document arenas live in that heap; drop the stale pointers so
  547. * the next br_parse_plain() allocates fresh ones. */
  548. doc.nodes = 0;
  549. doc.text = 0;
  550. doc.attrs = 0;
  551. image_io_buf = 0;
  552. page_backbuf = 0;
  553. pagebuf_w = pagebuf_h = 0;
  554. page_cache_valid = 0;
  555. }
  556. static void browser_rules_alloc(void)
  557. {
  558. struct br_rule *rules;
  559. rules = (struct br_rule *)malloc(
  560. (unsigned int)(BR_MAX_RULES * sizeof(struct br_rule)));
  561. br_set_rule_store(&doc, rules, rules ? BR_MAX_RULES : 0);
  562. }
  563. /* ---- status ---- */
  564. static void set_status(const char *s, int err, unsigned int ttl_ms)
  565. {
  566. s_copy(status_text, s, sizeof(status_text));
  567. status_error = err;
  568. status_until = ttl_ms ? u_ticks_ms() + ttl_ms : 0;
  569. ngui_invalidate(&ui);
  570. }
  571. /* Update the status text without forcing a frame; the throttled image
  572. * repaint picks it up. Starting one helper per image used to invalidate the
  573. * whole page before every decode. */
  574. static void set_status_quiet(const char *s)
  575. {
  576. s_copy(status_text, s, sizeof(status_text));
  577. status_error = 0;
  578. status_until = 0;
  579. }
  580. /* ---- JavaScript ---- */
  581. static int resolve_link(const char *base, const char *href, char *out,
  582. unsigned int cap);
  583. static char js_last_status[BR_STATUS_MAX];
  584. static int js_last_error;
  585. static void js_host_status(const char *msg, int error)
  586. {
  587. s_copy(js_last_status, msg, sizeof(js_last_status));
  588. js_last_error = error;
  589. set_status(msg, error, 6000);
  590. }
  591. static void js_host_report(const char *msg)
  592. {
  593. u_puts("[js] ");
  594. u_puts(msg);
  595. u_putc('\n');
  596. s_copy(js_last_status, msg, sizeof(js_last_status));
  597. js_last_error = 1;
  598. set_status(msg, 1, 8000);
  599. }
  600. static void js_host_navigate(const char *url)
  601. {
  602. char resolved[BR_URL_MAX];
  603. if (!url || !url[0])
  604. return;
  605. if (resolve_link(page_url, url, resolved, sizeof(resolved)) != 0)
  606. return;
  607. s_copy(pending_url, resolved, sizeof(pending_url));
  608. pending_action |= ACT_NAV;
  609. cancel_fetch = 1;
  610. }
  611. /* Same-document fragment change (location.hash, an <a href="#/x"> click,
  612. * back/forward between fragments): the page URL, address bar and history
  613. * follow, nothing is reloaded. `push` adds a history entry. */
  614. static int page_set_fragment(const char *url, int push)
  615. {
  616. if (!url || !url[0] || s_len(url) >= sizeof(page_url))
  617. return -1;
  618. s_copy(page_url, url, sizeof(page_url));
  619. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  620. url_in.len = s_len(url_in.text);
  621. url_in.cursor = url_in.len;
  622. url_in.scroll = 0;
  623. if (push)
  624. history_push(page_url);
  625. ngui_invalidate(&ui);
  626. return 0;
  627. }
  628. static int js_host_set_hash(const char *url)
  629. {
  630. return page_set_fragment(url, 1);
  631. }
  632. /* 1 when `url` is this page with a different #fragment (and JavaScript runs
  633. * the page, so a hash router can react). */
  634. static int same_doc_fragment(const char *url)
  635. {
  636. unsigned int a = 0, b = 0;
  637. if (!js_browser_active() || !url)
  638. return 0;
  639. while (url[a] && url[a] != '#')
  640. a++;
  641. while (page_url[b] && page_url[b] != '#')
  642. b++;
  643. return url[a] == '#' && a == b && !strncmp(url, page_url, a) &&
  644. !s_eq(url, page_url);
  645. }
  646. static void js_host_changed(void)
  647. {
  648. /* Class/style/attribute mutations change computed styles, not just the
  649. * text: drop the per-node style cache before the next layout. */
  650. br_reset_styles(&doc);
  651. layout_valid = 0;
  652. /* Script-built content (Angular's ng-repeat cards) brings new images
  653. * and inline background styles: rescan once the main loop is idle. */
  654. preload_rescan = 1;
  655. ngui_invalidate(&ui);
  656. }
  657. static int js_host_rect(unsigned int node, int *x, int *y, int *w, int *h)
  658. {
  659. if (node >= BR_MAX_NODES || !layout_boxes[node].valid)
  660. return 0;
  661. *x = layout_boxes[node].x - page_rect.x;
  662. *y = layout_boxes[node].y - page_rect.y;
  663. *w = layout_boxes[node].w;
  664. *h = layout_boxes[node].h;
  665. return 1;
  666. }
  667. static void form_copy_out(const char *s, char *buf, int cap)
  668. {
  669. int i = 0;
  670. if (!buf || cap <= 0)
  671. return;
  672. while (s && s[i] && i + 1 < cap) {
  673. buf[i] = s[i];
  674. i++;
  675. }
  676. buf[i] = '\0';
  677. }
  678. static int js_host_form_value(unsigned int node, char *buf, int cap)
  679. {
  680. struct form_state *fs;
  681. int kind;
  682. if (!form_is_control(node))
  683. return 0;
  684. kind = form_kind_of(node);
  685. if (kind == FORM_CHECKBOX || kind == FORM_RADIO)
  686. return 0;
  687. if (kind == FORM_SELECT) {
  688. char opt[64] = "";
  689. unsigned int c, i = 0;
  690. fs = form_get(node, 1);
  691. if (!fs)
  692. return 0;
  693. form_option_text(node, fs->selected, opt, sizeof(opt));
  694. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  695. if (doc.nodes[c].type != BR_NODE_ELEM ||
  696. doc.nodes[c].tag != BR_TAG_OPTION)
  697. continue;
  698. if (i == fs->selected) {
  699. const char *v = br_value(&doc, c);
  700. if (v && v[0])
  701. form_copy_out(v, buf, cap);
  702. else
  703. form_copy_out(opt, buf, cap);
  704. return 1;
  705. }
  706. i++;
  707. }
  708. form_copy_out(opt, buf, cap);
  709. return 1;
  710. }
  711. fs = form_get(node, 1);
  712. if (!fs)
  713. return 0;
  714. form_copy_out(fs->value, buf, cap);
  715. return 1;
  716. }
  717. static int js_host_form_checked(unsigned int node)
  718. {
  719. struct form_state *fs;
  720. int kind;
  721. if (!form_is_control(node))
  722. return -1;
  723. kind = form_kind_of(node);
  724. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  725. return -1;
  726. fs = form_get(node, 1);
  727. return fs ? fs->checked : 0;
  728. }
  729. static int js_host_form_selected(unsigned int node)
  730. {
  731. struct form_state *fs;
  732. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  733. return -1;
  734. fs = form_get(node, 1);
  735. return fs ? fs->selected : 0;
  736. }
  737. static int js_host_form_set_value(unsigned int node, const char *value)
  738. {
  739. struct form_state *fs;
  740. unsigned int n;
  741. if (!form_is_control(node))
  742. return 0;
  743. fs = form_get(node, 1);
  744. if (!fs)
  745. return 0;
  746. n = s_len(value ? value : "");
  747. if (n > FORM_VALUE_MAX)
  748. n = FORM_VALUE_MAX;
  749. for (unsigned int i = 0; i < n; i++)
  750. fs->value[i] = value[i];
  751. fs->value[n] = '\0';
  752. fs->len = (unsigned char)n;
  753. fs->caret = (unsigned char)n;
  754. layout_valid = 0;
  755. ngui_invalidate(&ui);
  756. return 1;
  757. }
  758. static int js_host_form_set_checked(unsigned int node, int checked)
  759. {
  760. struct form_state *fs;
  761. int kind;
  762. if (!form_is_control(node))
  763. return 0;
  764. kind = form_kind_of(node);
  765. if (kind != FORM_CHECKBOX && kind != FORM_RADIO)
  766. return 0;
  767. fs = form_get(node, 1);
  768. if (!fs)
  769. return 0;
  770. fs->checked = (unsigned char)(checked != 0);
  771. layout_valid = 0;
  772. ngui_invalidate(&ui);
  773. return 1;
  774. }
  775. static int js_host_form_set_selected(unsigned int node, int index)
  776. {
  777. struct form_state *fs;
  778. unsigned int n;
  779. if (!form_is_control(node) || form_kind_of(node) != FORM_SELECT)
  780. return 0;
  781. fs = form_get(node, 1);
  782. if (!fs)
  783. return 0;
  784. n = form_option_count(node);
  785. if (index < 0)
  786. index = 0;
  787. if (n && (unsigned int)index >= n)
  788. index = (int)n - 1;
  789. fs->selected = (unsigned char)index;
  790. layout_valid = 0;
  791. ngui_invalidate(&ui);
  792. return 1;
  793. }
  794. static int js_host_form_elements(unsigned int form, unsigned int *out, int cap)
  795. {
  796. unsigned int i;
  797. int n = 0;
  798. if (!form || form >= doc.nnode || doc.nodes[form].type != BR_NODE_ELEM ||
  799. doc.nodes[form].tag != BR_TAG_FORM)
  800. return 0;
  801. for (i = 0; i < doc.nnode && n < cap; i++) {
  802. struct br_node *nd = &doc.nodes[i];
  803. if (i == form || nd->type != BR_NODE_ELEM)
  804. continue;
  805. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_SELECT &&
  806. nd->tag != BR_TAG_TEXTAREA && nd->tag != BR_TAG_BUTTON)
  807. continue;
  808. if (!form_descendant(i, form))
  809. continue;
  810. out[n++] = i;
  811. }
  812. return n;
  813. }
  814. static int js_host_form_submit(unsigned int form)
  815. {
  816. form_submit_form(form, 0);
  817. return 1;
  818. }
  819. static int js_host_form_reset(unsigned int form)
  820. {
  821. form_reset_event(form);
  822. return 1;
  823. }
  824. static void css_computed_name(const char *p, char *out, int cap)
  825. {
  826. int n = 0;
  827. for (; p && *p && n + 2 < cap; p++) {
  828. char c = *p;
  829. if (c >= 'A' && c <= 'Z') {
  830. out[n++] = '-';
  831. c = (char)(c - 'A' + 'a');
  832. } else if (c == '_') {
  833. c = '-';
  834. } else if (c >= 'a' && c <= 'z') {
  835. /* keep */
  836. }
  837. out[n++] = c;
  838. }
  839. out[n] = '\0';
  840. if (!strcmp(out, "css-float"))
  841. strcpy(out, "float");
  842. }
  843. static void css_rgb(unsigned short c, char *buf, int cap)
  844. {
  845. int r = ((c >> 11) & 31) * 255 / 31;
  846. int g = ((c >> 5) & 63) * 255 / 63;
  847. int b = (c & 31) * 255 / 31;
  848. snprintf(buf, cap, "rgb(%d, %d, %d)", r, g, b);
  849. }
  850. static void css_mp_value(char *buf, int cap, int raw, int unit, int px,
  851. int font_px)
  852. {
  853. if (unit == 4) {
  854. snprintf(buf, cap, "auto");
  855. } else if (unit == 0) {
  856. snprintf(buf, cap, "%dpx", raw);
  857. } else if (unit == 1) {
  858. snprintf(buf, cap, "%d.%02d%%", raw / 100, raw % 100);
  859. } else if (unit == 2) {
  860. /* Chrome's getComputedStyle() reports used pixel values. */
  861. snprintf(buf, cap, "%dpx", font_px * raw / 100);
  862. } else if (unit == 3) {
  863. snprintf(buf, cap, "%dpx",
  864. (int)br_root_font_px() * raw / 100);
  865. } else {
  866. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  867. raw / 100, raw % 100, px);
  868. }
  869. }
  870. static int js_host_computed(unsigned int node, const char *property,
  871. char *buf, int cap)
  872. {
  873. struct br_style st;
  874. char name[40];
  875. if (!buf || cap <= 0 || node >= doc.nnode || node == 0)
  876. return 0;
  877. buf[0] = '\0';
  878. css_computed_name(property, name, sizeof(name));
  879. style_for_node(node, &st);
  880. if (!strcmp(name, "display")) {
  881. const char *v = "inline";
  882. if (st.display == BR_DISPLAY_BLOCK)
  883. v = "block";
  884. else if (st.display == BR_DISPLAY_NONE)
  885. v = "none";
  886. else if (st.display == BR_DISPLAY_FLEX)
  887. v = "flex";
  888. else if (st.display == BR_DISPLAY_GRID)
  889. v = "grid";
  890. else if (st.display == BR_DISPLAY_INLINE_BLOCK)
  891. v = "inline-block";
  892. snprintf(buf, cap, "%s", v);
  893. } else if (!strcmp(name, "position")) {
  894. static const char *pos[] = {
  895. "static", "absolute", "fixed", "relative", "sticky"
  896. };
  897. snprintf(buf, cap, "%s", pos[st.pos < 5 ? st.pos : 0]);
  898. } else if (!strcmp(name, "width") || !strcmp(name, "height")) {
  899. int is_w = name[0] == 'w';
  900. int kind = is_w ? st.width_kind : st.height_kind;
  901. int val = is_w ? st.width : st.height;
  902. if (kind == 3) {
  903. if (is_w)
  904. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  905. st.width_calc_pct / 100,
  906. st.width_calc_pct % 100,
  907. st.width_calc_px);
  908. else
  909. snprintf(buf, cap, "calc(%d.%02d%% + %dpx)",
  910. st.height_calc_pct / 100,
  911. st.height_calc_pct % 100,
  912. st.height_calc_px);
  913. } else if (kind == 1) {
  914. snprintf(buf, cap, "%dpx", val);
  915. } else if (kind == 2) {
  916. snprintf(buf, cap, "%d.%02d%%", val / 100, val % 100);
  917. } else {
  918. snprintf(buf, cap, "auto");
  919. }
  920. } else if (!strcmp(name, "color") ||
  921. !strcmp(name, "background-color")) {
  922. if (!strcmp(name, "background-color") && !st.has_bg)
  923. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  924. else
  925. css_rgb(name[0] == 'c' ? st.color : st.bg, buf, cap);
  926. } else if (!strcmp(name, "fill") || !strcmp(name, "stroke")) {
  927. int is_fill = name[0] == 'f';
  928. int mode = is_fill ? st.fill_mode : st.stroke_mode;
  929. if (mode == BR_PAINT_COLOR)
  930. css_rgb(is_fill ? st.fill : st.stroke, buf, cap);
  931. else if (mode == BR_PAINT_CURRENT)
  932. css_rgb(st.color, buf, cap);
  933. else if (mode == BR_PAINT_UNSET && is_fill)
  934. snprintf(buf, cap, "rgb(0, 0, 0)");
  935. else if (mode == BR_PAINT_URL)
  936. snprintf(buf, cap, "url()");
  937. else
  938. snprintf(buf, cap, "none");
  939. } else if (!strcmp(name, "font-size")) {
  940. snprintf(buf, cap, "%dpx", st.font_px);
  941. } else if (!strcmp(name, "font-weight")) {
  942. snprintf(buf, cap, "%s", st.bold ? "700" : "400");
  943. } else if (!strcmp(name, "font-style")) {
  944. snprintf(buf, cap, "%s", st.italic ? "italic" : "normal");
  945. } else if (!strcmp(name, "font-family")) {
  946. if (st.font_face > 0 && st.font_face <= BR_MAX_FACES &&
  947. br_font_face_family(st.font_face)[0])
  948. snprintf(buf, cap, "%s",
  949. br_font_face_family(st.font_face));
  950. else
  951. snprintf(buf, cap, "%s",
  952. st.mono ? "monospace" : "sans-serif");
  953. } else if (!strcmp(name, "text-align")) {
  954. static const char *al[] = { "left", "center", "right", "justify" };
  955. snprintf(buf, cap, "%s", al[st.align < 4 ? st.align : 0]);
  956. } else if (!strcmp(name, "float")) {
  957. snprintf(buf, cap, "%s", st.float_left == 1 ? "left" :
  958. st.float_left == 2 ? "right" : "none");
  959. } else if (!strcmp(name, "clear")) {
  960. static const char *cl[] = { "none", "left", "right", "both" };
  961. snprintf(buf, cap, "%s", cl[st.clear < 4 ? st.clear : 0]);
  962. } else if (!strcmp(name, "opacity")) {
  963. snprintf(buf, cap, "%s", st.opacity_hidden ? "0" : "1");
  964. } else if (!strcmp(name, "visibility")) {
  965. snprintf(buf, cap, "%s", st.vis_hidden ? "hidden" : "visible");
  966. } else if (!strcmp(name, "overflow")) {
  967. snprintf(buf, cap, "%s",
  968. st.overflow_hidden ? "hidden" : "visible");
  969. } else if (!strcmp(name, "white-space")) {
  970. snprintf(buf, cap, "%s", st.nowrap ? "nowrap" : "normal");
  971. } else if (!strcmp(name, "text-transform")) {
  972. snprintf(buf, cap, "%s", st.uppercase ? "uppercase" : "none");
  973. } else if (!strcmp(name, "box-sizing")) {
  974. snprintf(buf, cap, "%s",
  975. st.box_sizing ? "border-box" : "content-box");
  976. } else if (!strcmp(name, "line-height")) {
  977. if (st.line_h_px)
  978. snprintf(buf, cap, "%dpx", st.line_h_px);
  979. else if (st.line_h_pct)
  980. snprintf(buf, cap, "%d%%", st.line_h_pct);
  981. else
  982. snprintf(buf, cap, "normal");
  983. } else if (!strcmp(name, "z-index")) {
  984. if (st.z_set)
  985. snprintf(buf, cap, "%d", st.z_index);
  986. else
  987. snprintf(buf, cap, "auto");
  988. } else if (!strcmp(name, "top") || !strcmp(name, "left") ||
  989. !strcmp(name, "right") || !strcmp(name, "bottom")) {
  990. int set = name[0] == 't' ? st.top_set :
  991. name[0] == 'l' ? st.left_set :
  992. name[0] == 'r' ? st.right_set : st.bottom_set;
  993. int v = name[0] == 't' ? st.top :
  994. name[0] == 'l' ? st.left :
  995. name[0] == 'r' ? st.right : st.bottom;
  996. if (set)
  997. snprintf(buf, cap, "%dpx", v);
  998. else
  999. snprintf(buf, cap, "auto");
  1000. } else if (!strcmp(name, "margin-top") || !strcmp(name, "margin-right") ||
  1001. !strcmp(name, "margin-bottom") ||
  1002. !strcmp(name, "margin-left") ||
  1003. !strcmp(name, "padding-top") ||
  1004. !strcmp(name, "padding-right") ||
  1005. !strcmp(name, "padding-bottom") ||
  1006. !strcmp(name, "padding-left")) {
  1007. int is_pad = name[0] == 'p';
  1008. int side = name[strlen(name) - 1] == 'p' ? 0 :
  1009. name[strlen(name) - 1] == 't' ? 1 :
  1010. name[strlen(name) - 1] == 'm' ? 2 : 3;
  1011. /* last letter: top p, right t, bottom m, left t (ambiguity). */
  1012. if (!strcmp(name, "margin-right") ||
  1013. !strcmp(name, "padding-right"))
  1014. side = 1;
  1015. else if (!strcmp(name, "margin-bottom") ||
  1016. !strcmp(name, "padding-bottom"))
  1017. side = 2;
  1018. else if (!strcmp(name, "margin-left") ||
  1019. !strcmp(name, "padding-left"))
  1020. side = 3;
  1021. else
  1022. side = 0;
  1023. side += is_pad ? 4 : 0;
  1024. css_mp_value(buf, cap,
  1025. side == 0 ? st.mt : side == 1 ? st.mr :
  1026. side == 2 ? st.mb : side == 3 ? st.ml :
  1027. side == 4 ? st.pt : side == 5 ? st.pr :
  1028. side == 6 ? st.pb : st.pl,
  1029. st.mp_unit[side], st.mp_calc_px[side],
  1030. st.font_px);
  1031. } else if (!strcmp(name, "border-top-width") ||
  1032. !strcmp(name, "border-right-width") ||
  1033. !strcmp(name, "border-bottom-width") ||
  1034. !strcmp(name, "border-left-width")) {
  1035. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1036. name[7] == 'b' ? 2 : 3;
  1037. snprintf(buf, cap, "%dpx", st.border_w[side]);
  1038. } else if (!strcmp(name, "border-top-color") ||
  1039. !strcmp(name, "border-right-color") ||
  1040. !strcmp(name, "border-bottom-color") ||
  1041. !strcmp(name, "border-left-color")) {
  1042. int side = name[7] == 't' ? 0 : name[7] == 'r' ? 1 :
  1043. name[7] == 'b' ? 2 : 3;
  1044. if (st.border_w[side] && !st.border_t[side])
  1045. css_rgb(st.border_c[side], buf, cap);
  1046. else
  1047. snprintf(buf, cap, "rgba(0, 0, 0, 0)");
  1048. } else if (!strcmp(name, "background-image")) {
  1049. if (st.bg_image)
  1050. snprintf(buf, cap, "url(\"%s\")",
  1051. br_bg_image_url(st.bg_image - 1));
  1052. else
  1053. snprintf(buf, cap, "none");
  1054. } else if (!strcmp(name, "background-repeat")) {
  1055. static const char *rp[] = {
  1056. "repeat", "no-repeat", "repeat-x", "repeat-y"
  1057. };
  1058. snprintf(buf, cap, "%s", rp[st.bg_repeat < 4 ?
  1059. st.bg_repeat : 0]);
  1060. } else if (!strcmp(name, "background-position")) {
  1061. if (st.bg_pos_x_kind == 1)
  1062. snprintf(buf, cap, "%d%% %d%%", st.bg_pos_x,
  1063. st.bg_pos_y);
  1064. else
  1065. snprintf(buf, cap, "%dpx %dpx", st.bg_pos_x,
  1066. st.bg_pos_y);
  1067. } else if (!strcmp(name, "background-size")) {
  1068. if (st.bg_size_kind == 3)
  1069. snprintf(buf, cap, "cover");
  1070. else if (st.bg_size_kind == 4)
  1071. snprintf(buf, cap, "contain");
  1072. else if (st.bg_size_kind == 1)
  1073. snprintf(buf, cap, "%dpx %dpx", st.bg_size_w,
  1074. st.bg_size_h);
  1075. else if (st.bg_size_kind == 2)
  1076. snprintf(buf, cap, "%d%% %d%%", st.bg_size_w,
  1077. st.bg_size_h);
  1078. else
  1079. snprintf(buf, cap, "auto");
  1080. } else if (!strcmp(name, "transform")) {
  1081. char tmp[128];
  1082. unsigned int n = 0;
  1083. if (!st.transform_set) {
  1084. snprintf(buf, cap, "none");
  1085. } else {
  1086. tmp[0] = '\0';
  1087. if (st.tx || st.ty) {
  1088. snprintf(tmp + n, sizeof(tmp) - n,
  1089. "translate(%dpx, %dpx)", st.tx, st.ty);
  1090. n = (unsigned int)strlen(tmp);
  1091. }
  1092. if (st.transform_scale) {
  1093. snprintf(tmp + n, sizeof(tmp) - n,
  1094. "%sscale(%d.%02d, %d.%02d)",
  1095. n ? " " : "", st.scale_x / 100,
  1096. st.scale_x % 100, st.scale_y / 100,
  1097. st.scale_y % 100);
  1098. n = (unsigned int)strlen(tmp);
  1099. if (st.rotate_x100) {
  1100. snprintf(tmp + n, sizeof(tmp) - n,
  1101. " rotate(%d.%02ddeg)",
  1102. st.rotate_x100 / 100,
  1103. st.rotate_x100 % 100);
  1104. }
  1105. } else if (st.rotate_x100) {
  1106. snprintf(tmp + n, sizeof(tmp) - n,
  1107. "%srotate(%d.%02ddeg)",
  1108. n ? " " : "", st.rotate_x100 / 100,
  1109. st.rotate_x100 % 100);
  1110. }
  1111. snprintf(buf, cap, "%s", tmp[0] ? tmp : "none");
  1112. }
  1113. } else {
  1114. return 0;
  1115. }
  1116. return buf[0] != '\0';
  1117. }
  1118. static int js_host_click(unsigned int node)
  1119. {
  1120. char url[BR_URL_MAX];
  1121. const char *href;
  1122. if (node >= doc.nnode)
  1123. return 0;
  1124. if (form_is_control(node)) {
  1125. form_click(node); /* dispatches its own click event */
  1126. return 1;
  1127. }
  1128. /* element.click() fires a bubbling, cancelable click before the
  1129. * default action, like a real click (delegated list handlers). */
  1130. if (!js_browser_event(node, "click", 1, 1))
  1131. return 1;
  1132. if (link_fragment_nav(node))
  1133. return 1;
  1134. href = br_href(&doc, node);
  1135. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  1136. return 0;
  1137. s_copy(pending_url, url, sizeof(pending_url));
  1138. pending_action |= ACT_NAV;
  1139. cancel_fetch = 1;
  1140. ngui_invalidate(&ui);
  1141. return 1;
  1142. }
  1143. static int fetch_script_text(const char *url, unsigned char **out,
  1144. unsigned int *outlen, char *err,
  1145. unsigned int errcap);
  1146. struct fetch_worker;
  1147. static struct fetch_worker *fetch_worker_alloc(void);
  1148. static void fetch_worker_release(struct fetch_worker *w);
  1149. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  1150. unsigned int cap, const char *post,
  1151. unsigned int post_len, unsigned int node,
  1152. int bg, char *err, unsigned int errcap);
  1153. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  1154. unsigned int errcap);
  1155. static int fetch_worker_read_body(struct fetch_worker *w,
  1156. unsigned char *plain,
  1157. unsigned int plaincap,
  1158. unsigned char *comp,
  1159. unsigned int compcap,
  1160. int *truncated, char *err,
  1161. unsigned int errcap);
  1162. static void fetch_workers_stop_all(void);
  1163. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  1164. unsigned int cap, const char *method,
  1165. const char *ctype, const char *post,
  1166. unsigned int post_len, unsigned int node,
  1167. int bg, unsigned int dec_w,
  1168. unsigned int dec_h, char *err,
  1169. unsigned int errcap);
  1170. static int script_cache_has(const char *url);
  1171. static void script_cache_put(const char *url, const unsigned char *data,
  1172. unsigned int len);
  1173. static unsigned int script_cache_hash(const char *s);
  1174. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  1175. unsigned int errcap);
  1176. static void fetch_workers_cancel_busy(void);
  1177. static void worker_wait_ui(void);
  1178. static int fetch_worker_status(const struct fetch_worker *w);
  1179. /* Nonzero while JavaScript is suspended in a synchronous fetch()/XHR or a
  1180. * module load: the wait must not pump input, or a click would dispatch DOM
  1181. * events into the middle of the running script. */
  1182. static int fetch_wait_passive;
  1183. static void script_error(const char *what, const char *url, const char *why)
  1184. {
  1185. char msg[192];
  1186. unsigned int n = 0;
  1187. s_append(msg, &n, what, sizeof(msg));
  1188. if (url && url[0]) {
  1189. s_append(msg, &n, " ", sizeof(msg));
  1190. s_append(msg, &n, url, sizeof(msg));
  1191. }
  1192. if (why && why[0]) {
  1193. s_append(msg, &n, ": ", sizeof(msg));
  1194. s_append(msg, &n, why, sizeof(msg));
  1195. }
  1196. js_host_report(msg);
  1197. }
  1198. /* ---- fetch()/XHR, ES modules and Web Storage for js_browser.c ---- */
  1199. /* Largest fetch()/XHR response body (the helper's FETCH_MAX) and request
  1200. * body (FETCH_POST_MAX in ucmd_curl.c). */
  1201. #define JS_HTTP_MAX (2u * 1024u * 1024u)
  1202. #define JS_HTTP_POST_MAX (16u * 1024u)
  1203. /* struct fetch_meta / fetch_worker internals come later in the file. */
  1204. static int js_worker_http(const char *method, const char *url,
  1205. const char *ctype, const char *body,
  1206. unsigned int body_len, struct js_http_resp *r,
  1207. char *err, int errcap);
  1208. static int js_host_http(const char *method, const char *url,
  1209. const char *ctype, const char *body,
  1210. unsigned int body_len, struct js_http_resp *r,
  1211. char *err, int errcap)
  1212. {
  1213. if (pending_action) {
  1214. s_copy(err, "page is navigating", (unsigned int)errcap);
  1215. return -1;
  1216. }
  1217. if (url[0] == '/') {
  1218. /* Local file: GET only. */
  1219. unsigned char *buf = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  1220. int rv;
  1221. if (!buf) {
  1222. s_copy(err, "out of memory", (unsigned int)errcap);
  1223. return -1;
  1224. }
  1225. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)buf,
  1226. (int)JS_HTTP_MAX);
  1227. r->status = rv < 0 ? 404 : 200;
  1228. r->len = rv < 0 ? 0 : (unsigned int)rv;
  1229. buf[r->len] = '\0';
  1230. r->body = (char *)buf;
  1231. s_copy(r->url, url, sizeof(r->url));
  1232. if (contains_ci(url, ".json"))
  1233. s_copy(r->ctype, "application/json", sizeof(r->ctype));
  1234. return 0;
  1235. }
  1236. if (!starts_with(url, "http://") && !starts_with(url, "https://")) {
  1237. s_copy(err, "unsupported URL scheme", (unsigned int)errcap);
  1238. return -1;
  1239. }
  1240. if (body_len > JS_HTTP_POST_MAX) {
  1241. s_copy(err, "request body too large", (unsigned int)errcap);
  1242. return -1;
  1243. }
  1244. return js_worker_http(method, url, ctype, body, body_len, r, err,
  1245. errcap);
  1246. }
  1247. /* Module source for the engine's loader: the boot script cache first, then
  1248. * one blocking fetch with input pumping disabled (the loader runs inside
  1249. * JavaScript). */
  1250. static char *js_host_load_script(const char *url, unsigned int *len)
  1251. {
  1252. unsigned char *data = 0;
  1253. char err[64];
  1254. int rv;
  1255. fetch_wait_passive++;
  1256. set_status("Loading module...", 0, 0);
  1257. rv = fetch_script_text(url, &data, len, err, sizeof(err));
  1258. fetch_wait_passive--;
  1259. if (rv != 0) {
  1260. script_error("Cannot load module", url,
  1261. rv == FETCH_ABORT ? "navigation" : err);
  1262. return 0;
  1263. }
  1264. return (char *)data;
  1265. }
  1266. /* Web Storage lives in /share, outside the page heap that every navigation
  1267. * resets: localStorage per origin for the boot, sessionStorage per origin
  1268. * and browser window. */
  1269. #define JS_ORIGIN_MAX 160
  1270. /* scheme://host[:port] of the page (a local page's whole path). */
  1271. static void js_page_origin(char *origin, unsigned int cap)
  1272. {
  1273. unsigned int i = 0, slashes = 0;
  1274. while (page_url[i] && i + 1 < cap) {
  1275. if (page_url[i] == '/' && ++slashes == 3)
  1276. break;
  1277. origin[i] = page_url[i];
  1278. i++;
  1279. }
  1280. origin[i] = '\0';
  1281. }
  1282. static void js_origin_path(const char *origin, char *out, unsigned int cap)
  1283. {
  1284. unsigned int n = 0;
  1285. s_append(out, &n, "/share/bls", cap);
  1286. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1287. }
  1288. static void js_storage_path(int kind, char *out, unsigned int cap)
  1289. {
  1290. char origin[JS_ORIGIN_MAX];
  1291. unsigned int n = 0;
  1292. js_page_origin(origin, sizeof(origin));
  1293. if (!kind) {
  1294. js_origin_path(origin, out, cap);
  1295. return;
  1296. }
  1297. s_append(out, &n, "/share/bss", cap);
  1298. if (kind) {
  1299. s_append_dec(out, &n, (unsigned int)u_getpid(), cap);
  1300. s_append(out, &n, "-", cap);
  1301. }
  1302. s_append_dec(out, &n, script_cache_hash(origin), cap);
  1303. }
  1304. static void persist_mark_origin(const char *origin);
  1305. static int persist_store_lookup(const char *origin, char *out, int cap);
  1306. static int js_host_storage(int kind, const char *set, char *out, int cap)
  1307. {
  1308. char path[48], origin[JS_ORIGIN_MAX];
  1309. int rv;
  1310. js_storage_path(kind, path, sizeof(path));
  1311. if (set) {
  1312. if (kind) {
  1313. if (!set[0] || !strcmp(set, "{}")) {
  1314. u_syscall1(SYS_UNLINK, (int)path);
  1315. return 0;
  1316. }
  1317. } else {
  1318. /* localStorage keeps an explicit "{}" rather than no
  1319. * file: a missing /share file means "not loaded from
  1320. * /data yet", and a cleared store must not come back
  1321. * from the disk copy before it is flushed. */
  1322. if (!set[0])
  1323. set = "{}";
  1324. js_page_origin(origin, sizeof(origin));
  1325. persist_mark_origin(origin);
  1326. }
  1327. return u_syscall3(SYS_WRITE_FILE, (int)path, (int)set,
  1328. (int)strlen(set)) < 0 ? -1 : 0;
  1329. }
  1330. rv = u_syscall3(SYS_READ_FILE, (int)path, (int)out, cap - 1);
  1331. if (rv < 0 && !kind) {
  1332. /* First use this boot: the persistent copy on /data. */
  1333. js_page_origin(origin, sizeof(origin));
  1334. rv = persist_store_lookup(origin, out, cap);
  1335. if (rv >= 0)
  1336. u_syscall3(SYS_WRITE_FILE, (int)path, (int)out, rv);
  1337. }
  1338. if (rv < 0)
  1339. return -1;
  1340. out[rv] = '\0';
  1341. return rv;
  1342. }
  1343. /* ---- persistence on /data ----
  1344. *
  1345. * /share is the working copy (RAM, shared by every helper and window); the
  1346. * installed disk's /data volume keeps the cookie jar and localStorage
  1347. * across reboots when it is mounted. The browser owns the disk copies: at
  1348. * start it restores the jar into /share, and its main loop writes back
  1349. * whatever changed at most every PERSIST_MS, so a burst of cookie or
  1350. * setItem updates costs one FAT write. The helpers only touch /share (they
  1351. * are killed on focus loss, so they cannot be trusted to flush). Without a
  1352. * /data mount every disk access simply fails. Both files are plaintext
  1353. * bearer credentials, like /data/CHAT.CFG. sessionStorage stays in RAM. */
  1354. #define PERSIST_MS 3000u
  1355. #define SHARE_COOKIES "/share/bcookies"
  1356. #define DATA_COOKIES "/data/BCOOKIES.BIN"
  1357. #define DATA_STORE "/data/BSTORE.DAT"
  1358. #define DATA_STORE_MAGIC "NBLS1\n"
  1359. #define DATA_STORE_MAX (192u * 1024u)
  1360. #define PERSIST_DIRTY_MAX 8
  1361. static unsigned int persist_due;
  1362. static unsigned int cookie_sum_saved;
  1363. static int cookie_sum_valid;
  1364. static char persist_dirty[PERSIST_DIRTY_MAX][JS_ORIGIN_MAX];
  1365. static int persist_ndirty;
  1366. static unsigned int persist_sum(const unsigned char *p, unsigned int n)
  1367. {
  1368. unsigned int h = 2166136261u, i;
  1369. for (i = 0; i < n; i++)
  1370. h = (h ^ p[i]) * 16777619u;
  1371. return h;
  1372. }
  1373. /* Called once at startup, before any helper runs. */
  1374. static void persist_restore(void)
  1375. {
  1376. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1377. int n;
  1378. if (!jar)
  1379. return;
  1380. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1381. (int)sizeof(struct uhttp_jar));
  1382. if (n != (int)sizeof(struct uhttp_jar)) {
  1383. n = u_syscall3(SYS_READ_FILE, (int)DATA_COOKIES, (int)jar,
  1384. (int)sizeof(struct uhttp_jar));
  1385. if (n == (int)sizeof(struct uhttp_jar)) {
  1386. u_syscall3(SYS_WRITE_FILE, (int)SHARE_COOKIES,
  1387. (int)jar, n);
  1388. cookie_sum_saved = persist_sum(jar, (unsigned int)n);
  1389. cookie_sum_valid = 1;
  1390. }
  1391. }
  1392. free(jar);
  1393. persist_due = u_ticks_ms() + PERSIST_MS;
  1394. }
  1395. static void persist_mark_origin(const char *origin)
  1396. {
  1397. int i;
  1398. for (i = 0; i < persist_ndirty; i++)
  1399. if (s_eq(persist_dirty[i], origin))
  1400. return;
  1401. if (persist_ndirty < PERSIST_DIRTY_MAX)
  1402. s_copy(persist_dirty[persist_ndirty++], origin, JS_ORIGIN_MAX);
  1403. }
  1404. /* BSTORE.DAT: "NBLS1\n", then per origin "<origin>\n<length>\n<json>\n".
  1405. * Walk it; returns 1 with the record's fields, 0 at the end. */
  1406. static int store_next(const char *buf, unsigned int len, unsigned int *pos,
  1407. unsigned int *o_off, unsigned int *o_len,
  1408. unsigned int *d_off, unsigned int *d_len,
  1409. unsigned int *rec_end)
  1410. {
  1411. unsigned int p = *pos, v = 0;
  1412. if (p >= len)
  1413. return 0;
  1414. *o_off = p;
  1415. while (p < len && buf[p] != '\n')
  1416. p++;
  1417. if (p >= len)
  1418. return 0;
  1419. *o_len = p - *o_off;
  1420. p++;
  1421. while (p < len && buf[p] >= '0' && buf[p] <= '9')
  1422. v = v * 10 + (unsigned int)(buf[p++] - '0');
  1423. if (p >= len || buf[p] != '\n')
  1424. return 0;
  1425. p++;
  1426. if (v > len - p)
  1427. return 0;
  1428. *d_off = p;
  1429. *d_len = v;
  1430. p += v;
  1431. if (p < len && buf[p] == '\n')
  1432. p++;
  1433. *rec_end = p;
  1434. *pos = p;
  1435. return 1;
  1436. }
  1437. static int store_load(char **out)
  1438. {
  1439. char *buf = (char *)malloc(DATA_STORE_MAX + 1);
  1440. int n;
  1441. *out = buf;
  1442. if (!buf)
  1443. return -1;
  1444. n = u_syscall3(SYS_READ_FILE, (int)DATA_STORE, (int)buf,
  1445. (int)DATA_STORE_MAX);
  1446. if (n < (int)s_len(DATA_STORE_MAGIC) ||
  1447. !starts_with(buf, DATA_STORE_MAGIC))
  1448. return 0;
  1449. return n;
  1450. }
  1451. static int persist_store_lookup(const char *origin, char *out, int cap)
  1452. {
  1453. char *buf;
  1454. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e;
  1455. unsigned int olen = s_len(origin);
  1456. int n = store_load(&buf), rv = -1;
  1457. while (n > 0 && store_next(buf, (unsigned int)n, &pos, &oo, &ol, &d,
  1458. &dl, &e)) {
  1459. if (ol == olen && !memcmp(buf + oo, origin, olen)) {
  1460. if ((int)dl < cap) {
  1461. memcpy(out, buf + d, dl);
  1462. out[dl] = '\0';
  1463. rv = (int)dl;
  1464. }
  1465. break;
  1466. }
  1467. }
  1468. free(buf);
  1469. return rv;
  1470. }
  1471. /* Rewrite BSTORE.DAT with the dirty origins' current /share copies. */
  1472. static void persist_store_flush(void)
  1473. {
  1474. char *old, *nb, path[48];
  1475. unsigned int pos = s_len(DATA_STORE_MAGIC), oo, ol, d, dl, e, nn = 0;
  1476. int n = store_load(&old), i, w;
  1477. nb = (char *)malloc(DATA_STORE_MAX + 1);
  1478. if (n < 0 || !nb) {
  1479. free(old);
  1480. free(nb);
  1481. return;
  1482. }
  1483. s_append(nb, &nn, DATA_STORE_MAGIC, DATA_STORE_MAX);
  1484. /* Untouched origins first, in their old order. */
  1485. while (n > 0 && store_next(old, (unsigned int)n, &pos, &oo, &ol, &d,
  1486. &dl, &e)) {
  1487. int dirty = 0;
  1488. for (i = 0; i < persist_ndirty; i++)
  1489. if (s_len(persist_dirty[i]) == ol &&
  1490. !memcmp(persist_dirty[i], old + oo, ol))
  1491. dirty = 1;
  1492. if (dirty || nn + (e - oo) > DATA_STORE_MAX)
  1493. continue;
  1494. memcpy(nb + nn, old + oo, e - oo);
  1495. nn += e - oo;
  1496. }
  1497. /* Then the changed ones (an emptied store is dropped). */
  1498. for (i = 0; i < persist_ndirty; i++) {
  1499. char num[12];
  1500. unsigned int k = 0;
  1501. js_origin_path(persist_dirty[i], path, sizeof(path));
  1502. w = u_syscall3(SYS_READ_FILE, (int)path, (int)old,
  1503. (int)DATA_STORE_MAX);
  1504. if (w <= 2) /* missing or "{}" */
  1505. continue;
  1506. s_append_dec(num, &k, (unsigned int)w, sizeof(num));
  1507. if (nn + s_len(persist_dirty[i]) + k + (unsigned int)w + 3 >
  1508. DATA_STORE_MAX) {
  1509. set_status("Saved site data is full; a site's "
  1510. "localStorage was not saved", 1, 6000);
  1511. continue;
  1512. }
  1513. s_append(nb, &nn, persist_dirty[i], DATA_STORE_MAX);
  1514. nb[nn++] = '\n';
  1515. s_append(nb, &nn, num, DATA_STORE_MAX);
  1516. nb[nn++] = '\n';
  1517. memcpy(nb + nn, old, (unsigned int)w);
  1518. nn += (unsigned int)w;
  1519. nb[nn++] = '\n';
  1520. }
  1521. u_syscall3(SYS_WRITE_FILE, (int)DATA_STORE, (int)nb, (int)nn);
  1522. persist_ndirty = 0;
  1523. free(old);
  1524. free(nb);
  1525. }
  1526. static void persist_cookies_flush(void)
  1527. {
  1528. unsigned char *jar = (unsigned char *)malloc(sizeof(struct uhttp_jar));
  1529. unsigned int sum;
  1530. int n;
  1531. if (!jar)
  1532. return;
  1533. n = u_syscall3(SYS_READ_FILE, (int)SHARE_COOKIES, (int)jar,
  1534. (int)sizeof(struct uhttp_jar));
  1535. if (n == (int)sizeof(struct uhttp_jar)) {
  1536. sum = persist_sum(jar, (unsigned int)n);
  1537. if (!cookie_sum_valid || sum != cookie_sum_saved) {
  1538. if (u_syscall3(SYS_WRITE_FILE, (int)DATA_COOKIES,
  1539. (int)jar, n) >= 0) {
  1540. cookie_sum_saved = sum;
  1541. cookie_sum_valid = 1;
  1542. }
  1543. }
  1544. }
  1545. free(jar);
  1546. }
  1547. /* Main-loop hook: write back to /data at most every PERSIST_MS. */
  1548. static void persist_tick(void)
  1549. {
  1550. unsigned int now = u_ticks_ms();
  1551. if ((int)(now - persist_due) < 0)
  1552. return;
  1553. persist_due = now + PERSIST_MS;
  1554. persist_cookies_flush();
  1555. if (persist_ndirty)
  1556. persist_store_flush();
  1557. }
  1558. /* <link rel="modulepreload">: download the page's module graph on all
  1559. * helpers at once into the boot script cache, before any script runs. The
  1560. * engine's module loader is sequential (one blocking fetch per import), so
  1561. * without this a Vite app with a dozen chunks pays every round trip in a
  1562. * row. Failures are ignored; the loader fetches what is missing. */
  1563. #define MODULE_PRELOAD_MAX 24
  1564. static void prefetch_module_preloads(void)
  1565. {
  1566. static char urls[MODULE_PRELOAD_MAX][BR_URL_MAX];
  1567. struct fetch_worker *slot[MODULE_PRELOAD_MAX];
  1568. unsigned int count = 0, next = 0, done = 0, i;
  1569. char err[64];
  1570. for (i = 1; i < doc.nnode && count < MODULE_PRELOAD_MAX; i++) {
  1571. struct br_node *nd = &doc.nodes[i];
  1572. const char *rel, *href;
  1573. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  1574. continue;
  1575. rel = br_rel(&doc, i);
  1576. href = br_href(&doc, i);
  1577. if (!rel || !href || !href[0] || !contains_ci(rel, "modulepreload"))
  1578. continue;
  1579. if (resolve_link(page_url, href, urls[count],
  1580. sizeof(urls[count])) != 0 ||
  1581. urls[count][0] == '/' || script_cache_has(urls[count]))
  1582. continue;
  1583. slot[count++] = 0;
  1584. }
  1585. if (!count)
  1586. return;
  1587. set_status("Loading modules...", 0, 0);
  1588. while (done < count) {
  1589. struct fetch_worker *w;
  1590. while (next < count && (w = fetch_worker_alloc()) != 0) {
  1591. if (fetch_worker_submit(w, urls[next], BR_SCRIPT_MAX, 0,
  1592. 0, 0, 0, err,
  1593. sizeof(err)) != 0) {
  1594. fetch_worker_release(w);
  1595. done++;
  1596. } else {
  1597. slot[next] = w;
  1598. }
  1599. next++;
  1600. }
  1601. worker_wait_ui();
  1602. if (cancel_fetch || pending_action) {
  1603. fetch_workers_cancel_busy();
  1604. return;
  1605. }
  1606. for (i = 0; i < next; i++) {
  1607. unsigned char *body;
  1608. int rv, tr = 0;
  1609. if (!slot[i])
  1610. continue;
  1611. rv = fetch_worker_poll(slot[i], err, sizeof(err));
  1612. if (rv == 0)
  1613. continue;
  1614. body = rv == 1 && fetch_worker_status(slot[i]) == 200 ?
  1615. (unsigned char *)malloc(BR_SCRIPT_MAX + 1) : 0;
  1616. if (body) {
  1617. rv = fetch_worker_read_body(slot[i], body,
  1618. BR_SCRIPT_MAX, image_io_buf,
  1619. BR_PAGE_COMP_MAX, &tr, err,
  1620. sizeof(err));
  1621. if (rv > 0 && !tr)
  1622. script_cache_put(urls[i], body,
  1623. (unsigned int)rv);
  1624. free(body);
  1625. }
  1626. fetch_worker_release(slot[i]);
  1627. slot[i] = 0;
  1628. done++;
  1629. }
  1630. u_sleep_ms(10);
  1631. }
  1632. }
  1633. /* Script prefetch state: one entry per <script> block. Remote bodies are
  1634. * submitted to helper workers ahead of time, but scripts still execute in
  1635. * document order. */
  1636. #define SCRIPT_INLINE 0
  1637. #define SCRIPT_LOCAL 1
  1638. #define SCRIPT_REMOTE 2
  1639. #define SCRIPT_ERROR 3
  1640. static char script_urls[BR_MAX_SCRIPTS][BR_URL_MAX];
  1641. static unsigned char script_kind[BR_MAX_SCRIPTS];
  1642. static struct fetch_worker *script_slot[BR_MAX_SCRIPTS];
  1643. static void script_submit_window(unsigned int *next, char *err,
  1644. unsigned int errcap)
  1645. {
  1646. while (*next < doc.nscripts) {
  1647. struct fetch_worker *w;
  1648. if (script_kind[*next] != SCRIPT_REMOTE) {
  1649. (*next)++;
  1650. continue;
  1651. }
  1652. w = fetch_worker_alloc();
  1653. if (!w)
  1654. return;
  1655. if (fetch_worker_submit(w, script_urls[*next], BR_SCRIPT_MAX,
  1656. 0, 0, 0, 0, err, errcap) != 0) {
  1657. fetch_worker_release(w);
  1658. script_kind[*next] = SCRIPT_ERROR;
  1659. (*next)++;
  1660. continue;
  1661. }
  1662. script_slot[*next] = w;
  1663. (*next)++;
  1664. }
  1665. }
  1666. /* Run the page's scripts in document order. External bodies are prefetched
  1667. * in parallel so downloading script N+1 overlaps executing script N; inline
  1668. * bodies are copied because the engine needs NUL-terminated text. */
  1669. static void run_page_scripts(void)
  1670. {
  1671. struct js_browser_host host;
  1672. unsigned int i, next = 0;
  1673. char err[64], ferr[64];
  1674. if (!doc.nscripts)
  1675. return;
  1676. host.status = js_host_status;
  1677. host.report = js_host_report;
  1678. host.navigate = js_host_navigate;
  1679. host.changed = js_host_changed;
  1680. host.rect = js_host_rect;
  1681. host.form_value = js_host_form_value;
  1682. host.form_checked = js_host_form_checked;
  1683. host.form_selected = js_host_form_selected;
  1684. host.form_set_value = js_host_form_set_value;
  1685. host.form_set_checked = js_host_form_set_checked;
  1686. host.form_set_selected = js_host_form_set_selected;
  1687. host.form_elements = js_host_form_elements;
  1688. host.form_submit = js_host_form_submit;
  1689. host.form_reset = js_host_form_reset;
  1690. host.click = js_host_click;
  1691. host.computed = js_host_computed;
  1692. host.http = js_host_http;
  1693. host.load_script = js_host_load_script;
  1694. host.storage = js_host_storage;
  1695. host.set_hash = js_host_set_hash;
  1696. host.page_url = page_url;
  1697. host.width = ui.w;
  1698. host.height = ui.h;
  1699. if (js_browser_start(&doc, &host) != 0) {
  1700. js_host_status("JavaScript: out of memory", 1);
  1701. return;
  1702. }
  1703. resize_sent_w = -1;
  1704. resize_pending = 0;
  1705. prefetch_module_preloads();
  1706. for (i = 0; i < doc.nscripts; i++) {
  1707. struct br_script *script = &doc.scripts[i];
  1708. const char *src_attr = script->src_off ?
  1709. doc.attrs + script->src_off : "";
  1710. script_slot[i] = 0;
  1711. if (!script->src_off) {
  1712. script_kind[i] = SCRIPT_INLINE;
  1713. continue;
  1714. }
  1715. if (!src_attr[0] ||
  1716. resolve_link(page_url, src_attr, script_urls[i],
  1717. sizeof(script_urls[i])) != 0) {
  1718. script_urls[i][0] = '\0';
  1719. script_kind[i] = SCRIPT_ERROR;
  1720. continue;
  1721. }
  1722. if (script_urls[i][0] == '/' ||
  1723. script_cache_has(script_urls[i]))
  1724. script_kind[i] = SCRIPT_LOCAL;
  1725. else
  1726. script_kind[i] = SCRIPT_REMOTE;
  1727. }
  1728. script_submit_window(&next, ferr, sizeof(ferr));
  1729. for (i = 0; i < doc.nscripts; i++) {
  1730. struct br_script *script = &doc.scripts[i];
  1731. /* document.currentScript for classic scripts (null for modules) */
  1732. js_browser_set_current_script(script->module ? 0 : script->node);
  1733. if (script_kind[i] == SCRIPT_INLINE) {
  1734. unsigned int off = script->off;
  1735. unsigned int len = script->len;
  1736. unsigned int k;
  1737. char *src = (char *)malloc(len + 1);
  1738. if (!src) {
  1739. js_host_status("JavaScript: out of memory", 1);
  1740. break;
  1741. }
  1742. for (k = 0; k < len; k++)
  1743. src[k] = doc.script_src[off + k];
  1744. src[len] = '\0';
  1745. if (script->module) {
  1746. /* A distinct module name per inline module
  1747. * (QuickJS registers modules by name); the
  1748. * fragment keeps relative imports resolving
  1749. * against the page. */
  1750. char mname[BR_URL_MAX + 16];
  1751. unsigned int mn = 0;
  1752. s_append(mname, &mn, page_url, sizeof(mname));
  1753. s_append(mname, &mn, "#module", sizeof(mname));
  1754. s_append_dec(mname, &mn, i, sizeof(mname));
  1755. js_browser_run_module(src, mname);
  1756. } else {
  1757. js_browser_run(src, page_url);
  1758. }
  1759. free(src);
  1760. } else if (script->src_off) {
  1761. const char *src_attr = doc.attrs + script->src_off;
  1762. if (script_kind[i] == SCRIPT_ERROR) {
  1763. script_error("Cannot load script", src_attr,
  1764. script_urls[i][0] ?
  1765. "network busy" :
  1766. "unsupported URL");
  1767. continue;
  1768. }
  1769. if (script_kind[i] == SCRIPT_LOCAL) {
  1770. unsigned char *data = 0;
  1771. unsigned int len = 0;
  1772. int rv;
  1773. set_status("Loading script...", 0, 0);
  1774. rv = fetch_script_text(script_urls[i], &data,
  1775. &len, err, sizeof(err));
  1776. if (rv == FETCH_ABORT)
  1777. break;
  1778. if (rv != 0) {
  1779. script_error("Cannot load script",
  1780. script_urls[i], err);
  1781. continue;
  1782. }
  1783. if (script->module)
  1784. js_browser_run_module(
  1785. (const char *)data,
  1786. script_urls[i]);
  1787. else
  1788. js_browser_run((const char *)data,
  1789. script_urls[i]);
  1790. free(data);
  1791. } else {
  1792. struct fetch_worker *w = script_slot[i];
  1793. unsigned char *body = 0;
  1794. int tr = 0, rv;
  1795. if (!w) {
  1796. w = fetch_worker_alloc();
  1797. if (!w)
  1798. continue;
  1799. if (fetch_worker_submit(w,
  1800. script_urls[i],
  1801. BR_SCRIPT_MAX,
  1802. 0, 0, 0, 0, err,
  1803. sizeof(err)) != 0) {
  1804. fetch_worker_release(w);
  1805. script_kind[i] = SCRIPT_ERROR;
  1806. if (i == next)
  1807. next++;
  1808. continue;
  1809. }
  1810. script_slot[i] = w;
  1811. if (i == next)
  1812. next++;
  1813. }
  1814. set_status("Loading script...", 0, 0);
  1815. rv = fetch_worker_wait(w, err, sizeof(err));
  1816. if (rv == FETCH_ABORT) {
  1817. fetch_workers_stop_all();
  1818. break;
  1819. }
  1820. /* The body gets its own buffer (scripts are up
  1821. * to 2 MB); image_io_buf takes the gzip
  1822. * stream. */
  1823. body = rv == 0 ? (unsigned char *)malloc(
  1824. BR_SCRIPT_MAX + 1) : 0;
  1825. if (body)
  1826. rv = fetch_worker_read_body(w, body,
  1827. BR_SCRIPT_MAX, image_io_buf,
  1828. BR_PAGE_COMP_MAX, &tr, err,
  1829. sizeof(err));
  1830. else {
  1831. if (rv == 0)
  1832. s_copy(err, "out of memory",
  1833. sizeof(err));
  1834. rv = -1;
  1835. }
  1836. fetch_worker_release(w);
  1837. script_slot[i] = 0;
  1838. script_submit_window(&next, ferr, sizeof(ferr));
  1839. if (rv <= 0)
  1840. script_error("Cannot load script",
  1841. script_urls[i], err);
  1842. else if (tr || (unsigned int)rv >=
  1843. BR_SCRIPT_MAX)
  1844. script_error("Cannot load script",
  1845. script_urls[i],
  1846. "script is too large");
  1847. else {
  1848. body[rv] = '\0';
  1849. script_cache_put(script_urls[i], body,
  1850. (unsigned int)rv);
  1851. if (script->module)
  1852. js_browser_run_module(
  1853. (const char *)body,
  1854. script_urls[i]);
  1855. else
  1856. js_browser_run(
  1857. (const char *)body,
  1858. script_urls[i]);
  1859. }
  1860. free(body);
  1861. }
  1862. }
  1863. if (pending_action)
  1864. break;
  1865. }
  1866. js_browser_set_current_script(0);
  1867. /* Keep the state alive for setTimeout/ready callbacks; load_page() and
  1868. * load_home() stop it before the next navigation. */
  1869. if (doc.scripts_truncated && !js_last_error)
  1870. js_host_status("Page has more than 32 scripts; extra scripts skipped",
  1871. 1);
  1872. }
  1873. /* ---- images ---- */
  1874. static void image_reset(void)
  1875. {
  1876. int i;
  1877. for (i = 0; i < BR_MAX_IMAGES; i++) {
  1878. images[i].state = 0;
  1879. images[i].native_w = images[i].native_h = 0;
  1880. images[i].err[0] = '\0';
  1881. /* heap_clear() ran before us, so these pointers are stale: drop
  1882. * them without calling free(). */
  1883. memset(&images[i].disp, 0, sizeof(images[i].disp));
  1884. images[i].disp_pixels = 0;
  1885. images[i].disp_last = 0;
  1886. }
  1887. image_count = 0;
  1888. image_pixels = 0;
  1889. image_disp_pixels = 0;
  1890. image_disp_clock = 0;
  1891. memset(img_stat_log, 0, sizeof(img_stat_log));
  1892. img_stat_log_len = 0;
  1893. img_stat_start = 0;
  1894. img_stat_wall = 0;
  1895. img_stat_net = img_stat_open = img_stat_first = 0;
  1896. img_stat_io = img_stat_dec = img_stat_scale = 0;
  1897. img_stat_paint = img_stat_reflow = 0;
  1898. img_stat_bytes = 0;
  1899. img_stat_n = 0;
  1900. img_last_dec_ms = img_last_scale_ms = 0;
  1901. img_repaint_ms = 0;
  1902. img_repaint_pending = 0;
  1903. preload_active = 0;
  1904. preload_pending = 0;
  1905. preload_wait = 0;
  1906. preload_node = 0;
  1907. preload_loaded = 0;
  1908. }
  1909. /* Ask for a repaint, but not more often than BR_IMG_REPAINT_MS while images
  1910. * are arriving. The main loop draws once per dirty frame; without this a
  1911. * page of N images did N full layout+paint passes. */
  1912. static void image_repaint(void)
  1913. {
  1914. unsigned int now = u_ticks_ms();
  1915. if (!img_repaint_ms || (now - img_repaint_ms) >= BR_IMG_REPAINT_MS) {
  1916. img_repaint_ms = now;
  1917. img_repaint_pending = 0;
  1918. ngui_invalidate(&ui);
  1919. } else {
  1920. img_repaint_pending = 1;
  1921. }
  1922. }
  1923. static void image_disp_drop(struct br_image *bi)
  1924. {
  1925. if (bi->disp.px)
  1926. free(bi->disp.px);
  1927. if (bi->disp.alpha)
  1928. free(bi->disp.alpha);
  1929. memset(&bi->disp, 0, sizeof(bi->disp));
  1930. if (bi->disp_pixels) {
  1931. if (image_disp_pixels >= bi->disp_pixels)
  1932. image_disp_pixels -= bi->disp_pixels;
  1933. bi->disp_pixels = 0;
  1934. }
  1935. }
  1936. /* Free the least recently used display caches until need pixels fit. The
  1937. * source bitmap (bi->img) is never evicted; a later draw rescales it again. */
  1938. static int image_disp_room(unsigned int need)
  1939. {
  1940. while (image_disp_pixels + need > BR_IMG_DISP_BUDGET) {
  1941. unsigned int oldest = ~0u;
  1942. int i, victim = -1;
  1943. for (i = 0; i < image_count; i++) {
  1944. if (!images[i].disp.px)
  1945. continue;
  1946. if (images[i].disp_last < oldest) {
  1947. oldest = images[i].disp_last;
  1948. victim = i;
  1949. }
  1950. }
  1951. if (victim < 0)
  1952. return -1;
  1953. image_disp_drop(&images[victim]);
  1954. }
  1955. return 0;
  1956. }
  1957. /* Return a bitmap at exactly dw x dh, building it once from the capped source
  1958. * bitmap. Callers then draw with scale 1 and img_draw's copy fast path. */
  1959. static struct img_image *image_display_get(struct br_image *bi, int dw, int dh)
  1960. {
  1961. struct img_blit b;
  1962. unsigned int px;
  1963. if (!bi || bi->state != 1 || !bi->img.px || dw < 1 || dh < 1)
  1964. return 0;
  1965. if (dw == (int)bi->img.w && dh == (int)bi->img.h)
  1966. return &bi->img;
  1967. if (dw > 4096 || dh > 4096)
  1968. return &bi->img;
  1969. if (bi->disp.px && bi->disp.w == (unsigned int)dw &&
  1970. bi->disp.h == (unsigned int)dh) {
  1971. bi->disp_last = ++image_disp_clock;
  1972. return &bi->disp;
  1973. }
  1974. px = (unsigned int)dw * (unsigned int)dh;
  1975. if (px > BR_IMG_DISP_BUDGET || image_disp_room(px) != 0)
  1976. return &bi->img;
  1977. image_disp_drop(bi);
  1978. bi->disp.px = (unsigned short *)malloc(px * 2u);
  1979. if (!bi->disp.px)
  1980. return &bi->img;
  1981. if (bi->img.alpha) {
  1982. bi->disp.alpha = (unsigned char *)malloc(px);
  1983. if (!bi->disp.alpha) {
  1984. free(bi->disp.px);
  1985. bi->disp.px = 0;
  1986. return &bi->img;
  1987. }
  1988. }
  1989. bi->disp.w = (unsigned int)dw;
  1990. bi->disp.h = (unsigned int)dh;
  1991. bi->disp.format = bi->img.format;
  1992. bi->disp.flags = 0;
  1993. memset(&b, 0, sizeof(b));
  1994. b.dst = bi->disp.px;
  1995. b.dst_w = dw;
  1996. b.dst_h = dh;
  1997. b.clip_w = dw;
  1998. b.clip_h = dh;
  1999. b.scale = ((unsigned int)dw << 16) / bi->img.w;
  2000. b.dst_a = bi->disp.alpha;
  2001. b.flags = bi->disp.alpha ? IMG_BLIT_SAVE_ALPHA : 0;
  2002. img_draw(&bi->img, &b);
  2003. bi->disp_pixels = px;
  2004. image_disp_pixels += px;
  2005. bi->disp_last = ++image_disp_clock;
  2006. return &bi->disp;
  2007. }
  2008. /* Decode into the shared arena, then copy/scale the result into a display
  2009. * bitmap of at most BR_IMG_LAYOUT_W pixels wide. The arena is reused by the
  2010. * next image, so the per-image cost is its scaled bitmap, not full 4K RGBA
  2011. * pixels. Transparent edges are composited over white. */
  2012. /* One decode scratch arena per page, reused across images. Allocating and
  2013. * freeing a multi-megabyte arena per image fragmented the first-fit heap:
  2014. * each small display bitmap landed in the hole the previous arena left, so
  2015. * the next arena no longer fit and the heap ratcheted up until an app
  2016. * store's 200 icons ran out of memory. Arenas above DECODE_ARENA_KEEP are
  2017. * still released right after their one image. */
  2018. #define DECODE_ARENA_KEEP (8u * 1024u * 1024u)
  2019. static unsigned char *decode_arena_get(unsigned int bytes)
  2020. {
  2021. if (decode_arena && decode_arena_size >= bytes)
  2022. return decode_arena;
  2023. free(decode_arena);
  2024. decode_arena = (unsigned char *)malloc(bytes);
  2025. decode_arena_size = decode_arena ? bytes : 0;
  2026. return decode_arena;
  2027. }
  2028. static void decode_arena_put(void)
  2029. {
  2030. if (decode_arena_size > DECODE_ARENA_KEEP) {
  2031. free(decode_arena);
  2032. decode_arena = 0;
  2033. decode_arena_size = 0;
  2034. }
  2035. }
  2036. /* box_w/box_h: the laid-out box a background image paints, or 0. The
  2037. * bitmap then only needs to cover that box (an app-store icon is 48 px), not
  2038. * BR_IMG_LAYOUT_W, which keeps hundreds of small images inside the budget. */
  2039. static int svg_text_sniff(const unsigned char *d, unsigned int len);
  2040. static int svg_decode_image(const unsigned char *data, unsigned int len,
  2041. struct br_image *bi, int box_w, int box_h);
  2042. static int decode_image_data(const unsigned char *data, unsigned int len,
  2043. struct br_image *bi, int box_w, int box_h,
  2044. int fit_w, int fit_h)
  2045. {
  2046. struct img_info info;
  2047. struct img_options opt;
  2048. struct img_mem mem;
  2049. struct img_image decoded;
  2050. unsigned char *arena;
  2051. unsigned int est, bytes, i;
  2052. unsigned int t0;
  2053. unsigned short *px;
  2054. unsigned char *alpha = 0;
  2055. int dw, dh, r;
  2056. bi->url_hash = 0;
  2057. img_last_dec_ms = 0;
  2058. img_last_scale_ms = 0;
  2059. if (img_sniff(data, len, &info) != 0) {
  2060. if (svg_text_sniff(data, len))
  2061. return svg_decode_image(data, len, bi,
  2062. box_w > 0 && box_h > 0 ? box_w : fit_w,
  2063. box_w > 0 && box_h > 0 ? box_h : fit_h);
  2064. s_copy(bi->err, "unknown image format", sizeof(bi->err));
  2065. return -1;
  2066. }
  2067. est = img_estimate(&info);
  2068. if (est == 0xFFFFFFFFu || est > BR_IMG_ARENA_MAX) {
  2069. s_copy(bi->err, "image too large", sizeof(bi->err));
  2070. return -1;
  2071. }
  2072. arena = decode_arena_get(est);
  2073. if (!arena) {
  2074. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2075. return -1;
  2076. }
  2077. img_mem_init(&mem, arena, est);
  2078. opt.max_pixels = BR_IMG_PIX_MAX;
  2079. opt.max_w = fit_w > 0 ? (unsigned int)fit_w :
  2080. (box_w > 0 ? (unsigned int)box_w : 0);
  2081. opt.max_h = fit_h > 0 ? (unsigned int)fit_h :
  2082. (box_h > 0 ? (unsigned int)box_h : 0);
  2083. t0 = u_ticks_ms();
  2084. r = img_decode(data, len, &opt, &mem, &decoded);
  2085. img_last_dec_ms = u_ticks_ms() - t0;
  2086. if (r != 0) {
  2087. s_copy(bi->err, img_error_string(r), sizeof(bi->err));
  2088. goto fail;
  2089. }
  2090. if (decoded.w == 0 || decoded.h == 0) {
  2091. s_copy(bi->err, "empty image", sizeof(bi->err));
  2092. goto fail;
  2093. }
  2094. /* The JPEG decoder may have reduced the IDCT output; the layout still
  2095. * needs the intrinsic dimensions from the header. */
  2096. bi->native_w = info.width ? (int)info.width : (int)decoded.w;
  2097. bi->native_h = info.height ? (int)info.height : (int)decoded.h;
  2098. dw = (int)decoded.w;
  2099. dh = (int)decoded.h;
  2100. /* An <img> with a CSS/attribute box only ever needs a bitmap that big:
  2101. * decoding 1200x800 and then box-filtering it to 1000x666, only to
  2102. * paint it at 400x267, doubled the decode-time scaling work. cap both
  2103. * axes with one scale so the aspect ratio is preserved. */
  2104. if (fit_w > 0 || fit_h > 0) {
  2105. unsigned int scw = fit_w > 0 ?
  2106. ((unsigned int)fit_w << 16) / decoded.w : ~0u;
  2107. unsigned int sch = fit_h > 0 ?
  2108. ((unsigned int)fit_h << 16) / decoded.h : ~0u;
  2109. unsigned int sc = scw < sch ? scw : sch;
  2110. if (sc < 0x10000u) {
  2111. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2112. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2113. if (dw < 1)
  2114. dw = 1;
  2115. if (dh < 1)
  2116. dh = 1;
  2117. }
  2118. }
  2119. if (box_w > 0 && box_h > 0) {
  2120. /* cover: scale so both box sides are filled, never up */
  2121. unsigned int sw = ((unsigned int)box_w << 16) / decoded.w;
  2122. unsigned int sh = ((unsigned int)box_h << 16) / decoded.h;
  2123. unsigned int sc = sw > sh ? sw : sh;
  2124. if (sc < 0x10000u) {
  2125. dw = (int)((decoded.w * sc + 0xFFFFu) >> 16);
  2126. dh = (int)((decoded.h * sc + 0xFFFFu) >> 16);
  2127. }
  2128. }
  2129. if (dw > BR_IMG_LAYOUT_W) {
  2130. dh = (int)((unsigned int)dh * BR_IMG_LAYOUT_W / (unsigned int)dw);
  2131. dw = BR_IMG_LAYOUT_W;
  2132. }
  2133. if (dh < 1)
  2134. dh = 1;
  2135. if (dw < 1)
  2136. dw = 1;
  2137. if (image_pixels + (unsigned int)dw * (unsigned int)dh >
  2138. BR_IMG_PIXEL_BUDGET) {
  2139. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  2140. goto fail;
  2141. }
  2142. bytes = (unsigned int)dw * (unsigned int)dh * 2u;
  2143. px = (unsigned short *)malloc(bytes);
  2144. if (!px) {
  2145. s_copy(bi->err, "out of memory", sizeof(bi->err));
  2146. goto fail;
  2147. }
  2148. /* Keep the alpha plane for the scaled image so transparent logos and
  2149. * icons composite over the page instead of the browser's dark theme
  2150. * background. Very large alpha images stay flattened to bound the
  2151. * heap use. */
  2152. if (decoded.alpha && (unsigned int)dw * (unsigned int)dh <= (1u << 20)) {
  2153. alpha = (unsigned char *)malloc((unsigned int)dw *
  2154. (unsigned int)dh);
  2155. if (alpha) {
  2156. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2157. alpha[i] = 255;
  2158. }
  2159. }
  2160. /* With an alpha plane the colour under transparent pixels only shows
  2161. * through partially covered edge pixels of the downscale: use white,
  2162. * as documented above, not the dark browser theme (which left a dark
  2163. * fringe around scaled app icons). */
  2164. for (i = 0; i < (unsigned int)dw * (unsigned int)dh; i++)
  2165. px[i] = alpha ? 0xFFFF : ui.theme.bg;
  2166. {
  2167. struct img_blit b;
  2168. b.dst = px;
  2169. b.dst_w = dw;
  2170. b.dst_h = dh;
  2171. b.clip_x = 0;
  2172. b.clip_y = 0;
  2173. b.clip_w = dw;
  2174. b.clip_h = dh;
  2175. b.x = 0;
  2176. b.y = 0;
  2177. b.scale = ((unsigned int)dw << 16) / decoded.w;
  2178. b.bg = alpha ? 0xFFFF : ui.theme.bg;
  2179. b.bg2 = b.bg;
  2180. b.dst_a = alpha;
  2181. b.flags = alpha ? IMG_BLIT_SAVE_ALPHA : IMG_BLIT_OVER_DST;
  2182. t0 = u_ticks_ms();
  2183. img_draw(&decoded, &b);
  2184. img_last_scale_ms = u_ticks_ms() - t0;
  2185. }
  2186. bi->img.format = decoded.format;
  2187. bi->img.w = (unsigned int)dw;
  2188. bi->img.h = (unsigned int)dh;
  2189. bi->img.px = px;
  2190. bi->img.alpha = alpha;
  2191. bi->img.flags = 0;
  2192. bi->state = 1;
  2193. image_pixels += (unsigned int)dw * (unsigned int)dh;
  2194. decode_arena_put();
  2195. return 0;
  2196. fail:
  2197. decode_arena_put();
  2198. return -1;
  2199. }
  2200. /* ---- URL / local path handling ---- */
  2201. static int is_http(const char *s)
  2202. {
  2203. return starts_with(s, "http://") || starts_with(s, "https://");
  2204. }
  2205. /* Collapse "/./", "/../" and duplicate slashes in an absolute path. */
  2206. static int normalize_abs(const char *in, char *out, unsigned int cap)
  2207. {
  2208. char seg[64];
  2209. unsigned int i = 0, o = 1;
  2210. int depth = 0;
  2211. int trailing;
  2212. if (!in || in[0] != '/' || cap < 2)
  2213. return -1;
  2214. trailing = 0;
  2215. {
  2216. unsigned int n = s_len(in);
  2217. if (n > 1 && in[n - 1] == '/')
  2218. trailing = 1;
  2219. }
  2220. out[0] = '/';
  2221. while (in[i]) {
  2222. unsigned int n = 0;
  2223. while (in[i] == '/')
  2224. i++;
  2225. while (in[i] && in[i] != '/' && in[i] != '?' && in[i] != '#') {
  2226. if (n + 1 < sizeof(seg))
  2227. seg[n++] = in[i];
  2228. i++;
  2229. }
  2230. seg[n] = '\0';
  2231. if (n == 0)
  2232. break;
  2233. if (s_eq(seg, "."))
  2234. continue;
  2235. if (s_eq(seg, "..")) {
  2236. if (depth > 0) {
  2237. while (o > 1 && out[o - 1] != '/')
  2238. o--;
  2239. if (o > 1)
  2240. o--;
  2241. depth--;
  2242. }
  2243. continue;
  2244. }
  2245. if (o > 1) {
  2246. if (o + 1 >= cap)
  2247. return -1;
  2248. out[o++] = '/';
  2249. }
  2250. if (o + n + 1 >= cap)
  2251. return -1;
  2252. {
  2253. unsigned int j;
  2254. for (j = 0; j < n; j++)
  2255. out[o++] = seg[j];
  2256. }
  2257. depth++;
  2258. }
  2259. if (trailing && o > 1 && in[i] != '?' && in[i] != '#') {
  2260. if (o + 1 >= cap)
  2261. return -1;
  2262. out[o++] = '/';
  2263. }
  2264. /* Keep the query/fragment suffix for form GET and in-page anchors. */
  2265. if (in[i] == '?' || in[i] == '#') {
  2266. while (in[i]) {
  2267. if (o + 1 >= cap)
  2268. return -1;
  2269. out[o++] = in[i++];
  2270. }
  2271. }
  2272. out[o] = '\0';
  2273. return 0;
  2274. }
  2275. static void make_abs_local(const char *in, char *out, unsigned int cap)
  2276. {
  2277. char joined[BR_URL_MAX];
  2278. if (!in || !in[0]) {
  2279. s_copy(out, cwd[0] ? cwd : "/", cap);
  2280. return;
  2281. }
  2282. if (in[0] == '/') {
  2283. if (normalize_abs(in, out, cap) != 0)
  2284. s_copy(out, in, cap);
  2285. return;
  2286. }
  2287. {
  2288. unsigned int n = 0;
  2289. s_append(joined, &n, cwd[0] ? cwd : "/", sizeof(joined));
  2290. s_append(joined, &n, "/", sizeof(joined));
  2291. s_append(joined, &n, in, sizeof(joined));
  2292. }
  2293. if (normalize_abs(joined, out, cap) != 0)
  2294. s_copy(out, joined, cap);
  2295. }
  2296. /* ---- canonical origin cache ---- *
  2297. *
  2298. * Sites commonly redirect http://host to https://host and then to
  2299. * https://www.host. Remember the final scheme/host of the last navigation so
  2300. * a bare domain typed again goes straight there instead of paying for two
  2301. * more connections and TLS handshakes. Only default-port requests are
  2302. * rewritten; explicit ports are left alone. */
  2303. #define ORIGIN_CACHE_MAX 8
  2304. #define ORIGIN_FILE "/share/borigins"
  2305. #define ORIGIN_BUF_SIZE (ORIGIN_CACHE_MAX * (UHTTP_HOST_MAX + 16 + \
  2306. UHTTP_HOST_MAX + 2))
  2307. struct origin_cache_entry {
  2308. char host[UHTTP_HOST_MAX];
  2309. char origin[UHTTP_HOST_MAX + 16];
  2310. };
  2311. static struct origin_cache_entry origins[ORIGIN_CACHE_MAX];
  2312. static int origin_count;
  2313. static char origin_buf[ORIGIN_BUF_SIZE];
  2314. static int default_port(const struct uhttp_url *u)
  2315. {
  2316. return u->secure ? u->port == 443 : u->port == 80;
  2317. }
  2318. static void url_origin(const struct uhttp_url *u, char *out,
  2319. unsigned int cap)
  2320. {
  2321. unsigned int n = 0;
  2322. s_append(out, &n, u->secure ? "https://" : "http://", cap);
  2323. s_append(out, &n, u->host, cap);
  2324. if (!default_port(u)) {
  2325. s_append(out, &n, ":", cap);
  2326. s_append_dec(out, &n, u->port, cap);
  2327. }
  2328. }
  2329. static void origin_cache_apply(char *url, unsigned int cap)
  2330. {
  2331. struct uhttp_url u;
  2332. char out[BR_URL_MAX];
  2333. unsigned int n = 0;
  2334. int i;
  2335. if (uhttp_parse_url(url, &u) != 0 || !default_port(&u))
  2336. return;
  2337. for (i = 0; i < origin_count; i++) {
  2338. if (!s_eq(u.host, origins[i].host))
  2339. continue;
  2340. s_append(out, &n, origins[i].origin, sizeof(out));
  2341. s_append(out, &n, u.path, sizeof(out));
  2342. s_copy(url, out, cap);
  2343. return;
  2344. }
  2345. }
  2346. static void origin_cache_save(void)
  2347. {
  2348. unsigned int n = 0;
  2349. int i;
  2350. for (i = 0; i < origin_count; i++) {
  2351. s_append(origin_buf, &n, origins[i].host, sizeof(origin_buf));
  2352. s_append(origin_buf, &n, " ", sizeof(origin_buf));
  2353. s_append(origin_buf, &n, origins[i].origin, sizeof(origin_buf));
  2354. s_append(origin_buf, &n, "\n", sizeof(origin_buf));
  2355. }
  2356. if (n)
  2357. u_syscall3(SYS_WRITE_FILE, (int)ORIGIN_FILE,
  2358. (int)origin_buf, (int)n);
  2359. }
  2360. static void origin_cache_load(void)
  2361. {
  2362. char *p;
  2363. int rn;
  2364. rn = u_syscall3(SYS_READ_FILE, (int)ORIGIN_FILE, (int)origin_buf,
  2365. (int)(sizeof(origin_buf) - 1));
  2366. if (rn <= 0)
  2367. return;
  2368. origin_buf[rn] = '\0';
  2369. p = origin_buf;
  2370. while (*p && origin_count < ORIGIN_CACHE_MAX) {
  2371. char *line = p, *origin;
  2372. while (*p && *p != '\n')
  2373. p++;
  2374. if (*p)
  2375. *p++ = '\0';
  2376. if (!line[0])
  2377. continue;
  2378. origin = line;
  2379. while (*origin && *origin != ' ')
  2380. origin++;
  2381. if (!*origin)
  2382. continue;
  2383. *origin++ = '\0';
  2384. if (!line[0] || !is_http(origin))
  2385. continue;
  2386. {
  2387. struct uhttp_url uo;
  2388. if (uhttp_parse_url(origin, &uo) != 0 ||
  2389. !s_eq(uo.path, "/"))
  2390. continue;
  2391. }
  2392. s_copy(origins[origin_count].host, line,
  2393. sizeof(origins[origin_count].host));
  2394. s_copy(origins[origin_count].origin, origin,
  2395. sizeof(origins[origin_count].origin));
  2396. origin_count++;
  2397. }
  2398. }
  2399. static int host_is_www_of(const char *host, const char *base)
  2400. {
  2401. return host[0] == 'w' && host[1] == 'w' && host[2] == 'w' &&
  2402. host[3] == '.' && s_eq(host + 4, base);
  2403. }
  2404. static void origin_cache_learn(const char *requested, const char *final)
  2405. {
  2406. struct uhttp_url from, to;
  2407. char origin[UHTTP_HOST_MAX + 16];
  2408. int i;
  2409. if (!is_http(requested) || !is_http(final))
  2410. return;
  2411. if (uhttp_parse_url(requested, &from) != 0 ||
  2412. uhttp_parse_url(final, &to) != 0)
  2413. return;
  2414. if (!default_port(&from))
  2415. return;
  2416. if (s_eq(from.host, to.host) && from.secure == to.secure &&
  2417. from.port == to.port)
  2418. return;
  2419. /* Only remember origin-level canonicalisation: the same path, and
  2420. * either the same host or its www./apex sibling. A path- or
  2421. * host-specific redirect (a shortener, a login page) must not poison
  2422. * every request to the typed host. */
  2423. if (!s_eq(from.path, to.path))
  2424. return;
  2425. if (!s_eq(from.host, to.host) &&
  2426. !host_is_www_of(to.host, from.host) &&
  2427. !host_is_www_of(from.host, to.host))
  2428. return;
  2429. url_origin(&to, origin, sizeof(origin));
  2430. for (i = 0; i < origin_count; i++) {
  2431. if (s_eq(origins[i].host, from.host)) {
  2432. if (!s_eq(origins[i].origin, origin)) {
  2433. s_copy(origins[i].origin, origin,
  2434. sizeof(origins[i].origin));
  2435. origin_cache_save();
  2436. }
  2437. return;
  2438. }
  2439. }
  2440. i = origin_count < ORIGIN_CACHE_MAX ? origin_count++ : 0;
  2441. s_copy(origins[i].host, from.host, sizeof(origins[i].host));
  2442. s_copy(origins[i].origin, origin, sizeof(origins[i].origin));
  2443. origin_cache_save();
  2444. }
  2445. static int path_dir(const char *path, char *out, unsigned int cap)
  2446. {
  2447. unsigned int i, last = 0;
  2448. for (i = 0; path[i]; i++)
  2449. if (path[i] == '/')
  2450. last = i;
  2451. if (last == 0) {
  2452. if (cap < 2)
  2453. return -1;
  2454. out[0] = '/';
  2455. out[1] = '\0';
  2456. return 0;
  2457. }
  2458. if (last + 1 >= cap)
  2459. return -1;
  2460. {
  2461. unsigned int j;
  2462. for (j = 0; j < last; j++)
  2463. out[j] = path[j];
  2464. out[last] = '\0';
  2465. }
  2466. return 0;
  2467. }
  2468. /* Resolve an href against the current page. 0 = ok, -1 = ignore. */
  2469. static int resolve_link(const char *base, const char *href, char *out,
  2470. unsigned int cap)
  2471. {
  2472. char joined[BR_URL_MAX];
  2473. if (!href || !href[0] || href[0] == '#')
  2474. return -1;
  2475. if (starts_with(href, "mailto:") || starts_with(href, "javascript:") ||
  2476. starts_with(href, "data:") || starts_with(href, "tel:"))
  2477. return -1;
  2478. if (starts_with(href, "about:")) {
  2479. s_copy(out, href, cap);
  2480. return 0;
  2481. }
  2482. if (is_http(href)) {
  2483. s_copy(out, href, cap);
  2484. return 0;
  2485. }
  2486. if (starts_with(href, "//")) {
  2487. if (is_http(base)) {
  2488. unsigned int n = 0;
  2489. s_append(out, &n, starts_with(base, "https:") ?
  2490. "https:" : "http:", cap);
  2491. s_append(out, &n, href, cap);
  2492. return 0;
  2493. }
  2494. return -1;
  2495. }
  2496. if (is_http(base)) {
  2497. return uhttp_resolve(base, href, out, cap) == 0 ? 0 : -1;
  2498. }
  2499. /* local page */
  2500. if (href[0] == '/') {
  2501. if (normalize_abs(href, out, cap) != 0)
  2502. return -1;
  2503. return 0;
  2504. }
  2505. {
  2506. char dir[BR_URL_MAX];
  2507. unsigned int n = 0;
  2508. if (s_eq(base, "about:home"))
  2509. s_copy(dir, cwd[0] ? cwd : "/", sizeof(dir));
  2510. else if (path_dir(base, dir, sizeof(dir)) != 0)
  2511. s_copy(dir, "/", sizeof(dir));
  2512. s_append(joined, &n, dir, sizeof(joined));
  2513. if (n == 0 || joined[n - 1] != '/')
  2514. s_append(joined, &n, "/", sizeof(joined));
  2515. s_append(joined, &n, href, sizeof(joined));
  2516. }
  2517. return normalize_abs(joined, out, cap) == 0 ? 0 : -1;
  2518. }
  2519. /* Best-effort decompression: keep the first `cap` bytes and discard the
  2520. * rest instead of failing when a page or stylesheet is larger than the
  2521. * buffer. The stream is still walked to the end, so a normal page is
  2522. * verified; a truncated compressed input still returns whatever was decoded
  2523. * so far. */
  2524. struct trunc_buf {
  2525. unsigned char *dst;
  2526. unsigned int cap, pos;
  2527. int full;
  2528. };
  2529. static int trunc_write(void *ctx, const unsigned char *data, unsigned int len)
  2530. {
  2531. struct trunc_buf *m = (struct trunc_buf *)ctx;
  2532. if (len > m->cap - m->pos) {
  2533. unsigned int room = m->cap - m->pos;
  2534. if (room) {
  2535. unsigned int i;
  2536. for (i = 0; i < room; i++)
  2537. m->dst[m->pos + i] = data[i];
  2538. m->pos += room;
  2539. }
  2540. m->full = 1;
  2541. return 0;
  2542. }
  2543. {
  2544. unsigned int i;
  2545. for (i = 0; i < len; i++)
  2546. m->dst[m->pos + i] = data[i];
  2547. }
  2548. m->pos += len;
  2549. return 0;
  2550. }
  2551. static void worker_wait_ui(void);
  2552. static void inflate_ui_pump(void *ctx)
  2553. {
  2554. static unsigned int last;
  2555. unsigned int now = u_ticks_ms();
  2556. (void)ctx;
  2557. if ((int)(now - last) >= 50) {
  2558. last = now;
  2559. worker_wait_ui();
  2560. }
  2561. }
  2562. static int inflate_trunc(const unsigned char *src, unsigned int len,
  2563. unsigned char *dst, unsigned int cap,
  2564. unsigned int *outlen, int gzip, int *truncated)
  2565. {
  2566. struct inflate_src in;
  2567. struct inflate_sink sink;
  2568. struct trunc_buf m;
  2569. unsigned int got = 0;
  2570. int r;
  2571. in.p = src;
  2572. in.len = len;
  2573. in.more = 0;
  2574. in.ctx = 0;
  2575. m.dst = dst;
  2576. m.cap = cap;
  2577. m.pos = 0;
  2578. m.full = 0;
  2579. sink.write = trunc_write;
  2580. sink.ctx = &m;
  2581. inflate_init(&image_inflate_ws, &in, &sink);
  2582. image_inflate_ws.progress = inflate_ui_pump;
  2583. image_inflate_ws.progress_ctx = 0;
  2584. r = gzip ? inflate_gzip(&image_inflate_ws, &got) :
  2585. inflate_zlib(&image_inflate_ws, &got);
  2586. *outlen = m.pos;
  2587. *truncated = m.full || r != 0;
  2588. if (r != 0 && m.pos == 0)
  2589. return -1;
  2590. return 0;
  2591. }
  2592. /* ---- headless fetch workers ------------------------------------------ *
  2593. *
  2594. * Network I/O runs in separate ring-3 processes (`curl __serve <slot>`): each
  2595. * writes the raw response, a small metadata file and a done marker under
  2596. * /share. Up to FETCH_WORKERS jobs run at once, so a slow DNS/TLS handshake
  2597. * or a multi-megabyte body never freezes the UI and images download in
  2598. * parallel.
  2599. */
  2600. struct fetch_meta {
  2601. int status;
  2602. int error;
  2603. int trunc;
  2604. unsigned int len;
  2605. unsigned int open_ms;
  2606. unsigned int first_ms;
  2607. unsigned int total_ms;
  2608. /* Optional decoded bitmap produced by the helper (image jobs). */
  2609. unsigned int dw, dh, nw, nh;
  2610. unsigned int alpha;
  2611. unsigned int px_len;
  2612. unsigned int dec_ms;
  2613. int dec_err;
  2614. char encoding[16];
  2615. char ctype[64];
  2616. char final[BR_URL_MAX];
  2617. };
  2618. static void draw(unsigned int *action);
  2619. static void handle_keys(unsigned int *action);
  2620. static void handle_page_click(unsigned int *action);
  2621. #define FETCH_WORKERS 4
  2622. #define FETCH_PATH_MAX 32
  2623. /* One long-lived curl __serve helper per worker. Each worker has its own
  2624. * request/body/meta/done files under /share so several downloads can be in
  2625. * flight at once; the keep-alive connection stays in the helper process, so
  2626. * tls.c's per-process state remains valid. */
  2627. struct fetch_worker {
  2628. int pid;
  2629. int slot;
  2630. int busy;
  2631. int ready;
  2632. int image_job;
  2633. unsigned int seq;
  2634. unsigned int deadline;
  2635. int retried;
  2636. unsigned int dec_w, dec_h;
  2637. int dec_retried;
  2638. char req[FETCH_PATH_MAX];
  2639. char body[FETCH_PATH_MAX];
  2640. char meta[FETCH_PATH_MAX];
  2641. char done[FETCH_PATH_MAX];
  2642. char post[FETCH_PATH_MAX];
  2643. char px[FETCH_PATH_MAX];
  2644. /* Optional preload job attached to this worker. */
  2645. unsigned int node;
  2646. int bg;
  2647. char url[BR_URL_MAX];
  2648. struct fetch_meta m;
  2649. };
  2650. static struct fetch_worker fetch_workers[FETCH_WORKERS];
  2651. static int fetch_tty = -2;
  2652. static void fetch_tty_drain(void);
  2653. static unsigned int fetch_session;
  2654. static unsigned int fetch_seq;
  2655. static struct fetch_meta fetch_meta;
  2656. /* UHTTP_ERR_* of the last failed fetch_remote(), 0 when the failure was not
  2657. * an HTTP-level error (helper died, timeout in the browser, ...). */
  2658. static int fetch_last_error;
  2659. static unsigned int meta_uint(char **pp)
  2660. {
  2661. char *p = *pp;
  2662. unsigned int v = 0;
  2663. while (*p >= '0' && *p <= '9') {
  2664. v = v * 10 + (unsigned int)(*p - '0');
  2665. p++;
  2666. }
  2667. while (*p && *p != '\n')
  2668. p++;
  2669. if (*p == '\n')
  2670. p++;
  2671. *pp = p;
  2672. return v;
  2673. }
  2674. static void meta_str(char **pp, char *out, unsigned int cap)
  2675. {
  2676. char *p = *pp;
  2677. unsigned int n = 0;
  2678. while (*p && *p != '\n' && n + 1 < cap)
  2679. out[n++] = *p++;
  2680. out[n] = '\0';
  2681. while (*p && *p != '\n')
  2682. p++;
  2683. if (*p == '\n')
  2684. p++;
  2685. *pp = p;
  2686. }
  2687. static void worker_wait_ui(void)
  2688. {
  2689. unsigned int action = 0;
  2690. if (!ngui_begin(&ui))
  2691. return;
  2692. draw(&action);
  2693. handle_keys(&action);
  2694. handle_page_click(&action);
  2695. if (action & ACT_WAIT_NAV) {
  2696. pending_action |= action & ACT_WAIT_NAV;
  2697. if ((action & ACT_NAV) && click_url[0])
  2698. s_copy(pending_url, click_url, sizeof(pending_url));
  2699. click_url[0] = '\0';
  2700. cancel_fetch = 1;
  2701. }
  2702. if (!ngui_focus(&ui) && ngui_scroll_keys(&ui, &page_scroll))
  2703. ngui_invalidate(&ui);
  2704. ngui_end(&ui);
  2705. }
  2706. static void fetch_path(char *out, unsigned int cap, const char *kind,
  2707. unsigned int session, int slot)
  2708. {
  2709. unsigned int n = 0;
  2710. s_append(out, &n, "/share/bf", cap);
  2711. s_append_dec(out, &n, session, cap);
  2712. s_append(out, &n, "_", cap);
  2713. s_append_dec(out, &n, (unsigned int)slot, cap);
  2714. s_append(out, &n, kind, cap);
  2715. }
  2716. static void fetch_pool_init(void)
  2717. {
  2718. static int ready;
  2719. int i;
  2720. if (ready)
  2721. return;
  2722. ready = 1;
  2723. fetch_session = ((unsigned int)u_getpid() << 16) ^
  2724. (u_ticks_ms() & 0xFFFFu);
  2725. if (!fetch_session)
  2726. fetch_session = 1;
  2727. for (i = 0; i < FETCH_WORKERS; i++) {
  2728. struct fetch_worker *w = &fetch_workers[i];
  2729. w->pid = -1;
  2730. w->slot = i;
  2731. fetch_path(w->req, sizeof(w->req), "req", fetch_session, i);
  2732. fetch_path(w->body, sizeof(w->body), "body", fetch_session, i);
  2733. fetch_path(w->meta, sizeof(w->meta), "meta", fetch_session, i);
  2734. fetch_path(w->done, sizeof(w->done), "done", fetch_session, i);
  2735. fetch_path(w->post, sizeof(w->post), "post", fetch_session, i);
  2736. fetch_path(w->px, sizeof(w->px), "px", fetch_session, i);
  2737. }
  2738. }
  2739. static void fetch_worker_stop(struct fetch_worker *w)
  2740. {
  2741. int i;
  2742. /* An abandoned image job leaves its node loadable again. */
  2743. if (w->busy && w->image_job && w->node < doc.nnode) {
  2744. if (w->bg && doc.nodes[w->node].bg_img_index == -3)
  2745. doc.nodes[w->node].bg_img_index = -1;
  2746. else if (!w->bg && doc.nodes[w->node].img_index == -3)
  2747. doc.nodes[w->node].img_index = -1;
  2748. }
  2749. if (w->pid > 0) {
  2750. u_kill((unsigned int)w->pid);
  2751. for (i = 0; i < 40 && u_alive((unsigned int)w->pid); i++)
  2752. u_sleep_ms(5);
  2753. /* Let the reaper close the socket before we reuse the slot. */
  2754. u_sleep_ms(10);
  2755. }
  2756. w->pid = -1;
  2757. w->busy = 0;
  2758. w->ready = 0;
  2759. w->image_job = 0;
  2760. if (w->req[0]) {
  2761. u_syscall1(SYS_UNLINK, (int)w->done);
  2762. u_syscall1(SYS_UNLINK, (int)w->meta);
  2763. u_syscall1(SYS_UNLINK, (int)w->body);
  2764. u_syscall1(SYS_UNLINK, (int)w->post);
  2765. u_syscall1(SYS_UNLINK, (int)w->req);
  2766. }
  2767. }
  2768. static void fetch_workers_stop_all(void)
  2769. {
  2770. int i;
  2771. for (i = 0; i < FETCH_WORKERS; i++)
  2772. fetch_worker_stop(&fetch_workers[i]);
  2773. }
  2774. /* Abandon the transfers of the current page but keep idle helpers and their
  2775. * TCP/TLS connections warm for the next navigation. A busy helper is killed
  2776. * because its response would otherwise land in a reused /share slot. */
  2777. static void fetch_workers_cancel_busy(void)
  2778. {
  2779. int i;
  2780. for (i = 0; i < FETCH_WORKERS; i++)
  2781. if (fetch_workers[i].busy)
  2782. fetch_worker_stop(&fetch_workers[i]);
  2783. }
  2784. static void fetch_workers_prepare_nav(const char *url)
  2785. {
  2786. int i;
  2787. (void)url;
  2788. for (i = 0; i < FETCH_WORKERS; i++) {
  2789. struct fetch_worker *w = &fetch_workers[i];
  2790. if (w->pid <= 0)
  2791. continue;
  2792. /* Only an in-flight transfer must be aborted. Idle helpers
  2793. * stay warm across origins: there are just FETCH_WORKERS of
  2794. * them, and uhttp_open drops the old connection when the
  2795. * next job is for another host. Killing and respawning all
  2796. * four on every navigation churned processes and sockets
  2797. * while images were still loading. */
  2798. if (w->busy)
  2799. fetch_worker_stop(w);
  2800. }
  2801. }
  2802. /* The browser is no longer the active window and no fetch is running: give
  2803. * the NIC back so raw commands (ping/netrecv/websrv) can acquire it. */
  2804. static void fetch_workers_stop_if_unfocused(void)
  2805. {
  2806. int i;
  2807. fetch_tty_drain();
  2808. if (ui.focused || page_loading || preload_active)
  2809. return;
  2810. for (i = 0; i < FETCH_WORKERS; i++)
  2811. if (fetch_workers[i].pid > 0) {
  2812. fetch_workers_stop_all();
  2813. return;
  2814. }
  2815. }
  2816. /* The helpers (and this process, since u_tty_create() rebinds our own
  2817. * output) write their DNS/TLS/[js] log lines to fetch_tty. Nobody renders
  2818. * it, and a full 4 KB tty ring blocks its writers: after a page that opened
  2819. * a dozen TLS connections every helper hung in its next log line, so the
  2820. * following cross-origin navigation sat at "Loading..." until it timed out.
  2821. * Drain and discard it from every wait/poll loop. */
  2822. static void fetch_tty_drain(void)
  2823. {
  2824. char sink[512];
  2825. int i;
  2826. if (fetch_tty <= 0)
  2827. return;
  2828. for (i = 0; i < 16; i++)
  2829. if (u_tty_read(fetch_tty, sink, sizeof(sink)) <= 0)
  2830. break;
  2831. }
  2832. static int fetch_worker_start(struct fetch_worker *w, char *err,
  2833. unsigned int errcap)
  2834. {
  2835. char arg[40];
  2836. unsigned int n = 0;
  2837. if (w->pid > 0 && u_alive((unsigned int)w->pid))
  2838. return 0;
  2839. w->pid = -1;
  2840. fetch_pool_init();
  2841. if (fetch_tty == -2) {
  2842. int t = u_tty_create();
  2843. fetch_tty = t > 0 ? t : 0;
  2844. }
  2845. s_append(arg, &n, "__serve ", sizeof(arg));
  2846. s_append_dec(arg, &n, fetch_session, sizeof(arg));
  2847. s_append(arg, &n, " ", sizeof(arg));
  2848. s_append_dec(arg, &n, (unsigned int)w->slot, sizeof(arg));
  2849. w->pid = u_spawn("/ramfs/bin/curl", arg, fetch_tty, "/");
  2850. if (w->pid <= 0) {
  2851. w->pid = -1;
  2852. s_copy(err, "cannot start network helper", errcap);
  2853. return -1;
  2854. }
  2855. return 0;
  2856. }
  2857. static struct fetch_worker *fetch_worker_alloc(void)
  2858. {
  2859. int i;
  2860. fetch_pool_init();
  2861. for (i = 0; i < FETCH_WORKERS; i++)
  2862. if (!fetch_workers[i].busy)
  2863. return &fetch_workers[i];
  2864. return 0;
  2865. }
  2866. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2867. unsigned int cap, const char *method,
  2868. const char *ctype, const char *post,
  2869. unsigned int post_len, unsigned int node,
  2870. int bg, unsigned int dec_w,
  2871. unsigned int dec_h, char *err,
  2872. unsigned int errcap);
  2873. static int fetch_worker_submit(struct fetch_worker *w, const char *url,
  2874. unsigned int cap, const char *post,
  2875. unsigned int post_len, unsigned int node,
  2876. int bg, char *err, unsigned int errcap)
  2877. {
  2878. /* A body pointer with no bytes is still a POST: the classic request
  2879. * line would turn it into a GET. */
  2880. if (post && !post_len)
  2881. return fetch_worker_submit_req(w, url, cap, "POST",
  2882. "application/x-www-form-urlencoded", post, 0, node,
  2883. bg, 0, 0, err, errcap);
  2884. return fetch_worker_submit_req(w, url, cap, 0, 0, post, post_len,
  2885. node, bg, 0, 0, err, errcap);
  2886. }
  2887. /* Image job: ask the helper to decode at these display bounds as well. */
  2888. static int fetch_worker_submit_image(struct fetch_worker *w, const char *url,
  2889. unsigned int cap, unsigned int node,
  2890. int bg, unsigned int dec_w,
  2891. unsigned int dec_h, char *err,
  2892. unsigned int errcap)
  2893. {
  2894. return fetch_worker_submit_req(w, url, cap, 0, 0, 0, 0, node, bg,
  2895. dec_w, dec_h, err, errcap);
  2896. }
  2897. /* `method` NULL keeps the classic GET / form-POST request line; otherwise
  2898. * the helper gets "X <method> <len> <content type> <url>" (fetch()/XHR). */
  2899. static int fetch_worker_submit_req(struct fetch_worker *w, const char *url,
  2900. unsigned int cap, const char *method,
  2901. const char *ctype, const char *post,
  2902. unsigned int post_len, unsigned int node,
  2903. int bg, unsigned int dec_w,
  2904. unsigned int dec_h, char *err,
  2905. unsigned int errcap)
  2906. {
  2907. static char req[1024];
  2908. unsigned int n = 0;
  2909. fetch_seq++;
  2910. if (!fetch_seq)
  2911. fetch_seq = 1;
  2912. w->seq = fetch_seq;
  2913. w->ready = 0;
  2914. w->image_job = 0;
  2915. w->retried = 0;
  2916. w->m.error = 0;
  2917. w->node = node;
  2918. w->bg = bg;
  2919. w->dec_w = dec_w;
  2920. w->dec_h = dec_h;
  2921. w->dec_retried = 0;
  2922. s_copy(w->url, url, sizeof(w->url));
  2923. s_append_dec(req, &n, w->seq, sizeof(req));
  2924. s_append(req, &n, " ", sizeof(req));
  2925. s_append_dec(req, &n, cap, sizeof(req));
  2926. s_append(req, &n, " ", sizeof(req));
  2927. if (dec_w || dec_h) {
  2928. s_append(req, &n, "D ", sizeof(req));
  2929. s_append_dec(req, &n, dec_w, sizeof(req));
  2930. s_append(req, &n, " ", sizeof(req));
  2931. s_append_dec(req, &n, dec_h, sizeof(req));
  2932. s_append(req, &n, " ", sizeof(req));
  2933. } else if (method) {
  2934. unsigned int k;
  2935. s_append(req, &n, "X ", sizeof(req));
  2936. s_append(req, &n, method, sizeof(req));
  2937. s_append(req, &n, " ", sizeof(req));
  2938. s_append_dec(req, &n, post_len, sizeof(req));
  2939. s_append(req, &n, " ", sizeof(req));
  2940. if (!ctype || !ctype[0])
  2941. s_append(req, &n, "-", sizeof(req));
  2942. /* One token on the request line: drop the spaces
  2943. * ("application/json; charset=utf-8" stays valid). */
  2944. for (k = 0; ctype && ctype[k] && n + 2 < sizeof(req); k++)
  2945. if (ctype[k] != ' ')
  2946. req[n++] = ctype[k];
  2947. req[n] = '\0';
  2948. s_append(req, &n, " ", sizeof(req));
  2949. } else if (post_len) {
  2950. s_append(req, &n, "POST ", sizeof(req));
  2951. s_append_dec(req, &n, post_len, sizeof(req));
  2952. s_append(req, &n, " ", sizeof(req));
  2953. }
  2954. s_append(req, &n, url, sizeof(req));
  2955. s_append(req, &n, "\n", sizeof(req));
  2956. if (post_len && u_syscall3(SYS_WRITE_FILE, (int)w->post,
  2957. (int)post, (int)post_len) < 0) {
  2958. s_copy(err, "cannot queue form body", errcap);
  2959. return -1;
  2960. }
  2961. u_syscall1(SYS_UNLINK, (int)w->done);
  2962. u_syscall1(SYS_UNLINK, (int)w->meta);
  2963. if (u_syscall3(SYS_WRITE_FILE, (int)w->req, (int)req, (int)n) < 0) {
  2964. s_copy(err, "cannot queue network request", errcap);
  2965. return -1;
  2966. }
  2967. if (fetch_worker_start(w, err, errcap) != 0)
  2968. return -1;
  2969. w->busy = 1;
  2970. w->deadline = u_ticks_ms() + UHTTP_TOTAL_TIMEOUT_MS + 5000;
  2971. return 0;
  2972. }
  2973. /* Read and parse w->meta after w->done matched. Returns 0 when ready. */
  2974. static int fetch_worker_read_meta(struct fetch_worker *w, char *err,
  2975. unsigned int errcap)
  2976. {
  2977. static char meta[1024];
  2978. char *p;
  2979. int rn, mseq;
  2980. rn = u_syscall3(SYS_READ_FILE, (int)w->meta, (int)meta,
  2981. (int)(sizeof(meta) - 1));
  2982. if (rn <= 0) {
  2983. s_copy(err, "network helper failed", errcap);
  2984. return -1;
  2985. }
  2986. meta[rn] = '\0';
  2987. p = meta;
  2988. mseq = (int)meta_uint(&p);
  2989. if (mseq != (int)w->seq) {
  2990. s_copy(err, "stale network response", errcap);
  2991. return -1;
  2992. }
  2993. w->m.status = (int)meta_uint(&p);
  2994. w->m.error = (int)meta_uint(&p);
  2995. w->m.trunc = (int)meta_uint(&p);
  2996. meta_str(&p, w->m.encoding, sizeof(w->m.encoding));
  2997. meta_str(&p, w->m.ctype, sizeof(w->m.ctype));
  2998. meta_str(&p, w->m.final, sizeof(w->m.final));
  2999. w->m.len = meta_uint(&p);
  3000. w->m.open_ms = 0;
  3001. w->m.first_ms = 0;
  3002. w->m.total_ms = 0;
  3003. if (*p) {
  3004. w->m.open_ms = meta_uint(&p);
  3005. w->m.first_ms = meta_uint(&p);
  3006. w->m.total_ms = meta_uint(&p);
  3007. }
  3008. w->m.dw = w->m.dh = w->m.nw = w->m.nh = 0;
  3009. w->m.alpha = w->m.px_len = w->m.dec_ms = 0;
  3010. w->m.dec_err = 0;
  3011. if (*p) {
  3012. w->m.dw = meta_uint(&p);
  3013. w->m.dh = meta_uint(&p);
  3014. w->m.nw = meta_uint(&p);
  3015. w->m.nh = meta_uint(&p);
  3016. w->m.alpha = meta_uint(&p);
  3017. w->m.px_len = meta_uint(&p);
  3018. w->m.dec_err = (int)meta_uint(&p);
  3019. w->m.dec_ms = meta_uint(&p);
  3020. }
  3021. if (w->m.error) {
  3022. s_copy(err, uhttp_error_string(w->m.error), errcap);
  3023. return -1;
  3024. }
  3025. w->ready = 1;
  3026. return 0;
  3027. }
  3028. /* Non-blocking poll: 1 ready, 0 still running, -1 failed. */
  3029. static int fetch_worker_poll(struct fetch_worker *w, char *err,
  3030. unsigned int errcap)
  3031. {
  3032. static char done[24];
  3033. char *p;
  3034. int rn, mseq;
  3035. fetch_tty_drain();
  3036. if (!w->busy)
  3037. return -1;
  3038. if (w->ready)
  3039. return 1;
  3040. rn = u_syscall3(SYS_READ_FILE, (int)w->done, (int)done,
  3041. (int)(sizeof(done) - 1));
  3042. if (rn > 0) {
  3043. done[rn] = '\0';
  3044. p = done;
  3045. mseq = (int)meta_uint(&p);
  3046. if (mseq == (int)w->seq) {
  3047. if (fetch_worker_read_meta(w, err, errcap) != 0) {
  3048. fetch_worker_stop(w);
  3049. return -1;
  3050. }
  3051. return 1;
  3052. }
  3053. }
  3054. if (!u_alive((unsigned int)w->pid)) {
  3055. w->pid = -1;
  3056. if (!w->retried && fetch_worker_start(w, err, errcap) == 0) {
  3057. w->retried = 1;
  3058. return 0;
  3059. }
  3060. s_copy(err, "network helper stopped", errcap);
  3061. fetch_worker_stop(w);
  3062. return -1;
  3063. }
  3064. if ((int)(u_ticks_ms() - w->deadline) >= 0) {
  3065. s_copy(err, "network request timed out", errcap);
  3066. fetch_worker_stop(w);
  3067. return -1;
  3068. }
  3069. return 0;
  3070. }
  3071. /* Copy the completed body, inflating it if the server ignored our identity
  3072. * request. Mirrors the old fetch_remote body path. */
  3073. static int fetch_worker_read_body(struct fetch_worker *w,
  3074. unsigned char *plain,
  3075. unsigned int plaincap,
  3076. unsigned char *comp,
  3077. unsigned int compcap,
  3078. int *truncated, char *err,
  3079. unsigned int errcap)
  3080. {
  3081. int rv, zr, was_trunc;
  3082. if (contains_ci(w->m.encoding, "gzip") ||
  3083. contains_ci(w->m.encoding, "deflate")) {
  3084. unsigned int comp_len = 0, plen = 0;
  3085. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)comp,
  3086. (int)compcap);
  3087. if (rv < 0) {
  3088. s_copy(err, "empty response", errcap);
  3089. return -1;
  3090. }
  3091. comp_len = (unsigned int)rv;
  3092. if (comp_len < w->m.len) {
  3093. s_copy(err, "compressed response is too large", errcap);
  3094. return -1;
  3095. }
  3096. if (contains_ci(w->m.encoding, "deflate"))
  3097. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3098. &plen, 0, &was_trunc);
  3099. else
  3100. zr = inflate_trunc(comp, comp_len, plain, plaincap,
  3101. &plen, 1, &was_trunc);
  3102. if (zr != 0) {
  3103. s_copy(err, "compressed response is corrupt", errcap);
  3104. return -1;
  3105. }
  3106. *truncated = w->m.trunc || was_trunc;
  3107. return (int)plen;
  3108. }
  3109. rv = u_syscall3(SYS_READ_FILE, (int)w->body, (int)plain, (int)plaincap);
  3110. if (rv < 0) {
  3111. s_copy(err, "empty response", errcap);
  3112. return -1;
  3113. }
  3114. *truncated = w->m.trunc || ((unsigned int)rv < w->m.len);
  3115. return rv;
  3116. }
  3117. static void fetch_worker_release(struct fetch_worker *w)
  3118. {
  3119. u_syscall1(SYS_UNLINK, (int)w->done);
  3120. u_syscall1(SYS_UNLINK, (int)w->meta);
  3121. u_syscall1(SYS_UNLINK, (int)w->body);
  3122. u_syscall1(SYS_UNLINK, (int)w->post);
  3123. u_syscall1(SYS_UNLINK, (int)w->px);
  3124. u_syscall1(SYS_UNLINK, (int)w->req);
  3125. w->busy = 0;
  3126. w->ready = 0;
  3127. w->image_job = 0;
  3128. w->dec_w = 0;
  3129. w->dec_h = 0;
  3130. w->dec_retried = 0;
  3131. }
  3132. /* Blocking wait used by page/CSS/script fetches; keeps the UI alive. */
  3133. static int fetch_worker_wait(struct fetch_worker *w, char *err,
  3134. unsigned int errcap)
  3135. {
  3136. for (;;) {
  3137. int rv;
  3138. if (!fetch_wait_passive)
  3139. worker_wait_ui();
  3140. if (cancel_fetch || pending_action) {
  3141. fetch_workers_cancel_busy();
  3142. return FETCH_ABORT;
  3143. }
  3144. rv = fetch_worker_poll(w, err, errcap);
  3145. if (rv != 0)
  3146. return rv == 1 ? 0 : -1;
  3147. u_sleep_ms(10);
  3148. }
  3149. }
  3150. static int fetch_remote(const char *url, unsigned int cap,
  3151. const char *post, unsigned int post_len,
  3152. unsigned char *plain, unsigned int plaincap,
  3153. unsigned char *comp, unsigned int compcap,
  3154. struct fetch_meta *m, int *truncated,
  3155. char *err, unsigned int errcap)
  3156. {
  3157. struct fetch_worker *w = fetch_worker_alloc();
  3158. int rv;
  3159. fetch_last_error = 0;
  3160. if (!w) {
  3161. s_copy(err, "network busy", errcap);
  3162. return -1;
  3163. }
  3164. if (fetch_worker_submit(w, url, cap, post, post_len, 0, 0,
  3165. err, errcap) != 0) {
  3166. fetch_worker_release(w);
  3167. return -1;
  3168. }
  3169. rv = fetch_worker_wait(w, err, errcap);
  3170. if (rv == FETCH_ABORT) {
  3171. fetch_worker_release(w);
  3172. return FETCH_ABORT;
  3173. }
  3174. if (rv != 0) {
  3175. fetch_last_error = w->m.error;
  3176. fetch_worker_release(w);
  3177. return -1;
  3178. }
  3179. *m = w->m;
  3180. rv = fetch_worker_read_body(w, plain, plaincap, comp, compcap,
  3181. truncated, err, errcap);
  3182. fetch_worker_release(w);
  3183. if (rv >= 0 && (cancel_fetch || pending_action))
  3184. return FETCH_ABORT;
  3185. return rv;
  3186. }
  3187. static int fetch_worker_status(const struct fetch_worker *w)
  3188. {
  3189. return w->m.status;
  3190. }
  3191. /* fetch()/XHR through a helper: one request, the status and body come back
  3192. * whatever the HTTP status (a 401 is an answer, not a network error). */
  3193. static int js_worker_http(const char *method, const char *url,
  3194. const char *ctype, const char *body,
  3195. unsigned int body_len, struct js_http_resp *r,
  3196. char *err, int errcap)
  3197. {
  3198. struct fetch_worker *w = fetch_worker_alloc();
  3199. unsigned char *plain;
  3200. int rv, tr = 0;
  3201. if (!w) {
  3202. s_copy(err, "network busy", (unsigned int)errcap);
  3203. return -1;
  3204. }
  3205. if (fetch_worker_submit_req(w, url, JS_HTTP_MAX, method, ctype, body,
  3206. body_len, 0, 0, 0, 0, err,
  3207. (unsigned int)errcap) != 0) {
  3208. fetch_worker_release(w);
  3209. return -1;
  3210. }
  3211. fetch_wait_passive++;
  3212. rv = fetch_worker_wait(w, err, (unsigned int)errcap);
  3213. fetch_wait_passive--;
  3214. if (rv != 0) {
  3215. if (rv == FETCH_ABORT)
  3216. s_copy(err, "page is navigating", (unsigned int)errcap);
  3217. fetch_worker_release(w);
  3218. return -1;
  3219. }
  3220. r->status = w->m.status;
  3221. s_copy(r->ctype, w->m.ctype, sizeof(r->ctype));
  3222. s_copy(r->url, w->m.final[0] ? w->m.final : url, sizeof(r->url));
  3223. plain = (unsigned char *)malloc(JS_HTTP_MAX + 1);
  3224. if (!plain) {
  3225. fetch_worker_release(w);
  3226. s_copy(err, "out of memory", (unsigned int)errcap);
  3227. return -1;
  3228. }
  3229. if (w->m.len == 0) {
  3230. rv = 0; /* 204, an empty 200: no body file */
  3231. } else {
  3232. rv = fetch_worker_read_body(w, plain, JS_HTTP_MAX,
  3233. image_io_buf, BR_PAGE_COMP_MAX,
  3234. &tr, err, (unsigned int)errcap);
  3235. }
  3236. fetch_worker_release(w);
  3237. if (rv < 0) {
  3238. free(plain);
  3239. return -1;
  3240. }
  3241. plain[rv] = '\0';
  3242. r->body = (char *)plain;
  3243. r->len = (unsigned int)rv;
  3244. return 0;
  3245. }
  3246. /* ---- HTTP / file fetch ---- */
  3247. static int read_url(const char *url, unsigned int cap, unsigned char **out,
  3248. unsigned int *outlen, int *is_local, char *ctype,
  3249. unsigned int ctcap, char *final, unsigned int finalcap,
  3250. char *err, unsigned int errcap, int *truncated,
  3251. const char *post, unsigned int post_len)
  3252. {
  3253. unsigned char *buf;
  3254. unsigned int len;
  3255. int tr = 0;
  3256. int rv;
  3257. *out = 0;
  3258. *outlen = 0;
  3259. *truncated = 0;
  3260. if (final && finalcap)
  3261. final[0] = '\0';
  3262. if (ctype && ctcap)
  3263. ctype[0] = '\0';
  3264. if (url[0] == '/') {
  3265. char pathbuf[BR_URL_MAX];
  3266. const char *open_url = url;
  3267. unsigned int i = 0;
  3268. /* A local form GET keeps ?query in the address bar but the
  3269. * file lookup uses the path alone, like a real browser. */
  3270. while (url[i] && url[i] != '?' && url[i] != '#')
  3271. i++;
  3272. if (url[i]) {
  3273. s_copy(pathbuf, url, i + 1);
  3274. open_url = pathbuf;
  3275. }
  3276. buf = (unsigned char *)malloc(cap);
  3277. if (!buf) {
  3278. s_copy(err, "out of memory", errcap);
  3279. return -1;
  3280. }
  3281. rv = u_syscall3(SYS_READ_FILE, (int)open_url, (int)buf, (int)cap);
  3282. if (rv < 0) {
  3283. free(buf);
  3284. s_copy(err, "file not found", errcap);
  3285. return -1;
  3286. }
  3287. *out = buf;
  3288. *outlen = (unsigned int)rv;
  3289. *is_local = 1;
  3290. if (ctype)
  3291. s_copy(ctype, "text/html", ctcap);
  3292. if (final)
  3293. s_copy(final, url, finalcap);
  3294. if ((unsigned int)rv == cap)
  3295. *truncated = 1;
  3296. return 0;
  3297. }
  3298. buf = (unsigned char *)malloc(cap);
  3299. if (!buf) {
  3300. s_copy(err, "out of memory", errcap);
  3301. return -1;
  3302. }
  3303. rv = fetch_remote(url, cap, post, post_len, buf, cap, image_io_buf,
  3304. BR_PAGE_COMP_MAX, &fetch_meta, &tr, err, errcap);
  3305. if (rv == FETCH_ABORT) {
  3306. free(buf);
  3307. return FETCH_ABORT;
  3308. }
  3309. if (rv < 0) {
  3310. free(buf);
  3311. return -1;
  3312. }
  3313. len = (unsigned int)rv;
  3314. if (len == 0) {
  3315. free(buf);
  3316. s_copy(err, "empty response", errcap);
  3317. return -1;
  3318. }
  3319. if (ctype)
  3320. s_copy(ctype, fetch_meta.ctype, ctcap);
  3321. if (final && fetch_meta.final[0])
  3322. s_copy(final, fetch_meta.final, finalcap);
  3323. *is_local = 0;
  3324. *out = buf;
  3325. *outlen = len;
  3326. *truncated = tr;
  3327. return 0;
  3328. }
  3329. /* Load every @font-face the parser registered. Local files go through
  3330. * ufont_face_open_path(); remote files use the fetch helper (identity, the
  3331. * TTF parser has no gzip). A failed face stays NULL: layout then falls back
  3332. * to the built-in regular/bold/italic/mono set. */
  3333. static void load_font_faces(void)
  3334. {
  3335. unsigned int i;
  3336. memset(font_faces, 0, sizeof(font_faces));
  3337. for (i = 1; i <= (unsigned int)br_font_face_count() &&
  3338. i <= BR_MAX_FACES; i++) {
  3339. const char *url = br_font_face_url((int)i);
  3340. const char *base = br_font_face_base((int)i);
  3341. char abs[BR_URL_MAX];
  3342. if (!url || !url[0])
  3343. continue;
  3344. if (resolve_link(base && base[0] ? base : page_url, url, abs,
  3345. sizeof(abs)) != 0)
  3346. continue;
  3347. if (abs[0] == '/') {
  3348. font_faces[i - 1] = ufont_face_open_path(abs);
  3349. } else if (is_http(abs)) {
  3350. unsigned char *buf;
  3351. char err[64];
  3352. int rv, tr = 0;
  3353. buf = (unsigned char *)malloc(UFONT_MAX_FILE);
  3354. if (!buf)
  3355. continue;
  3356. rv = fetch_remote(abs, UFONT_MAX_FILE, 0, 0, buf,
  3357. UFONT_MAX_FILE, image_io_buf,
  3358. BR_PAGE_COMP_MAX, &fetch_meta, &tr,
  3359. err, sizeof(err));
  3360. if (rv > 0)
  3361. font_faces[i - 1] = ufont_face_open_mem(buf,
  3362. rv);
  3363. free(buf);
  3364. }
  3365. }
  3366. }
  3367. /* Remote scripts are cached under /share for the current boot, like the
  3368. * stylesheet cache, so reloads and later visits skip the network. */
  3369. static int script_cache_count;
  3370. static unsigned int script_cache_hash(const char *s)
  3371. {
  3372. unsigned int h = 2166136261u;
  3373. while (*s) {
  3374. h ^= (unsigned char)*s++;
  3375. h *= 16777619u;
  3376. }
  3377. return h;
  3378. }
  3379. static void script_cache_path(const char *url, char *out, unsigned int cap)
  3380. {
  3381. unsigned int n = 0;
  3382. s_append(out, &n, "/share/" SCRIPT_CACHE_PREFIX, cap);
  3383. s_append_dec(out, &n, script_cache_hash(url), cap);
  3384. }
  3385. static void script_cache_clear(void)
  3386. {
  3387. struct sys_dirent d;
  3388. char path[96];
  3389. for (;;) {
  3390. int i, found = 0;
  3391. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3392. (int)&d) == 1; i++) {
  3393. unsigned int n = 0;
  3394. if (!starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3395. continue;
  3396. s_append(path, &n, "/share/", sizeof(path));
  3397. s_append(path, &n, d.name, sizeof(path));
  3398. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3399. return;
  3400. found = 1;
  3401. break;
  3402. }
  3403. if (!found)
  3404. break;
  3405. }
  3406. script_cache_count = 0;
  3407. }
  3408. static void script_cache_init(void)
  3409. {
  3410. struct sys_dirent d;
  3411. int i, count = 0;
  3412. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3413. (int)&d) == 1; i++)
  3414. if (starts_with(d.name, SCRIPT_CACHE_PREFIX))
  3415. count++;
  3416. if (count >= SCRIPT_CACHE_MAX) {
  3417. script_cache_clear();
  3418. return;
  3419. }
  3420. script_cache_count = count;
  3421. }
  3422. static int script_cache_get(const char *url, unsigned char **out,
  3423. unsigned int *outlen)
  3424. {
  3425. char path[96];
  3426. struct sys_stat st;
  3427. unsigned char *buf;
  3428. int rn;
  3429. script_cache_path(url, path, sizeof(path));
  3430. if (u_stat(path, &st) != 0 || st.is_dir || st.size == 0 ||
  3431. st.size >= SCRIPT_CACHE_FILE_MAX)
  3432. return 0;
  3433. buf = (unsigned char *)malloc(st.size + 1);
  3434. if (!buf)
  3435. return 0;
  3436. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)buf, (int)st.size);
  3437. if (rn != (int)st.size) {
  3438. free(buf);
  3439. return 0;
  3440. }
  3441. buf[st.size] = '\0';
  3442. *out = buf;
  3443. *outlen = st.size;
  3444. return 1;
  3445. }
  3446. static void script_cache_put(const char *url, const unsigned char *data,
  3447. unsigned int len)
  3448. {
  3449. char path[96];
  3450. if (script_cache_count >= SCRIPT_CACHE_MAX || len == 0 ||
  3451. len >= SCRIPT_CACHE_FILE_MAX)
  3452. return;
  3453. script_cache_path(url, path, sizeof(path));
  3454. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3455. (int)len) >= 0)
  3456. script_cache_count++;
  3457. }
  3458. static int script_cache_has(const char *url)
  3459. {
  3460. char path[96];
  3461. struct sys_stat st;
  3462. script_cache_path(url, path, sizeof(path));
  3463. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3464. st.size < SCRIPT_CACHE_FILE_MAX;
  3465. }
  3466. /* Fetch one external script into a heap buffer and NUL-terminate it. */
  3467. static int fetch_script_text(const char *url, unsigned char **out,
  3468. unsigned int *outlen, char *err,
  3469. unsigned int errcap)
  3470. {
  3471. unsigned char *buf;
  3472. unsigned int len;
  3473. int local, truncated = 0;
  3474. char ctype[64], final[BR_URL_MAX];
  3475. int rv;
  3476. *out = 0;
  3477. *outlen = 0;
  3478. if (url[0] != '/' && script_cache_get(url, out, outlen))
  3479. return 0;
  3480. rv = read_url(url, BR_SCRIPT_MAX, &buf, &len, &local, ctype,
  3481. sizeof(ctype), final, sizeof(final), err, errcap,
  3482. &truncated, 0, 0);
  3483. if (rv != 0)
  3484. return rv;
  3485. if (truncated || len >= BR_SCRIPT_MAX) {
  3486. free(buf);
  3487. s_copy(err, "script is too large", errcap);
  3488. return -1;
  3489. }
  3490. buf[len] = '\0';
  3491. if (!local)
  3492. script_cache_put(url, buf, len);
  3493. *out = buf;
  3494. *outlen = len;
  3495. return 0;
  3496. }
  3497. /* Fetch an image into the fixed scratch buffers. The scaled bitmaps live on
  3498. * the heap, so images must not allocate their file body from it as well. */
  3499. static int fetch_image(const char *url, unsigned int cap,
  3500. unsigned char **out, unsigned int *outlen,
  3501. char *err, unsigned int errcap)
  3502. {
  3503. unsigned int len;
  3504. int tr = 0;
  3505. int rv;
  3506. *out = 0;
  3507. *outlen = 0;
  3508. if (cap > BR_IMG_FILE_MAX)
  3509. cap = BR_IMG_FILE_MAX;
  3510. if (url[0] == '/') {
  3511. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_file_buf,
  3512. (int)cap);
  3513. if (rv < 0) {
  3514. s_copy(err, "file not found", errcap);
  3515. return -1;
  3516. }
  3517. *out = image_file_buf;
  3518. *outlen = (unsigned int)rv;
  3519. return 0;
  3520. }
  3521. rv = fetch_remote(url, cap, 0, 0, image_file_buf, cap, image_comp_buf,
  3522. BR_IMG_FILE_MAX, &fetch_meta, &tr, err, errcap);
  3523. if (rv == FETCH_ABORT)
  3524. return FETCH_ABORT;
  3525. if (rv < 0)
  3526. return -1;
  3527. len = (unsigned int)rv;
  3528. if (len == 0) {
  3529. s_copy(err, "empty image", errcap);
  3530. return -1;
  3531. }
  3532. *out = image_file_buf;
  3533. *outlen = len;
  3534. return 0;
  3535. }
  3536. /* Remote stylesheets are immutable enough for the current boot: keep
  3537. * successful responses under /share so a reload, a second visit or a fresh
  3538. * browser launch does not fetch the same five sheets over the network again.
  3539. * /share is cleared by reboot/kexec; when the cache fills up it is reset. */
  3540. static int css_cache_count;
  3541. static unsigned int css_cache_hash(const char *s)
  3542. {
  3543. unsigned int h = 2166136261u;
  3544. while (*s) {
  3545. h ^= (unsigned char)*s++;
  3546. h *= 16777619u;
  3547. }
  3548. return h;
  3549. }
  3550. static void css_cache_path(const char *url, char *out, unsigned int cap)
  3551. {
  3552. unsigned int n = 0;
  3553. s_append(out, &n, "/share/" CSS_CACHE_PREFIX, cap);
  3554. s_append_dec(out, &n, css_cache_hash(url), cap);
  3555. }
  3556. static void css_cache_clear(void)
  3557. {
  3558. struct sys_dirent d;
  3559. char path[96];
  3560. for (;;) {
  3561. int i, found = 0;
  3562. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3563. (int)&d) == 1; i++) {
  3564. unsigned int n = 0;
  3565. if (!starts_with(d.name, CSS_CACHE_PREFIX))
  3566. continue;
  3567. s_append(path, &n, "/share/", sizeof(path));
  3568. s_append(path, &n, d.name, sizeof(path));
  3569. if (u_syscall1(SYS_UNLINK, (int)path) < 0)
  3570. return;
  3571. found = 1;
  3572. break;
  3573. }
  3574. if (!found)
  3575. break;
  3576. }
  3577. css_cache_count = 0;
  3578. }
  3579. static void css_cache_init(void)
  3580. {
  3581. struct sys_dirent d;
  3582. int i, count = 0;
  3583. for (i = 0; u_syscall3(SYS_LIST_DIR, (int)"/share", i,
  3584. (int)&d) == 1; i++)
  3585. if (starts_with(d.name, CSS_CACHE_PREFIX))
  3586. count++;
  3587. if (count >= CSS_CACHE_MAX) {
  3588. css_cache_clear();
  3589. return;
  3590. }
  3591. css_cache_count = count;
  3592. }
  3593. static int css_cache_get(const char *url, unsigned char **out,
  3594. unsigned int *outlen)
  3595. {
  3596. char path[96];
  3597. int rn;
  3598. css_cache_path(url, path, sizeof(path));
  3599. rn = u_syscall3(SYS_READ_FILE, (int)path, (int)image_io_buf,
  3600. (int)CSS_CACHE_FILE_MAX);
  3601. if (rn <= 0 || (unsigned int)rn >= CSS_CACHE_FILE_MAX)
  3602. return 0;
  3603. *out = image_io_buf;
  3604. *outlen = (unsigned int)rn;
  3605. return 1;
  3606. }
  3607. static void css_cache_put(const char *url, const unsigned char *data,
  3608. unsigned int len)
  3609. {
  3610. char path[96];
  3611. if (css_cache_count >= CSS_CACHE_MAX || len == 0 ||
  3612. len >= CSS_CACHE_FILE_MAX)
  3613. return;
  3614. css_cache_path(url, path, sizeof(path));
  3615. if (u_syscall3(SYS_WRITE_FILE, (int)path, (int)data,
  3616. (int)len) >= 0)
  3617. css_cache_count++;
  3618. }
  3619. static int css_cache_has(const char *url)
  3620. {
  3621. char path[96];
  3622. struct sys_stat st;
  3623. css_cache_path(url, path, sizeof(path));
  3624. return u_stat(path, &st) == 0 && !st.is_dir && st.size > 0 &&
  3625. st.size < CSS_CACHE_FILE_MAX;
  3626. }
  3627. /* Read one stylesheet into the shared static buffer. CSS is parsed
  3628. * immediately, so it does not need the page heap; this leaves the heap for
  3629. * the 2 MB page body, the rules and the scaled image bitmaps. */
  3630. static int fetch_css(const char *url, unsigned char **out, unsigned int *outlen,
  3631. char *err, unsigned int errcap)
  3632. {
  3633. unsigned int len;
  3634. int tr = 0;
  3635. int rv;
  3636. *out = 0;
  3637. *outlen = 0;
  3638. if (url[0] == '/') {
  3639. rv = u_syscall3(SYS_READ_FILE, (int)url, (int)image_io_buf,
  3640. (int)BR_CSS_MAX);
  3641. if (rv < 0) {
  3642. s_copy(err, "stylesheet not found", errcap);
  3643. return -1;
  3644. }
  3645. *out = image_io_buf;
  3646. *outlen = (unsigned int)rv;
  3647. return 0;
  3648. }
  3649. if (css_cache_get(url, out, outlen))
  3650. return 0;
  3651. rv = fetch_remote(url, BR_CSS_MAX, 0, 0, image_io_buf, BR_CSS_MAX,
  3652. image_io_buf + BR_CSS_MAX, BR_CSS_COMP_MAX,
  3653. &fetch_meta, &tr, err, errcap);
  3654. if (rv == FETCH_ABORT)
  3655. return FETCH_ABORT;
  3656. if (rv < 0)
  3657. return -1;
  3658. len = (unsigned int)rv;
  3659. if (len == 0) {
  3660. s_copy(err, "empty stylesheet", errcap);
  3661. return -1;
  3662. }
  3663. *out = image_io_buf;
  3664. *outlen = len;
  3665. css_cache_put(url, image_io_buf, len);
  3666. return 0;
  3667. }
  3668. static void redraw_now(void);
  3669. static char error_page[1024];
  3670. static void show_error(const char *title, const char *detail)
  3671. {
  3672. char *page = error_page;
  3673. unsigned int n = 0;
  3674. s_append(page, &n, "<html><body><h2>", sizeof(error_page));
  3675. s_append(page, &n, title, sizeof(error_page));
  3676. s_append(page, &n, "</h2><p>", sizeof(error_page));
  3677. {
  3678. const char *p = detail;
  3679. while (*p && n + 1 < sizeof(error_page)) {
  3680. if (*p == '<') s_append(page, &n, "&lt;", sizeof(error_page));
  3681. else if (*p == '>') s_append(page, &n, "&gt;", sizeof(error_page));
  3682. else if (*p == '&') s_append(page, &n, "&amp;", sizeof(error_page));
  3683. else page[n++] = *p;
  3684. p++;
  3685. }
  3686. }
  3687. page[n] = '\0';
  3688. s_append(page, &n, "</p><p>", sizeof(error_page));
  3689. s_append(page, &n, page_url, sizeof(error_page));
  3690. s_append(page, &n, "</p><p><a href=\"/\">home</a></p></body></html>",
  3691. sizeof(error_page));
  3692. br_parse(&doc, page, n);
  3693. layout_valid = 0;
  3694. preload_active = 0;
  3695. preload_pending = 0;
  3696. preload_wait = 0;
  3697. fetch_workers_cancel_busy();
  3698. s_copy(page_title, title, sizeof(page_title));
  3699. page_loading = 0;
  3700. set_status(title, 1, 0);
  3701. ngui_invalidate(&ui);
  3702. }
  3703. static int decode_direct_image(const unsigned char *data, unsigned int len,
  3704. unsigned int node)
  3705. {
  3706. if (image_count >= BR_MAX_IMAGES)
  3707. return -1;
  3708. if (decode_image_data(data, len, &images[0], 0, 0, 0, 0) != 0)
  3709. return -1;
  3710. doc.nodes[node].img_index = 0;
  3711. image_count = 1;
  3712. return 0;
  3713. }
  3714. static int ancestor_is(unsigned int node, unsigned int tag)
  3715. {
  3716. unsigned int p = doc.nodes[node].parent;
  3717. while (p) {
  3718. if (doc.nodes[p].tag == tag)
  3719. return 1;
  3720. p = doc.nodes[p].parent;
  3721. }
  3722. return 0;
  3723. }
  3724. /* Fetch and parse the page's stylesheets. Remote bodies are downloaded in
  3725. * parallel but parsed in document order, so the cascade is unchanged. */
  3726. static int load_stylesheets(void)
  3727. {
  3728. static char urls[BR_MAX_SHEETS][BR_URL_MAX];
  3729. static unsigned char remote[BR_MAX_SHEETS];
  3730. struct fetch_worker *slot[BR_MAX_SHEETS];
  3731. unsigned int i, n = 0, next = 0, k;
  3732. char err[64];
  3733. for (i = 0; i < doc.nnode && n < BR_MAX_SHEETS; i++) {
  3734. struct br_node *nd = &doc.nodes[i];
  3735. const char *rel, *href;
  3736. char url[BR_URL_MAX];
  3737. int dup = 0;
  3738. if (nd->type != BR_NODE_ELEM || nd->tag != BR_TAG_LINK)
  3739. continue;
  3740. rel = br_rel(&doc, i);
  3741. if (!contains_ci(rel, "stylesheet"))
  3742. continue;
  3743. href = br_href(&doc, i);
  3744. if (!href[0])
  3745. continue;
  3746. if (resolve_link(page_url, href, url, sizeof(url)) != 0)
  3747. continue;
  3748. for (k = 0; k < n; k++)
  3749. if (s_eq(urls[k], url)) {
  3750. dup = 1;
  3751. break;
  3752. }
  3753. if (dup)
  3754. continue;
  3755. s_copy(urls[n], url, BR_URL_MAX);
  3756. remote[n] = url[0] != '/' && !css_cache_has(url);
  3757. n++;
  3758. }
  3759. for (i = 0; i < BR_MAX_SHEETS; i++)
  3760. slot[i] = 0;
  3761. /* Start as many remote sheets as there are free workers. */
  3762. for (; next < n; next++) {
  3763. struct fetch_worker *w;
  3764. if (!remote[next])
  3765. continue;
  3766. w = fetch_worker_alloc();
  3767. if (!w)
  3768. break;
  3769. if (fetch_worker_submit(w, urls[next], BR_CSS_MAX, 0, 0, 0, 0,
  3770. err, sizeof(err)) != 0) {
  3771. fetch_worker_release(w);
  3772. remote[next] = 0;
  3773. continue;
  3774. }
  3775. slot[next] = w;
  3776. }
  3777. for (i = 0; i < n; i++) {
  3778. unsigned char *data = 0;
  3779. unsigned int len = 0;
  3780. int rv;
  3781. if (!remote[i]) {
  3782. rv = fetch_css(urls[i], &data, &len, err, sizeof(err));
  3783. if (rv == FETCH_ABORT) {
  3784. fetch_workers_stop_all();
  3785. return FETCH_ABORT;
  3786. }
  3787. if (rv != 0 || !len)
  3788. continue;
  3789. } else {
  3790. struct fetch_worker *w = slot[i];
  3791. int tr = 0;
  3792. if (!w) {
  3793. w = fetch_worker_alloc();
  3794. if (!w) {
  3795. rv = -1;
  3796. goto css_failed;
  3797. }
  3798. if (fetch_worker_submit(w, urls[i], BR_CSS_MAX,
  3799. 0, 0, 0, 0, err,
  3800. sizeof(err)) != 0) {
  3801. fetch_worker_release(w);
  3802. remote[i] = 0;
  3803. if (i == next)
  3804. next++;
  3805. continue;
  3806. }
  3807. slot[i] = w;
  3808. if (i == next)
  3809. next++;
  3810. }
  3811. rv = fetch_worker_wait(w, err, sizeof(err));
  3812. if (rv == FETCH_ABORT) {
  3813. fetch_workers_stop_all();
  3814. return FETCH_ABORT;
  3815. }
  3816. if (rv == 0)
  3817. rv = fetch_worker_read_body(w, image_io_buf,
  3818. BR_CSS_MAX,
  3819. image_io_buf + BR_CSS_MAX,
  3820. BR_CSS_COMP_MAX, &tr,
  3821. err, sizeof(err));
  3822. else
  3823. rv = -1;
  3824. fetch_worker_release(w);
  3825. slot[i] = 0;
  3826. /* Refill the worker window before parsing this sheet. */
  3827. for (; next < n; next++) {
  3828. struct fetch_worker *nw;
  3829. if (!remote[next])
  3830. continue;
  3831. nw = fetch_worker_alloc();
  3832. if (!nw)
  3833. break;
  3834. if (fetch_worker_submit(nw, urls[next],
  3835. BR_CSS_MAX, 0, 0, 0, 0,
  3836. err, sizeof(err)) != 0) {
  3837. fetch_worker_release(nw);
  3838. remote[next] = 0;
  3839. continue;
  3840. }
  3841. slot[next] = nw;
  3842. }
  3843. css_failed:
  3844. if (rv <= 0) {
  3845. /* One synchronous retry: a dropped sheet leaves the
  3846. * whole page unstyled (seen intermittently on
  3847. * arstechnica's CDN). */
  3848. u_puts("[css] retry ");
  3849. u_puts(urls[i]);
  3850. u_puts(": ");
  3851. u_puts(err[0] ? err : "no worker/empty body");
  3852. u_putc('\n');
  3853. err[0] = '\0';
  3854. rv = fetch_css(urls[i], &data, &len, err,
  3855. sizeof(err));
  3856. if (rv == FETCH_ABORT) {
  3857. fetch_workers_stop_all();
  3858. return FETCH_ABORT;
  3859. }
  3860. if (rv != 0 || !len) {
  3861. u_puts("[css] failed: ");
  3862. u_puts(err);
  3863. u_putc('\n');
  3864. continue;
  3865. }
  3866. } else {
  3867. len = (unsigned int)rv;
  3868. data = image_io_buf;
  3869. css_cache_put(urls[i], data, len);
  3870. }
  3871. }
  3872. if (len) {
  3873. br_set_font_base(urls[i]);
  3874. br_parse_css_text(&doc, (const char *)data, len);
  3875. }
  3876. }
  3877. br_set_font_base(page_url);
  3878. br_parse_inline_css(&doc);
  3879. load_font_faces();
  3880. br_reset_styles(&doc);
  3881. layout_valid = 0;
  3882. return 0;
  3883. }
  3884. static void preload_begin(void)
  3885. {
  3886. preload_active = 1;
  3887. preload_pending = 0;
  3888. preload_wait = 1;
  3889. preload_max_jobs = FETCH_WORKERS;
  3890. preload_node = 0;
  3891. preload_loaded = 0;
  3892. preload_scroll = 0;
  3893. img_stat_start = u_ticks_ms();
  3894. img_stat_wall = 0;
  3895. img_stat_net = img_stat_open = img_stat_first = 0;
  3896. img_stat_io = img_stat_dec = img_stat_scale = 0;
  3897. img_stat_paint = img_stat_reflow = 0;
  3898. img_stat_bytes = 0;
  3899. img_stat_n = 0;
  3900. img_stat_log_len = 0;
  3901. if (img_stat_log[0])
  3902. img_stat_log[0] = '\0';
  3903. img_repaint_ms = 0;
  3904. img_repaint_pending = 0;
  3905. }
  3906. /* Styles are computed top-down during layout, but images inside a hidden
  3907. * menu/carousel are never visited and keep img_top == 0. Without this check
  3908. * the preloader walks the DOM in node order and spends the whole image
  3909. * budget on logos and off-canvas thumbnails the reader cannot see. */
  3910. static int node_hidden(unsigned int node)
  3911. {
  3912. unsigned int path[32], n = 0, p = node, i;
  3913. struct br_style st, parent;
  3914. while (p && n < sizeof(path) / sizeof(path[0])) {
  3915. path[n++] = p;
  3916. p = doc.nodes[p].parent;
  3917. }
  3918. parent = (struct br_style){0};
  3919. parent.font_px = 16;
  3920. parent.display = BR_DISPLAY_BLOCK;
  3921. for (i = n; i > 0; i--) {
  3922. br_style_for(&doc, path[i - 1], &parent, &st);
  3923. if (st.display == BR_DISPLAY_NONE || st.vis_hidden ||
  3924. st.opacity_hidden)
  3925. return 1;
  3926. parent = st;
  3927. }
  3928. return 0;
  3929. }
  3930. static struct br_style base_style(void);
  3931. static int style_width_px(const struct br_style *st, int base);
  3932. static int style_height_px(const struct br_style *st, int base);
  3933. static void style_for_node(unsigned int node, struct br_style *out)
  3934. {
  3935. unsigned int p = doc.nodes[node].parent;
  3936. struct br_style parent;
  3937. if (p) {
  3938. style_for_node(p, &parent);
  3939. br_style_for(&doc, node, &parent, out);
  3940. } else {
  3941. parent = base_style();
  3942. br_style_for(&doc, node, &parent, out);
  3943. }
  3944. }
  3945. /* ---- parallel image preloading ---- *
  3946. *
  3947. * Up to FETCH_WORKERS image downloads run in separate curl helpers at once.
  3948. * preload_step() only starts jobs and harvests completed ones; the browser
  3949. * main loop keeps drawing between calls, instead of blocking on one fetch.
  3950. */
  3951. static int preload_active_jobs(void)
  3952. {
  3953. int i, n = 0;
  3954. for (i = 0; i < FETCH_WORKERS; i++)
  3955. if (fetch_workers[i].busy && fetch_workers[i].image_job)
  3956. n++;
  3957. return n;
  3958. }
  3959. static void preload_job_error(struct fetch_worker *w)
  3960. {
  3961. if (w->node < doc.nnode) {
  3962. if (w->bg)
  3963. doc.nodes[w->node].bg_img_index = -2;
  3964. else
  3965. doc.nodes[w->node].img_index = -2;
  3966. image_repaint();
  3967. }
  3968. }
  3969. /* Is the image's box anywhere near the visible page? A decode below the
  3970. * fold changes the layout (scroll extent) but not a single on-screen pixel,
  3971. * so it does not need a repaint. top/h come from the last layout; treat an
  3972. * unknown box as visible to stay safe. */
  3973. static int image_preload_visible(unsigned int node, int bg)
  3974. {
  3975. int top, h, scroll;
  3976. if (node >= BR_MAX_NODES || node >= doc.nnode || page_rect.h <= 0)
  3977. return 1;
  3978. if (bg) {
  3979. top = (int)block_top[node];
  3980. h = (int)block_h[node];
  3981. } else {
  3982. top = (int)img_top[node];
  3983. h = (int)img_h[node];
  3984. }
  3985. if (!top && !h)
  3986. return 1;
  3987. scroll = (int)page_scroll.offset;
  3988. if (top > scroll + page_rect.h + 160)
  3989. return 0;
  3990. if (top + h + 160 < scroll)
  3991. return 0;
  3992. return 1;
  3993. }
  3994. /* Upper bounds for the bitmap an <img> will paint. Zero means "unbounded";
  3995. * decode_image_data applies one scale to both axes so the aspect ratio is
  3996. * preserved. This is what keeps a 1200x800 photo that CSS paints at 400 px
  3997. * from being decoded and box-filtered to the 1000 px layout cap first. */
  3998. static void image_fit_size(unsigned int node, int *out_w, int *out_h)
  3999. {
  4000. struct br_style st;
  4001. struct br_node *nd;
  4002. unsigned int p;
  4003. int cw, w = 0, h = 0;
  4004. *out_w = *out_h = 0;
  4005. if (node >= doc.nnode)
  4006. return;
  4007. nd = &doc.nodes[node];
  4008. style_for_node(node, &st);
  4009. cw = page_rect.w > 24 ? page_rect.w - 24 : 0;
  4010. p = doc.nodes[node].parent;
  4011. if (p && p < BR_MAX_NODES && layout_boxes[p].valid &&
  4012. layout_boxes[p].w > 0 && layout_boxes[p].w < cw)
  4013. cw = layout_boxes[p].w;
  4014. if (st.width_kind)
  4015. w = style_width_px(&st, cw);
  4016. else if (nd->width_attr)
  4017. w = nd->width_pct ? cw * (int)nd->width_attr / 100 :
  4018. (int)nd->width_attr;
  4019. if (st.height_kind)
  4020. h = style_height_px(&st, cw);
  4021. else if (nd->height_attr)
  4022. h = nd->height_pct ? cw * (int)nd->height_attr / 100 :
  4023. (int)nd->height_attr;
  4024. if (st.max_width_kind) {
  4025. int mw = st.max_width_kind == 3 ?
  4026. cw * st.max_width_calc_pct / 100 +
  4027. st.max_width_calc_px :
  4028. st.max_width_kind == 2 ?
  4029. cw * (int)st.max_width / 100 :
  4030. (int)st.max_width;
  4031. if (mw > 0 && (w == 0 || w > mw))
  4032. w = mw;
  4033. }
  4034. if (st.max_height_kind) {
  4035. int mh = st.max_height_kind == 3 ?
  4036. cw * st.max_height_calc_pct / 100 +
  4037. st.max_height_calc_px :
  4038. st.max_height_kind == 2 ?
  4039. cw * (int)st.max_height / 100 :
  4040. (int)st.max_height;
  4041. if (mh > 0 && (h == 0 || h > mh))
  4042. h = mh;
  4043. }
  4044. if (w > BR_IMG_LAYOUT_W)
  4045. w = BR_IMG_LAYOUT_W;
  4046. if (h > 4096)
  4047. h = 4096;
  4048. if (w < 0)
  4049. w = 0;
  4050. if (h < 0)
  4051. h = 0;
  4052. *out_w = w;
  4053. *out_h = h;
  4054. }
  4055. static void preload_accept_image(unsigned int node, int bg, const char *url)
  4056. {
  4057. /* An <img> bitmap only depends on its URL, so the next <img> with the
  4058. * same source reuses it (heise repeats one comment icon 85 times).
  4059. * Backgrounds are scaled to their box and are not shared. */
  4060. images[image_count].url_hash =
  4061. !bg && url ? script_cache_hash(url) | 1u : 0;
  4062. if (bg)
  4063. doc.nodes[node].bg_img_index = (short)image_count;
  4064. else
  4065. doc.nodes[node].img_index = (short)image_count;
  4066. image_count++;
  4067. preload_loaded++;
  4068. /* A background bitmap never changes its box, so keep the (expensive)
  4069. * measured layout and only repaint the pixels. */
  4070. if (bg)
  4071. page_cache_valid = 0;
  4072. else
  4073. layout_valid = 0;
  4074. if (image_preload_visible(node, bg))
  4075. image_repaint();
  4076. }
  4077. /* Install a bitmap decoded by the fetch helper. The helper already applied
  4078. * the display bounds (and the JPEG reduced IDCT), so this is a read + copy
  4079. * on the UI thread instead of a decode. */
  4080. static int preload_store_helper(unsigned int node, int bg,
  4081. unsigned char *px, unsigned int pxlen,
  4082. unsigned int dw, unsigned int dh,
  4083. int alpha, unsigned int nw, unsigned int nh,
  4084. const char *url)
  4085. {
  4086. struct br_image *bi;
  4087. unsigned int npx;
  4088. if (image_count >= BR_MAX_IMAGES || !px || !dw || !dh ||
  4089. dw > 4096 || dh > 4096) {
  4090. free(px);
  4091. return -1;
  4092. }
  4093. npx = dw * dh;
  4094. if (image_pixels + npx > BR_IMG_PIXEL_BUDGET ||
  4095. pxlen < npx * 2u + (alpha ? npx : 0)) {
  4096. free(px);
  4097. return -1;
  4098. }
  4099. bi = &images[image_count];
  4100. bi->img.format = 0;
  4101. bi->img.w = dw;
  4102. bi->img.h = dh;
  4103. bi->img.px = (unsigned short *)px;
  4104. bi->img.alpha = alpha ? px + npx * 2u : 0;
  4105. bi->img.flags = 0;
  4106. bi->native_w = nw ? (int)nw : (int)dw;
  4107. bi->native_h = nh ? (int)nh : (int)dh;
  4108. bi->state = 1;
  4109. image_pixels += npx;
  4110. preload_accept_image(node, bg, url);
  4111. return 0;
  4112. }
  4113. static void preload_decode(unsigned int node, int bg,
  4114. const unsigned char *data, unsigned int len,
  4115. const char *url)
  4116. {
  4117. int fit_w = 0, fit_h = 0;
  4118. if (image_count >= BR_MAX_IMAGES) {
  4119. if (bg)
  4120. doc.nodes[node].bg_img_index = -2;
  4121. else
  4122. doc.nodes[node].img_index = -2;
  4123. return;
  4124. }
  4125. if (!bg)
  4126. image_fit_size(node, &fit_w, &fit_h);
  4127. if (decode_image_data(data, len, &images[image_count],
  4128. bg && node < BR_MAX_NODES &&
  4129. layout_boxes[node].valid ? layout_boxes[node].w : 0,
  4130. bg && node < BR_MAX_NODES &&
  4131. layout_boxes[node].valid ? layout_boxes[node].h : 0,
  4132. fit_w, fit_h) == 0) {
  4133. preload_accept_image(node, bg, url);
  4134. } else {
  4135. if (bg)
  4136. doc.nodes[node].bg_img_index = -2;
  4137. else
  4138. doc.nodes[node].img_index = -2;
  4139. layout_valid = 0;
  4140. }
  4141. if (image_preload_visible(node, bg))
  4142. image_repaint();
  4143. }
  4144. /* A local file image bypasses the helpers: count its decode so a page opened
  4145. * from /share or /data still produces the same timing breakdown. */
  4146. static void img_stat_local(int before, unsigned int bytes, unsigned int io_ms)
  4147. {
  4148. img_stat_n++;
  4149. img_stat_bytes += bytes;
  4150. img_stat_io += io_ms;
  4151. if (image_count > before) {
  4152. struct br_image *bi = &images[image_count - 1];
  4153. img_stat_dec += img_last_dec_ms;
  4154. img_stat_scale += img_last_scale_ms;
  4155. if (img_stat_log_len + 100 < sizeof(img_stat_log)) {
  4156. unsigned int n = img_stat_log_len;
  4157. s_append(img_stat_log, &n, "local ", sizeof(img_stat_log));
  4158. s_append_dec(img_stat_log, &n, bytes,
  4159. sizeof(img_stat_log));
  4160. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4161. s_append_dec(img_stat_log, &n, img_last_dec_ms,
  4162. sizeof(img_stat_log));
  4163. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4164. s_append_dec(img_stat_log, &n, img_last_scale_ms,
  4165. sizeof(img_stat_log));
  4166. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4167. s_append_dec(img_stat_log, &n,
  4168. (unsigned int)bi->native_w,
  4169. sizeof(img_stat_log));
  4170. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4171. s_append_dec(img_stat_log, &n,
  4172. (unsigned int)bi->native_h,
  4173. sizeof(img_stat_log));
  4174. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4175. s_append_dec(img_stat_log, &n, bi->img.w,
  4176. sizeof(img_stat_log));
  4177. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4178. s_append_dec(img_stat_log, &n, bi->img.h,
  4179. sizeof(img_stat_log));
  4180. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4181. s_append_dec(img_stat_log, &n,
  4182. bi->img.alpha ? 1u : 0u,
  4183. sizeof(img_stat_log));
  4184. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4185. img_stat_log_len = n;
  4186. }
  4187. }
  4188. }
  4189. /* Harvest one completed worker. Returns 1 when a job was finished. */
  4190. static int preload_finish_worker(struct fetch_worker *w)
  4191. {
  4192. char err[64];
  4193. int rv, tr = 0;
  4194. unsigned int t0, io_ms;
  4195. int before;
  4196. int used_px = 0;
  4197. rv = fetch_worker_poll(w, err, sizeof(err));
  4198. if (rv < 0) {
  4199. /* A helper from an older pack does not understand the image
  4200. * decode request; retry once without it and decode in-process. */
  4201. if (w->image_job && w->dec_w && !w->dec_retried &&
  4202. fetch_worker_submit_req(w, w->url, BR_IMG_FILE_MAX,
  4203. 0, 0, 0, 0, w->node, w->bg,
  4204. 0, 0, err, sizeof(err)) == 0) {
  4205. w->image_job = 1;
  4206. w->dec_retried = 1;
  4207. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4208. return 0;
  4209. }
  4210. preload_job_error(w);
  4211. if (img_stat_log_len + 64 < sizeof(img_stat_log)) {
  4212. unsigned int n = img_stat_log_len;
  4213. char u[48];
  4214. s_copy(u, w->url, sizeof(u));
  4215. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4216. s_append(img_stat_log, &n, " error\n",
  4217. sizeof(img_stat_log));
  4218. img_stat_log_len = n;
  4219. }
  4220. img_stat_n++;
  4221. fetch_worker_release(w);
  4222. return 1;
  4223. }
  4224. if (rv == 0)
  4225. return 0;
  4226. t0 = u_ticks_ms();
  4227. rv = -1;
  4228. before = image_count;
  4229. if (w->m.px_len && !w->m.dec_err && w->m.dw && w->m.dh &&
  4230. w->m.px_len <= 8u * 1024u * 1024u) {
  4231. unsigned char *px = (unsigned char *)malloc(w->m.px_len);
  4232. int pr = -1;
  4233. if (px)
  4234. pr = u_syscall3(SYS_READ_FILE, (int)w->px, (int)px,
  4235. (int)w->m.px_len);
  4236. if (pr == (int)w->m.px_len) {
  4237. if (preload_store_helper(w->node, w->bg, px,
  4238. w->m.px_len, w->m.dw,
  4239. w->m.dh, (int)w->m.alpha,
  4240. w->m.nw, w->m.nh,
  4241. w->url) == 0) {
  4242. rv = (int)w->m.len;
  4243. img_last_dec_ms = w->m.dec_ms;
  4244. img_last_scale_ms = 0;
  4245. used_px = 1;
  4246. } else {
  4247. px = 0; /* the helper freed it */
  4248. }
  4249. }
  4250. if (px && !(pr == (int)w->m.px_len))
  4251. free(px);
  4252. }
  4253. io_ms = u_ticks_ms() - t0;
  4254. if (rv < 0) {
  4255. t0 = u_ticks_ms();
  4256. rv = fetch_worker_read_body(w, image_file_buf, BR_IMG_FILE_MAX,
  4257. image_comp_buf, BR_IMG_FILE_MAX,
  4258. &tr, err, sizeof(err));
  4259. io_ms += u_ticks_ms() - t0;
  4260. before = image_count;
  4261. if (rv >= 0)
  4262. preload_decode(w->node, w->bg, image_file_buf,
  4263. (unsigned int)rv, w->url);
  4264. else
  4265. preload_job_error(w);
  4266. }
  4267. img_stat_n++;
  4268. img_stat_net += w->m.total_ms;
  4269. img_stat_open += w->m.open_ms;
  4270. img_stat_first += w->m.first_ms;
  4271. img_stat_io += io_ms;
  4272. img_stat_bytes += rv > 0 ? (unsigned int)rv : 0;
  4273. img_stat_dec += w->m.dec_ms;
  4274. if (rv >= 0 && !used_px) {
  4275. img_stat_dec += img_last_dec_ms;
  4276. img_stat_scale += img_last_scale_ms;
  4277. }
  4278. if (img_stat_log_len + 160 < sizeof(img_stat_log)) {
  4279. unsigned int n = img_stat_log_len;
  4280. char u[48];
  4281. s_copy(u, w->url, sizeof(u));
  4282. s_append(img_stat_log, &n, u, sizeof(img_stat_log));
  4283. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4284. s_append_dec(img_stat_log, &n,
  4285. rv > 0 ? (unsigned int)rv : 0,
  4286. sizeof(img_stat_log));
  4287. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4288. s_append_dec(img_stat_log, &n, w->m.open_ms,
  4289. sizeof(img_stat_log));
  4290. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4291. s_append_dec(img_stat_log, &n, w->m.first_ms,
  4292. sizeof(img_stat_log));
  4293. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4294. s_append_dec(img_stat_log, &n, w->m.total_ms,
  4295. sizeof(img_stat_log));
  4296. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4297. s_append_dec(img_stat_log, &n, io_ms, sizeof(img_stat_log));
  4298. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4299. s_append_dec(img_stat_log, &n,
  4300. rv >= 0 ? img_last_dec_ms : 0,
  4301. sizeof(img_stat_log));
  4302. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4303. s_append_dec(img_stat_log, &n,
  4304. rv >= 0 ? img_last_scale_ms : 0,
  4305. sizeof(img_stat_log));
  4306. if (image_count > before) {
  4307. struct br_image *bi = &images[image_count - 1];
  4308. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4309. s_append_dec(img_stat_log, &n,
  4310. (unsigned int)bi->native_w,
  4311. sizeof(img_stat_log));
  4312. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4313. s_append_dec(img_stat_log, &n,
  4314. (unsigned int)bi->native_h,
  4315. sizeof(img_stat_log));
  4316. s_append(img_stat_log, &n, " ", sizeof(img_stat_log));
  4317. s_append_dec(img_stat_log, &n, bi->img.w,
  4318. sizeof(img_stat_log));
  4319. s_append(img_stat_log, &n, "x", sizeof(img_stat_log));
  4320. s_append_dec(img_stat_log, &n, bi->img.h,
  4321. sizeof(img_stat_log));
  4322. s_append(img_stat_log, &n, " a", sizeof(img_stat_log));
  4323. s_append_dec(img_stat_log, &n,
  4324. bi->img.alpha ? 1u : 0u,
  4325. sizeof(img_stat_log));
  4326. }
  4327. s_append(img_stat_log, &n, "\n", sizeof(img_stat_log));
  4328. img_stat_log_len = n;
  4329. }
  4330. fetch_worker_release(w);
  4331. return 1;
  4332. }
  4333. /* Fill free workers from the DOM, scanning past ineligible nodes. Returns
  4334. * the number of jobs started. */
  4335. static int preload_fill_jobs(void)
  4336. {
  4337. int started = 0;
  4338. char err[64];
  4339. while (preload_active && preload_node < doc.nnode) {
  4340. unsigned int i = preload_node;
  4341. struct br_node *nd = &doc.nodes[i];
  4342. const char *src;
  4343. char url[BR_URL_MAX];
  4344. struct fetch_worker *w;
  4345. if (preload_active_jobs() >= preload_max_jobs)
  4346. break;
  4347. if (nd->type != BR_NODE_ELEM) {
  4348. preload_node++;
  4349. continue;
  4350. }
  4351. if (nd->tag != BR_TAG_IMG) {
  4352. if (nd->bg_img_index == -1) {
  4353. struct br_style bs;
  4354. style_for_node(i, &bs);
  4355. if (bs.display != BR_DISPLAY_NONE &&
  4356. !bs.vis_hidden && bs.bg_image) {
  4357. const char *bsrc =
  4358. br_bg_image_url(bs.bg_image - 1);
  4359. /* Lazy like <img>: a background box
  4360. * below the viewport (or not laid
  4361. * out yet) waits for the next scan. */
  4362. if (bsrc[0] &&
  4363. (!layout_boxes[i].valid ||
  4364. block_top[i] >
  4365. (unsigned int)(page_scroll.offset +
  4366. page_rect.h + 160))) {
  4367. preload_pending = 1;
  4368. preload_node++;
  4369. continue;
  4370. }
  4371. if (bsrc[0] &&
  4372. !starts_with(bsrc, "data:") &&
  4373. resolve_link(page_url, bsrc, url,
  4374. sizeof(url)) == 0) {
  4375. if (image_count +
  4376. preload_active_jobs() >=
  4377. BR_MAX_IMAGES) {
  4378. preload_node = doc.nnode;
  4379. break;
  4380. }
  4381. if (url[0] == '/') {
  4382. unsigned char *data = 0;
  4383. unsigned int len = 0;
  4384. unsigned int t0;
  4385. int before;
  4386. preload_node = i + 1;
  4387. before = image_count;
  4388. t0 = u_ticks_ms();
  4389. if (fetch_image(url,
  4390. BR_IMG_FILE_MAX,
  4391. &data, &len,
  4392. err,
  4393. sizeof(err)) == 0) {
  4394. preload_decode(i, 1, data, len, 0);
  4395. img_stat_local(before, len,
  4396. u_ticks_ms() - t0);
  4397. } else {
  4398. nd->bg_img_index = -2;
  4399. }
  4400. continue;
  4401. }
  4402. w = fetch_worker_alloc();
  4403. if (!w)
  4404. return started;
  4405. preload_node = i + 1;
  4406. if (fetch_worker_submit(w, url,
  4407. BR_IMG_FILE_MAX,
  4408. 0, 0, i, 1,
  4409. err,
  4410. sizeof(err)) != 0) {
  4411. nd->bg_img_index = -2;
  4412. fetch_worker_release(w);
  4413. continue;
  4414. }
  4415. w->image_job = 1;
  4416. w->deadline = u_ticks_ms() +
  4417. BR_IMG_JOB_TIMEOUT_MS;
  4418. /* in flight: rescans skip it */
  4419. nd->bg_img_index = -3;
  4420. started++;
  4421. continue;
  4422. }
  4423. }
  4424. nd->bg_img_index = -2;
  4425. }
  4426. preload_node++;
  4427. continue;
  4428. }
  4429. if (nd->img_index != -1) {
  4430. preload_node++;
  4431. continue;
  4432. }
  4433. if (ancestor_is(i, BR_TAG_NOSCRIPT) || node_hidden(i)) {
  4434. preload_node++;
  4435. continue;
  4436. }
  4437. src = br_src(&doc, i);
  4438. if (!src[0] || starts_with(src, "data:")) {
  4439. preload_node++;
  4440. continue;
  4441. }
  4442. if (resolve_link(page_url, src, url, sizeof(url)) != 0) {
  4443. preload_node++;
  4444. continue;
  4445. }
  4446. if (image_count + preload_active_jobs() >= BR_MAX_IMAGES) {
  4447. preload_node = doc.nnode;
  4448. break;
  4449. }
  4450. /* Do not stop at the first below-fold image: DOM order is
  4451. * not visual order, and a footer/ad image early in the DOM
  4452. * used to hide every later article image from the loader. */
  4453. if (img_top[i] >
  4454. (unsigned int)(page_scroll.offset + page_rect.h + 160)) {
  4455. preload_pending = 1;
  4456. preload_node++;
  4457. continue;
  4458. }
  4459. {
  4460. unsigned int uh = script_cache_hash(url) | 1u;
  4461. int k;
  4462. for (k = 0; k < image_count; k++)
  4463. if (images[k].state == 1 &&
  4464. images[k].url_hash == uh)
  4465. break;
  4466. if (k < image_count) {
  4467. nd->img_index = (short)k;
  4468. layout_valid = 0;
  4469. preload_node = i + 1;
  4470. image_repaint();
  4471. continue;
  4472. }
  4473. }
  4474. if (url[0] == '/') {
  4475. unsigned char *data = 0;
  4476. unsigned int len = 0;
  4477. unsigned int t0;
  4478. int before;
  4479. preload_node = i + 1;
  4480. before = image_count;
  4481. t0 = u_ticks_ms();
  4482. if (fetch_image(url, BR_IMG_FILE_MAX, &data, &len,
  4483. err, sizeof(err)) == 0) {
  4484. preload_decode(i, 0, data, len, url);
  4485. img_stat_local(before, len, u_ticks_ms() - t0);
  4486. } else {
  4487. nd->img_index = -2;
  4488. }
  4489. continue;
  4490. }
  4491. w = fetch_worker_alloc();
  4492. if (!w)
  4493. return started;
  4494. preload_node = i + 1;
  4495. {
  4496. char msg[64];
  4497. unsigned int n = 0;
  4498. s_append(msg, &n, "Loading images ", sizeof(msg));
  4499. s_append_dec(msg, &n,
  4500. (unsigned int)preload_loaded + 1,
  4501. sizeof(msg));
  4502. s_append(msg, &n, "...", sizeof(msg));
  4503. set_status_quiet(msg);
  4504. image_repaint();
  4505. }
  4506. {
  4507. int fit_w = 0, fit_h = 0;
  4508. image_fit_size(i, &fit_w, &fit_h);
  4509. if (!fit_w)
  4510. fit_w = BR_IMG_LAYOUT_W;
  4511. if (fetch_worker_submit_image(w, url, BR_IMG_FILE_MAX,
  4512. i, 0,
  4513. (unsigned int)fit_w,
  4514. (unsigned int)fit_h,
  4515. err, sizeof(err)) != 0) {
  4516. nd->img_index = -2;
  4517. fetch_worker_release(w);
  4518. continue;
  4519. }
  4520. }
  4521. w->image_job = 1;
  4522. w->deadline = u_ticks_ms() + BR_IMG_JOB_TIMEOUT_MS;
  4523. nd->img_index = -3; /* in flight: rescans skip it */
  4524. started++;
  4525. }
  4526. return started;
  4527. }
  4528. /* Report where the image batch spent its time: status bar for the headline,
  4529. * /share/IMGSTAT for the per-image breakdown (cat it from a terminal). */
  4530. static void img_stats_report(void)
  4531. {
  4532. char msg[80];
  4533. static char out[BR_IMG_STAT_LOG + 512];
  4534. unsigned int n = 0, o = 0;
  4535. if (!img_stat_n)
  4536. return;
  4537. img_stat_wall = img_stat_start ?
  4538. u_ticks_ms() - img_stat_start : 1;
  4539. if (!img_stat_wall)
  4540. img_stat_wall = 1;
  4541. /* Compact on-screen form; /share/IMGSTAT has the full breakdown. */
  4542. s_append(msg, &n, "img ", sizeof(msg));
  4543. s_append_dec(msg, &n, (unsigned int)img_stat_n, sizeof(msg));
  4544. s_append(msg, &n, " ", sizeof(msg));
  4545. s_append_dec(msg, &n, img_stat_wall, sizeof(msg));
  4546. s_append(msg, &n, "ms net ", sizeof(msg));
  4547. s_append_dec(msg, &n, img_stat_net, sizeof(msg));
  4548. s_append(msg, &n, " dec ", sizeof(msg));
  4549. s_append_dec(msg, &n, img_stat_dec, sizeof(msg));
  4550. s_append(msg, &n, " sc ", sizeof(msg));
  4551. s_append_dec(msg, &n, img_stat_scale, sizeof(msg));
  4552. s_append(msg, &n, " paint ", sizeof(msg));
  4553. s_append_dec(msg, &n, img_stat_paint, sizeof(msg));
  4554. /* Keep the page's phase breakdown and append the image summary when
  4555. * it fits; never hide a JS error or a truncation notice. */
  4556. if (!post_status_error && !contains_ci(post_status_text, "truncated")) {
  4557. unsigned int plen = s_len(post_status_text);
  4558. if (!plen) {
  4559. s_copy(post_status_text, msg, sizeof(post_status_text));
  4560. } else if (plen + s_len(msg) + 4 < sizeof(post_status_text)) {
  4561. unsigned int pn = plen;
  4562. s_append(post_status_text, &pn, " | ",
  4563. sizeof(post_status_text));
  4564. s_append(post_status_text, &pn, msg,
  4565. sizeof(post_status_text));
  4566. } else {
  4567. s_copy(post_status_text, msg, sizeof(post_status_text));
  4568. }
  4569. post_status_ttl = 12000;
  4570. }
  4571. s_append(out, &o, "browser image stats\n", sizeof(out));
  4572. s_append(out, &o, "n=", sizeof(out));
  4573. s_append_dec(out, &o, (unsigned int)img_stat_n, sizeof(out));
  4574. s_append(out, &o, " wall=", sizeof(out));
  4575. s_append_dec(out, &o, img_stat_wall, sizeof(out));
  4576. s_append(out, &o, " net=", sizeof(out));
  4577. s_append_dec(out, &o, img_stat_net, sizeof(out));
  4578. s_append(out, &o, " open=", sizeof(out));
  4579. s_append_dec(out, &o, img_stat_open, sizeof(out));
  4580. s_append(out, &o, " first=", sizeof(out));
  4581. s_append_dec(out, &o, img_stat_first, sizeof(out));
  4582. s_append(out, &o, " io=", sizeof(out));
  4583. s_append_dec(out, &o, img_stat_io, sizeof(out));
  4584. s_append(out, &o, " dec=", sizeof(out));
  4585. s_append_dec(out, &o, img_stat_dec, sizeof(out));
  4586. s_append(out, &o, " scale=", sizeof(out));
  4587. s_append_dec(out, &o, img_stat_scale, sizeof(out));
  4588. s_append(out, &o, " paint=", sizeof(out));
  4589. s_append_dec(out, &o, img_stat_paint, sizeof(out));
  4590. s_append(out, &o, " reflow=", sizeof(out));
  4591. s_append_dec(out, &o, img_stat_reflow, sizeof(out));
  4592. s_append(out, &o, " bytes=", sizeof(out));
  4593. s_append_dec(out, &o, img_stat_bytes, sizeof(out));
  4594. s_append(out, &o, "\nurl bytes open first total io dec scale native bitmap\n",
  4595. sizeof(out));
  4596. s_append(out, &o, img_stat_log, sizeof(out));
  4597. u_syscall3(SYS_WRITE_FILE, (int)"/share/IMGSTAT", (int)out,
  4598. (int)s_len(out));
  4599. }
  4600. static void preload_step(void)
  4601. {
  4602. int i;
  4603. unsigned int t0;
  4604. if (!preload_active)
  4605. return;
  4606. if (cancel_fetch || pending_action) {
  4607. preload_active = 0;
  4608. preload_pending = 0;
  4609. fetch_workers_cancel_busy();
  4610. return;
  4611. }
  4612. preload_fill_jobs();
  4613. /* Decode completed images in a short batch instead of one per pass.
  4614. * A pass used to decode one image and then sleep 10 ms, so a page of
  4615. * small icons trickled in at the decode rate. The budget keeps a
  4616. * single huge JPEG from monopolising the UI while small images
  4617. * finish together. */
  4618. t0 = u_ticks_ms();
  4619. for (i = 0; i < FETCH_WORKERS; i++) {
  4620. if (!fetch_workers[i].busy)
  4621. continue;
  4622. if (preload_finish_worker(&fetch_workers[i]) &&
  4623. u_ticks_ms() - t0 >= BR_IMG_DECODE_BUDGET_MS)
  4624. break;
  4625. }
  4626. if (preload_active && preload_node >= doc.nnode &&
  4627. preload_active_jobs() == 0) {
  4628. preload_active = 0;
  4629. if (preload_pending)
  4630. preload_scroll = page_scroll.offset;
  4631. else
  4632. preload_pending = 0;
  4633. /* Keep the now idle helpers and their connections; a later
  4634. * navigation reuses them. They exit after ten idle seconds,
  4635. * and losing window focus stops them at once. */
  4636. if (img_repaint_pending) {
  4637. img_repaint_pending = 0;
  4638. ngui_invalidate(&ui);
  4639. }
  4640. img_stats_report();
  4641. set_status(post_status_text, post_status_error, post_status_ttl);
  4642. ngui_invalidate(&ui);
  4643. }
  4644. }
  4645. /* Set by navigate() when it turned a typed bare host into https://; the next
  4646. * load_page() consumes it and may retry over http. */
  4647. static int nav_https_upgraded;
  4648. /* Errors that mean "https is not served here" rather than "the site is
  4649. * down": a refused/reset/unanswered port 443 or a failed TLS handshake. */
  4650. static int https_fallback_error(int e)
  4651. {
  4652. return e == UHTTP_ERR_REFUSED || e == UHTTP_ERR_TIMEOUT ||
  4653. e == UHTTP_ERR_TLS || e == UHTTP_ERR_CONNECT ||
  4654. e == UHTTP_ERR_RESET;
  4655. }
  4656. static void history_push(const char *url)
  4657. {
  4658. if (!url || !url[0])
  4659. return;
  4660. if (hist_len > 0 && hist_pos >= 0 && hist_pos < hist_len &&
  4661. s_eq(history[hist_pos], url))
  4662. return;
  4663. if (hist_len > 0 && hist_pos + 1 < hist_len)
  4664. hist_len = hist_pos + 1;
  4665. if (hist_len < BR_HISTORY) {
  4666. s_copy(history[hist_len], url, BR_URL_MAX);
  4667. hist_pos = hist_len;
  4668. hist_len++;
  4669. } else {
  4670. int i;
  4671. for (i = 1; i < BR_HISTORY; i++)
  4672. s_copy(history[i - 1], history[i], BR_URL_MAX);
  4673. s_copy(history[BR_HISTORY - 1], url, BR_URL_MAX);
  4674. hist_pos = BR_HISTORY - 1;
  4675. }
  4676. }
  4677. static void load_page(const char *url, int local, int push)
  4678. {
  4679. unsigned char *body = 0;
  4680. unsigned int len = 0;
  4681. int truncated = 0;
  4682. struct img_info image_info;
  4683. char ctype[64];
  4684. char final[BR_URL_MAX];
  4685. char err[80];
  4686. const char *detail = 0;
  4687. const char *post = pending_post_is ? pending_post : 0;
  4688. unsigned int post_len = pending_post_len;
  4689. unsigned int page_open_ms = 0, page_first_ms = 0, page_total_ms = 0;
  4690. /* Phase timings for the status line: where a slow load spends it. */
  4691. unsigned int t_start = u_ticks_ms(), t_fetch = 0, t_parse = 0;
  4692. unsigned int t_css = 0, t_paint = 0, t_js = 0, t_mark;
  4693. int upgraded = nav_https_upgraded;
  4694. int retried = 0;
  4695. int rv;
  4696. nav_https_upgraded = 0;
  4697. final[0] = '\0';
  4698. pending_post_len = 0;
  4699. pending_post_is = 0;
  4700. cancel_fetch = 0;
  4701. preload_active = 0;
  4702. preload_pending = 0;
  4703. fetch_workers_prepare_nav(url);
  4704. js_browser_stop();
  4705. js_last_status[0] = '\0';
  4706. js_last_error = 0;
  4707. heap_clear();
  4708. image_reset();
  4709. form_reset_state();
  4710. layout_valid = 0;
  4711. page_scroll.offset = 0;
  4712. page_scroll.dragging = 0;
  4713. page_title[0] = '\0';
  4714. page_loading = 1;
  4715. page_is_local = local;
  4716. s_copy(page_url, url, sizeof(page_url));
  4717. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4718. url_in.len = s_len(url_in.text);
  4719. url_in.cursor = url_in.len;
  4720. url_in.scroll = 0;
  4721. ngui_set_focus(&ui, 0);
  4722. if (final[0])
  4723. final[0] = '\0';
  4724. if (push)
  4725. history_push(url);
  4726. set_status("Loading...", 0, 0);
  4727. ngui_invalidate(&ui);
  4728. /* heap_clear() detaches the fonts, so attach them again before the
  4729. * first frame or the URL bar flashes in the 8x16 bitmap fallback. */
  4730. if (heap_start() != 0) {
  4731. show_error("Out of memory", "Cannot allocate the page buffer");
  4732. return;
  4733. }
  4734. br_parse_plain(&doc, "", 0); /* blank while loading */
  4735. ngui_font_attach(&ui);
  4736. redraw_now();
  4737. browser_rules_alloc();
  4738. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4739. sizeof(ctype), final, sizeof(final), err, sizeof(err),
  4740. &truncated, post, post_len);
  4741. if (rv != 0 && rv != FETCH_ABORT && !local && !retried &&
  4742. fetch_last_error == UHTTP_ERR_DNS) {
  4743. /* A busy previous page can leave the receiver ring full just
  4744. * long enough to lose a DNS reply. Tear the old helpers down
  4745. * and try once more before giving up. */
  4746. retried = 1;
  4747. fetch_workers_stop_all();
  4748. u_sleep_ms(500);
  4749. rv = read_url(url, BR_PAGE_MAX, &body, &len, &local, ctype,
  4750. sizeof(ctype), final, sizeof(final), err,
  4751. sizeof(err), &truncated, post, post_len);
  4752. }
  4753. if (rv == FETCH_ABORT)
  4754. return;
  4755. t_fetch = u_ticks_ms() - t_start;
  4756. /* Capture the page timing before CSS/script/image fetches overwrite the
  4757. * shared fetch_meta block. */
  4758. if (rv == 0 && !local) {
  4759. page_open_ms = fetch_meta.open_ms;
  4760. page_first_ms = fetch_meta.first_ms;
  4761. page_total_ms = fetch_meta.total_ms;
  4762. }
  4763. if (rv != 0 && upgraded && !local && starts_with(url, "https://") &&
  4764. https_fallback_error(fetch_last_error)) {
  4765. char http_url[BR_URL_MAX];
  4766. unsigned int n = 0;
  4767. s_append(http_url, &n, "http://", sizeof(http_url));
  4768. s_append(http_url, &n, url + 8, sizeof(http_url));
  4769. /* Replace the https entry instead of adding a second one. */
  4770. if (push && hist_pos >= 0 && hist_pos < hist_len &&
  4771. s_eq(history[hist_pos], url))
  4772. s_copy(history[hist_pos], http_url, BR_URL_MAX);
  4773. load_page(http_url, 0, 0);
  4774. return;
  4775. }
  4776. if (rv != 0) {
  4777. detail = err;
  4778. show_error("Cannot load this page", detail);
  4779. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4780. url_in.len = s_len(url_in.text);
  4781. url_in.cursor = url_in.len;
  4782. url_in.scroll = 0;
  4783. return;
  4784. }
  4785. if (!local)
  4786. origin_cache_learn(url, final[0] ? final : url);
  4787. page_is_local = local;
  4788. if (final[0]) {
  4789. s_copy(page_url, final, sizeof(page_url));
  4790. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4791. url_in.len = s_len(url_in.text);
  4792. url_in.cursor = url_in.len;
  4793. url_in.scroll = 0;
  4794. }
  4795. if (contains_ci(ctype, "text/plain")) {
  4796. br_parse_plain(&doc, (const char *)body, len);
  4797. } else if (contains_ci(ctype, "image/") ||
  4798. (!contains_ci(ctype, "text/html") &&
  4799. img_sniff(body, len, &image_info) == 0)) {
  4800. unsigned int node = br_parse_image_doc(&doc, page_url);
  4801. if (node)
  4802. decode_direct_image(body, len, node);
  4803. s_copy(page_title, "Image", sizeof(page_title));
  4804. } else {
  4805. br_set_viewport(ui.w);
  4806. t_mark = u_ticks_ms();
  4807. br_parse(&doc, (const char *)body, len);
  4808. t_parse = u_ticks_ms() - t_mark;
  4809. s_copy(page_title, doc.title[0] ? doc.title : page_url,
  4810. sizeof(page_title));
  4811. t_mark = u_ticks_ms();
  4812. if (load_stylesheets() == FETCH_ABORT)
  4813. return;
  4814. t_css = u_ticks_ms() - t_mark;
  4815. if (pending_action)
  4816. return;
  4817. }
  4818. preload_begin();
  4819. page_loading = 0;
  4820. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4821. url_in.len = s_len(url_in.text);
  4822. url_in.cursor = url_in.len;
  4823. url_in.scroll = 0;
  4824. ngui_set_focus(&ui, 0);
  4825. /* Paint the parsed page before fetching/running scripts. A slow
  4826. * remote <script src> then does not hide the page behind the loading
  4827. * screen; the fetch helper pumps this UI while it waits. */
  4828. set_status("Loading scripts...", 0, 0);
  4829. t_mark = u_ticks_ms();
  4830. redraw_now();
  4831. t_paint = u_ticks_ms() - t_mark;
  4832. /* Start one image download before the scripts. The other workers
  4833. * fetch the external script bodies in parallel, and the remaining
  4834. * images start as soon as the script phase ends. */
  4835. preload_max_jobs = 1;
  4836. preload_fill_jobs();
  4837. preload_wait = 0;
  4838. t_mark = u_ticks_ms();
  4839. run_page_scripts();
  4840. t_js = u_ticks_ms() - t_mark;
  4841. preload_max_jobs = FETCH_WORKERS;
  4842. if (pending_action)
  4843. return;
  4844. post_status_text[0] = '\0';
  4845. post_status_error = 0;
  4846. post_status_ttl = 0;
  4847. if (js_last_status[0]) {
  4848. s_copy(post_status_text, js_last_status,
  4849. sizeof(post_status_text));
  4850. post_status_error = js_last_error;
  4851. post_status_ttl = 8000;
  4852. } else if (truncated) {
  4853. s_copy(post_status_text, "Page truncated at the buffer limit",
  4854. sizeof(post_status_text));
  4855. post_status_ttl = 6000;
  4856. } else if (doc.truncated) {
  4857. s_copy(post_status_text, "Page truncated by the parser",
  4858. sizeof(post_status_text));
  4859. post_status_ttl = 6000;
  4860. } else if (page_total_ms) {
  4861. /* "Loaded in 2410 ms: page 84 (headers 69), parse 40, css 310,
  4862. * paint 220, js 1750" -- the phases of this load. */
  4863. unsigned int n = 0;
  4864. static const char *const names[] = {
  4865. ", parse ", ", css ", ", paint ", ", js "
  4866. };
  4867. unsigned int vals[4];
  4868. int k;
  4869. vals[0] = t_parse;
  4870. vals[1] = t_css;
  4871. vals[2] = t_paint;
  4872. vals[3] = t_js;
  4873. (void)page_first_ms;
  4874. if (starts_with(page_url, "https://"))
  4875. s_append(post_status_text, &n,
  4876. "HTTPS (not verified), ",
  4877. sizeof(post_status_text));
  4878. s_append(post_status_text, &n, "Loaded in ",
  4879. sizeof(post_status_text));
  4880. s_append_dec(post_status_text, &n, u_ticks_ms() - t_start,
  4881. sizeof(post_status_text));
  4882. s_append(post_status_text, &n, " ms: page ",
  4883. sizeof(post_status_text));
  4884. s_append_dec(post_status_text, &n, t_fetch,
  4885. sizeof(post_status_text));
  4886. s_append(post_status_text, &n, " (headers ",
  4887. sizeof(post_status_text));
  4888. s_append_dec(post_status_text, &n, page_open_ms,
  4889. sizeof(post_status_text));
  4890. s_append(post_status_text, &n, ")", sizeof(post_status_text));
  4891. for (k = 0; k < 4; k++) {
  4892. s_append(post_status_text, &n, names[k],
  4893. sizeof(post_status_text));
  4894. s_append_dec(post_status_text, &n, vals[k],
  4895. sizeof(post_status_text));
  4896. }
  4897. post_status_ttl = 12000;
  4898. } else if (starts_with(page_url, "https://")) {
  4899. s_copy(post_status_text, "HTTPS: certificate NOT verified",
  4900. sizeof(post_status_text));
  4901. post_status_ttl = 6000;
  4902. }
  4903. set_status(post_status_text, post_status_error, post_status_ttl);
  4904. ngui_invalidate(&ui);
  4905. }
  4906. static void load_home(int push)
  4907. {
  4908. pending_post_len = 0;
  4909. pending_post_is = 0;
  4910. cancel_fetch = 0;
  4911. preload_active = 0;
  4912. preload_pending = 0;
  4913. js_browser_stop();
  4914. js_last_status[0] = '\0';
  4915. js_last_error = 0;
  4916. heap_clear();
  4917. image_reset();
  4918. form_reset_state();
  4919. layout_valid = 0;
  4920. page_scroll.offset = 0;
  4921. page_scroll.dragging = 0;
  4922. page_loading = 1;
  4923. page_is_local = 0;
  4924. s_copy(page_url, "about:home", sizeof(page_url));
  4925. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4926. url_in.len = s_len(url_in.text);
  4927. url_in.cursor = url_in.len;
  4928. url_in.scroll = 0;
  4929. ngui_set_focus(&ui, 0);
  4930. if (push)
  4931. history_push(page_url);
  4932. ngui_invalidate(&ui);
  4933. /* See load_page(): reattach the fonts before the first redraw. */
  4934. if (heap_start() != 0) {
  4935. show_error("Out of memory", "Cannot allocate the browser heap");
  4936. return;
  4937. }
  4938. br_parse_plain(&doc, "", 0);
  4939. ngui_font_attach(&ui);
  4940. redraw_now();
  4941. browser_rules_alloc();
  4942. {
  4943. static const char home[] =
  4944. "<html><head><title>NebOS Browser</title><style>"
  4945. "body { margin: 10px; color: #e4e6f0; }"
  4946. "h1 { color: #7fb0ff; }"
  4947. ".box { background-color: #262b3a; margin: 12px; "
  4948. "padding: 10px; }"
  4949. "a { color: #7fb0ff; }"
  4950. "pre { background-color: #32384a; }"
  4951. "</style></head><body>"
  4952. "<h1>NebOS Browser</h1>"
  4953. "<p>A small HTML/CSS browser built on <b>ngui</b>, the "
  4954. "shared HTTP client and the image library.</p>"
  4955. "<div class=\"box\"><b>Try:</b>"
  4956. "<ul><li><a href=\"/floppy1/DEMO.HTM\">/"
  4957. "floppy1/DEMO.HTM</a> on the root floppy</li>"
  4958. "<li><a href=\"/floppy1/JS.HTM\">/"
  4959. "floppy1/JS.HTM</a> inline JavaScript demo</li>"
  4960. "<li><a href=\"http://10.0.2.2:8000/\">"
  4961. "http://10.0.2.2:8000/</a> on the QEMU host</li>"
  4962. "<li><a href=\"https://example.com/\">"
  4963. "https://example.com/</a> (TLS, not verified)</li>"
  4964. "</ul></div>"
  4965. "<p>Type a URL in the bar above. Esc closes the "
  4966. "window, Ctrl+L focuses the address bar.</p>"
  4967. "<pre>javascript: inline + external scripts (limited DOM)\nforms: not supported"
  4968. "\nimages: PNG JPEG GIF BMP TGA PNM ICO</pre>"
  4969. "</body></html>";
  4970. br_set_viewport(ui.w);
  4971. br_parse(&doc, home, sizeof(home) - 1);
  4972. br_parse_inline_css(&doc);
  4973. br_reset_styles(&doc);
  4974. s_copy(page_title, doc.title, sizeof(page_title));
  4975. }
  4976. post_status_text[0] = '\0';
  4977. post_status_error = 0;
  4978. post_status_ttl = 0;
  4979. page_loading = 0;
  4980. set_status("", 0, 0);
  4981. s_copy(url_in.text, page_url, NGUI_INPUT_MAX);
  4982. url_in.len = s_len(url_in.text);
  4983. url_in.cursor = url_in.len;
  4984. url_in.scroll = 0;
  4985. ngui_set_focus(&ui, 0);
  4986. ngui_invalidate(&ui);
  4987. }
  4988. /* Extensions the browser opens from the local filesystem. A dotted input
  4989. * with one of these still resolves relative to the cwd. */
  4990. static int local_file_ext(const char *s)
  4991. {
  4992. static const char *const exts[] = {
  4993. "htm", "html", "txt", "text", "md", "css", "js", "json", "xml",
  4994. "png", "jpg", "jpeg", "gif", "bmp", "tga", "ppm", "pgm", "pbm",
  4995. "ico", "cur", "pam", "svg", "elf", "bin", "ttf", "log", "ini",
  4996. "cfg", "conf", 0
  4997. };
  4998. unsigned int i = 0, start = 0, len = 0, e;
  4999. while (s[i] && s[i] != '/' && s[i] != ':' && s[i] != '?' &&
  5000. s[i] != '#') {
  5001. if (s[i] == '.') {
  5002. start = i + 1;
  5003. len = 0;
  5004. } else if (start) {
  5005. len++;
  5006. }
  5007. i++;
  5008. }
  5009. if (!len)
  5010. return 0;
  5011. for (e = 0; exts[e]; e++) {
  5012. const char *x = exts[e];
  5013. unsigned int xn = s_len(x), k;
  5014. if (xn != len)
  5015. continue;
  5016. for (k = 0; k < len; k++) {
  5017. char a = s[start + k];
  5018. if (a >= 'A' && a <= 'Z')
  5019. a = (char)(a - 'A' + 'a');
  5020. if (a != x[k])
  5021. break;
  5022. }
  5023. if (k == len)
  5024. return 1;
  5025. }
  5026. return 0;
  5027. }
  5028. /* A dotted first component (cloudron.io) is a hostname, not a local file.
  5029. * Skipping the VFS stat keeps a slow FAT/floppy lookup off the path from
  5030. * Enter to the first network request. */
  5031. static int looks_like_host(const char *s)
  5032. {
  5033. unsigned int i = 0;
  5034. int dot = 0;
  5035. while (s[i] && s[i] != '/' && s[i] != '?' && s[i] != '#' &&
  5036. s[i] != ':') {
  5037. char c = s[i];
  5038. if (c == '.') {
  5039. dot = 1;
  5040. } else if (!((c >= 'a' && c <= 'z') ||
  5041. (c >= 'A' && c <= 'Z') ||
  5042. (c >= '0' && c <= '9') ||
  5043. c == '-' || c == '_')) {
  5044. return 0;
  5045. }
  5046. i++;
  5047. }
  5048. return dot && i > 0 && !local_file_ext(s);
  5049. }
  5050. static void load_remote(const char *url, int push)
  5051. {
  5052. char canon[BR_URL_MAX];
  5053. s_copy(canon, url, sizeof(canon));
  5054. origin_cache_apply(canon, sizeof(canon));
  5055. load_page(canon, 0, push);
  5056. }
  5057. static void navigate(const char *input, int push)
  5058. {
  5059. char target[BR_URL_MAX];
  5060. char *t;
  5061. if (!input)
  5062. return;
  5063. s_copy(target, input, sizeof(target));
  5064. t = trim(target);
  5065. if (!t[0])
  5066. return;
  5067. if (s_eq(t, "about:home")) {
  5068. load_home(push);
  5069. return;
  5070. }
  5071. if (starts_with(t, "file://")) {
  5072. make_abs_local(t + 7, target, sizeof(target));
  5073. load_page(target, 1, push);
  5074. return;
  5075. }
  5076. if (is_http(t)) {
  5077. load_remote(t, push);
  5078. return;
  5079. }
  5080. if (t[0] == '/') {
  5081. make_abs_local(t, target, sizeof(target));
  5082. load_page(target, 1, push);
  5083. return;
  5084. }
  5085. if (!looks_like_host(t)) {
  5086. struct sys_stat st;
  5087. if (u_stat(t, &st) == 0 && !st.is_dir) {
  5088. make_abs_local(t, target, sizeof(target));
  5089. load_page(target, 1, push);
  5090. return;
  5091. }
  5092. }
  5093. {
  5094. /* A typed bare host tries https first: nearly every site
  5095. * redirects http -> https anyway, and that hop costs a whole
  5096. * extra connection. load_page() falls back to http when the
  5097. * https connection itself fails. */
  5098. char with_scheme[BR_URL_MAX];
  5099. unsigned int n = 0;
  5100. s_append(with_scheme, &n, "https://", sizeof(with_scheme));
  5101. s_append(with_scheme, &n, t, sizeof(with_scheme));
  5102. nav_https_upgraded = 1;
  5103. load_remote(with_scheme, push);
  5104. }
  5105. }
  5106. /* ---- layout ---- */
  5107. static struct ufont_face *style_face(const struct br_style *st)
  5108. {
  5109. if (st && st->font_face && st->font_face <= BR_MAX_FACES)
  5110. return font_faces[st->font_face - 1];
  5111. return 0;
  5112. }
  5113. static struct ufont_face *run_face(const struct lay_run *r)
  5114. {
  5115. if (r->font_face && r->font_face <= BR_MAX_FACES)
  5116. return font_faces[r->font_face - 1];
  5117. return 0;
  5118. }
  5119. static unsigned int face_text_width(struct ngui *gui,
  5120. const struct br_style *st,
  5121. const char *s, unsigned int n)
  5122. {
  5123. return ngui_text_width_face(gui, style_face(st), s, n, st->font_px,
  5124. st->bold, st->italic, st->mono);
  5125. }
  5126. static int face_line_height(struct ngui *gui, const struct br_style *st)
  5127. {
  5128. return ngui_text_line_height_face(gui, style_face(st), st->font_px,
  5129. st->mono);
  5130. }
  5131. static unsigned int run_text_width(struct ngui *gui,
  5132. const struct lay_run *r,
  5133. const char *s, unsigned int n)
  5134. {
  5135. return ngui_text_width_face(gui, run_face(r), s, n, r->font_px,
  5136. r->bold, r->italic, r->mono);
  5137. }
  5138. static int run_line_height(struct ngui *gui, const struct lay_run *r)
  5139. {
  5140. return ngui_text_line_height_face(gui, run_face(r), r->font_px,
  5141. r->mono);
  5142. }
  5143. static int run_ascent(struct ngui *gui, const struct lay_run *r)
  5144. {
  5145. return ngui_text_ascent_face(gui, run_face(r), r->font_px, r->mono);
  5146. }
  5147. static struct br_style base_style(void)
  5148. {
  5149. struct br_style s = { 0 };
  5150. s.color = ui.theme.text;
  5151. s.bg = ui.theme.bg;
  5152. s.has_bg = 0;
  5153. for (int i = 0; i < 4; i++) {
  5154. s.border_c[i] = 0;
  5155. s.border_w[i] = 0;
  5156. s.border_s[i] = BR_BORDER_SOLID;
  5157. }
  5158. s.font_px = 16;
  5159. s.bold = 0;
  5160. s.italic = 0;
  5161. s.mono = 0;
  5162. s.underline = 0;
  5163. s.strike = 0;
  5164. s.overline = 0;
  5165. s.align = BR_ALIGN_LEFT;
  5166. s.display = BR_DISPLAY_BLOCK;
  5167. s.no_bullet = 0;
  5168. s.list_style = BR_LIST_AUTO;
  5169. s.uppercase = 0;
  5170. s.width_kind = s.max_width_kind = s.min_width_kind = 0;
  5171. s.height_kind = s.min_height_kind = s.max_height_kind = 0;
  5172. s.width = s.max_width = s.min_width = 0;
  5173. s.height = s.min_height = s.max_height = 0;
  5174. s.box_sizing = 0;
  5175. s.ml_auto = s.mr_auto = 0;
  5176. s.line_h_pct = 0;
  5177. s.line_h_px = 0;
  5178. s.mt = s.mb = s.ml = s.mr = 0;
  5179. s.pt = s.pb = s.pl = s.pr = 0;
  5180. return s;
  5181. }
  5182. /* Resolve a margin/padding raw value. Percentages use the containing
  5183. * block width for all four sides, as CSS specifies. */
  5184. static int css_mp_px(const struct br_style *st, int v, int unit, int base)
  5185. {
  5186. if (unit == 1)
  5187. return base * v / 10000;
  5188. if (unit == 2)
  5189. return st->font_px * v / 100;
  5190. if (unit == 3)
  5191. return (int)br_root_font_px() * v / 100;
  5192. if (unit == 4)
  5193. return 0;
  5194. return v;
  5195. }
  5196. static int mp_px(const struct br_style *st, int side, int base)
  5197. {
  5198. int raw;
  5199. switch (side) {
  5200. case 0: raw = st->mt; break;
  5201. case 1: raw = st->mr; break;
  5202. case 2: raw = st->mb; break;
  5203. case 3: raw = st->ml; break;
  5204. case 4: raw = st->pt; break;
  5205. case 5: raw = st->pr; break;
  5206. case 6: raw = st->pb; break;
  5207. default: raw = st->pl; break;
  5208. }
  5209. if (st->mp_unit[side] == 5)
  5210. return base * raw / 100 + st->mp_calc_px[side];
  5211. return css_mp_px(st, raw, st->mp_unit[side], base);
  5212. }
  5213. static int style_width_px(const struct br_style *st, int base)
  5214. {
  5215. if (st->width_kind == 1)
  5216. return st->width;
  5217. if (st->width_kind == 2)
  5218. return base * (int)st->width / 100;
  5219. if (st->width_kind == 3)
  5220. return base * st->width_calc_pct / 100 + st->width_calc_px;
  5221. return 0;
  5222. }
  5223. static int style_height_px(const struct br_style *st, int base)
  5224. {
  5225. if (st->height_kind == 1)
  5226. return st->height;
  5227. if (st->height_kind == 2)
  5228. return base * (int)st->height / 100;
  5229. if (st->height_kind == 3)
  5230. return base * st->height_calc_pct / 100 + st->height_calc_px;
  5231. return 0;
  5232. }
  5233. static int css_size(unsigned char kind, int val, int base)
  5234. {
  5235. if (kind == 1)
  5236. return val;
  5237. if (kind == 2)
  5238. return base * val / 100;
  5239. return -1;
  5240. }
  5241. static void draw_border_side(struct ngui *ui, int x, int y, int len,
  5242. int thick, int horizontal, unsigned short color,
  5243. unsigned char style)
  5244. {
  5245. int pos;
  5246. if (len <= 0 || thick <= 0)
  5247. return;
  5248. if (style != BR_BORDER_DASHED && style != BR_BORDER_DOTTED) {
  5249. if (horizontal)
  5250. ngui_fill_rect(ui, (struct ngui_rect){
  5251. x, y, len, thick}, color);
  5252. else
  5253. ngui_fill_rect(ui, (struct ngui_rect){
  5254. x, y, thick, len}, color);
  5255. return;
  5256. }
  5257. for (pos = 0; pos < len; pos += style == BR_BORDER_DASHED ? 7 : 5) {
  5258. int seg = len - pos;
  5259. if (seg > (style == BR_BORDER_DASHED ? 4 : 2))
  5260. seg = style == BR_BORDER_DASHED ? 4 : 2;
  5261. if (horizontal)
  5262. ngui_fill_rect(ui, (struct ngui_rect){
  5263. x + pos, y, seg, thick}, color);
  5264. else
  5265. ngui_fill_rect(ui, (struct ngui_rect){
  5266. x, y + pos, thick, seg}, color);
  5267. }
  5268. }
  5269. static void draw_border_box(struct ngui *ui, struct ngui_rect r,
  5270. const struct br_style *st)
  5271. {
  5272. int top = st->border_w[0], right = st->border_w[1];
  5273. int bottom = st->border_w[2], left = st->border_w[3];
  5274. if (r.w <= 0 || r.h <= 0)
  5275. return;
  5276. if (top >= r.h || bottom >= r.h || left >= r.w || right >= r.w) {
  5277. int i;
  5278. for (i = 0; i < 4; i++)
  5279. if (st->border_w[i] && !st->border_t[i]) {
  5280. ngui_fill_rect(ui, r, st->border_c[i]);
  5281. break;
  5282. }
  5283. return;
  5284. }
  5285. if (top && !st->border_t[0])
  5286. draw_border_side(ui, r.x, r.y, r.w, top, 1,
  5287. st->border_c[0], st->border_s[0]);
  5288. if (bottom && !st->border_t[2])
  5289. draw_border_side(ui, r.x, r.y + r.h - bottom, r.w, bottom, 1,
  5290. st->border_c[2], st->border_s[2]);
  5291. if (left && !st->border_t[3])
  5292. draw_border_side(ui, r.x, r.y + top, r.h - top - bottom,
  5293. left, 0, st->border_c[3], st->border_s[3]);
  5294. if (right && !st->border_t[1])
  5295. draw_border_side(ui, r.x + r.w - right, r.y + top,
  5296. r.h - top - bottom, right, 0,
  5297. st->border_c[1], st->border_s[1]);
  5298. }
  5299. static void transform_origin(const struct br_style *st, int w, int h,
  5300. int *ox, int *oy)
  5301. {
  5302. *ox = st->origin_x_kind ? w * st->origin_x / 100 : st->origin_x;
  5303. *oy = st->origin_y_kind ? h * st->origin_y / 100 : st->origin_y;
  5304. }
  5305. static unsigned short blend_rgb565(unsigned short d, unsigned short s,
  5306. unsigned int a)
  5307. {
  5308. unsigned int dr, dg, db, sr, sg, sb;
  5309. if (a >= 255)
  5310. return s;
  5311. dr = (d >> 11) & 31;
  5312. dg = (d >> 5) & 63;
  5313. db = d & 31;
  5314. sr = (s >> 11) & 31;
  5315. sg = (s >> 5) & 63;
  5316. sb = s & 31;
  5317. dr = (dr * (255 - a) + sr * a) / 255;
  5318. dg = (dg * (255 - a) + sg * a) / 255;
  5319. db = (db * (255 - a) + sb * a) / 255;
  5320. return (unsigned short)((dr << 11) | (dg << 5) | db);
  5321. }
  5322. /* Paint a solid box through scale()/rotate() around transform-origin. This
  5323. * transforms the element's own background box; text and descendants keep
  5324. * their layout (documented approximation). */
  5325. static void fill_transformed_rect(struct ngui *gui, struct ngui_rect box,
  5326. unsigned short color,
  5327. const struct br_style *st)
  5328. {
  5329. double sx = st->scale_x / 100.0;
  5330. double sy = st->scale_y / 100.0;
  5331. double th = st->rotate_x100 / 100.0 * 3.14159265358979 / 180.0;
  5332. double c = cos(th), sn = sin(th);
  5333. int ox, oy, minx, miny, maxx, maxy, x, y;
  5334. double ax, ay;
  5335. double px[4], py[4];
  5336. int cx1, cy1, cx2, cy2, i;
  5337. if (sx == 0)
  5338. sx = 0.01;
  5339. if (sy == 0)
  5340. sy = 0.01;
  5341. transform_origin(st, box.w, box.h, &ox, &oy);
  5342. ax = box.x + ox;
  5343. ay = box.y + oy;
  5344. px[0] = -ox; py[0] = -oy;
  5345. px[1] = box.w - ox; py[1] = -oy;
  5346. px[2] = box.w - ox; py[2] = box.h - oy;
  5347. px[3] = -ox; py[3] = box.h - oy;
  5348. minx = miny = 1000000;
  5349. maxx = maxy = -1000000;
  5350. for (i = 0; i < 4; i++) {
  5351. double rx = (px[i] * sx) * c - (py[i] * sy) * sn;
  5352. double ry = (px[i] * sx) * sn + (py[i] * sy) * c;
  5353. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5354. if (dx < minx) minx = dx;
  5355. if (dx > maxx) maxx = dx;
  5356. if (dy < miny) miny = dy;
  5357. if (dy > maxy) maxy = dy;
  5358. }
  5359. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5360. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5361. cx2 = page_rect.x + page_rect.w - 12;
  5362. cy2 = page_rect.y + page_rect.h;
  5363. if (cx2 > gui->w) cx2 = gui->w;
  5364. if (cy2 > gui->h) cy2 = gui->h;
  5365. if (minx < cx1) minx = cx1;
  5366. if (miny < cy1) miny = cy1;
  5367. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5368. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5369. for (y = miny; y <= maxy; y++) {
  5370. for (x = minx; x <= maxx; x++) {
  5371. double dx = x + 0.5 - ax, dy = y + 0.5 - ay;
  5372. double rx = dx * c + dy * sn;
  5373. double ry = -dx * sn + dy * c;
  5374. double bx = rx / sx + ox;
  5375. double by = ry / sy + oy;
  5376. if (bx >= 0 && bx < box.w && by >= 0 && by < box.h)
  5377. gui->px[y * gui->w + x] = color;
  5378. }
  5379. }
  5380. }
  5381. static void draw_image_transformed(struct ngui *gui,
  5382. const struct img_image *im,
  5383. int x, int y, int w, int h,
  5384. int sx100, int sy100, int rot100,
  5385. int origin_x, int origin_y,
  5386. int origin_x_kind, int origin_y_kind)
  5387. {
  5388. double sx = sx100 / 100.0, sy = sy100 / 100.0;
  5389. double th = rot100 / 100.0 * 3.14159265358979 / 180.0;
  5390. double c = cos(th), sn = sin(th);
  5391. int ox, oy, minx, miny, maxx, maxy, px, py, i;
  5392. double ax, ay;
  5393. double bx[4], by[4];
  5394. int cx1, cy1, cx2, cy2;
  5395. if (!im || !im->px || w <= 0 || h <= 0 || sx == 0 || sy == 0)
  5396. return;
  5397. ox = origin_x_kind ? w * origin_x / 100 : origin_x;
  5398. oy = origin_y_kind ? h * origin_y / 100 : origin_y;
  5399. ax = x + ox;
  5400. ay = y + oy;
  5401. bx[0] = -ox; by[0] = -oy;
  5402. bx[1] = w - ox; by[1] = -oy;
  5403. bx[2] = w - ox; by[2] = h - oy;
  5404. bx[3] = -ox; by[3] = h - oy;
  5405. minx = miny = 1000000;
  5406. maxx = maxy = -1000000;
  5407. for (i = 0; i < 4; i++) {
  5408. double rx = (bx[i] * sx) * c - (by[i] * sy) * sn;
  5409. double ry = (bx[i] * sx) * sn + (by[i] * sy) * c;
  5410. int dx = (int)(ax + rx), dy = (int)(ay + ry);
  5411. if (dx < minx) minx = dx;
  5412. if (dx > maxx) maxx = dx;
  5413. if (dy < miny) miny = dy;
  5414. if (dy > maxy) maxy = dy;
  5415. }
  5416. cx1 = page_rect.x > 0 ? page_rect.x : 0;
  5417. cy1 = page_rect.y > 0 ? page_rect.y : 0;
  5418. cx2 = page_rect.x + page_rect.w - 12;
  5419. cy2 = page_rect.y + page_rect.h;
  5420. if (cx2 > gui->w) cx2 = gui->w;
  5421. if (cy2 > gui->h) cy2 = gui->h;
  5422. if (minx < cx1) minx = cx1;
  5423. if (miny < cy1) miny = cy1;
  5424. if (maxx > cx2 - 1) maxx = cx2 - 1;
  5425. if (maxy > cy2 - 1) maxy = cy2 - 1;
  5426. for (py = miny; py <= maxy; py++) {
  5427. for (px = minx; px <= maxx; px++) {
  5428. double dx = px + 0.5 - ax, dy = py + 0.5 - ay;
  5429. double rx = dx * c + dy * sn;
  5430. double ry = -dx * sn + dy * c;
  5431. double fx = rx / sx + ox;
  5432. double fy = ry / sy + oy;
  5433. int ix, iy;
  5434. unsigned int si, a;
  5435. unsigned short src;
  5436. if (fx < 0 || fx >= w || fy < 0 || fy >= h)
  5437. continue;
  5438. ix = (int)(fx * (double)im->w / w);
  5439. iy = (int)(fy * (double)im->h / h);
  5440. if (ix < 0 || ix >= (int)im->w ||
  5441. iy < 0 || iy >= (int)im->h)
  5442. continue;
  5443. si = (unsigned int)iy * im->w + (unsigned int)ix;
  5444. src = im->px[si];
  5445. a = im->alpha ? im->alpha[si] : 255;
  5446. gui->px[py * gui->w + px] =
  5447. a >= 255 ? src :
  5448. blend_rgb565(gui->px[py * gui->w + px],
  5449. src, a);
  5450. }
  5451. }
  5452. }
  5453. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5454. unsigned int node, const struct br_style *st);
  5455. /* draw_bg_image() clipped to rounded corners: the corner squares are saved
  5456. * first and every pixel outside a corner's arc is restored afterwards. */
  5457. #define BG_ROUND_MAX 64
  5458. static unsigned short bg_round_save[4][BG_ROUND_MAX * BG_ROUND_MAX];
  5459. static void draw_bg_image_round(struct lay *l, struct ngui_rect box,
  5460. unsigned int node, const struct br_style *st,
  5461. int rtl, int rtr, int rbr, int rbl)
  5462. {
  5463. struct ngui *ui = l->ui;
  5464. struct ngui_rect clip = { 0, 0, ui->w, ui->h };
  5465. int r[4] = { rtl, rtr, rbr, rbl }, c, dx, dy;
  5466. if (ui->nclip > 0)
  5467. clip = ui->clip[ui->nclip - 1];
  5468. for (c = 0; c < 4; c++) {
  5469. if (r[c] > BG_ROUND_MAX)
  5470. r[c] = BG_ROUND_MAX;
  5471. if (r[c] > box.w / 2)
  5472. r[c] = box.w / 2;
  5473. if (r[c] > box.h / 2)
  5474. r[c] = box.h / 2;
  5475. }
  5476. for (c = 0; c < 4; c++) {
  5477. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5478. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5479. for (dy = 0; dy < r[c]; dy++)
  5480. for (dx = 0; dx < r[c]; dx++) {
  5481. int px = ox + dx, py = oy + dy;
  5482. if (px >= clip.x && py >= clip.y &&
  5483. px < clip.x + clip.w && py < clip.y + clip.h)
  5484. bg_round_save[c][dy * BG_ROUND_MAX + dx] =
  5485. ui->px[py * ui->w + px];
  5486. }
  5487. }
  5488. draw_bg_image(l, box, node, st);
  5489. for (c = 0; c < 4; c++) {
  5490. int ox = (c == 1 || c == 2) ? box.x + box.w - r[c] : box.x;
  5491. int oy = (c >= 2) ? box.y + box.h - r[c] : box.y;
  5492. /* arc centre, in corner-square coordinates */
  5493. int cx = (c == 1 || c == 2) ? 0 : r[c];
  5494. int cy = (c >= 2) ? 0 : r[c];
  5495. for (dy = 0; dy < r[c]; dy++)
  5496. for (dx = 0; dx < r[c]; dx++) {
  5497. int px = ox + dx, py = oy + dy;
  5498. int ex = 2 * dx + 1 - 2 * cx, ey = 2 * dy + 1 - 2 * cy;
  5499. if (ex * ex + ey * ey <= 4 * r[c] * r[c])
  5500. continue;
  5501. if (px >= clip.x && py >= clip.y &&
  5502. px < clip.x + clip.w && py < clip.y + clip.h)
  5503. ui->px[py * ui->w + px] =
  5504. bg_round_save[c][dy * BG_ROUND_MAX + dx];
  5505. }
  5506. }
  5507. }
  5508. static void draw_bg_image(struct lay *l, struct ngui_rect box,
  5509. unsigned int node, const struct br_style *st)
  5510. {
  5511. struct br_image *bi;
  5512. struct img_blit b;
  5513. int tw, th, x, y, rep_x, rep_y, posx, posy;
  5514. unsigned int scale = 65536;
  5515. int legacy, tiles = 0, rows = 0;
  5516. int cx1, cy1, cx2, cy2;
  5517. if (!st->bg_image || box.w <= 0 || box.h <= 0)
  5518. return;
  5519. if (doc.nodes[node].bg_img_index < 0 ||
  5520. doc.nodes[node].bg_img_index >= image_count)
  5521. return;
  5522. bi = &images[doc.nodes[node].bg_img_index];
  5523. if (bi->state != 1 || bi->img.w <= 0 || bi->img.h <= 0)
  5524. return;
  5525. legacy = st->bg_size_kind == 0 && st->bg_repeat == 0 &&
  5526. st->bg_pos_x_kind == 0 && st->bg_pos_x == 0 &&
  5527. st->bg_pos_y_kind == 0 && st->bg_pos_y == 0;
  5528. if (legacy) {
  5529. scale = ((unsigned int)box.w << 16) / bi->img.w;
  5530. tw = box.w;
  5531. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5532. x = box.x;
  5533. y = box.y;
  5534. rep_x = rep_y = 0;
  5535. } else {
  5536. if (st->bg_size_kind == 3 || st->bg_size_kind == 4) {
  5537. unsigned int sx = ((unsigned int)box.w << 16) /
  5538. bi->img.w;
  5539. unsigned int sy = ((unsigned int)box.h << 16) /
  5540. bi->img.h;
  5541. scale = st->bg_size_kind == 3 ?
  5542. (sx > sy ? sx : sy) : (sx < sy ? sx : sy);
  5543. } else if (st->bg_size_kind == 1 ||
  5544. st->bg_size_kind == 2) {
  5545. int w = st->bg_size_w;
  5546. int h = st->bg_size_h;
  5547. if (st->bg_size_kind == 2) {
  5548. if (w)
  5549. w = box.w * w / 100;
  5550. if (h)
  5551. h = box.h * h / 100;
  5552. }
  5553. if (w)
  5554. scale = ((unsigned int)w << 16) / bi->img.w;
  5555. else if (h)
  5556. scale = ((unsigned int)h << 16) / bi->img.h;
  5557. }
  5558. tw = (int)(((unsigned int)bi->img.w * scale) >> 16);
  5559. th = (int)(((unsigned int)bi->img.h * scale) >> 16);
  5560. if (tw < 1)
  5561. tw = 1;
  5562. if (th < 1)
  5563. th = 1;
  5564. posx = st->bg_pos_x_kind == 1 ?
  5565. (box.w - tw) * st->bg_pos_x / 100 : st->bg_pos_x;
  5566. posy = st->bg_pos_y_kind == 1 ?
  5567. (box.h - th) * st->bg_pos_y / 100 : st->bg_pos_y;
  5568. x = box.x + posx;
  5569. y = box.y + posy;
  5570. rep_x = st->bg_repeat == 0 || st->bg_repeat == 2;
  5571. rep_y = st->bg_repeat == 0 || st->bg_repeat == 3;
  5572. if (rep_x) {
  5573. int m = (x - box.x) % tw;
  5574. if (m > 0)
  5575. m -= tw;
  5576. x = box.x + m;
  5577. }
  5578. if (rep_y) {
  5579. int m = (y - box.y) % th;
  5580. if (m > 0)
  5581. m -= th;
  5582. y = box.y + m;
  5583. }
  5584. }
  5585. cx1 = box.x > page_rect.x ? box.x : page_rect.x;
  5586. cy1 = box.y > page_rect.y ? box.y : page_rect.y;
  5587. cx2 = box.x + box.w;
  5588. cy2 = box.y + box.h;
  5589. if (cx2 > page_rect.x + page_rect.w - 12)
  5590. cx2 = page_rect.x + page_rect.w - 12;
  5591. if (cy2 > page_rect.y + page_rect.h)
  5592. cy2 = page_rect.y + page_rect.h;
  5593. if (cx1 >= cx2 || cy1 >= cy2)
  5594. return;
  5595. b.dst = l->ui->px;
  5596. b.dst_w = l->ui->w;
  5597. b.dst_h = l->ui->h;
  5598. b.clip_x = cx1;
  5599. b.clip_y = cy1;
  5600. b.clip_w = cx2 - cx1;
  5601. b.clip_h = cy2 - cy1;
  5602. b.bg = ui.theme.bg;
  5603. b.bg2 = ui.theme.bg;
  5604. b.dst_a = 0;
  5605. {
  5606. struct img_image *src = image_display_get(bi, tw, th);
  5607. int row_x;
  5608. if (!src)
  5609. src = &bi->img;
  5610. b.scale = ((unsigned int)tw << 16) / src->w;
  5611. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  5612. row_x = x;
  5613. for (;;) {
  5614. for (;;) {
  5615. b.x = x;
  5616. b.y = y;
  5617. img_draw(src, &b);
  5618. if (!rep_x || ++tiles > 512)
  5619. break;
  5620. x += tw;
  5621. if (x >= box.x + box.w)
  5622. break;
  5623. }
  5624. if (!rep_y || ++rows > 64)
  5625. break;
  5626. y += th;
  5627. if (y >= box.y + box.h)
  5628. break;
  5629. x = row_x;
  5630. }
  5631. }
  5632. }
  5633. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  5634. int *out_w, int *out_h);
  5635. static void svg_paint_box(struct ngui *ui, unsigned int node,
  5636. const struct br_style *st, int x, int y, int w,
  5637. int h);
  5638. /* Run kinds besides text: img >= 0 an <img> bitmap, -2 a button label,
  5639. * RUN_SVG an inline <svg> icon (its node in off). */
  5640. #define RUN_SVG (-3)
  5641. static int run_width(const struct lay_run *r)
  5642. {
  5643. if (r->img >= 0)
  5644. return r->iw;
  5645. if (r->img == -2 || r->img == RUN_SVG)
  5646. return r->iw;
  5647. return (int)r->w;
  5648. }
  5649. static void start_line(struct lay *l, const struct br_style *st)
  5650. {
  5651. (void)st;
  5652. if (l->nruns == 0) {
  5653. l->line_y = l->y;
  5654. l->line_h = 0;
  5655. }
  5656. l->line_left = l->left;
  5657. l->line_right = l->right;
  5658. if (l->float_active && l->line_y < l->float_bottom) {
  5659. if (l->float_left > l->line_left)
  5660. l->line_left = l->float_left;
  5661. if (l->float_right < l->line_right)
  5662. l->line_right = l->float_right;
  5663. }
  5664. if (l->line_right < l->line_left + 8)
  5665. l->line_right = l->line_left + 8;
  5666. l->line_x = l->line_left;
  5667. l->run_x = l->line_left;
  5668. }
  5669. static void flush_line(struct lay *l)
  5670. {
  5671. int total, x, i, vis;
  5672. if (!l->nruns && l->line_x == l->line_left) {
  5673. l->line_h = 0;
  5674. return;
  5675. }
  5676. total = l->line_x - l->line_left;
  5677. x = l->line_left;
  5678. vis = 1;
  5679. if (l->draw) {
  5680. int lh = l->line_h ? l->line_h : 16;
  5681. vis = l->line_y + lh >= page_rect.y &&
  5682. l->line_y <= page_rect.y + page_rect.h;
  5683. }
  5684. if (l->align == BR_ALIGN_CENTER)
  5685. x += (l->line_right - l->line_left - total) / 2;
  5686. else if (l->align == BR_ALIGN_RIGHT)
  5687. x = l->line_right - total;
  5688. if (x < l->line_left)
  5689. x = l->line_left;
  5690. for (i = 0; i < l->nruns; i++) {
  5691. struct lay_run *r = &l->runs[i];
  5692. int w = run_width(r);
  5693. int ry = l->line_y + r->dy;
  5694. x += r->gap;
  5695. if (l->draw && vis) {
  5696. if (r->form) {
  5697. unsigned int node = r->form - 1;
  5698. struct form_state *fs = form_get(node, 1);
  5699. int hh = r->ih ? r->ih : 20;
  5700. int focused = form_focus == node;
  5701. int disabled = r->form_disabled;
  5702. unsigned short bg = l->ui->theme.panel_alt;
  5703. unsigned short fg = disabled ? 0x8410 : r->color;
  5704. struct ngui_rect box = {x, ry, w, hh};
  5705. if (r->form_kind == FORM_CHECKBOX ||
  5706. r->form_kind == FORM_RADIO) {
  5707. ngui_fill_rect(l->ui, box, bg);
  5708. ngui_frame(l->ui, box,
  5709. focused ? l->ui->theme.accent :
  5710. l->ui->theme.border);
  5711. if (fs && fs->checked) {
  5712. struct ngui_rect dot = {
  5713. x + 4, ry + 4,
  5714. w > 8 ? w - 8 : 1,
  5715. hh > 8 ? hh - 8 : 1
  5716. };
  5717. if (r->form_kind == FORM_RADIO)
  5718. ngui_fill_round_rect(
  5719. l->ui, dot, 4,
  5720. 4, 4, 4,
  5721. l->ui->theme.accent);
  5722. else
  5723. ngui_fill_rect(l->ui,
  5724. dot,
  5725. l->ui->theme.accent);
  5726. }
  5727. } else {
  5728. int editable =
  5729. r->form_kind == FORM_TEXT ||
  5730. r->form_kind == FORM_PASSWORD ||
  5731. r->form_kind == FORM_TEXTAREA;
  5732. int scroll = 0;
  5733. /* Editable fields draw the live value
  5734. * (r->lit is a short copy). */
  5735. static char shown[FORM_VALUE_MAX + 1];
  5736. const char *txt = r->lit;
  5737. unsigned int tl = s_len(r->lit);
  5738. if (editable && fs && fs->len) {
  5739. unsigned int k;
  5740. if (r->form_kind == FORM_PASSWORD) {
  5741. for (k = 0; k < fs->len; k++)
  5742. shown[k] = '*';
  5743. shown[k] = '\0';
  5744. txt = shown;
  5745. } else {
  5746. txt = fs->value;
  5747. }
  5748. tl = fs->len;
  5749. }
  5750. /* The box is drawn in theme colours, so
  5751. * the text is too: the page's CSS colour
  5752. * (dark on a light page) would vanish on
  5753. * the dark field. */
  5754. if (!disabled)
  5755. fg = editable && fs && !fs->len ?
  5756. l->ui->theme.text_dim :
  5757. l->ui->theme.text;
  5758. ngui_fill_rect(l->ui, box, bg);
  5759. ngui_frame(l->ui, box,
  5760. focused ? l->ui->theme.accent :
  5761. l->ui->theme.border);
  5762. /* A value wider than the field shows its
  5763. * tail (where typing happens). */
  5764. if (editable && fs && fs->len && w > 12) {
  5765. int tw = (int)run_text_width(l->ui,
  5766. r, txt, tl);
  5767. if (tw > w - 12)
  5768. scroll = tw - (w - 12);
  5769. }
  5770. ngui_push_clip(l->ui, (struct ngui_rect){
  5771. x + 1, ry + 1,
  5772. w > 2 ? w - 2 : 1,
  5773. hh > 2 ? hh - 2 : 1 });
  5774. ngui_text_px_face(l->ui, run_face(r),
  5775. x + 6 - scroll,
  5776. ry + (hh - r->font_px) / 2 - 1,
  5777. txt, tl, fg, r->font_px,
  5778. r->bold, r->italic, r->mono);
  5779. if (focused && fs && editable) {
  5780. int cw = 0;
  5781. if (fs->len && fs->caret)
  5782. cw = (int)run_text_width(
  5783. l->ui, r, txt,
  5784. fs->caret < fs->len ?
  5785. fs->caret : fs->len);
  5786. ngui_fill_rect(l->ui,
  5787. (struct ngui_rect){
  5788. x + 6 + cw - scroll,
  5789. ry + 4, 1,
  5790. hh > 8 ? hh - 8 : 1
  5791. },
  5792. l->ui->theme.accent);
  5793. }
  5794. ngui_pop_clip(l->ui);
  5795. if (r->form_kind == FORM_SELECT) {
  5796. ngui_text_px(l->ui, x + w - 12,
  5797. ry + 2, "v", 1, fg,
  5798. r->font_px, 0, 0, 0);
  5799. }
  5800. }
  5801. } else if (r->img == RUN_SVG) {
  5802. struct br_style sst;
  5803. style_for_node(r->off, &sst);
  5804. svg_paint_box(l->ui, r->off, &sst, x, ry, w,
  5805. r->ih);
  5806. } else if (r->img == -2) {
  5807. int hh = r->ih ? r->ih : 20;
  5808. ngui_fill_rect(l->ui,
  5809. (struct ngui_rect){x, ry, w, hh},
  5810. l->ui->theme.panel_alt);
  5811. ngui_frame(l->ui,
  5812. (struct ngui_rect){x, ry, w, hh},
  5813. l->ui->theme.border);
  5814. ngui_text_px_face(l->ui, run_face(r),
  5815. x + 6, ry + 2, r->lit,
  5816. s_len(r->lit), r->color,
  5817. r->font_px, r->bold, r->italic,
  5818. r->mono);
  5819. } else if (r->img >= 0) {
  5820. struct br_image *bi = &images[r->img];
  5821. if (bi->state == 1 && r->transform_scale) {
  5822. draw_image_transformed(l->ui, &bi->img,
  5823. x, ry, r->iw, r->ih,
  5824. r->scale_x, r->scale_y,
  5825. r->rotate_x100, r->origin_x,
  5826. r->origin_y, r->origin_x_kind,
  5827. r->origin_y_kind);
  5828. } else if (bi->state == 1) {
  5829. struct img_image *src =
  5830. image_display_get(bi, r->iw, r->ih);
  5831. struct img_blit b;
  5832. if (!src)
  5833. src = &bi->img;
  5834. b.dst = l->ui->px;
  5835. b.dst_w = l->ui->w;
  5836. b.dst_h = l->ui->h;
  5837. b.clip_x = page_rect.x;
  5838. b.clip_y = page_rect.y;
  5839. b.clip_w = page_rect.w - 12;
  5840. b.clip_h = page_rect.h;
  5841. b.x = x;
  5842. b.y = ry;
  5843. b.scale = ((unsigned int)r->iw << 16) /
  5844. src->w;
  5845. b.bg = ui.theme.bg;
  5846. b.bg2 = ui.theme.bg;
  5847. b.dst_a = 0;
  5848. b.flags = src->alpha ?
  5849. IMG_BLIT_OVER_DST : 0;
  5850. img_draw(src, &b);
  5851. }
  5852. } else {
  5853. const char *s = r->has_lit ? r->lit :
  5854. doc.text + r->off;
  5855. unsigned int n = r->has_lit ? s_len(r->lit) :
  5856. r->len;
  5857. ngui_text_px_face(l->ui, run_face(r), x, ry,
  5858. s, n, r->color, r->font_px,
  5859. r->bold, r->italic, r->mono);
  5860. if (r->underline)
  5861. ngui_fill_rect(l->ui,
  5862. (struct ngui_rect){x,
  5863. ry + run_ascent(l->ui, r) + 2,
  5864. w, 1}, r->color);
  5865. if (r->strike)
  5866. ngui_fill_rect(l->ui,
  5867. (struct ngui_rect){x,
  5868. ry + run_ascent(l->ui, r) -
  5869. (r->font_px > 3 ?
  5870. r->font_px / 3 : 1),
  5871. w, 1}, r->color);
  5872. if (r->overline)
  5873. ngui_fill_rect(l->ui,
  5874. (struct ngui_rect){x, ry,
  5875. w, 1}, r->color);
  5876. }
  5877. if (r->form || r->href) {
  5878. if (nhits < HIT_MAX) {
  5879. struct hit *h = &hits[nhits];
  5880. unsigned int target = r->form ?
  5881. r->form - 1 : r->href;
  5882. int hh = (r->form || r->img >= 0 ||
  5883. r->img == RUN_SVG) ?
  5884. r->ih :
  5885. run_line_height(l->ui, r);
  5886. int merge = nhits > 0 &&
  5887. hits[nhits - 1].node == target &&
  5888. hits[nhits - 1].y == ry &&
  5889. hits[nhits - 1].h == hh &&
  5890. x <= hits[nhits - 1].x +
  5891. hits[nhits - 1].w + 2;
  5892. if (merge) {
  5893. struct hit *p = &hits[nhits - 1];
  5894. int end = x + w;
  5895. if (end > p->x + p->w)
  5896. p->w = end - p->x;
  5897. } else {
  5898. h->x = x;
  5899. h->y = ry;
  5900. h->w = w;
  5901. h->h = hh;
  5902. h->node = (unsigned short)target;
  5903. nhits++;
  5904. }
  5905. }
  5906. }
  5907. }
  5908. x += w;
  5909. }
  5910. l->y += l->line_h + 2;
  5911. if (l->float_active && l->y >= l->float_bottom)
  5912. l->float_active = 0;
  5913. l->nruns = 0;
  5914. l->line_x = l->left;
  5915. l->run_x = l->left;
  5916. l->line_left = l->left;
  5917. l->line_right = l->right;
  5918. l->line_h = 0;
  5919. l->space_pending = 0;
  5920. }
  5921. static void add_run(struct lay *l, unsigned int off, unsigned short len,
  5922. const struct br_style *st, unsigned short href,
  5923. const char *lit)
  5924. {
  5925. unsigned int n = lit ? s_len(lit) : len;
  5926. const char *tp = lit ? lit : doc.text + off;
  5927. int w = (int)face_text_width(l->ui, st, tp, n);
  5928. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  5929. flush_line(l);
  5930. if (l->nruns == 0) {
  5931. l->line_y = l->y;
  5932. l->line_h = 0;
  5933. start_line(l, st);
  5934. }
  5935. {
  5936. struct lay_run *r = &l->runs[l->nruns++];
  5937. int gap = l->line_x - l->run_x;
  5938. if (gap < 0)
  5939. gap = 0;
  5940. r->gap = (unsigned short)gap;
  5941. r->off = off;
  5942. r->len = len;
  5943. r->color = st->color;
  5944. r->href = href;
  5945. r->dy = 0;
  5946. r->has_lit = 0;
  5947. r->form = 0;
  5948. r->form_kind = 0;
  5949. r->form_disabled = 0;
  5950. r->lit[0] = '\0';
  5951. if (lit && lit[0]) {
  5952. unsigned int i;
  5953. for (i = 0; i + 1 < sizeof(r->lit) && lit[i]; i++)
  5954. r->lit[i] = lit[i];
  5955. r->lit[i] = '\0';
  5956. r->has_lit = 1;
  5957. }
  5958. r->img = -1;
  5959. r->iw = r->ih = 0;
  5960. r->font_px = st->font_px;
  5961. r->bold = st->bold;
  5962. r->italic = st->italic;
  5963. r->mono = st->mono;
  5964. r->font_face = st->font_face;
  5965. /* A control with its own background is a button, not body copy;
  5966. * an inherited link underline would strike through the fill. */
  5967. r->underline = st->underline && !st->has_bg;
  5968. r->strike = st->strike && !st->has_bg;
  5969. r->overline = st->overline && !st->has_bg;
  5970. r->w = (unsigned short)w;
  5971. if (r->has_lit)
  5972. r->w = (unsigned short)run_text_width(
  5973. l->ui, r, r->lit, s_len(r->lit));
  5974. w = r->w;
  5975. }
  5976. l->line_x += w;
  5977. l->run_x = l->line_x;
  5978. {
  5979. int lh = face_line_height(l->ui, st);
  5980. if (st->line_h_px)
  5981. lh = st->line_h_px;
  5982. else if (st->line_h_pct)
  5983. lh = st->font_px * st->line_h_pct / 100;
  5984. if (lh < face_line_height(l->ui, st))
  5985. lh = face_line_height(l->ui, st);
  5986. if (l->line_h < lh)
  5987. l->line_h = lh;
  5988. }
  5989. }
  5990. static void add_image_run(struct lay *l, unsigned int node,
  5991. const struct br_style *st, unsigned short href)
  5992. {
  5993. struct br_image *bi = 0;
  5994. int idx = doc.nodes[node].img_index;
  5995. int dw, dh, maxw;
  5996. if (idx >= 0 && idx < image_count && images[idx].state == 1)
  5997. bi = &images[idx];
  5998. if (l->nruns == 0)
  5999. start_line(l, st);
  6000. if (l->space_pending &&
  6001. (l->nruns > 0 || l->line_x > l->line_left)) {
  6002. int sp = (int)face_text_width(l->ui, st, " ", 1);
  6003. if (l->line_x + sp <= l->line_right)
  6004. l->line_x += sp;
  6005. }
  6006. l->space_pending = 0;
  6007. if (!bi) {
  6008. const char *alt = br_alt(&doc, node);
  6009. struct br_style gs = *st;
  6010. char tmp[96];
  6011. unsigned int n = 0;
  6012. int w;
  6013. gs.color = BR_GRAY;
  6014. gs.underline = 0;
  6015. s_append(tmp, &n, "[", sizeof(tmp));
  6016. s_append(tmp, &n, alt[0] ? alt : "image", sizeof(tmp));
  6017. s_append(tmp, &n, "]", sizeof(tmp));
  6018. w = (int)face_text_width(l->ui, &gs, tmp, n);
  6019. if (l->line_x + w > l->line_right &&
  6020. (l->nruns > 0 || l->line_x > l->line_left))
  6021. flush_line(l);
  6022. add_run(l, 0, 0, &gs, href, tmp);
  6023. if (!l->draw) {
  6024. int t = l->line_y < 0 ? 0 : l->line_y;
  6025. int hh = face_line_height(l->ui, &gs);
  6026. if (t > 65535)
  6027. t = 65535;
  6028. if (hh > 65535)
  6029. hh = 65535;
  6030. img_top[node] = (unsigned short)t;
  6031. img_h[node] = (unsigned short)hh;
  6032. }
  6033. return;
  6034. }
  6035. maxw = l->line_right - l->line_left;
  6036. if (maxw < 8)
  6037. maxw = 8;
  6038. {
  6039. int iw = bi->native_w, ih = bi->native_h;
  6040. int have_w = 0, have_h = 0, css_w = 0, css_h = 0;
  6041. if (iw <= 0 || ih <= 0) {
  6042. iw = (int)bi->img.w;
  6043. ih = (int)bi->img.h;
  6044. }
  6045. dw = iw;
  6046. dh = ih;
  6047. if (doc.nodes[node].width_attr) {
  6048. int want = doc.nodes[node].width_attr;
  6049. dw = doc.nodes[node].width_pct ? maxw * want / 100 : want;
  6050. have_w = 1;
  6051. }
  6052. if (doc.nodes[node].height_attr) {
  6053. int want = doc.nodes[node].height_attr;
  6054. dh = doc.nodes[node].height_pct ? maxw * want / 100 : want;
  6055. have_h = 1;
  6056. }
  6057. if (have_w && !have_h)
  6058. dh = ih ? ih * dw / iw : 0;
  6059. if (have_h && !have_w)
  6060. dw = iw ? iw * dh / ih : 0;
  6061. if (st->width_kind) {
  6062. css_w = 1;
  6063. if (st->width_kind == 3)
  6064. dw = maxw * st->width_calc_pct / 100 +
  6065. st->width_calc_px;
  6066. else
  6067. dw = st->width_kind == 2 ?
  6068. maxw * (int)st->width / 100 :
  6069. (int)st->width;
  6070. }
  6071. if (st->height_kind) {
  6072. css_h = 1;
  6073. if (st->height_kind == 3)
  6074. dh = maxw * st->height_calc_pct / 100 +
  6075. st->height_calc_px;
  6076. else
  6077. dh = st->height_kind == 2 ?
  6078. maxw * (int)st->height / 100 :
  6079. (int)st->height;
  6080. }
  6081. if (css_w && !css_h)
  6082. dh = ih ? ih * dw / iw : 0;
  6083. if (css_h && !css_w)
  6084. dw = iw ? iw * dh / ih : 0;
  6085. if (st->max_width_kind) {
  6086. int mw = st->max_width_kind == 3 ?
  6087. maxw * st->max_width_calc_pct / 100 +
  6088. st->max_width_calc_px :
  6089. st->max_width_kind == 2 ?
  6090. maxw * (int)st->max_width / 100 :
  6091. (int)st->max_width;
  6092. if (mw > 0 && dw > mw) {
  6093. dh = iw ? ih * mw / iw : 0;
  6094. dw = mw;
  6095. }
  6096. }
  6097. }
  6098. if (dw < 8)
  6099. dw = 8;
  6100. if (dh < 8)
  6101. dh = 8;
  6102. if (dw > maxw) {
  6103. dh = dw ? dh * maxw / dw : dh;
  6104. dw = maxw;
  6105. }
  6106. if (!l->draw) {
  6107. int t = l->line_y < 0 ? 0 : l->line_y;
  6108. if (t > 65535)
  6109. t = 65535;
  6110. if (dh > 65535)
  6111. dh = 65535;
  6112. img_top[node] = (unsigned short)t;
  6113. img_h[node] = (unsigned short)dh;
  6114. }
  6115. if (l->line_x + dw > l->line_right && (l->nruns > 0 ||
  6116. l->line_x > l->line_left))
  6117. flush_line(l);
  6118. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6119. flush_line(l);
  6120. if (l->nruns == 0) {
  6121. l->line_y = l->y;
  6122. l->line_h = 0;
  6123. start_line(l, st);
  6124. }
  6125. {
  6126. struct lay_run *r = &l->runs[l->nruns++];
  6127. int gap = l->line_x - l->run_x;
  6128. if (gap < 0)
  6129. gap = 0;
  6130. r->gap = (unsigned short)gap;
  6131. r->off = 0;
  6132. r->len = 0;
  6133. r->color = 0;
  6134. r->href = href;
  6135. r->form = 0;
  6136. r->form_kind = 0;
  6137. r->form_disabled = 0;
  6138. /* Inline replaced elements honour their vertical margins; this
  6139. * is how Bootstrap's negative logo margins centre the wordmark. */
  6140. {
  6141. int idy = mp_px(st, 0, l->right - l->left);
  6142. if (idy < -2048)
  6143. idy = -2048;
  6144. if (idy > 2048)
  6145. idy = 2048;
  6146. r->dy = (signed short)idy;
  6147. }
  6148. r->has_lit = 0;
  6149. r->lit[0] = '\0';
  6150. r->img = (short)idx;
  6151. r->iw = (unsigned short)dw;
  6152. r->ih = (unsigned short)dh;
  6153. r->w = (unsigned short)dw;
  6154. r->font_px = st->font_px;
  6155. r->bold = st->bold;
  6156. r->italic = st->italic;
  6157. r->mono = st->mono;
  6158. r->font_face = st->font_face;
  6159. r->transform_scale = st->transform_scale;
  6160. r->scale_x = st->scale_x;
  6161. r->scale_y = st->scale_y;
  6162. r->rotate_x100 = st->rotate_x100;
  6163. r->origin_x = st->origin_x;
  6164. r->origin_y = st->origin_y;
  6165. r->origin_x_kind = st->origin_x_kind;
  6166. r->origin_y_kind = st->origin_y_kind;
  6167. r->underline = 0;
  6168. }
  6169. if (node < BR_MAX_NODES) {
  6170. layout_boxes[node].x = l->line_x;
  6171. layout_boxes[node].y = l->line_y +
  6172. mp_px(st, 0, l->right - l->left);
  6173. layout_boxes[node].w = dw;
  6174. layout_boxes[node].h = dh;
  6175. layout_boxes[node].valid = 1;
  6176. }
  6177. l->line_x += dw;
  6178. l->run_x = l->line_x;
  6179. if (l->line_h < dh)
  6180. l->line_h = dh;
  6181. }
  6182. /* An inline (or inline-block) <svg> is a replaced element in the text
  6183. * line, like an <img>: comment bubbles and arrows sit next to their label
  6184. * instead of starting a block of their own. */
  6185. static void add_svg_run(struct lay *l, unsigned int node,
  6186. const struct br_style *st, unsigned short href)
  6187. {
  6188. struct lay_run *r;
  6189. int lw = l->line_right - l->line_left, cw, dw, dh, ml, mr;
  6190. if (lw < 8)
  6191. lw = 8;
  6192. cw = st->width_kind ? style_width_px(st, lw) : lw;
  6193. if (cw < 1)
  6194. cw = 1;
  6195. svg_size(node, st, cw, &dw, &dh);
  6196. if (dw > lw)
  6197. dw = lw;
  6198. ml = mp_px(st, 3, lw);
  6199. mr = mp_px(st, 1, lw);
  6200. if (ml < 0)
  6201. ml = 0;
  6202. if (mr < 0)
  6203. mr = 0;
  6204. if (l->line_x + ml + dw > l->line_right &&
  6205. (l->nruns > 0 || l->line_x > l->line_left))
  6206. flush_line(l);
  6207. if (l->nruns >= (int)(sizeof(l->runs) / sizeof(l->runs[0])))
  6208. flush_line(l);
  6209. if (l->nruns == 0) {
  6210. l->line_y = l->y;
  6211. l->line_h = 0;
  6212. start_line(l, st);
  6213. }
  6214. l->line_x += ml;
  6215. r = &l->runs[l->nruns++];
  6216. memset(r, 0, sizeof(*r));
  6217. r->gap = (unsigned short)(l->line_x > l->run_x ?
  6218. l->line_x - l->run_x : 0);
  6219. r->off = node;
  6220. r->color = st->color;
  6221. r->href = href;
  6222. r->img = RUN_SVG;
  6223. r->iw = (unsigned short)dw;
  6224. r->ih = (unsigned short)dh;
  6225. r->w = (unsigned short)dw;
  6226. r->font_px = st->font_px;
  6227. if (node < BR_MAX_NODES) {
  6228. layout_boxes[node].x = l->line_x;
  6229. layout_boxes[node].y = l->line_y;
  6230. layout_boxes[node].w = dw;
  6231. layout_boxes[node].h = dh;
  6232. layout_boxes[node].valid = 1;
  6233. }
  6234. l->line_x += dw + mr;
  6235. l->run_x = l->line_x;
  6236. if (l->line_h < dh)
  6237. l->line_h = dh;
  6238. }
  6239. static int text_width(struct lay *l, const char *s, unsigned int n,
  6240. const struct br_style *st)
  6241. {
  6242. return (int)face_text_width(l->ui, st, s, n);
  6243. }
  6244. /* Longest prefix that fits in maxw, at least one byte. */
  6245. static unsigned int fit_prefix(struct lay *l, const char *s, unsigned int n,
  6246. const struct br_style *st, int maxw)
  6247. {
  6248. unsigned int take = 0;
  6249. while (take < n) {
  6250. if (text_width(l, s, take + 1, st) > maxw)
  6251. break;
  6252. take++;
  6253. }
  6254. return take ? take : 1;
  6255. }
  6256. static void emit_word(struct lay *l, const char *s, unsigned int start,
  6257. unsigned int n, unsigned int base,
  6258. const struct br_style *st, unsigned short href)
  6259. {
  6260. int avail;
  6261. int w = text_width(l, s + start, n, st);
  6262. unsigned int off = start;
  6263. if (l->nruns == 0)
  6264. start_line(l, st);
  6265. avail = l->line_right - l->line_left;
  6266. if (st->nowrap) {
  6267. if (n)
  6268. add_run(l, base + start,
  6269. (unsigned short)n, st, href, 0);
  6270. return;
  6271. }
  6272. /* A padded/bordered one-word button can be a few pixels wider than
  6273. * the content box; keep it on one line instead of splitting it. */
  6274. if (l->nruns == 0 && st->has_bg && w > avail && w <= avail + 8) {
  6275. add_run(l, base + start,
  6276. (unsigned short)n, st, href, 0);
  6277. return;
  6278. }
  6279. if (l->line_x + w > l->line_right &&
  6280. (l->nruns > 0 || l->line_x > l->line_left)) {
  6281. flush_line(l);
  6282. start_line(l, st);
  6283. avail = l->line_right - l->line_left;
  6284. }
  6285. if (w <= avail) {
  6286. if (n)
  6287. add_run(l, base + start,
  6288. (unsigned short)n, st, href, 0);
  6289. return;
  6290. }
  6291. while (n > 0) {
  6292. unsigned int take = fit_prefix(l, s + off, n, st, avail);
  6293. add_run(l, base + off,
  6294. (unsigned short)take, st, href, 0);
  6295. off += take;
  6296. n -= take;
  6297. if (n) {
  6298. flush_line(l);
  6299. start_line(l, st);
  6300. avail = l->line_right - l->line_left;
  6301. }
  6302. }
  6303. }
  6304. static void emit_text(struct lay *l, const char *s, unsigned int len,
  6305. const struct br_style *st, unsigned short href, int pre)
  6306. {
  6307. unsigned int i = 0;
  6308. unsigned int base;
  6309. int space_w = (int)face_text_width(l->ui, st, " ", 1);
  6310. if (!s || !len)
  6311. return;
  6312. if (space_w <= 0)
  6313. space_w = 8;
  6314. if (l->nruns == 0)
  6315. start_line(l, st);
  6316. base = (unsigned int)(s - doc.text);
  6317. if (st->uppercase) {
  6318. char *p = (char *)s;
  6319. unsigned int j;
  6320. for (j = 0; j < len; j++)
  6321. if (p[j] >= 'a' && p[j] <= 'z')
  6322. p[j] = (char)(p[j] - 'a' + 'A');
  6323. }
  6324. if (pre) {
  6325. while (i < len) {
  6326. unsigned int start;
  6327. if (s[i] == '\n') {
  6328. flush_line(l);
  6329. start_line(l, st);
  6330. i++;
  6331. continue;
  6332. }
  6333. if (s[i] == ' ') {
  6334. if (l->line_x + space_w > l->line_right &&
  6335. (l->nruns > 0 || l->line_x > l->line_left)) {
  6336. flush_line(l);
  6337. start_line(l, st);
  6338. } else {
  6339. l->line_x += space_w;
  6340. }
  6341. i++;
  6342. continue;
  6343. }
  6344. start = i;
  6345. while (i < len && s[i] != ' ' && s[i] != '\n')
  6346. i++;
  6347. emit_word(l, s, start, i - start, base, st, href);
  6348. }
  6349. return;
  6350. }
  6351. while (i < len) {
  6352. unsigned int start, n;
  6353. if (s[i] == ' ') {
  6354. l->space_pending = 1;
  6355. i++;
  6356. continue;
  6357. }
  6358. start = i;
  6359. while (i < len && s[i] != ' ')
  6360. i++;
  6361. n = i - start;
  6362. if (l->space_pending &&
  6363. (l->nruns > 0 || l->line_x > l->line_left)) {
  6364. if (st->nowrap ||
  6365. l->line_x + space_w <= l->line_right)
  6366. l->line_x += space_w;
  6367. }
  6368. l->space_pending = 0;
  6369. emit_word(l, s, start, n, base, st, href);
  6370. }
  6371. }
  6372. static int list_index(unsigned int parent, unsigned int node)
  6373. {
  6374. unsigned int n = 0, i;
  6375. for (i = doc.nodes[parent].first; i && i != node;
  6376. i = doc.nodes[i].next)
  6377. if (doc.nodes[i].tag == BR_TAG_LI)
  6378. n++;
  6379. return (int)n + 1;
  6380. }
  6381. static void list_roman(char *m, unsigned int *n, int v, int upper,
  6382. unsigned int cap)
  6383. {
  6384. static const int val[] = { 1000, 900, 500, 400, 100, 90,
  6385. 50, 40, 10, 9, 5, 4, 1 };
  6386. static const char *lo[] = { "m", "cm", "d", "cd", "c", "xc",
  6387. "l", "xl", "x", "ix", "v", "iv", "i" };
  6388. static const char *up[] = { "M", "CM", "D", "CD", "C", "XC",
  6389. "L", "XL", "X", "IX", "V", "IV", "I" };
  6390. unsigned int i;
  6391. for (i = 0; i < sizeof(val) / sizeof(val[0]); i++) {
  6392. while (v >= val[i] && *n + 1 < cap) {
  6393. const char *s = upper ? up[i] : lo[i];
  6394. while (*s && *n + 1 < cap)
  6395. m[(*n)++] = *s++;
  6396. v -= val[i];
  6397. }
  6398. }
  6399. }
  6400. static void list_marker_text(char *m, unsigned int cap, int style, int idx)
  6401. {
  6402. unsigned int n = 0;
  6403. if (style == BR_LIST_DISC) {
  6404. m[n++] = '-';
  6405. } else if (style == BR_LIST_CIRCLE) {
  6406. m[n++] = 'o';
  6407. } else if (style == BR_LIST_SQUARE) {
  6408. m[n++] = '+';
  6409. } else if (style == BR_LIST_LOWER_ALPHA ||
  6410. style == BR_LIST_UPPER_ALPHA) {
  6411. if (idx >= 1 && idx <= 26)
  6412. m[n++] = (char)((style == BR_LIST_UPPER_ALPHA ?
  6413. 'A' : 'a') + idx - 1);
  6414. else
  6415. m[n++] = '?';
  6416. m[n++] = '.';
  6417. } else if (style == BR_LIST_LOWER_ROMAN ||
  6418. style == BR_LIST_UPPER_ROMAN) {
  6419. list_roman(m, &n, idx, style == BR_LIST_UPPER_ROMAN, cap);
  6420. if (n + 1 < cap)
  6421. m[n++] = '.';
  6422. } else {
  6423. s_append_dec(m, &n, (unsigned int)idx, cap);
  6424. if (n + 1 < cap)
  6425. m[n++] = '.';
  6426. }
  6427. m[n] = '\0';
  6428. }
  6429. /* Set by the layout when the control is stretched to its line: a flex item
  6430. * (its box width was assigned by the flex row) or a child of a flex column,
  6431. * whose default align-items: stretch makes inputs full width. */
  6432. static int form_fill_line;
  6433. static void add_form_run(struct lay *l, unsigned int node,
  6434. const struct br_style *st, unsigned short href)
  6435. {
  6436. struct form_state *fs = form_get(node, 1);
  6437. char shown[FORM_VALUE_MAX + 1];
  6438. char opt[64];
  6439. const char *text = "";
  6440. struct lay_run *r;
  6441. int kind = form_kind_of(node);
  6442. int disabled = form_disabled(node);
  6443. int tw, w = 120, h = 20, i;
  6444. if (!fs)
  6445. return;
  6446. if (l->nruns == 0)
  6447. start_line(l, st);
  6448. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  6449. text = "";
  6450. w = 16;
  6451. h = 16;
  6452. } else if (kind == FORM_SELECT) {
  6453. if (!form_option_text(node, fs->selected, opt, sizeof(opt)))
  6454. s_copy(opt, "Select", sizeof(opt));
  6455. text = opt;
  6456. w = 120;
  6457. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  6458. kind == FORM_RESET) {
  6459. if (fs->len)
  6460. text = fs->value;
  6461. else
  6462. text = kind == FORM_SUBMIT ? "Submit" :
  6463. kind == FORM_RESET ? "Reset" : "Button";
  6464. } else if (kind == FORM_PASSWORD) {
  6465. for (i = 0; i < fs->len; i++)
  6466. shown[i] = '*';
  6467. shown[fs->len] = '\0';
  6468. text = fs->len ? shown : br_placeholder(&doc, node);
  6469. } else {
  6470. if (fs->len)
  6471. text = fs->value;
  6472. else
  6473. text = br_placeholder(&doc, node);
  6474. if (kind == FORM_TEXTAREA) {
  6475. w = 180;
  6476. h = 40;
  6477. }
  6478. }
  6479. tw = (int)face_text_width(l->ui, st, text, s_len(text));
  6480. if (kind == FORM_BUTTON || kind == FORM_SUBMIT || kind == FORM_RESET) {
  6481. w = tw + 18;
  6482. if (w < 64)
  6483. w = 64;
  6484. h = 22;
  6485. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD) {
  6486. int line_w = l->line_right - l->line_left;
  6487. if (st->width_kind == 1)
  6488. w = st->width;
  6489. else if (st->width_kind == 2)
  6490. w = css_size(st->width_kind, st->width, line_w);
  6491. else if (form_fill_line || st->display == BR_DISPLAY_BLOCK)
  6492. w = line_w - (l->line_x - l->line_left);
  6493. else
  6494. w = 120;
  6495. /* Taller fields for large text (min-height/padding on login
  6496. * pages): keep the box around the glyphs. */
  6497. if (st->font_px + 8 > h)
  6498. h = st->font_px + 8;
  6499. } else if (kind == FORM_SELECT) {
  6500. w = st->width_kind == 1 ? st->width : 120;
  6501. }
  6502. if (w > l->line_right - l->line_left)
  6503. w = l->line_right - l->line_left;
  6504. if (w < 8)
  6505. w = 8;
  6506. if (l->line_x + w > l->line_right &&
  6507. (l->nruns > 0 || l->line_x > l->line_left))
  6508. flush_line(l);
  6509. if (l->nruns >= 96)
  6510. return;
  6511. if (l->nruns == 0) {
  6512. l->line_y = l->y;
  6513. l->line_h = 0;
  6514. start_line(l, st);
  6515. }
  6516. r = &l->runs[l->nruns++];
  6517. r->gap = (unsigned short)(l->line_x - l->run_x);
  6518. r->off = r->len = 0;
  6519. r->color = st->color;
  6520. r->href = href;
  6521. r->dy = 0;
  6522. r->has_lit = 1;
  6523. for (i = 0; i + 1 < (int)sizeof(r->lit) && text[i]; i++)
  6524. r->lit[i] = text[i];
  6525. r->lit[i] = '\0';
  6526. r->img = -2;
  6527. r->iw = (unsigned short)w;
  6528. r->ih = (unsigned short)h;
  6529. r->w = (unsigned short)w;
  6530. r->font_px = st->font_px;
  6531. r->bold = st->bold;
  6532. r->italic = st->italic;
  6533. r->mono = st->mono;
  6534. r->font_face = st->font_face;
  6535. r->underline = 0;
  6536. r->form = node + 1;
  6537. r->form_kind = (unsigned char)kind;
  6538. r->form_disabled = (unsigned char)disabled;
  6539. if (node < BR_MAX_NODES) {
  6540. layout_boxes[node].x = l->line_x;
  6541. layout_boxes[node].y = l->line_y;
  6542. layout_boxes[node].w = w;
  6543. layout_boxes[node].h = h;
  6544. layout_boxes[node].valid = 1;
  6545. }
  6546. l->line_x += w;
  6547. l->run_x = l->line_x;
  6548. if (l->line_h < h)
  6549. l->line_h = h;
  6550. }
  6551. /* A poster wrapper is absolutely positioned over the media slot; the
  6552. * measured height of its picture is normally added back to the flow. When a
  6553. * loading-skeleton sibling already reserves that slot, adding both doubles
  6554. * the media height and pushes the article text a full screen down. */
  6555. static int has_skeleton_sibling(unsigned int node)
  6556. {
  6557. unsigned int p = doc.nodes[node].parent, c;
  6558. for (c = doc.nodes[p].first; c; c = doc.nodes[c].next) {
  6559. if (c == node || doc.nodes[c].type != BR_NODE_ELEM)
  6560. continue;
  6561. if (doc.nodes[c].class_off &&
  6562. contains_ci(doc.attrs + doc.nodes[c].class_off,
  6563. "skeleton"))
  6564. return 1;
  6565. }
  6566. return 0;
  6567. }
  6568. static void layout_children(struct lay *l, unsigned int parent,
  6569. const struct br_style *pst, int depth,
  6570. unsigned short link);
  6571. static void layout_flex_children(struct lay *l, unsigned int parent,
  6572. const struct br_style *pst, int depth,
  6573. unsigned short link);
  6574. static void layout_grid_children(struct lay *l, unsigned int parent,
  6575. const struct br_style *pst, int depth,
  6576. unsigned short link);
  6577. static void layout_grid_auto(struct lay *l, unsigned int parent,
  6578. const struct br_style *pst, int depth,
  6579. unsigned short link);
  6580. static int flex_item_width(struct lay *l, unsigned int n,
  6581. const struct br_style *cs, int avail);
  6582. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  6583. const struct br_style *pst, int depth,
  6584. unsigned short link);
  6585. static void layout_table_row(struct lay *l, unsigned int row,
  6586. const struct br_style *pst, int depth,
  6587. unsigned short link);
  6588. static int table_has_rowspan(unsigned int table);
  6589. static void layout_table(struct lay *l, unsigned int table,
  6590. const struct br_style *st, int depth,
  6591. unsigned short link);
  6592. /* A flex container whose items are only inline spans is usually just a
  6593. * heading/icon pair. Our flex row positions such items without emitting
  6594. * their inline text in some deep page contexts; normal inline flow renders
  6595. * the same content correctly. */
  6596. static int flex_wants_row(unsigned int parent, const struct br_style *pst)
  6597. {
  6598. unsigned int c;
  6599. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  6600. struct br_node *nd = &doc.nodes[c];
  6601. struct br_style cs;
  6602. if (nd->type == BR_NODE_TEXT)
  6603. continue;
  6604. br_style_for(&doc, c, pst, &cs);
  6605. if (cs.display == BR_DISPLAY_NONE)
  6606. continue;
  6607. if (cs.display != BR_DISPLAY_INLINE || cs.flex_grow ||
  6608. cs.width_kind || cs.has_bg ||
  6609. cs.border_w[0] || cs.border_w[1] ||
  6610. cs.border_w[2] || cs.border_w[3] ||
  6611. nd->tag == BR_TAG_IMG)
  6612. return 1;
  6613. }
  6614. return 0;
  6615. }
  6616. static int css_radius(const struct br_style *st, int corner,
  6617. int w, int h)
  6618. {
  6619. int r = st->radius[corner];
  6620. if (r <= 0)
  6621. return 0;
  6622. if (r > w / 2)
  6623. r = w / 2;
  6624. if (r > h / 2)
  6625. r = h / 2;
  6626. return r;
  6627. }
  6628. /* ---- inline SVG ----
  6629. *
  6630. * An inline <svg> is rendered once per size into an RGB565 + alpha layer by
  6631. * svg_raster.c (filled/stroked geometry: every path command, rect, circle,
  6632. * ellipse, line, polyline, polygon, <g>/<a>/<use>/<symbol>, transforms,
  6633. * opacity and solid paint; a gradient paints the average of its stops) and
  6634. * the layer is blitted on every repaint. <text> is drawn per frame on top. */
  6635. #define SVG_CACHE_MAX 48
  6636. #define SVG_CACHE_PIXELS (640 * 1024)
  6637. #define SVG_MAX_POINTS 24576
  6638. struct svg_cache_ent {
  6639. unsigned int node;
  6640. int w, h;
  6641. unsigned short *px;
  6642. unsigned char *a;
  6643. unsigned int stamp;
  6644. };
  6645. static struct svg_cache_ent svg_cache[SVG_CACHE_MAX];
  6646. static unsigned int svg_cache_pixels, svg_cache_clock;
  6647. static struct svgr svg_geom;
  6648. static void *svg_geom_buf;
  6649. /* Current viewport in user units: percentage lengths resolve against it
  6650. * (the viewBox size, not the device pixels). */
  6651. static double svg_vp_w = 300, svg_vp_h = 150;
  6652. /* The layers live in the page heap: forget them before heap_reset(). */
  6653. static void svg_cache_clear(void)
  6654. {
  6655. memset(svg_cache, 0, sizeof(svg_cache));
  6656. svg_cache_pixels = 0;
  6657. svg_geom_buf = 0;
  6658. }
  6659. static int svg_name_is(const char *a, const char *b)
  6660. {
  6661. while (*a && *b) {
  6662. char x = *a, y = *b;
  6663. if (x >= 'A' && x <= 'Z')
  6664. x = (char)(x - 'A' + 'a');
  6665. if (x != y)
  6666. return 0;
  6667. a++;
  6668. b++;
  6669. }
  6670. return *a == *b;
  6671. }
  6672. static const char *svg_elem_name(unsigned int node)
  6673. {
  6674. const struct br_node *nd = &doc.nodes[node];
  6675. if (nd->name_off)
  6676. return doc.attrs + nd->name_off;
  6677. return br_tag_name(nd->tag);
  6678. }
  6679. /* A numeric attribute; a percentage resolves against `base`. */
  6680. static double svg_attr_num(unsigned int node, const char *name, double def,
  6681. double base)
  6682. {
  6683. const char *v = br_find_attr(&doc, node, name);
  6684. const char *p = v;
  6685. int ok = 0;
  6686. double x;
  6687. if (!v)
  6688. return def;
  6689. x = svgr_num(&p, &ok);
  6690. if (!ok)
  6691. return def;
  6692. if (*p == '%')
  6693. x = x * base / 100.0;
  6694. return x;
  6695. }
  6696. /* viewBox="minx miny w h"; 0 when absent or invalid. */
  6697. static int svg_viewbox4(unsigned int node, double vb[4])
  6698. {
  6699. const char *v = br_find_attr(&doc, node, "viewbox");
  6700. const char *p = v;
  6701. int i, ok = 1;
  6702. if (!v)
  6703. return 0;
  6704. for (i = 0; i < 4 && ok; i++)
  6705. vb[i] = svgr_num(&p, &ok);
  6706. return ok && vb[2] > 0 && vb[3] > 0;
  6707. }
  6708. /* Map a viewBox into a w x h viewport (preserveAspectRatio: default
  6709. * xMidYMid meet, "none" stretches, xMin/xMax and slice are honoured). */
  6710. static void svg_viewport_matrix(unsigned int node, const double vb[4],
  6711. double w, double h, double m[6])
  6712. {
  6713. const char *par = br_find_attr(&doc, node, "preserveaspectratio");
  6714. double sx = w / vb[2], sy = h / vb[3], s, tx, ty;
  6715. int ax = 1, ay = 1;
  6716. if (par && contains_ci(par, "none")) {
  6717. m[0] = sx; m[1] = 0; m[2] = 0; m[3] = sy;
  6718. m[4] = -vb[0] * sx;
  6719. m[5] = -vb[1] * sy;
  6720. return;
  6721. }
  6722. if (par) {
  6723. if (contains_ci(par, "xmin"))
  6724. ax = 0;
  6725. else if (contains_ci(par, "xmax"))
  6726. ax = 2;
  6727. if (contains_ci(par, "ymin"))
  6728. ay = 0;
  6729. else if (contains_ci(par, "ymax"))
  6730. ay = 2;
  6731. }
  6732. s = (par && contains_ci(par, "slice")) ? (sx > sy ? sx : sy) :
  6733. (sx < sy ? sx : sy);
  6734. tx = (w - vb[2] * s) * ax / 2.0;
  6735. ty = (h - vb[3] * s) * ay / 2.0;
  6736. m[0] = s; m[1] = 0; m[2] = 0; m[3] = s;
  6737. m[4] = tx - vb[0] * s;
  6738. m[5] = ty - vb[1] * s;
  6739. }
  6740. /* Resolve url(#id) on the nearest element (self or an ancestor) carrying
  6741. * the paint attribute, then average the gradient's stops. */
  6742. static int svg_url_paint(unsigned int node, const char *attr,
  6743. unsigned short *color, unsigned int *alpha)
  6744. {
  6745. const char *v = 0, *h;
  6746. char id[64];
  6747. unsigned int k, n = 0, g, c, sr = 0, sg = 0, sb = 0, sa = 0, cnt = 0;
  6748. for (k = 0; node && k < 32 && !v; k++) {
  6749. v = br_find_attr(&doc, node, attr);
  6750. if (!v) {
  6751. const char *style = br_find_attr(&doc, node, "style");
  6752. if (style && contains_ci(style, "url(#"))
  6753. v = strstr(style, "url(#");
  6754. }
  6755. if (v && !contains_ci(v, "url("))
  6756. v = 0;
  6757. node = doc.nodes[node].parent;
  6758. }
  6759. if (!v || !(h = strstr(v, "#")))
  6760. return 0;
  6761. h++;
  6762. while (*h && *h != ')' && *h != '"' && *h != '\'' && n + 1 < sizeof(id))
  6763. id[n++] = *h++;
  6764. id[n] = '\0';
  6765. g = br_find_id(&doc, id);
  6766. /* Follow href chains (a gradient that only references another one's
  6767. * stops), at most a few hops. */
  6768. for (k = 0; g && k < 4; k++) {
  6769. unsigned int gi = g - 1;
  6770. const char *ref;
  6771. for (c = doc.nodes[gi].first; c; c = doc.nodes[c].next) {
  6772. const char *nm, *sc, *so;
  6773. unsigned short col = 0;
  6774. double op = 1;
  6775. if (doc.nodes[c].type != BR_NODE_ELEM)
  6776. continue;
  6777. nm = svg_elem_name(c);
  6778. if (!svg_name_is(nm, "stop"))
  6779. continue;
  6780. sc = br_find_attr(&doc, c, "stop-color");
  6781. so = br_find_attr(&doc, c, "stop-opacity");
  6782. {
  6783. const char *st = br_find_attr(&doc, c, "style");
  6784. const char *q;
  6785. if (st && (q = strstr(st, "stop-color:")) != 0)
  6786. sc = q + 11;
  6787. if (st && (q = strstr(st, "stop-opacity:")) != 0)
  6788. so = q + 13;
  6789. }
  6790. if (sc) {
  6791. unsigned int L = 0;
  6792. while (sc[L] && sc[L] != ';' && sc[L] != '"')
  6793. L++;
  6794. if (!br_parse_color(sc, L, &col))
  6795. col = 0;
  6796. }
  6797. if (so) {
  6798. const char *p = so;
  6799. int ok = 0;
  6800. double x = svgr_num(&p, &ok);
  6801. if (ok)
  6802. op = x < 0 ? 0 : x > 1 ? 1 : x;
  6803. }
  6804. sr += (col >> 11) & 31;
  6805. sg += (col >> 5) & 63;
  6806. sb += col & 31;
  6807. sa += (unsigned int)(op * 255);
  6808. cnt++;
  6809. }
  6810. if (cnt)
  6811. break;
  6812. ref = br_find_attr(&doc, gi, "href");
  6813. if (!ref)
  6814. ref = br_find_attr(&doc, gi, "xlink:href");
  6815. if (!ref || ref[0] != '#')
  6816. break;
  6817. g = br_find_id(&doc, ref + 1);
  6818. }
  6819. if (!cnt)
  6820. return 0;
  6821. *color = (unsigned short)(((sr / cnt) << 11) | ((sg / cnt) << 5) |
  6822. (sb / cnt));
  6823. *alpha = sa / cnt;
  6824. return 1;
  6825. }
  6826. static int svg_paint(unsigned int node, const struct br_style *st, int fill,
  6827. unsigned short *color, unsigned int *alpha)
  6828. {
  6829. int mode = fill ? st->fill_mode : st->stroke_mode;
  6830. const char *op = br_find_attr(&doc, node,
  6831. fill ? "fill-opacity" : "stroke-opacity");
  6832. *alpha = 255;
  6833. switch (mode) {
  6834. case BR_PAINT_UNSET:
  6835. if (!fill)
  6836. return 0;
  6837. *color = 0;
  6838. break;
  6839. case BR_PAINT_COLOR:
  6840. *color = fill ? st->fill : st->stroke;
  6841. break;
  6842. case BR_PAINT_CURRENT:
  6843. *color = st->color;
  6844. break;
  6845. case BR_PAINT_URL:
  6846. if (!svg_url_paint(node, fill ? "fill" : "stroke", color,
  6847. alpha))
  6848. return 0;
  6849. break;
  6850. default:
  6851. return 0;
  6852. }
  6853. if (op) {
  6854. const char *p = op;
  6855. int ok = 0;
  6856. double x = svgr_num(&p, &ok);
  6857. if (ok)
  6858. *alpha = (unsigned int)(*alpha *
  6859. (x < 0 ? 0 : x > 1 ? 1 : x));
  6860. }
  6861. return *alpha > 0;
  6862. }
  6863. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6864. const double m[6], const struct br_style *pst,
  6865. unsigned int alpha, int depth);
  6866. static void svg_draw_children(struct svgr_layer *L, unsigned int node,
  6867. const double m[6], const struct br_style *st,
  6868. unsigned int alpha, int depth)
  6869. {
  6870. unsigned int c;
  6871. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next)
  6872. if (doc.nodes[c].type == BR_NODE_ELEM)
  6873. svg_draw_node(L, c, m, st, alpha, depth + 1);
  6874. }
  6875. static void svg_draw_node(struct svgr_layer *L, unsigned int node,
  6876. const double pm[6], const struct br_style *pst,
  6877. unsigned int alpha, int depth)
  6878. {
  6879. struct br_style st;
  6880. const char *nm = svg_elem_name(node);
  6881. const char *tf;
  6882. double m[6];
  6883. unsigned short color;
  6884. unsigned int pa;
  6885. int shape = 0, fillable = 1;
  6886. if (depth > 24 || !nm)
  6887. return;
  6888. if (svg_name_is(nm, "defs") || svg_name_is(nm, "clippath") ||
  6889. svg_name_is(nm, "mask") || svg_name_is(nm, "symbol") ||
  6890. svg_name_is(nm, "lineargradient") ||
  6891. svg_name_is(nm, "radialgradient") || svg_name_is(nm, "pattern") ||
  6892. svg_name_is(nm, "filter") || svg_name_is(nm, "marker") ||
  6893. svg_name_is(nm, "style") || svg_name_is(nm, "script") ||
  6894. svg_name_is(nm, "title") || svg_name_is(nm, "desc") ||
  6895. svg_name_is(nm, "metadata") || svg_name_is(nm, "text") ||
  6896. svg_name_is(nm, "foreignobject"))
  6897. return;
  6898. br_style_for(&doc, node, pst, &st);
  6899. if (st.display == BR_DISPLAY_NONE)
  6900. return;
  6901. memcpy(m, pm, sizeof(m));
  6902. tf = br_find_attr(&doc, node, "transform");
  6903. if (tf)
  6904. svgr_transform(m, tf);
  6905. {
  6906. const char *op = br_find_attr(&doc, node, "opacity");
  6907. if (op) {
  6908. const char *p = op;
  6909. int ok = 0;
  6910. double x = svgr_num(&p, &ok);
  6911. if (ok)
  6912. alpha = (unsigned int)(alpha *
  6913. (x < 0 ? 0 :
  6914. x > 1 ? 1 : x));
  6915. }
  6916. }
  6917. if (!alpha)
  6918. return;
  6919. if (svg_name_is(nm, "g") || svg_name_is(nm, "a") ||
  6920. svg_name_is(nm, "switch")) {
  6921. svg_draw_children(L, node, m, &st, alpha, depth);
  6922. return;
  6923. }
  6924. if (svg_name_is(nm, "svg")) {
  6925. double vb[4], x = svg_attr_num(node, "x", 0, 0),
  6926. y = svg_attr_num(node, "y", 0, 0);
  6927. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6928. t[4] = x;
  6929. t[5] = y;
  6930. svgr_mat_mul(m, m, t);
  6931. double ow = svg_vp_w, oh = svg_vp_h;
  6932. if (svg_viewbox4(node, vb)) {
  6933. double w = svg_attr_num(node, "width", vb[2], ow);
  6934. double h = svg_attr_num(node, "height", vb[3], oh);
  6935. double vm[6];
  6936. svg_viewport_matrix(node, vb, w, h, vm);
  6937. svgr_mat_mul(m, m, vm);
  6938. svg_vp_w = vb[2];
  6939. svg_vp_h = vb[3];
  6940. }
  6941. svg_draw_children(L, node, m, &st, alpha, depth);
  6942. svg_vp_w = ow;
  6943. svg_vp_h = oh;
  6944. return;
  6945. }
  6946. if (svg_name_is(nm, "use")) {
  6947. const char *ref = br_find_attr(&doc, node, "href");
  6948. unsigned int tgt;
  6949. double t[6] = { 1, 0, 0, 1, 0, 0 };
  6950. if (!ref)
  6951. ref = br_find_attr(&doc, node, "xlink:href");
  6952. if (!ref || ref[0] != '#')
  6953. return;
  6954. tgt = br_find_id(&doc, ref + 1);
  6955. if (!tgt || tgt - 1 == node)
  6956. return;
  6957. tgt--;
  6958. t[4] = svg_attr_num(node, "x", 0, 0);
  6959. t[5] = svg_attr_num(node, "y", 0, 0);
  6960. svgr_mat_mul(m, m, t);
  6961. if (svg_name_is(svg_elem_name(tgt), "symbol")) {
  6962. double vb[4];
  6963. double ow = svg_vp_w, oh = svg_vp_h;
  6964. if (svg_viewbox4(tgt, vb)) {
  6965. double w = svg_attr_num(node, "width", vb[2],
  6966. ow);
  6967. double h = svg_attr_num(node, "height", vb[3],
  6968. oh);
  6969. double vm[6];
  6970. svg_viewport_matrix(tgt, vb, w, h, vm);
  6971. svgr_mat_mul(m, m, vm);
  6972. svg_vp_w = vb[2];
  6973. svg_vp_h = vb[3];
  6974. }
  6975. svg_draw_children(L, tgt, m, &st, alpha, depth);
  6976. svg_vp_w = ow;
  6977. svg_vp_h = oh;
  6978. } else {
  6979. svg_draw_node(L, tgt, m, &st, alpha, depth + 1);
  6980. }
  6981. return;
  6982. }
  6983. svgr_reset(&svg_geom, m);
  6984. if (svg_name_is(nm, "path")) {
  6985. const char *d = br_find_attr(&doc, node, "d");
  6986. if (d) {
  6987. svgr_path(&svg_geom, d);
  6988. shape = 1;
  6989. }
  6990. } else if (svg_name_is(nm, "rect")) {
  6991. double w = svg_attr_num(node, "width", 0, svg_vp_w);
  6992. double h = svg_attr_num(node, "height", 0, svg_vp_h);
  6993. double rx = svg_attr_num(node, "rx", -1, w);
  6994. double ry = svg_attr_num(node, "ry", -1, h);
  6995. if (rx < 0)
  6996. rx = ry < 0 ? 0 : ry;
  6997. if (ry < 0)
  6998. ry = rx;
  6999. svgr_rect(&svg_geom, svg_attr_num(node, "x", 0, svg_vp_w),
  7000. svg_attr_num(node, "y", 0, svg_vp_h), w, h, rx, ry);
  7001. shape = 1;
  7002. } else if (svg_name_is(nm, "circle")) {
  7003. double r = svg_attr_num(node, "r", 0, svg_vp_w);
  7004. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7005. svg_attr_num(node, "cy", 0, svg_vp_h), r, r);
  7006. shape = 1;
  7007. } else if (svg_name_is(nm, "ellipse")) {
  7008. svgr_ellipse(&svg_geom, svg_attr_num(node, "cx", 0, svg_vp_w),
  7009. svg_attr_num(node, "cy", 0, svg_vp_h),
  7010. svg_attr_num(node, "rx", 0, svg_vp_w),
  7011. svg_attr_num(node, "ry", 0, svg_vp_h));
  7012. shape = 1;
  7013. } else if (svg_name_is(nm, "line")) {
  7014. svgr_move(&svg_geom, svg_attr_num(node, "x1", 0, svg_vp_w),
  7015. svg_attr_num(node, "y1", 0, svg_vp_h));
  7016. svgr_line(&svg_geom, svg_attr_num(node, "x2", 0, svg_vp_w),
  7017. svg_attr_num(node, "y2", 0, svg_vp_h));
  7018. shape = 1;
  7019. fillable = 0;
  7020. } else if (svg_name_is(nm, "polyline") ||
  7021. svg_name_is(nm, "polygon")) {
  7022. const char *pts = br_find_attr(&doc, node, "points");
  7023. if (pts) {
  7024. svgr_points(&svg_geom, pts,
  7025. svg_name_is(nm, "polygon"));
  7026. shape = 1;
  7027. }
  7028. }
  7029. if (!shape)
  7030. return;
  7031. if (fillable && svg_paint(node, &st, 1, &color, &pa))
  7032. svgr_fill(&svg_geom, L, color, pa * alpha / 255,
  7033. st.fill_evenodd);
  7034. if (svg_paint(node, &st, 0, &color, &pa)) {
  7035. double sw = st.stroke_w ? st.stroke_w / 16.0 : 1.0;
  7036. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7037. svgr_stroke(&svg_geom, L, sw * sc, color, pa * alpha / 255);
  7038. }
  7039. }
  7040. /* <text> elements: drawn straight onto the page every frame (the glyph
  7041. * renderer targets the ngui canvas, not a layer). x/y map through the
  7042. * accumulated transform; the font size scales with it. */
  7043. static void svg_draw_text(struct ngui *ui, unsigned int node,
  7044. const double pm[6], const struct br_style *pst,
  7045. int ox, int oy, int depth)
  7046. {
  7047. unsigned int c;
  7048. if (depth > 24)
  7049. return;
  7050. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  7051. struct br_style st;
  7052. const char *nm, *tf;
  7053. double m[6];
  7054. if (doc.nodes[c].type != BR_NODE_ELEM)
  7055. continue;
  7056. nm = svg_elem_name(c);
  7057. if (!nm || svg_name_is(nm, "defs") ||
  7058. svg_name_is(nm, "symbol") || svg_name_is(nm, "mask") ||
  7059. svg_name_is(nm, "clippath"))
  7060. continue;
  7061. br_style_for(&doc, c, pst, &st);
  7062. if (st.display == BR_DISPLAY_NONE)
  7063. continue;
  7064. memcpy(m, pm, sizeof(m));
  7065. tf = br_find_attr(&doc, c, "transform");
  7066. if (tf)
  7067. svgr_transform(m, tf);
  7068. if (svg_name_is(nm, "text")) {
  7069. unsigned int t = doc.nodes[c].first;
  7070. const char *s;
  7071. unsigned int n, tw;
  7072. double x = svg_attr_num(c, "x", 0, 0),
  7073. y = svg_attr_num(c, "y", 0, 0);
  7074. double sc = sqrt(fabs(m[0] * m[3] - m[1] * m[2]));
  7075. int px = (int)((st.font_px ? st.font_px : 16) * sc + 0.5);
  7076. int tx, ty, anchor;
  7077. unsigned short col;
  7078. unsigned int pa;
  7079. if (!t || doc.nodes[t].type != BR_NODE_TEXT)
  7080. continue;
  7081. if (px < 6)
  7082. px = 6;
  7083. if (px > 72)
  7084. px = 72;
  7085. if (!svg_paint(c, &st, 1, &col, &pa))
  7086. continue;
  7087. s = doc.text + doc.nodes[t].text_off;
  7088. n = doc.nodes[t].text_len;
  7089. st.font_px = (unsigned char)px;
  7090. tw = face_text_width(ui, &st, s, n);
  7091. tx = ox + (int)(m[0] * x + m[2] * y + m[4]);
  7092. ty = oy + (int)(m[1] * x + m[3] * y + m[5]) -
  7093. ngui_text_ascent_face(ui, style_face(&st), px,
  7094. st.mono);
  7095. anchor = st.align;
  7096. if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_MIDDLE)
  7097. anchor = BR_ALIGN_CENTER;
  7098. else if (doc.nodes[c].attr_flags & BR_ATTR_ANCHOR_END)
  7099. anchor = BR_ALIGN_RIGHT;
  7100. if (anchor == BR_ALIGN_CENTER)
  7101. tx -= (int)tw / 2;
  7102. else if (anchor == BR_ALIGN_RIGHT)
  7103. tx -= (int)tw;
  7104. ngui_text_px_face(ui, style_face(&st), tx, ty, s, n,
  7105. col, px, st.bold, st.italic,
  7106. st.mono);
  7107. } else {
  7108. svg_draw_text(ui, c, m, &st, ox, oy, depth + 1);
  7109. }
  7110. }
  7111. }
  7112. static void svg_root_matrix(unsigned int node, int w, int h, double m[6])
  7113. {
  7114. double vb[4];
  7115. if (svg_viewbox4(node, vb)) {
  7116. svg_viewport_matrix(node, vb, w, h, m);
  7117. } else {
  7118. m[0] = 1; m[1] = 0; m[2] = 0; m[3] = 1; m[4] = 0; m[5] = 0;
  7119. }
  7120. }
  7121. static struct svg_cache_ent *svg_layer(unsigned int node, int w, int h,
  7122. const struct br_style *st)
  7123. {
  7124. struct svg_cache_ent *e = 0;
  7125. struct svgr_layer L;
  7126. double m[6];
  7127. unsigned int i, need = (unsigned int)w * (unsigned int)h;
  7128. svg_cache_clock++;
  7129. for (i = 0; i < SVG_CACHE_MAX; i++)
  7130. if (svg_cache[i].px && svg_cache[i].node == node &&
  7131. svg_cache[i].w == w && svg_cache[i].h == h) {
  7132. svg_cache[i].stamp = svg_cache_clock;
  7133. return &svg_cache[i];
  7134. }
  7135. if (need > SVG_CACHE_PIXELS)
  7136. return 0;
  7137. /* Evict least recently used layers until this one fits. */
  7138. for (;;) {
  7139. struct svg_cache_ent *lru = 0, *free_slot = 0;
  7140. for (i = 0; i < SVG_CACHE_MAX; i++) {
  7141. if (!svg_cache[i].px) {
  7142. if (!free_slot)
  7143. free_slot = &svg_cache[i];
  7144. } else if (!lru || svg_cache[i].stamp < lru->stamp) {
  7145. lru = &svg_cache[i];
  7146. }
  7147. }
  7148. if (free_slot && svg_cache_pixels + need <= SVG_CACHE_PIXELS) {
  7149. e = free_slot;
  7150. break;
  7151. }
  7152. if (!lru)
  7153. return 0;
  7154. svg_cache_pixels -= (unsigned int)(lru->w * lru->h);
  7155. free(lru->px);
  7156. free(lru->a);
  7157. memset(lru, 0, sizeof(*lru));
  7158. }
  7159. if (!svg_geom_buf) {
  7160. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7161. if (!svg_geom_buf)
  7162. return 0;
  7163. }
  7164. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7165. e->px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7166. e->a = (unsigned char *)calloc(need, 1);
  7167. if (!e->px || !e->a) {
  7168. free(e->px);
  7169. free(e->a);
  7170. memset(e, 0, sizeof(*e));
  7171. return 0;
  7172. }
  7173. e->node = node;
  7174. e->w = w;
  7175. e->h = h;
  7176. e->stamp = svg_cache_clock;
  7177. svg_cache_pixels += need;
  7178. L.px = e->px;
  7179. L.a = e->a;
  7180. L.w = w;
  7181. L.h = h;
  7182. svg_root_matrix(node, w, h, m);
  7183. {
  7184. double vb[4];
  7185. if (svg_viewbox4(node, vb)) {
  7186. svg_vp_w = vb[2];
  7187. svg_vp_h = vb[3];
  7188. } else {
  7189. svg_vp_w = w;
  7190. svg_vp_h = h;
  7191. }
  7192. }
  7193. svg_draw_children(&L, node, m, st, 255, 0);
  7194. return e;
  7195. }
  7196. /* ---- SVG files as images (<img src="logo.svg">, CSS backgrounds) ----
  7197. *
  7198. * The markup is parsed into a detached subtree of the page document and
  7199. * drawn with the inline-SVG renderer above into a fresh RGB565 + alpha
  7200. * bitmap, which then behaves like any decoded image. currentColor is
  7201. * black (an image has no inherited text colour); <text> is not drawn. */
  7202. static int svg_text_sniff(const unsigned char *d, unsigned int len)
  7203. {
  7204. unsigned int i = 0;
  7205. if (len >= 3 && d[0] == 0xEF && d[1] == 0xBB && d[2] == 0xBF)
  7206. i = 3;
  7207. while (i < len) {
  7208. while (i < len && (d[i] == ' ' || d[i] == '\t' ||
  7209. d[i] == '\r' || d[i] == '\n'))
  7210. i++;
  7211. if (i + 4 <= len && !memcmp(d + i, "<svg", 4))
  7212. return 1;
  7213. if (i + 4 <= len && !memcmp(d + i, "<!--", 4)) {
  7214. i += 4;
  7215. while (i + 3 <= len && memcmp(d + i, "-->", 3))
  7216. i++;
  7217. i += 3;
  7218. continue;
  7219. }
  7220. if (i + 1 < len && d[i] == '<' && (d[i + 1] == '?' || d[i + 1] == '!')) {
  7221. while (i < len && d[i] != '>')
  7222. i++;
  7223. i++;
  7224. continue;
  7225. }
  7226. return 0;
  7227. }
  7228. return 0;
  7229. }
  7230. static int svg_len_attr(unsigned int node, const char *name)
  7231. {
  7232. const char *v = br_find_attr(&doc, node, name);
  7233. int n = 0, any = 0;
  7234. if (!v)
  7235. return 0;
  7236. while (*v == ' ')
  7237. v++;
  7238. while (*v >= '0' && *v <= '9') {
  7239. n = n * 10 + (*v++ - '0');
  7240. any = 1;
  7241. }
  7242. if (*v == '.')
  7243. while (*++v >= '0' && *v <= '9')
  7244. ;
  7245. if (!any || *v == '%')
  7246. return 0;
  7247. return n;
  7248. }
  7249. static int svg_decode_image(const unsigned char *data, unsigned int len,
  7250. struct br_image *bi, int box_w, int box_h)
  7251. {
  7252. unsigned int holder, svg = 0, c, need, i;
  7253. struct br_style base = base_style(), st;
  7254. struct svgr_layer L;
  7255. double vb[4], m[6];
  7256. int w, h, have_vb, nat_w, nat_h;
  7257. holder = br_create_element(&doc, "div", 3);
  7258. if (!holder) {
  7259. s_copy(bi->err, "page is full", sizeof(bi->err));
  7260. return -1;
  7261. }
  7262. holder--;
  7263. br_set_inner_html(&doc, holder, (const char *)data, len);
  7264. for (c = doc.nodes[holder].first; c; c = doc.nodes[c].next)
  7265. if (doc.nodes[c].type == BR_NODE_ELEM &&
  7266. doc.nodes[c].tag == BR_TAG_SVG) {
  7267. svg = c;
  7268. break;
  7269. }
  7270. if (!svg) {
  7271. s_copy(bi->err, "bad SVG", sizeof(bi->err));
  7272. return -1;
  7273. }
  7274. have_vb = svg_viewbox4(svg, vb) && vb[2] > 0 && vb[3] > 0;
  7275. w = svg_len_attr(svg, "width");
  7276. h = svg_len_attr(svg, "height");
  7277. if (box_w > 0 && box_h > 0) {
  7278. w = box_w;
  7279. h = box_h;
  7280. } else if (!w && !h) {
  7281. w = have_vb ? (int)(vb[2] + 0.5) : 150;
  7282. h = have_vb ? (int)(vb[3] + 0.5) : 150;
  7283. } else if (!w) {
  7284. w = have_vb ? (int)(h * vb[2] / vb[3] + 0.5) : h;
  7285. } else if (!h) {
  7286. h = have_vb ? (int)(w * vb[3] / vb[2] + 0.5) : w;
  7287. }
  7288. /* Layout uses the intrinsic size; small icons are drawn at up to 4x
  7289. * so CSS scaling stays crisp. */
  7290. nat_w = w;
  7291. nat_h = h;
  7292. while (w < 96 && h < 96 && w * h > 0 && w * 2 <= 384) {
  7293. w *= 2;
  7294. h *= 2;
  7295. }
  7296. if (w > BR_IMG_LAYOUT_W) {
  7297. h = (int)((long)h * BR_IMG_LAYOUT_W / w);
  7298. w = BR_IMG_LAYOUT_W;
  7299. }
  7300. if (h > 2048)
  7301. h = 2048;
  7302. if (w < 1)
  7303. w = 1;
  7304. if (h < 1)
  7305. h = 1;
  7306. need = (unsigned int)w * (unsigned int)h;
  7307. if (image_pixels + need > BR_IMG_PIXEL_BUDGET) {
  7308. s_copy(bi->err, "image budget exhausted", sizeof(bi->err));
  7309. return -1;
  7310. }
  7311. if (!svg_geom_buf) {
  7312. svg_geom_buf = malloc(SVG_MAX_POINTS * (2 * sizeof(float) + 1));
  7313. if (!svg_geom_buf) {
  7314. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7315. return -1;
  7316. }
  7317. }
  7318. svgr_init(&svg_geom, svg_geom_buf, SVG_MAX_POINTS);
  7319. L.px = (unsigned short *)malloc(need * sizeof(unsigned short));
  7320. L.a = (unsigned char *)calloc(need, 1);
  7321. if (!L.px || !L.a) {
  7322. free(L.px);
  7323. free(L.a);
  7324. s_copy(bi->err, "out of memory", sizeof(bi->err));
  7325. return -1;
  7326. }
  7327. for (i = 0; i < need; i++)
  7328. L.px[i] = 0xFFFF;
  7329. L.w = w;
  7330. L.h = h;
  7331. base.color = 0x0000;
  7332. br_style_for(&doc, svg, &base, &st);
  7333. svg_root_matrix(svg, w, h, m);
  7334. svg_vp_w = have_vb ? vb[2] : w;
  7335. svg_vp_h = have_vb ? vb[3] : h;
  7336. svg_draw_children(&L, svg, m, &st, 255, 0);
  7337. bi->native_w = nat_w;
  7338. bi->native_h = nat_h;
  7339. bi->img.format = 0;
  7340. bi->img.w = (unsigned int)w;
  7341. bi->img.h = (unsigned int)h;
  7342. bi->img.px = L.px;
  7343. bi->img.alpha = L.a;
  7344. bi->img.flags = 0;
  7345. bi->state = 1;
  7346. image_pixels += need;
  7347. return 0;
  7348. }
  7349. /* Intrinsic size of an inline <svg> in a w-wide containing box. */
  7350. static void svg_size(unsigned int node, const struct br_style *st, int cw,
  7351. int *out_w, int *out_h)
  7352. {
  7353. double vb[4];
  7354. int has_vb = svg_viewbox4(node, vb);
  7355. double aw = svg_attr_num(node, "width", -1, cw);
  7356. double ah = svg_attr_num(node, "height", -1, 0);
  7357. int w, h;
  7358. if (st->width_kind)
  7359. w = cw;
  7360. else if (aw > 0)
  7361. w = (int)(aw + 0.5);
  7362. else if (st->height_kind == 1 && has_vb)
  7363. w = (int)(st->height * vb[2] / vb[3] + 0.5);
  7364. else if (ah > 0 && has_vb)
  7365. w = (int)(ah * vb[2] / vb[3] + 0.5);
  7366. else if (has_vb)
  7367. w = cw;
  7368. else
  7369. w = 300;
  7370. if (st->max_width_kind == 1 && w > st->max_width)
  7371. w = st->max_width;
  7372. if (w > cw && cw > 0 && !(aw > 0))
  7373. w = cw;
  7374. if (w < 1)
  7375. w = 1;
  7376. if (w > 2000)
  7377. w = 2000;
  7378. if (st->height_kind == 1)
  7379. h = st->height;
  7380. else if (ah > 0)
  7381. h = (int)(ah + 0.5);
  7382. else if (has_vb)
  7383. h = (int)(w * vb[3] / vb[2] + 0.5);
  7384. else
  7385. h = 150;
  7386. if (h < 1)
  7387. h = 1;
  7388. if (h > 1400)
  7389. h = 1400;
  7390. *out_w = w;
  7391. *out_h = h;
  7392. }
  7393. static void svg_paint_box(struct ngui *ui, unsigned int node,
  7394. const struct br_style *st, int x, int y, int w, int h)
  7395. {
  7396. struct svg_cache_ent *e;
  7397. struct ngui_rect clip = { 0, 0, ui->w, ui->h }, r = { x, y, w, h };
  7398. int cx0, cy0, cx1, cy1, px, py;
  7399. double m[6];
  7400. if (ui->nclip > 0)
  7401. clip = ui->clip[ui->nclip - 1];
  7402. cx0 = r.x > clip.x ? r.x : clip.x;
  7403. cy0 = r.y > clip.y ? r.y : clip.y;
  7404. cx1 = r.x + r.w < clip.x + clip.w ? r.x + r.w : clip.x + clip.w;
  7405. cy1 = r.y + r.h < clip.y + clip.h ? r.y + r.h : clip.y + clip.h;
  7406. if (cx0 >= cx1 || cy0 >= cy1)
  7407. return;
  7408. e = svg_layer(node, w, h, st);
  7409. if (e) {
  7410. for (py = cy0; py < cy1; py++) {
  7411. unsigned int srow = (unsigned int)(py - y) *
  7412. (unsigned int)w;
  7413. unsigned short *dst = ui->px + py * ui->w;
  7414. for (px = cx0; px < cx1; px++) {
  7415. unsigned int si = srow + (unsigned int)(px - x);
  7416. unsigned int a = e->a[si];
  7417. if (!a)
  7418. continue;
  7419. dst[px] = a >= 255 ? e->px[si] :
  7420. blend_rgb565(dst[px], e->px[si], a);
  7421. }
  7422. }
  7423. }
  7424. svg_root_matrix(node, w, h, m);
  7425. ngui_push_clip(ui, r);
  7426. svg_draw_text(ui, node, m, st, x, y, 0);
  7427. ngui_pop_clip(ui);
  7428. }
  7429. /* Size and paint a block-level/absolutely positioned <img>. Inline images
  7430. * keep using add_image_run(); this covers the CSS `position:absolute;
  7431. * width:100%` poster pattern used by news sites. */
  7432. static void image_block_size(unsigned int node, const struct br_style *st,
  7433. int cbw, int *out_w, int *out_h)
  7434. {
  7435. struct br_node *nd = &doc.nodes[node];
  7436. int idx = nd->img_index;
  7437. int iw = 0, ih = 0, w, h, aw, ah;
  7438. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7439. iw = (int)images[idx].img.w;
  7440. ih = (int)images[idx].img.h;
  7441. if (iw <= 0 || ih <= 0) {
  7442. iw = (int)images[idx].native_w;
  7443. ih = (int)images[idx].native_h;
  7444. }
  7445. }
  7446. if (st->width_kind)
  7447. w = style_width_px(st, cbw);
  7448. else if (nd->width_attr)
  7449. w = nd->width_pct ? cbw * nd->width_attr / 100 :
  7450. (int)nd->width_attr;
  7451. else if (nd->height_attr && !nd->height_pct && iw && ih)
  7452. w = iw * (int)nd->height_attr / ih;
  7453. else if (iw)
  7454. w = iw;
  7455. else
  7456. w = 64;
  7457. /* max-width/min-width against the containing block: Tailwind's
  7458. * img{max-width:100%;height:auto} plus "min-w-full absolute" sizes a
  7459. * 300x300 thumbnail to its 75 px avatar box. */
  7460. if (st->max_width_kind) {
  7461. int mw = st->max_width_kind == 3 ?
  7462. cbw * st->max_width_calc_pct / 100 +
  7463. st->max_width_calc_px :
  7464. st->max_width_kind == 2 ?
  7465. cbw * (int)st->max_width / 100 : (int)st->max_width;
  7466. if (mw > 0 && w > mw)
  7467. w = mw;
  7468. }
  7469. if (st->min_width_kind) {
  7470. int mn = st->min_width_kind == 3 ?
  7471. cbw * st->min_width_calc_pct / 100 +
  7472. st->min_width_calc_px :
  7473. st->min_width_kind == 2 ?
  7474. cbw * (int)st->min_width / 100 : (int)st->min_width;
  7475. if (mn > w)
  7476. w = mn;
  7477. }
  7478. if (w < 8)
  7479. w = 8;
  7480. if (cbw > 0 && w > cbw)
  7481. w = cbw;
  7482. /* Without a CSS height the attributes (or the bitmap) only give the
  7483. * aspect ratio: a width clamped by max-width scales the height too,
  7484. * instead of letterboxing the image into its attribute height. */
  7485. aw = nd->width_attr && !nd->width_pct ? (int)nd->width_attr : iw;
  7486. ah = nd->height_attr && !nd->height_pct ? (int)nd->height_attr : ih;
  7487. if (st->height_kind)
  7488. h = style_height_px(st, cbw);
  7489. else if (aw > 0 && ah > 0)
  7490. h = w * ah / aw;
  7491. else if (nd->height_attr)
  7492. h = nd->height_pct ? cbw * nd->height_attr / 100 :
  7493. (int)nd->height_attr;
  7494. else
  7495. h = 64;
  7496. if (h < 8)
  7497. h = 8;
  7498. *out_w = w;
  7499. *out_h = h;
  7500. }
  7501. static void draw_image_block(struct lay *l, unsigned int node, int x, int y,
  7502. int dw, int dh)
  7503. {
  7504. int idx = doc.nodes[node].img_index;
  7505. if (idx >= 0 && idx < image_count && images[idx].state == 1) {
  7506. struct img_image *src = image_display_get(&images[idx], dw, dh);
  7507. struct img_blit b;
  7508. if (!src)
  7509. src = &images[idx].img;
  7510. b.dst = l->ui->px;
  7511. b.dst_w = l->ui->w;
  7512. b.dst_h = l->ui->h;
  7513. b.clip_x = page_rect.x;
  7514. b.clip_y = page_rect.y;
  7515. b.clip_w = page_rect.w - 12;
  7516. b.clip_h = page_rect.h;
  7517. b.x = x;
  7518. b.y = y;
  7519. b.scale = ((unsigned int)dw << 16) / src->w;
  7520. b.bg = ui.theme.bg;
  7521. b.bg2 = ui.theme.bg;
  7522. b.dst_a = 0;
  7523. /* OVER_DST is only needed for an alpha source; an opaque one can
  7524. * take img_draw's 1:1 copy path. */
  7525. b.flags = src->alpha ? IMG_BLIT_OVER_DST : 0;
  7526. img_draw(src, &b);
  7527. } else if (l->draw) {
  7528. ngui_fill_rect(l->ui, (struct ngui_rect){x, y, dw, dh},
  7529. 0xD69A);
  7530. ngui_frame(l->ui, (struct ngui_rect){x, y, dw, dh}, 0x8410);
  7531. ngui_text(l->ui, x + 8, y + 8, "[image]", 0x4208);
  7532. }
  7533. }
  7534. static void layout_block(struct lay *l, unsigned int node,
  7535. const struct br_style *st, int depth,
  7536. unsigned short link)
  7537. {
  7538. int old_left = l->left, old_right = l->right, old_align = l->align;
  7539. int parent_cb_h = l->cb_h;
  7540. int saved_parent_top = l->parent_top;
  7541. int saved_cb_left = l->cb_left, saved_cb_right = l->cb_right;
  7542. int saved_cb_top = l->cb_top;
  7543. int top, l0, r0;
  7544. int flow_y, flow_left, flow_right, positioned, relative, sticky, shifted;
  7545. int cbw, ml, mr, bl, br, pl, pr, bt, bb, pt, pb;
  7546. int deco_w, deco_h, content_w, content_h, box_h;
  7547. int img_dh = 0;
  7548. int definite_w = 0;
  7549. int normal_top = 0;
  7550. int rel_dx = 0, rel_dy = 0;
  7551. int clip_pushed = 0;
  7552. struct ngui_rect clip_rect;
  7553. /* A DOM level costs about two depth units (layout_block ->
  7554. * layout_children), so 48 covers a ~24-level page. Real news pages
  7555. * nest a teaser 12+ levels deep; the old 24 skipped its text. */
  7556. if (depth > 48 || st->display == BR_DISPLAY_NONE)
  7557. return;
  7558. flow_y = l->y;
  7559. flow_left = l->left;
  7560. flow_right = l->right;
  7561. positioned = st->pos == 1 || st->pos == 2;
  7562. relative = st->pos == 3;
  7563. sticky = st->pos == 4;
  7564. shifted = relative || sticky || st->transform_set;
  7565. if (positioned) {
  7566. int def_w = st->width_kind == 1 ? st->width : -1;
  7567. if (st->pos == 2) {
  7568. int avail_w = page_rect.w - 12;
  7569. if (st->right_set && def_w >= 0)
  7570. l->left = page_rect.x + avail_w - st->right -
  7571. def_w;
  7572. else
  7573. l->left = page_rect.x +
  7574. (st->left_set ? st->left : 0);
  7575. l->right = def_w >= 0 ? l->left + def_w :
  7576. page_rect.x + avail_w;
  7577. if (st->bottom_set && st->height_kind)
  7578. l->y = page_rect.y + page_rect.h -
  7579. st->bottom -
  7580. style_height_px(st, page_rect.w);
  7581. else
  7582. l->y = page_rect.y +
  7583. (st->top_set ? st->top : 0);
  7584. } else {
  7585. int left = flow_left + (st->left_set ? st->left : 0);
  7586. unsigned int parent = doc.nodes[node].parent;
  7587. if (st->right_set && def_w >= 0)
  7588. left = flow_right - st->right - def_w;
  7589. l->left = left;
  7590. l->right = def_w >= 0 ? left + def_w :
  7591. flow_right +
  7592. (st->left_set ? st->left : 0);
  7593. l->y = flow_y + (st->top_set ? st->top : 0);
  7594. if (st->bottom_set && st->height_kind &&
  7595. parent < BR_MAX_NODES && block_h[parent] > 0)
  7596. l->y = flow_y + block_h[parent] - st->bottom -
  7597. style_height_px(st, old_right - old_left);
  7598. }
  7599. old_left = l->left;
  7600. old_right = l->right;
  7601. } else if (relative) {
  7602. rel_dx = st->left_set ? st->left :
  7603. (st->right_set ? -st->right : 0);
  7604. rel_dy = st->top_set ? st->top :
  7605. (st->bottom_set ? -st->bottom : 0);
  7606. }
  7607. if (st->transform_set) {
  7608. rel_dx += st->tx;
  7609. rel_dy += st->ty;
  7610. }
  7611. if ((doc.nodes[node].tag == BR_TAG_INPUT ||
  7612. doc.nodes[node].tag == BR_TAG_TEXTAREA ||
  7613. doc.nodes[node].tag == BR_TAG_SELECT ||
  7614. doc.nodes[node].tag == BR_TAG_BUTTON) &&
  7615. !button_has_elements(node)) {
  7616. if (doc.nodes[node].tag == BR_TAG_INPUT &&
  7617. s_eq(br_type(&doc, node), "hidden"))
  7618. return;
  7619. /* Reached as a block-level box (a flex item): the control
  7620. * fills the box the caller assigned, and its line is flushed
  7621. * here; flex layout resets the run list for the next item, so
  7622. * a queued run would never be drawn. */
  7623. form_fill_line = 1;
  7624. add_form_run(l, node, st, link);
  7625. form_fill_line = 0;
  7626. flush_line(l);
  7627. return;
  7628. }
  7629. flush_line(l);
  7630. cbw = old_right - old_left;
  7631. if (cbw < 8)
  7632. cbw = 8;
  7633. l->y += mp_px(st, 0, cbw);
  7634. top = l->y;
  7635. ml = mp_px(st, 3, cbw);
  7636. mr = mp_px(st, 1, cbw);
  7637. bl = st->border_w[3];
  7638. br = st->border_w[1];
  7639. pl = mp_px(st, 7, cbw);
  7640. pr = mp_px(st, 5, cbw);
  7641. bt = st->border_w[0];
  7642. bb = st->border_w[2];
  7643. pt = mp_px(st, 4, cbw);
  7644. pb = mp_px(st, 6, cbw);
  7645. deco_w = bl + br + pl + pr;
  7646. deco_h = bt + bb + pt + pb;
  7647. if (st->width_kind) {
  7648. int w;
  7649. if (st->width_kind == 3)
  7650. w = cbw * st->width_calc_pct / 100 +
  7651. st->width_calc_px;
  7652. else
  7653. w = css_size(st->width_kind, st->width, cbw);
  7654. if (w < 0)
  7655. w = 0;
  7656. content_w = st->box_sizing ? w - deco_w : w;
  7657. definite_w = 1;
  7658. } else if ((doc.nodes[node].tag == BR_TAG_TABLE ||
  7659. doc.nodes[node].tag == BR_TAG_TD ||
  7660. doc.nodes[node].tag == BR_TAG_TH) &&
  7661. doc.nodes[node].width_attr) {
  7662. /* Legacy table/cell width attributes: percentages resolve
  7663. * against the containing block, bare numbers are pixels. */
  7664. int w = doc.nodes[node].width_pct ?
  7665. cbw * doc.nodes[node].width_attr / 100 :
  7666. doc.nodes[node].width_attr;
  7667. if (w < 0)
  7668. w = 0;
  7669. content_w = st->box_sizing ? w - deco_w : w;
  7670. definite_w = 1;
  7671. } else {
  7672. content_w = cbw - ml - mr - deco_w;
  7673. }
  7674. if (content_w < 0)
  7675. content_w = 0;
  7676. if (st->max_width_kind) {
  7677. int mw = st->max_width_kind == 3 ?
  7678. cbw * st->max_width_calc_pct / 100 +
  7679. st->max_width_calc_px :
  7680. css_size(st->max_width_kind, st->max_width, cbw);
  7681. int max_box = st->box_sizing ? mw : mw + deco_w;
  7682. if (content_w + deco_w > max_box)
  7683. content_w = max_box - deco_w;
  7684. }
  7685. if (st->min_width_kind) {
  7686. int mw = st->min_width_kind == 3 ?
  7687. cbw * st->min_width_calc_pct / 100 +
  7688. st->min_width_calc_px :
  7689. css_size(st->min_width_kind, st->min_width, cbw);
  7690. int min_box = st->box_sizing ? mw : mw + deco_w;
  7691. if (content_w + deco_w < min_box) {
  7692. content_w = min_box - deco_w;
  7693. definite_w = 1;
  7694. }
  7695. }
  7696. if (content_w < 8)
  7697. content_w = 8;
  7698. if (definite_w) {
  7699. int free_w = cbw - ml - mr - deco_w - content_w;
  7700. if (free_w < 0)
  7701. free_w = 0;
  7702. if (st->ml_auto && st->mr_auto) {
  7703. ml = free_w / 2;
  7704. mr = free_w - ml;
  7705. } else if (st->ml_auto) {
  7706. ml = free_w;
  7707. } else if (st->mr_auto) {
  7708. mr = free_w;
  7709. }
  7710. }
  7711. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7712. int iw, ih;
  7713. image_block_size(node, st, cbw, &iw, &ih);
  7714. content_w = iw;
  7715. img_dh = ih;
  7716. }
  7717. l0 = old_left + ml;
  7718. r0 = l0 + deco_w + content_w;
  7719. if (r0 < l0 + 8)
  7720. r0 = l0 + 8;
  7721. normal_top = top;
  7722. if (sticky) {
  7723. if (st->top_set) {
  7724. int stick = page_rect.y + 4 + st->top;
  7725. if (normal_top < stick)
  7726. rel_dy += stick - normal_top;
  7727. } else if (st->bottom_set && block_h[node]) {
  7728. int stick = page_rect.y + page_rect.h - st->bottom -
  7729. block_h[node];
  7730. if (normal_top > stick)
  7731. rel_dy += stick - normal_top;
  7732. }
  7733. if (l->draw && doc.nodes[node].parent < BR_MAX_NODES &&
  7734. block_h[doc.nodes[node].parent]) {
  7735. unsigned int p = doc.nodes[node].parent;
  7736. int ptop = l->parent_top;
  7737. int pbottom = ptop + block_h[p];
  7738. int eh = block_h[node];
  7739. int moved_top = normal_top + rel_dy;
  7740. int moved_bottom = moved_top + eh;
  7741. if (moved_bottom > pbottom)
  7742. rel_dy -= moved_bottom - pbottom;
  7743. moved_top = normal_top + rel_dy;
  7744. if (moved_top < ptop)
  7745. rel_dy += ptop - moved_top;
  7746. }
  7747. }
  7748. if (shifted && l->draw) {
  7749. top += rel_dy;
  7750. l0 += rel_dx;
  7751. r0 += rel_dx;
  7752. }
  7753. l->parent_top = top;
  7754. if (st->pos != 0) {
  7755. /* Positioned boxes establish the containing block for their
  7756. * absolutely positioned descendants. */
  7757. l->cb_left = l0;
  7758. l->cb_right = r0;
  7759. l->cb_top = top;
  7760. }
  7761. if (l->draw && block_h[node] &&
  7762. top < page_rect.y + page_rect.h &&
  7763. top + block_h[node] > page_rect.y) {
  7764. struct ngui_rect box = {l0, top, r0 - l0, block_h[node]};
  7765. int rtl = css_radius(st, 0, box.w, box.h);
  7766. int rtr = css_radius(st, 1, box.w, box.h);
  7767. int rbr = css_radius(st, 2, box.w, box.h);
  7768. int rbl = css_radius(st, 3, box.w, box.h);
  7769. if (st->transform_scale) {
  7770. if (st->has_bg)
  7771. fill_transformed_rect(l->ui, box, st->bg, st);
  7772. } else if (rtl || rtr || rbr || rbl) {
  7773. if (st->has_bg) {
  7774. int bw = st->border_w[0];
  7775. if (bw > 0 && !st->border_t[0] &&
  7776. st->border_c[0] != st->bg &&
  7777. box.w > bw * 2 && box.h > bw * 2) {
  7778. struct ngui_rect inner = {
  7779. box.x + bw, box.y + bw,
  7780. box.w - bw * 2, box.h - bw * 2
  7781. };
  7782. int itl = rtl > bw ? rtl - bw : 0;
  7783. int itr = rtr > bw ? rtr - bw : 0;
  7784. int ibr = rbr > bw ? rbr - bw : 0;
  7785. int ibl = rbl > bw ? rbl - bw : 0;
  7786. ngui_fill_round_rect(l->ui, box, rtl,
  7787. rtr, rbr, rbl,
  7788. st->border_c[0]);
  7789. ngui_fill_round_rect(l->ui, inner,
  7790. itl, itr, ibr,
  7791. ibl, st->bg);
  7792. } else {
  7793. ngui_fill_round_rect(l->ui, box, rtl,
  7794. rtr, rbr, rbl,
  7795. st->bg);
  7796. }
  7797. } else if (st->border_w[0] && !st->border_t[0]) {
  7798. ngui_frame_round(l->ui, box, rtl, rtr, rbr,
  7799. rbl, st->border_w[0],
  7800. st->border_c[0]);
  7801. }
  7802. /* Rounded boxes paint their background image too
  7803. * (app icons are rounded squares), kept inside the
  7804. * corner arcs. */
  7805. if (st->bg_image)
  7806. draw_bg_image_round(l, box, node, st, rtl, rtr,
  7807. rbr, rbl);
  7808. } else {
  7809. if (st->has_bg)
  7810. ngui_fill_rect(l->ui, box, st->bg);
  7811. if (st->bg_image)
  7812. draw_bg_image(l, box, node, st);
  7813. if (st->border_w[0] || st->border_w[1] ||
  7814. st->border_w[2] || st->border_w[3])
  7815. draw_border_box(l->ui, box, st);
  7816. }
  7817. }
  7818. if (l->draw && doc.nodes[node].tag == BR_TAG_IMG)
  7819. draw_image_block(l, node, l0 + bl + pl, top + bt + pt,
  7820. content_w, img_dh);
  7821. if (l->draw && st->overflow_hidden && block_h[node] > 0 &&
  7822. l->ui && l->ui->nclip < 4) {
  7823. clip_rect.x = l0 + bl;
  7824. clip_rect.y = top + bt;
  7825. clip_rect.w = (r0 - l0) - bl - br;
  7826. clip_rect.h = (int)block_h[node] - bt - bb;
  7827. if (clip_rect.w > 0 && clip_rect.h > 0) {
  7828. ngui_push_clip(l->ui, clip_rect);
  7829. clip_pushed = 1;
  7830. }
  7831. }
  7832. l->left = l0 + bl + pl;
  7833. l->right = l->left + content_w;
  7834. if (l->right < l->left + 8)
  7835. l->right = l->left + 8;
  7836. l->align = st->align;
  7837. l->line_left = l->left;
  7838. l->line_right = l->right;
  7839. l->y = top + bt + pt;
  7840. if (doc.nodes[node].tag == BR_TAG_HR) {
  7841. if (l->draw)
  7842. ngui_fill_rect(l->ui, (struct ngui_rect){l->left,
  7843. l->y + 2, l->right - l->left, 1}, BR_GRAY);
  7844. l->y += 8;
  7845. } else if (doc.nodes[node].tag == BR_TAG_VIDEO) {
  7846. int vw = l->right - l->left;
  7847. int vh;
  7848. if (doc.nodes[node].width_pct)
  7849. vw = vw * doc.nodes[node].width_attr / 100;
  7850. else if (doc.nodes[node].width_attr)
  7851. vw = doc.nodes[node].width_attr;
  7852. if (vw > l->right - l->left)
  7853. vw = l->right - l->left;
  7854. if (vw < 8)
  7855. vw = 8;
  7856. vh = vw * 9 / 16;
  7857. if (vh > 240)
  7858. vh = 240;
  7859. if (vh < 80)
  7860. vh = 80;
  7861. if (l->draw) {
  7862. ngui_fill_rect(l->ui, (struct ngui_rect){l->left, l->y,
  7863. vw, vh}, 0xD69A);
  7864. ngui_frame(l->ui, (struct ngui_rect){l->left, l->y,
  7865. vw, vh}, 0x8410);
  7866. ngui_text(l->ui, l->left + 8, l->y + 8, "[video]",
  7867. 0x4208);
  7868. }
  7869. l->y += vh + 4;
  7870. } else if (doc.nodes[node].tag == BR_TAG_SVG) {
  7871. int dw, dh, cw = l->right - l->left;
  7872. svg_size(node, st, cw > 8 ? cw : 8, &dw, &dh);
  7873. if (l->draw && l->y < page_rect.y + page_rect.h &&
  7874. l->y + dh > page_rect.y)
  7875. svg_paint_box(l->ui, node, st, l->left, l->y, dw, dh);
  7876. l->y += dh;
  7877. } else {
  7878. if (doc.nodes[node].tag == BR_TAG_LI && st->list_item &&
  7879. !st->no_bullet) {
  7880. char *m = li_marker[node];
  7881. if (!m[0]) {
  7882. unsigned int parent = doc.nodes[node].parent;
  7883. int style = st->list_style;
  7884. int idx = parent ? list_index(parent, node) : 1;
  7885. if (style == BR_LIST_AUTO)
  7886. style = (parent &&
  7887. doc.nodes[parent].tag ==
  7888. BR_TAG_OL) ?
  7889. BR_LIST_DECIMAL : BR_LIST_DISC;
  7890. list_marker_text(m, sizeof(li_marker[node]),
  7891. style, idx);
  7892. }
  7893. if (l->draw && m[0]) {
  7894. int mw = (int)ngui_text_width_ui(l->ui, m);
  7895. ngui_text(l->ui, l->left - mw - 6, l->y, m,
  7896. st->color);
  7897. }
  7898. }
  7899. /* This box's definite content height, for its children's
  7900. * percentage heights. */
  7901. if (doc.nodes[node].tag == BR_TAG_HTML ||
  7902. doc.nodes[node].tag == BR_TAG_BODY)
  7903. l->cb_h = layout_view_h;
  7904. else if (st->height_kind == 1)
  7905. l->cb_h = (int)st->height -
  7906. (st->box_sizing ? deco_h : 0);
  7907. else if (st->height_kind == 2 && parent_cb_h > 0)
  7908. l->cb_h = parent_cb_h * (int)st->height / 100 -
  7909. (st->box_sizing ? deco_h : 0);
  7910. else if (!st->height_kind && st->aspect_w && st->aspect_h)
  7911. l->cb_h = content_w * (int)st->aspect_h /
  7912. (int)st->aspect_w;
  7913. else
  7914. l->cb_h = 0;
  7915. if (l->cb_h < 0)
  7916. l->cb_h = 0;
  7917. if (doc.nodes[node].tag == BR_TAG_TR)
  7918. layout_table_row(l, node, st, depth + 1, link);
  7919. else if (doc.nodes[node].tag == BR_TAG_TABLE &&
  7920. table_has_rowspan(node))
  7921. layout_table(l, node, st, depth + 1, link);
  7922. else if (st->grid_auto)
  7923. layout_grid_auto(l, node, st, depth + 1, link);
  7924. else if (st->display == BR_DISPLAY_GRID && st->grid_ncols >= 2 &&
  7925. st->grid_gap > 0)
  7926. layout_grid_children(l, node, st, depth + 1, link);
  7927. else if (st->display == BR_DISPLAY_FLEX && !st->flex_col &&
  7928. flex_wants_row(node, st))
  7929. layout_flex_children(l, node, st, depth + 1, link);
  7930. else if (st->display == BR_DISPLAY_FLEX && st->flex_col &&
  7931. st->align_items == 1) {
  7932. /* align-items: center in a column: the items' lines
  7933. * (an app card's icon and label) are centred; a child
  7934. * with its own text-align keeps it. */
  7935. struct br_style cst = *st;
  7936. cst.align = BR_ALIGN_CENTER;
  7937. l->align = BR_ALIGN_CENTER;
  7938. layout_children(l, node, &cst, depth + 1, link);
  7939. } else
  7940. layout_children(l, node, st, depth + 1, link);
  7941. l->cb_h = parent_cb_h;
  7942. }
  7943. flush_line(l);
  7944. if (clip_pushed)
  7945. ngui_pop_clip(l->ui);
  7946. if (l->float_active) {
  7947. if (l->y < l->float_bottom)
  7948. l->y = l->float_bottom;
  7949. l->float_active = 0;
  7950. }
  7951. if (doc.nodes[node].tag == BR_TAG_IMG) {
  7952. content_h = img_dh;
  7953. } else if (st->height_kind == 2 &&
  7954. doc.nodes[node].tag != BR_TAG_HTML &&
  7955. doc.nodes[node].tag != BR_TAG_BODY) {
  7956. /* A percentage of the containing block's definite height, or
  7957. * auto when it has none (it used to resolve against the
  7958. * width). The result is a minimum: without scrollable inner
  7959. * boxes, an app shell's height:100%; overflow:hidden column
  7960. * would otherwise clip everything past the first screen. */
  7961. int auto_h = l->y - (top + bt + pt);
  7962. content_h = parent_cb_h > 0 ?
  7963. parent_cb_h * (int)st->height / 100 -
  7964. (st->box_sizing ? deco_h : 0) : 0;
  7965. if (content_h < auto_h)
  7966. content_h = auto_h;
  7967. } else if (st->height_kind &&
  7968. !((doc.nodes[node].tag == BR_TAG_HTML ||
  7969. doc.nodes[node].tag == BR_TAG_BODY) &&
  7970. st->height_kind == 2)) {
  7971. content_h = style_height_px(st, cbw);
  7972. if (st->box_sizing)
  7973. content_h -= deco_h;
  7974. } else {
  7975. /* Percentage heights on html/body resolve against the
  7976. * viewport, but their content still defines the document
  7977. * scroll height. Treating them as auto avoids collapsing
  7978. * the measured page to the containing block width. */
  7979. content_h = l->y - (top + bt + pt);
  7980. /* aspect-ratio: the preferred height of an auto-height box
  7981. * (Tailwind aspect-video image frames); content can still
  7982. * make it taller, as with min-height: auto. */
  7983. if (st->aspect_w && st->aspect_h && content_w > 0) {
  7984. int ah = content_w * (int)st->aspect_h /
  7985. (int)st->aspect_w;
  7986. if (content_h < ah)
  7987. content_h = ah;
  7988. }
  7989. }
  7990. if (content_h < 0)
  7991. content_h = 0;
  7992. if (st->max_height_kind) {
  7993. int mh = st->max_height_kind == 3 ?
  7994. cbw * st->max_height_calc_pct / 100 +
  7995. st->max_height_calc_px :
  7996. css_size(st->max_height_kind, st->max_height, cbw);
  7997. int max_box = st->box_sizing ? mh : mh + deco_h;
  7998. if (content_h + deco_h > max_box)
  7999. content_h = max_box - deco_h;
  8000. }
  8001. if (st->min_height_kind &&
  8002. !((doc.nodes[node].tag == BR_TAG_HTML ||
  8003. doc.nodes[node].tag == BR_TAG_BODY) &&
  8004. st->min_height_kind == 2)) {
  8005. int mh = st->min_height_kind == 3 ?
  8006. cbw * st->min_height_calc_pct / 100 +
  8007. st->min_height_calc_px :
  8008. css_size(st->min_height_kind, st->min_height, cbw);
  8009. int min_box = st->box_sizing ? mh : mh + deco_h;
  8010. if (content_h + deco_h < min_box)
  8011. content_h = min_box - deco_h;
  8012. }
  8013. if (content_h < 0)
  8014. content_h = 0;
  8015. box_h = deco_h + content_h;
  8016. if (box_h < 0)
  8017. box_h = 0;
  8018. l->y = (shifted ? normal_top : top) + box_h;
  8019. if (node < BR_MAX_NODES) {
  8020. layout_boxes[node].x = l0;
  8021. layout_boxes[node].y = top;
  8022. layout_boxes[node].w = r0 - l0;
  8023. layout_boxes[node].h = box_h;
  8024. layout_boxes[node].valid = r0 > l0;
  8025. }
  8026. l->left = old_left;
  8027. l->right = old_right;
  8028. l->align = old_align;
  8029. l->y += mp_px(st, 2, cbw);
  8030. if (!l->draw) {
  8031. if (box_h > 65535)
  8032. box_h = 65535;
  8033. block_h[node] = (unsigned short)box_h;
  8034. block_top[node] = (unsigned short)(top < 0 ? 0 :
  8035. top > 65535 ? 65535 : top);
  8036. }
  8037. if (positioned) {
  8038. l->y = flow_y;
  8039. l->left = flow_left;
  8040. l->right = flow_right;
  8041. }
  8042. l->parent_top = saved_parent_top;
  8043. l->cb_left = saved_cb_left;
  8044. l->cb_right = saved_cb_right;
  8045. l->cb_top = saved_cb_top;
  8046. }
  8047. static int text_node_blank(const struct br_node *nd)
  8048. {
  8049. const char *t = doc.text + nd->text_off;
  8050. unsigned int i;
  8051. for (i = 0; i < nd->text_len; i++)
  8052. if (t[i] != ' ' && t[i] != '\t' && t[i] != '\n' &&
  8053. t[i] != '\r')
  8054. return 0;
  8055. return 1;
  8056. }
  8057. /* Rough shrink-to-fit width for a float without an explicit width: sum the
  8058. * text/image widths in the subtree, plus padding and margins. This keeps
  8059. * Bootstrap's floated nav items on one line instead of giving each the whole
  8060. * row. */
  8061. static int text_space(char c)
  8062. {
  8063. return c == ' ' || c == '\t' || c == '\n' || c == '\r' || c == '\f';
  8064. }
  8065. static int intrinsic_width(struct ngui *ui, unsigned int node,
  8066. const struct br_style *pst, int depth, int base)
  8067. {
  8068. unsigned int c;
  8069. int line_w = 0, max_w = 0;
  8070. int flex_row = pst->display == BR_DISPLAY_FLEX && !pst->flex_col;
  8071. if (depth > 32)
  8072. return 0;
  8073. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8074. struct br_node *nd = &doc.nodes[c];
  8075. struct br_style cs;
  8076. if (nd->type == BR_NODE_TEXT) {
  8077. const char *t = doc.text + nd->text_off;
  8078. unsigned int tn = nd->text_len;
  8079. if (doc.nodes[node].tag == BR_TAG_PRE) {
  8080. line_w += (int)face_text_width(ui, pst, t, tn);
  8081. } else {
  8082. unsigned int ti = 0;
  8083. int first = 1;
  8084. int lead = line_w > 0 && tn > 0 && text_space(t[0]);
  8085. int sp = (int)face_text_width(ui, pst, " ", 1);
  8086. while (ti < tn) {
  8087. unsigned int ts;
  8088. while (ti < tn && text_space(t[ti]))
  8089. ti++;
  8090. ts = ti;
  8091. while (ti < tn && !text_space(t[ti]))
  8092. ti++;
  8093. if (ti == ts)
  8094. break;
  8095. if (!first || lead)
  8096. line_w += sp;
  8097. lead = 0;
  8098. line_w += (int)face_text_width(ui, pst,
  8099. t + ts, ti - ts);
  8100. first = 0;
  8101. }
  8102. }
  8103. continue;
  8104. }
  8105. br_style_for(&doc, c, pst, &cs);
  8106. if (cs.display == BR_DISPLAY_NONE)
  8107. continue;
  8108. if (nd->tag == BR_TAG_BR) {
  8109. if (line_w > max_w)
  8110. max_w = line_w;
  8111. line_w = 0;
  8112. continue;
  8113. }
  8114. if (nd->tag == BR_TAG_IMG) {
  8115. /* Measure the image as layout will draw it: a CSS or
  8116. * attribute height keeps the intrinsic aspect ratio, and
  8117. * a CSS width overrides the native pixel width. Bootstrap
  8118. * sizes the Cloudron logo with height:40px only. */
  8119. int idx = nd->img_index;
  8120. int iw = 0, ih = 0;
  8121. if (idx >= 0 && idx < image_count &&
  8122. images[idx].state == 1) {
  8123. iw = (int)images[idx].native_w;
  8124. ih = (int)images[idx].native_h;
  8125. if (iw <= 0 || ih <= 0) {
  8126. iw = (int)images[idx].img.w;
  8127. ih = (int)images[idx].img.h;
  8128. }
  8129. }
  8130. if (cs.width_kind) {
  8131. int ww = style_width_px(&cs, base);
  8132. line_w += ww > 0 ? ww : 64;
  8133. } else if (nd->width_attr) {
  8134. line_w += nd->width_attr;
  8135. } else if (nd->height_attr && iw && ih) {
  8136. line_w += iw * (int)nd->height_attr / ih;
  8137. } else if (cs.height_kind && iw && ih) {
  8138. int hh = style_height_px(&cs, base);
  8139. line_w += hh > 0 ? iw * hh / ih : iw;
  8140. } else if (iw) {
  8141. line_w += iw;
  8142. } else {
  8143. line_w += 64;
  8144. }
  8145. continue;
  8146. }
  8147. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8148. nd->tag == BR_TAG_TEXTAREA) &&
  8149. !s_eq(br_type(&doc, c), "hidden")) {
  8150. /* Form controls are replaced: CSS width applies even
  8151. * when they are inline (add_form_run's sizes). */
  8152. int fw = cs.width_kind ? style_width_px(&cs, base) :
  8153. nd->tag == BR_TAG_TEXTAREA ? 180 : 120;
  8154. if (s_eq(br_type(&doc, c), "checkbox") ||
  8155. s_eq(br_type(&doc, c), "radio"))
  8156. fw = 16;
  8157. line_w += (fw > 0 ? fw : 120) +
  8158. mp_px(&cs, 3, base) + mp_px(&cs, 1, base) +
  8159. mp_px(&cs, 7, base) + mp_px(&cs, 5, base);
  8160. continue;
  8161. }
  8162. if (nd->tag == BR_TAG_SVG) {
  8163. /* A replaced element: its own size, like add_svg_run()
  8164. * (its path children have no width). */
  8165. int sw, sh, sb = cs.width_kind ?
  8166. style_width_px(&cs, base) : base;
  8167. svg_size(c, &cs, sb > 8 ? sb : 8, &sw, &sh);
  8168. sw += mp_px(&cs, 3, base) + mp_px(&cs, 1, base);
  8169. if (flex_row || cs.display == BR_DISPLAY_INLINE ||
  8170. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8171. line_w += sw;
  8172. } else {
  8173. if (line_w > max_w)
  8174. max_w = line_w;
  8175. line_w = 0;
  8176. if (sw > max_w)
  8177. max_w = sw;
  8178. }
  8179. continue;
  8180. }
  8181. {
  8182. int cw = mp_px(&cs, 7, base) +
  8183. mp_px(&cs, 5, base) +
  8184. mp_px(&cs, 3, base) +
  8185. mp_px(&cs, 1, base) +
  8186. cs.border_w[1] + cs.border_w[3];
  8187. /* width/height do not apply to non-replaced inline
  8188. * boxes. The tagesschau home label is an inline span
  8189. * with width:1px for the mobile icon-only header; using
  8190. * that width made the whole subnav collapse to a
  8191. * one-character column. */
  8192. if (cs.width_kind && cs.display != BR_DISPLAY_INLINE)
  8193. cw += cs.width_kind == 1 ? cs.width :
  8194. style_width_px(&cs, base);
  8195. else
  8196. cw += intrinsic_width(ui, c, &cs, depth + 1,
  8197. base);
  8198. if (flex_row || cs.float_left ||
  8199. cs.display == BR_DISPLAY_INLINE ||
  8200. cs.display == BR_DISPLAY_INLINE_BLOCK) {
  8201. line_w += cw;
  8202. } else {
  8203. if (line_w > max_w)
  8204. max_w = line_w;
  8205. line_w = 0;
  8206. if (cw > max_w)
  8207. max_w = cw;
  8208. }
  8209. }
  8210. if (line_w > 4096 || max_w > 4096)
  8211. break;
  8212. }
  8213. return line_w > max_w ? line_w : max_w;
  8214. }
  8215. /* Lay consecutive floated block children side by side. Bootstrap's grid is
  8216. * the main user: .row > .col-md-* with float:left and a percentage width.
  8217. * Each column is laid out with its own left/right edge and the row advances
  8218. * to the tallest column. Returns the first child not consumed. */
  8219. static unsigned int layout_float_group(struct lay *l, unsigned int first,
  8220. const struct br_style *pst, int depth,
  8221. unsigned short link)
  8222. {
  8223. unsigned int n = first;
  8224. int row_left = l->left, row_right = l->right;
  8225. int row_top, row_bottom, xl, xr, any = 0;
  8226. int fl_left = row_left, fl_right = row_right, fl_bottom;
  8227. flush_line(l);
  8228. row_top = l->y;
  8229. row_bottom = l->y;
  8230. fl_bottom = row_top;
  8231. xl = row_left;
  8232. xr = row_right;
  8233. while (n) {
  8234. struct br_node *nd = &doc.nodes[n];
  8235. struct br_style cs;
  8236. unsigned short lk = link;
  8237. int colw, right;
  8238. if (nd->type == BR_NODE_TEXT) {
  8239. if (text_node_blank(nd)) {
  8240. n = nd->next;
  8241. continue;
  8242. }
  8243. break;
  8244. }
  8245. br_style_for(&doc, n, pst, &cs);
  8246. if (cs.display == BR_DISPLAY_NONE) {
  8247. n = nd->next;
  8248. continue;
  8249. }
  8250. /* A float blockifies its box: Bootstrap floats inline
  8251. * anchors too (the navbar brand and its text links), and
  8252. * their padding must be honoured. */
  8253. if (!cs.float_left)
  8254. break;
  8255. if (nd->tag == BR_TAG_A && nd->href_off)
  8256. lk = (unsigned short)n;
  8257. right = cs.float_left == 2;
  8258. if (cs.width_kind == 2 || cs.width_kind == 3) {
  8259. colw = style_width_px(&cs, row_right - row_left);
  8260. } else if (cs.width_kind == 1) {
  8261. colw = (int)cs.width;
  8262. } else {
  8263. int base = row_right - row_left;
  8264. colw = intrinsic_width(l->ui, n, &cs, 0, base) +
  8265. mp_px(&cs, 7, base) +
  8266. mp_px(&cs, 5, base) +
  8267. mp_px(&cs, 3, base) +
  8268. mp_px(&cs, 1, base);
  8269. if (colw < 8)
  8270. colw = 8;
  8271. }
  8272. if (colw < 8)
  8273. colw = 8;
  8274. if (colw > row_right - row_left)
  8275. colw = row_right - row_left;
  8276. /* The float column width is already resolved. */
  8277. cs.width_kind = 0;
  8278. cs.max_width_kind = 0;
  8279. if (right) {
  8280. if (any && xr - colw < xl) {
  8281. row_top = row_bottom;
  8282. row_bottom = row_top;
  8283. xl = row_left;
  8284. xr = row_right;
  8285. }
  8286. if (xr - colw < xl)
  8287. colw = xr - xl;
  8288. if (colw < 8)
  8289. colw = 8;
  8290. l->left = xr - colw;
  8291. if (l->left < row_left)
  8292. l->left = row_left;
  8293. l->right = xr;
  8294. xr = l->left;
  8295. if (xr < fl_right)
  8296. fl_right = xr;
  8297. } else {
  8298. if (any && xl + colw > xr) {
  8299. row_top = row_bottom;
  8300. row_bottom = row_top;
  8301. xl = row_left;
  8302. xr = row_right;
  8303. }
  8304. l->left = xl;
  8305. l->right = xl + colw;
  8306. xl += colw;
  8307. if (xl > fl_left)
  8308. fl_left = xl;
  8309. }
  8310. if (l->right < l->left + 8)
  8311. l->right = l->left + 8;
  8312. l->y = row_top;
  8313. l->line_x = l->left;
  8314. l->run_x = l->left;
  8315. l->line_y = l->y;
  8316. l->line_h = 0;
  8317. l->nruns = 0;
  8318. l->space_pending = 0;
  8319. l->align = cs.align;
  8320. layout_block(l, n, &cs, depth + 1, lk);
  8321. if (l->y > row_bottom)
  8322. row_bottom = l->y;
  8323. if (l->y > fl_bottom)
  8324. fl_bottom = l->y;
  8325. any = 1;
  8326. n = nd->next;
  8327. }
  8328. l->left = row_left;
  8329. l->right = row_right;
  8330. if (n && any) {
  8331. struct br_node *nd = &doc.nodes[n];
  8332. int inline_next = 0;
  8333. if (nd->type == BR_NODE_TEXT) {
  8334. inline_next = 1;
  8335. } else if (nd->type == BR_NODE_ELEM) {
  8336. struct br_style cs;
  8337. br_style_for(&doc, n, pst, &cs);
  8338. inline_next = cs.display != BR_DISPLAY_BLOCK &&
  8339. cs.display != BR_DISPLAY_NONE &&
  8340. !br_tag_is_block(nd->tag);
  8341. }
  8342. if (inline_next) {
  8343. if (l->float_active) {
  8344. if (l->float_left > fl_left)
  8345. fl_left = l->float_left;
  8346. if (l->float_right < fl_right)
  8347. fl_right = l->float_right;
  8348. if (l->float_bottom > fl_bottom)
  8349. fl_bottom = l->float_bottom;
  8350. }
  8351. l->float_active = 1;
  8352. l->float_left = fl_left;
  8353. l->float_right = fl_right;
  8354. l->float_bottom = fl_bottom;
  8355. l->y = row_top;
  8356. } else {
  8357. l->float_active = 0;
  8358. l->y = row_bottom;
  8359. }
  8360. } else {
  8361. l->float_active = 0;
  8362. l->y = row_bottom;
  8363. }
  8364. l->line_x = l->left;
  8365. l->run_x = l->left;
  8366. l->line_left = l->left;
  8367. l->line_right = l->right;
  8368. l->line_y = l->y;
  8369. l->line_h = 0;
  8370. l->nruns = 0;
  8371. l->space_pending = 0;
  8372. return n;
  8373. }
  8374. static int flex_item_width(struct lay *l, unsigned int n,
  8375. const struct br_style *cs, int avail)
  8376. {
  8377. struct br_node *nd = &doc.nodes[n];
  8378. (void)l;
  8379. int w;
  8380. if (cs->width_kind == 2 || cs->width_kind == 3)
  8381. w = style_width_px(cs, avail);
  8382. else if (cs->width_kind == 1)
  8383. w = (int)cs->width;
  8384. else if (nd->tag == BR_TAG_IMG) {
  8385. int idx = nd->img_index;
  8386. if (idx >= 0 && idx < image_count &&
  8387. images[idx].state == 1)
  8388. w = (int)images[idx].img.w;
  8389. else if (nd->width_attr)
  8390. w = (int)nd->width_attr;
  8391. else
  8392. w = 64;
  8393. } else if (nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_SELECT ||
  8394. nd->tag == BR_TAG_TEXTAREA) {
  8395. /* A control has no content to measure: its default size
  8396. * (a search field in a filter bar). */
  8397. w = nd->tag == BR_TAG_TEXTAREA ? 180 : 150;
  8398. } else {
  8399. w = intrinsic_width(l->ui, n, cs, 0, avail);
  8400. }
  8401. /* Explicit widths are content-box sizes; the flex item's outer width
  8402. * must include padding, borders and margins. */
  8403. w += mp_px(cs, 7, avail);
  8404. w += mp_px(cs, 5, avail);
  8405. w += mp_px(cs, 3, avail);
  8406. w += mp_px(cs, 1, avail);
  8407. w += cs->border_w[1] + cs->border_w[3];
  8408. if (w < 24)
  8409. w = 24;
  8410. if (w > avail)
  8411. w = avail;
  8412. return w;
  8413. }
  8414. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8415. int depth);
  8416. /* An inline child of a text-only inline-block: the same test minus the
  8417. * display check (an inline <span> may have padding/background in CSS, but
  8418. * the inline path paints those for spans anyway). */
  8419. static int inline_block_flows_inline(unsigned int node,
  8420. const struct br_style *cs, int depth)
  8421. {
  8422. unsigned int c;
  8423. if (depth > 3 || cs->pos)
  8424. return 0;
  8425. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8426. const struct br_node *nd = &doc.nodes[c];
  8427. struct br_style ch;
  8428. if (nd->type != BR_NODE_ELEM)
  8429. continue;
  8430. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8431. br_tag_is_block(nd->tag))
  8432. return 0;
  8433. br_style_for(&doc, c, cs, &ch);
  8434. if (ch.display == BR_DISPLAY_NONE)
  8435. continue;
  8436. if (ch.display != BR_DISPLAY_INLINE ||
  8437. !inline_block_flows_inline(c, &ch, depth + 1))
  8438. return 0;
  8439. }
  8440. return 1;
  8441. }
  8442. /* An inline-block that is only text in a line (a <time> in a byline, a
  8443. * label) with no box of its own -- no size, background, border or padding
  8444. * -- lays out exactly like an inline element, so it stays in the text line
  8445. * instead of ending it. Boxes with any of those keep the row path. */
  8446. static int inline_block_flows(unsigned int node, const struct br_style *cs,
  8447. int depth)
  8448. {
  8449. unsigned int c;
  8450. int i;
  8451. if (cs->width_kind || cs->height_kind || cs->min_width_kind ||
  8452. cs->min_height_kind || cs->has_bg || cs->bg_image ||
  8453. cs->pos || depth > 3)
  8454. return 0;
  8455. for (i = 0; i < 4; i++)
  8456. if (cs->border_w[i])
  8457. return 0;
  8458. for (i = 4; i < 8; i++)
  8459. if (mp_px(cs, i, 0) > 0)
  8460. return 0;
  8461. for (c = doc.nodes[node].first; c; c = doc.nodes[c].next) {
  8462. const struct br_node *nd = &doc.nodes[c];
  8463. struct br_style ch;
  8464. if (nd->type != BR_NODE_ELEM)
  8465. continue;
  8466. if (nd->tag == BR_TAG_IMG || nd->tag == BR_TAG_SVG ||
  8467. br_tag_is_block(nd->tag))
  8468. return 0;
  8469. br_style_for(&doc, c, cs, &ch);
  8470. if (ch.display == BR_DISPLAY_NONE)
  8471. continue;
  8472. if (ch.display != BR_DISPLAY_INLINE ||
  8473. !inline_block_flows_inline(c, &ch, depth + 1))
  8474. return 0;
  8475. }
  8476. return 1;
  8477. }
  8478. /* A run of display:inline-block siblings (file tags, small buttons) belongs
  8479. * on one line, not one full-width block each. Place intrinsic widths from
  8480. * left to right and wrap when the row is full. */
  8481. static unsigned int layout_inline_blocks(struct lay *l, unsigned int first,
  8482. const struct br_style *pst, int depth,
  8483. unsigned short link)
  8484. {
  8485. unsigned int n = first;
  8486. int row_left = l->left, row_right = l->right;
  8487. int avail = row_right - row_left;
  8488. int x = row_left, y = l->y, row_h = 0, any = 0;
  8489. /* Each box sets l->align from its own style; the text after the row
  8490. * must keep the container's (a centred .fa-fw icon centred the menu
  8491. * label that followed it). */
  8492. unsigned char row_align = l->align;
  8493. flush_line(l);
  8494. y = l->y;
  8495. while (n) {
  8496. struct br_node *nd = &doc.nodes[n];
  8497. struct br_style cs;
  8498. unsigned short lk = link;
  8499. int colw, h;
  8500. if (nd->type == BR_NODE_TEXT) {
  8501. if (!text_node_blank(nd))
  8502. break;
  8503. if (any)
  8504. x += 4;
  8505. n = nd->next;
  8506. continue;
  8507. }
  8508. br_style_for(&doc, n, pst, &cs);
  8509. if (cs.display == BR_DISPLAY_NONE) {
  8510. n = nd->next;
  8511. continue;
  8512. }
  8513. if (cs.display != BR_DISPLAY_INLINE_BLOCK)
  8514. break;
  8515. if (nd->tag == BR_TAG_A && nd->href_off)
  8516. lk = (unsigned short)n;
  8517. colw = flex_item_width(l, n, &cs, avail);
  8518. /* A few pixels of slack keep a single long token (boot.S)
  8519. * from wrapping at the exact content width. */
  8520. colw += 8;
  8521. if (colw > avail)
  8522. colw = avail;
  8523. cs.width_kind = 0;
  8524. cs.max_width_kind = 0;
  8525. if (any && x + colw > row_right) {
  8526. y += row_h + 2;
  8527. x = row_left;
  8528. row_h = 0;
  8529. any = 0;
  8530. }
  8531. if (any && x > row_left)
  8532. x += 4;
  8533. l->left = x;
  8534. l->right = x + colw;
  8535. if (l->right < l->left + 8)
  8536. l->right = l->left + 8;
  8537. l->y = y;
  8538. l->line_x = l->left;
  8539. l->run_x = l->left;
  8540. l->line_y = l->y;
  8541. l->line_h = 0;
  8542. l->nruns = 0;
  8543. l->space_pending = 0;
  8544. l->align = cs.align;
  8545. layout_block(l, n, &cs, depth + 1, lk);
  8546. h = l->y - y;
  8547. if (h > row_h)
  8548. row_h = h;
  8549. x += colw;
  8550. any = 1;
  8551. n = nd->next;
  8552. }
  8553. if (any)
  8554. y += row_h;
  8555. l->left = row_left;
  8556. l->right = row_right;
  8557. l->align = row_align;
  8558. l->y = y;
  8559. l->line_x = l->left;
  8560. l->run_x = l->left;
  8561. l->line_y = l->y;
  8562. l->line_h = 0;
  8563. l->nruns = 0;
  8564. l->space_pending = 0;
  8565. return n;
  8566. }
  8567. struct flex_item {
  8568. unsigned int node;
  8569. unsigned short link;
  8570. int w;
  8571. };
  8572. static void layout_flex_children(struct lay *l, unsigned int parent,
  8573. const struct br_style *pst, int depth,
  8574. unsigned short link)
  8575. {
  8576. struct flex_item it[32];
  8577. unsigned int c;
  8578. int nitem = 0, grow_count = 0, fixed = 0, grow_w, gap = pst->grid_gap;
  8579. int row_left = l->left, row_right = l->right;
  8580. int avail = row_right - row_left;
  8581. int idx, row_top;
  8582. unsigned char row_align = l->align;
  8583. if (avail < 160 || depth > 48) {
  8584. layout_children(l, parent, pst, depth, link);
  8585. return;
  8586. }
  8587. /* If direct text is not just whitespace, normal block flow handles it
  8588. * better than pretending it is a flex item. */
  8589. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8590. struct br_node *nd = &doc.nodes[c];
  8591. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8592. layout_children(l, parent, pst, depth, link);
  8593. return;
  8594. }
  8595. }
  8596. for (c = doc.nodes[parent].first;
  8597. c && nitem < (int)(sizeof(it) / sizeof(it[0]));
  8598. c = doc.nodes[c].next) {
  8599. struct br_node *nd = &doc.nodes[c];
  8600. struct br_style cs;
  8601. if (nd->type == BR_NODE_TEXT)
  8602. continue;
  8603. br_style_for(&doc, c, pst, &cs);
  8604. if (cs.display == BR_DISPLAY_NONE)
  8605. continue;
  8606. it[nitem].node = c;
  8607. it[nitem].link = (nd->tag == BR_TAG_A && nd->href_off) ?
  8608. (unsigned short)c : link;
  8609. it[nitem].w = 0;
  8610. if (cs.flex_grow && !cs.width_kind)
  8611. grow_count++;
  8612. else
  8613. fixed += flex_item_width(l, c, &cs, avail);
  8614. nitem++;
  8615. }
  8616. grow_w = grow_count ? (avail - fixed) / grow_count : 0;
  8617. if (grow_w < 96)
  8618. grow_w = 96;
  8619. for (idx = 0; idx < nitem; idx++) {
  8620. struct br_style cs;
  8621. br_style_for(&doc, it[idx].node, pst, &cs);
  8622. if (cs.flex_grow && !cs.width_kind)
  8623. it[idx].w = grow_w;
  8624. else
  8625. it[idx].w = flex_item_width(l, it[idx].node, &cs, avail);
  8626. if (it[idx].w > avail)
  8627. it[idx].w = avail;
  8628. if (it[idx].w < 8)
  8629. it[idx].w = 8;
  8630. }
  8631. row_top = l->y;
  8632. idx = 0;
  8633. while (idx < nitem) {
  8634. int start = idx, count = 0, row_w = 0;
  8635. int free_w, x, extra = 0, row_h = 0, k;
  8636. while (idx < nitem) {
  8637. int add = it[idx].w + (count ? gap : 0);
  8638. /* CSS default is nowrap; only flex-wrap: wrap (1)
  8639. * starts a new row. */
  8640. if (count && pst->flex_wrap == 1 &&
  8641. row_w + add > avail)
  8642. break;
  8643. row_w += add;
  8644. count++;
  8645. idx++;
  8646. }
  8647. if (!count) {
  8648. count = 1;
  8649. row_w = it[start].w;
  8650. idx = start + 1;
  8651. }
  8652. free_w = avail - row_w;
  8653. if (free_w < 0)
  8654. free_w = 0;
  8655. x = row_left;
  8656. if (pst->justify == 1) {
  8657. x += free_w / 2;
  8658. } else if (pst->justify == 2) {
  8659. x += free_w;
  8660. } else if (pst->justify == 3) {
  8661. extra = count > 1 ? free_w / (count - 1) : 0;
  8662. } else if (pst->justify == 4) {
  8663. extra = count ? free_w / count : 0;
  8664. x += extra / 2;
  8665. } else if (pst->justify == 5) {
  8666. extra = count ? free_w / (count + 1) : 0;
  8667. x += extra;
  8668. }
  8669. for (k = 0; k < count; k++) {
  8670. int node = (int)it[start + k].node;
  8671. int h = block_h[node];
  8672. if (h > row_h)
  8673. row_h = h;
  8674. }
  8675. if (pst->height_kind) {
  8676. int hh = style_height_px(pst, avail);
  8677. if (hh > row_h)
  8678. row_h = hh;
  8679. }
  8680. for (k = 0; k < count; k++) {
  8681. struct br_style cs;
  8682. int node = (int)it[start + k].node;
  8683. int yoff = 0;
  8684. br_style_for(&doc, node, pst, &cs);
  8685. cs.width_kind = 0;
  8686. cs.max_width_kind = 0;
  8687. if (l->draw && pst->align_items &&
  8688. row_h > block_h[node]) {
  8689. if (pst->align_items == 1)
  8690. yoff = (row_h - block_h[node]) / 2;
  8691. else if (pst->align_items == 2)
  8692. yoff = row_h - block_h[node];
  8693. }
  8694. l->left = x;
  8695. l->right = x + it[start + k].w;
  8696. if (l->right < l->left + 8)
  8697. l->right = l->left + 8;
  8698. l->y = row_top + yoff;
  8699. l->line_x = l->left;
  8700. l->run_x = l->left;
  8701. l->line_y = l->y;
  8702. l->line_h = 0;
  8703. l->nruns = 0;
  8704. l->space_pending = 0;
  8705. l->align = cs.align;
  8706. layout_block(l, node, &cs, depth + 1, it[start + k].link);
  8707. if (!l->draw) {
  8708. int h = l->y - row_top;
  8709. if (h > row_h)
  8710. row_h = h;
  8711. }
  8712. x += it[start + k].w;
  8713. if (k + 1 < count)
  8714. x += gap + extra;
  8715. }
  8716. row_top += row_h;
  8717. }
  8718. l->left = row_left;
  8719. l->right = row_right;
  8720. l->align = row_align;
  8721. l->y = row_top;
  8722. l->line_x = l->left;
  8723. l->run_x = l->left;
  8724. l->line_y = l->y;
  8725. l->line_h = 0;
  8726. l->nruns = 0;
  8727. l->space_pending = 0;
  8728. }
  8729. /* Two-column CSS grid: track sizes from grid-template-columns (px, %, fr)
  8730. * plus the grid-area hints used by site shells (site notice/footer full
  8731. * width, column-start left, page-content right). Anything more elaborate
  8732. * falls back to normal block flow. */
  8733. static int grid_track_width(unsigned char kind, unsigned short val,
  8734. int avail, int other)
  8735. {
  8736. if (kind == 2)
  8737. return avail * (int)val / 100;
  8738. if (kind == 1)
  8739. return val;
  8740. return other;
  8741. }
  8742. static void layout_grid_children(struct lay *l, unsigned int parent,
  8743. const struct br_style *pst, int depth,
  8744. unsigned short link)
  8745. {
  8746. unsigned int n;
  8747. int row_left = l->left, row_right = l->right;
  8748. int avail = row_right - row_left;
  8749. int gap = pst->grid_gap;
  8750. int track_total = avail - gap;
  8751. int col0, col1, x0, x1;
  8752. int row_y, row_bottom, have_left = 0, have_right = 0;
  8753. unsigned int c;
  8754. if (avail < 32 || depth > 48)
  8755. return;
  8756. if (track_total < 16)
  8757. track_total = 16;
  8758. col0 = grid_track_width((unsigned char)(pst->width_kind),
  8759. pst->width, track_total, 0);
  8760. col1 = grid_track_width((unsigned char)(pst->max_width_kind),
  8761. pst->max_width, track_total, 0);
  8762. if (pst->width_kind == 3 && pst->max_width_kind == 3) {
  8763. int w0 = pst->width ? pst->width : 1;
  8764. int w1 = pst->max_width ? pst->max_width : 1;
  8765. col0 = track_total * w0 / (w0 + w1);
  8766. col1 = track_total - col0;
  8767. } else if (pst->width_kind == 3) {
  8768. col0 = track_total - col1;
  8769. if (col0 < 24)
  8770. col0 = 24;
  8771. } else if (pst->max_width_kind == 3) {
  8772. col1 = track_total - col0;
  8773. if (col1 < 24)
  8774. col1 = 24;
  8775. }
  8776. if (col0 < 24)
  8777. col0 = 24;
  8778. if (col1 < 24)
  8779. col1 = 24;
  8780. if (col0 + col1 > track_total) {
  8781. col1 = track_total - col0;
  8782. if (col1 < 24)
  8783. col1 = 24;
  8784. }
  8785. x0 = row_left;
  8786. x1 = row_left + col0 + gap;
  8787. /* Direct text makes a grid ambiguous; use block flow instead. */
  8788. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8789. struct br_node *nd = &doc.nodes[c];
  8790. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8791. layout_children(l, parent, pst, depth, link);
  8792. return;
  8793. }
  8794. }
  8795. row_y = row_bottom = l->y;
  8796. n = doc.nodes[parent].first;
  8797. while (n) {
  8798. struct br_node *nd = &doc.nodes[n];
  8799. struct br_style cs;
  8800. unsigned short lk = link;
  8801. int slot, x, w;
  8802. if (nd->type == BR_NODE_TEXT) {
  8803. n = nd->next;
  8804. continue;
  8805. }
  8806. br_style_for(&doc, n, pst, &cs);
  8807. if (cs.display == BR_DISPLAY_NONE) {
  8808. n = nd->next;
  8809. continue;
  8810. }
  8811. if (nd->tag == BR_TAG_A && nd->href_off)
  8812. lk = (unsigned short)n;
  8813. slot = cs.grid_slot;
  8814. if (!slot) {
  8815. if (!have_left)
  8816. slot = 2;
  8817. else if (!have_right)
  8818. slot = 3;
  8819. else
  8820. slot = 2;
  8821. }
  8822. if (slot == 1) {
  8823. if (have_left || have_right) {
  8824. row_y = row_bottom;
  8825. have_left = have_right = 0;
  8826. }
  8827. x = row_left;
  8828. w = avail;
  8829. } else if (slot == 2) {
  8830. if (have_left) {
  8831. row_y = row_bottom;
  8832. have_left = have_right = 0;
  8833. }
  8834. x = x0;
  8835. w = col0;
  8836. have_left = 1;
  8837. } else {
  8838. if (have_right) {
  8839. row_y = row_bottom;
  8840. have_left = have_right = 0;
  8841. }
  8842. x = x1;
  8843. w = col1;
  8844. have_right = 1;
  8845. }
  8846. cs.width_kind = 0;
  8847. cs.max_width_kind = 0;
  8848. l->left = x;
  8849. l->right = x + w;
  8850. if (l->right < l->left + 8)
  8851. l->right = l->left + 8;
  8852. l->y = row_y;
  8853. l->line_x = l->left;
  8854. l->run_x = l->left;
  8855. l->line_y = l->y;
  8856. l->line_h = 0;
  8857. l->nruns = 0;
  8858. l->space_pending = 0;
  8859. l->align = cs.align;
  8860. layout_block(l, n, &cs, depth + 1, lk);
  8861. if (l->y > row_bottom)
  8862. row_bottom = l->y;
  8863. n = nd->next;
  8864. }
  8865. l->left = row_left;
  8866. l->right = row_right;
  8867. l->y = row_bottom;
  8868. l->line_x = l->left;
  8869. l->run_x = l->left;
  8870. l->line_y = l->y;
  8871. l->line_h = 0;
  8872. l->nruns = 0;
  8873. l->space_pending = 0;
  8874. }
  8875. /* repeat(auto-fit, minmax(<min>, 1fr)): pick as many equal columns as fit,
  8876. * capped at four. Used by the project docs' card grids. A fixed
  8877. * repeat(N, 1fr) (Tailwind grid-cols-N) uses exactly N columns. */
  8878. static void layout_grid_auto(struct lay *l, unsigned int parent,
  8879. const struct br_style *pst, int depth,
  8880. unsigned short link)
  8881. {
  8882. unsigned int n, c;
  8883. int row_left = l->left, row_right = l->right;
  8884. int avail = row_right - row_left;
  8885. int gap = pst->grid_gap;
  8886. int minw = pst->width_kind == 1 ? pst->width : 200;
  8887. int ncols, colw, x, y = l->y, start_y = l->y, row_h = 0, col = 0;
  8888. if (avail < 32 || depth > 48) {
  8889. layout_children(l, parent, pst, depth, link);
  8890. return;
  8891. }
  8892. for (c = doc.nodes[parent].first; c; c = doc.nodes[c].next) {
  8893. struct br_node *nd = &doc.nodes[c];
  8894. if (nd->type == BR_NODE_TEXT && !text_node_blank(nd)) {
  8895. layout_children(l, parent, pst, depth, link);
  8896. return;
  8897. }
  8898. }
  8899. if (minw < 80)
  8900. minw = 80;
  8901. ncols = (avail + gap) / (minw + gap);
  8902. if (ncols < 1)
  8903. ncols = 1;
  8904. if (ncols > 4)
  8905. ncols = 4;
  8906. if (pst->grid_auto > BR_GRID_FIXED) {
  8907. /* grid-template-columns: repeat(N, 1fr) */
  8908. ncols = pst->grid_auto - BR_GRID_FIXED;
  8909. while (ncols > 1 && (avail - gap * (ncols - 1)) / ncols < 48)
  8910. ncols--;
  8911. }
  8912. colw = (avail - gap * (ncols - 1)) / ncols;
  8913. if (colw < 24)
  8914. colw = 24;
  8915. x = row_left;
  8916. n = doc.nodes[parent].first;
  8917. while (n) {
  8918. struct br_node *nd = &doc.nodes[n];
  8919. struct br_style cs;
  8920. unsigned short lk = link;
  8921. int h;
  8922. if (nd->type == BR_NODE_TEXT) {
  8923. n = nd->next;
  8924. continue;
  8925. }
  8926. br_style_for(&doc, n, pst, &cs);
  8927. if (cs.display == BR_DISPLAY_NONE) {
  8928. n = nd->next;
  8929. continue;
  8930. }
  8931. if (nd->tag == BR_TAG_A && nd->href_off)
  8932. lk = (unsigned short)n;
  8933. cs.width_kind = 0;
  8934. cs.max_width_kind = 0;
  8935. l->left = x;
  8936. l->right = x + colw;
  8937. if (l->right < l->left + 8)
  8938. l->right = l->left + 8;
  8939. l->y = y;
  8940. l->line_x = l->left;
  8941. l->run_x = l->left;
  8942. l->line_y = l->y;
  8943. l->line_h = 0;
  8944. l->nruns = 0;
  8945. l->space_pending = 0;
  8946. l->align = cs.align;
  8947. layout_block(l, n, &cs, depth + 1, lk);
  8948. h = l->y - y;
  8949. if (h > row_h)
  8950. row_h = h;
  8951. col++;
  8952. n = nd->next;
  8953. if (col == ncols) {
  8954. y += row_h + gap;
  8955. x = row_left;
  8956. row_h = 0;
  8957. col = 0;
  8958. } else {
  8959. x += colw + gap;
  8960. }
  8961. }
  8962. if (col)
  8963. y += row_h;
  8964. else if (y > start_y)
  8965. y -= gap;
  8966. l->left = row_left;
  8967. l->right = row_right;
  8968. l->y = y;
  8969. l->line_x = l->left;
  8970. l->run_x = l->left;
  8971. l->line_y = l->y;
  8972. l->line_h = 0;
  8973. l->nruns = 0;
  8974. l->space_pending = 0;
  8975. }
  8976. /* Column widths are the widest cell in each column across every row, so all
  8977. * rows line up. The table model is still deliberately basic: no colspan,
  8978. * border-collapse or percentage columns. */
  8979. static void table_columns(struct lay *l, unsigned int table,
  8980. const struct br_style *pst, int avail,
  8981. int *raw, int maxcols, int *out_cols,
  8982. int *out_total)
  8983. {
  8984. unsigned int r, c;
  8985. int cols = 0, total = 0, fixed_sum = 0, free_raw = 0, free_cols = 0;
  8986. int fixed[12];
  8987. for (c = 0; c < (unsigned int)maxcols; c++) {
  8988. raw[c] = 0;
  8989. fixed[c] = 0;
  8990. }
  8991. /* Intrinsic widths of single-column cells. */
  8992. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  8993. struct br_node *rn = &doc.nodes[r];
  8994. int col = 0;
  8995. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  8996. continue;
  8997. for (c = rn->first; c; c = doc.nodes[c].next) {
  8998. struct br_node *cn = &doc.nodes[c];
  8999. struct br_style cs;
  9000. int w, span;
  9001. if (cn->type != BR_NODE_ELEM ||
  9002. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9003. continue;
  9004. span = cn->colspan ? cn->colspan : 1;
  9005. br_style_for(&doc, c, pst, &cs);
  9006. if (cs.display == BR_DISPLAY_NONE)
  9007. continue;
  9008. if (col + span > maxcols)
  9009. span = maxcols - col;
  9010. if (span < 1)
  9011. break;
  9012. w = intrinsic_width(l->ui, c, &cs, 0, avail) +
  9013. mp_px(&cs, 7, avail) +
  9014. mp_px(&cs, 5, avail) +
  9015. mp_px(&cs, 3, avail) +
  9016. mp_px(&cs, 1, avail) +
  9017. cs.border_w[0] + cs.border_w[1] +
  9018. cs.border_w[2] + cs.border_w[3];
  9019. if (w < 24)
  9020. w = 24;
  9021. if (span == 1) {
  9022. if (w > raw[col])
  9023. raw[col] = w;
  9024. }
  9025. if (col + span > cols)
  9026. cols = col + span;
  9027. col += span;
  9028. }
  9029. }
  9030. /* A colspan cell only has to be as wide as the sum of its columns. */
  9031. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9032. struct br_node *rn = &doc.nodes[r];
  9033. int col = 0;
  9034. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9035. continue;
  9036. for (c = rn->first; c; c = doc.nodes[c].next) {
  9037. struct br_node *cn = &doc.nodes[c];
  9038. struct br_style cs;
  9039. int span, w, sum, i;
  9040. if (cn->type != BR_NODE_ELEM ||
  9041. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9042. continue;
  9043. span = cn->colspan ? cn->colspan : 1;
  9044. if (col + span > maxcols)
  9045. span = maxcols - col;
  9046. if (span < 1)
  9047. break;
  9048. if (span > 1) {
  9049. br_style_for(&doc, c, pst, &cs);
  9050. if (cs.display != BR_DISPLAY_NONE) {
  9051. w = intrinsic_width(l->ui, c, &cs,
  9052. 0, avail) +
  9053. mp_px(&cs, 7, avail) +
  9054. mp_px(&cs, 5, avail) +
  9055. mp_px(&cs, 3, avail) +
  9056. mp_px(&cs, 1, avail) +
  9057. cs.border_w[0] + cs.border_w[1] +
  9058. cs.border_w[2] + cs.border_w[3];
  9059. sum = 0;
  9060. for (i = 0; i < span; i++)
  9061. sum += raw[col + i];
  9062. if (w > sum)
  9063. raw[col + span - 1] += w - sum;
  9064. }
  9065. }
  9066. col += span;
  9067. }
  9068. }
  9069. /* Explicit and percentage widths override intrinsic widths. */
  9070. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9071. struct br_node *rn = &doc.nodes[r];
  9072. int col = 0;
  9073. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9074. continue;
  9075. for (c = rn->first; c; c = doc.nodes[c].next) {
  9076. struct br_node *cn = &doc.nodes[c];
  9077. struct br_style cs;
  9078. int span;
  9079. if (cn->type != BR_NODE_ELEM ||
  9080. (cn->tag != BR_TAG_TD && cn->tag != BR_TAG_TH))
  9081. continue;
  9082. span = cn->colspan ? cn->colspan : 1;
  9083. if (col + span > maxcols)
  9084. span = maxcols - col;
  9085. if (span < 1)
  9086. break;
  9087. if (span == 1) {
  9088. br_style_for(&doc, c, pst, &cs);
  9089. if (cs.display != BR_DISPLAY_NONE) {
  9090. if (cs.width_kind == 1) {
  9091. raw[col] = cs.width;
  9092. fixed[col] = 1;
  9093. } else if (cs.width_kind == 2 ||
  9094. cs.width_kind == 3) {
  9095. raw[col] = style_width_px(&cs,
  9096. avail);
  9097. fixed[col] = 1;
  9098. }
  9099. }
  9100. }
  9101. col += span;
  9102. }
  9103. }
  9104. for (c = 0; c < (unsigned int)cols; c++) {
  9105. if (raw[c] < 8)
  9106. raw[c] = 8;
  9107. total += raw[c];
  9108. if (fixed[c])
  9109. fixed_sum += raw[c];
  9110. else {
  9111. free_raw += raw[c];
  9112. free_cols++;
  9113. }
  9114. }
  9115. if (fixed_sum > 0 && fixed_sum < avail) {
  9116. int free_avail = avail - fixed_sum;
  9117. int i;
  9118. if (free_raw > 0) {
  9119. for (i = 0; i < cols; i++)
  9120. if (!fixed[i])
  9121. raw[i] = free_avail * raw[i] /
  9122. free_raw;
  9123. } else if (free_cols > 0) {
  9124. for (i = 0; i < cols; i++)
  9125. if (!fixed[i])
  9126. raw[i] = free_avail / free_cols;
  9127. }
  9128. total = 0;
  9129. for (i = 0; i < cols; i++)
  9130. total += raw[i];
  9131. } else if (total < avail && total > 0) {
  9132. int i;
  9133. for (i = 0; i < cols; i++)
  9134. raw[i] = raw[i] * avail / total;
  9135. total = 0;
  9136. for (i = 0; i < cols; i++)
  9137. total += raw[i];
  9138. }
  9139. *out_cols = cols;
  9140. *out_total = total;
  9141. }
  9142. static void layout_table_row(struct lay *l, unsigned int row,
  9143. const struct br_style *pst, int depth,
  9144. unsigned short link)
  9145. {
  9146. unsigned int n, cell[12];
  9147. int raw[12], colstart[12], colspan[12];
  9148. int prefix[13];
  9149. int ncell = 0, total = 0, cols = 0, col = 0;
  9150. int row_left = l->left, row_right = l->right;
  9151. int avail = row_right - row_left;
  9152. int y = l->y, bottom = l->y;
  9153. for (n = doc.nodes[row].first; n; n = doc.nodes[n].next) {
  9154. struct br_node *nd = &doc.nodes[n];
  9155. struct br_style cs;
  9156. int span;
  9157. if (nd->type == BR_NODE_TEXT) {
  9158. if (text_node_blank(nd))
  9159. continue;
  9160. layout_children(l, row, pst, depth, link);
  9161. return;
  9162. }
  9163. if (nd->tag != BR_TAG_TD && nd->tag != BR_TAG_TH) {
  9164. layout_children(l, row, pst, depth, link);
  9165. return;
  9166. }
  9167. br_style_for(&doc, n, pst, &cs);
  9168. if (cs.display == BR_DISPLAY_NONE)
  9169. continue;
  9170. if (ncell >= 12) {
  9171. layout_children(l, row, pst, depth, link);
  9172. return;
  9173. }
  9174. span = nd->colspan ? nd->colspan : 1;
  9175. if (span > 12 - col)
  9176. span = 12 - col;
  9177. if (span < 1)
  9178. continue;
  9179. cell[ncell] = n;
  9180. colstart[ncell] = col;
  9181. colspan[ncell] = span;
  9182. col += span;
  9183. ncell++;
  9184. }
  9185. if (ncell < 1 || avail < 32) {
  9186. layout_children(l, row, pst, depth, link);
  9187. return;
  9188. }
  9189. table_columns(l, doc.nodes[row].parent, pst, avail, raw, 12, &cols,
  9190. &total);
  9191. if (cols < 2 || total <= 0) {
  9192. int c;
  9193. total = 0;
  9194. for (c = 0; c < ncell; c++) {
  9195. struct br_style cs;
  9196. br_style_for(&doc, cell[c], pst, &cs);
  9197. raw[c] = intrinsic_width(l->ui, cell[c], &cs, 0,
  9198. avail) +
  9199. mp_px(&cs, 7, avail) +
  9200. mp_px(&cs, 5, avail) +
  9201. mp_px(&cs, 3, avail) +
  9202. mp_px(&cs, 1, avail);
  9203. if (raw[c] < 24)
  9204. raw[c] = 24;
  9205. total += raw[c];
  9206. }
  9207. /* A one-column table still has to fill its own width; the
  9208. * intrinsic fallback above otherwise leaves the cell at its
  9209. * text width (HN's outer table and nested story table). */
  9210. if (total > 0 && total < avail) {
  9211. int c;
  9212. for (c = 0; c < ncell; c++)
  9213. raw[c] = raw[c] * avail / total;
  9214. total = avail;
  9215. }
  9216. }
  9217. prefix[0] = row_left;
  9218. for (n = 0; n < (unsigned int)cols && n < 12; n++)
  9219. prefix[n + 1] = prefix[n] + raw[n];
  9220. for (n = 0; n < (unsigned int)ncell; n++) {
  9221. struct br_style cs;
  9222. int start = colstart[n];
  9223. int end = start + colspan[n];
  9224. int w;
  9225. if (end > cols)
  9226. end = cols;
  9227. if (start >= cols)
  9228. continue;
  9229. w = prefix[end] - prefix[start];
  9230. br_style_for(&doc, cell[n], pst, &cs);
  9231. /* The column width already reflects the cell's width property. */
  9232. cs.width_kind = 0;
  9233. cs.max_width_kind = 0;
  9234. if (w < 24)
  9235. w = 24;
  9236. if (w < 8)
  9237. w = 8;
  9238. l->left = prefix[start];
  9239. l->right = l->left + w;
  9240. l->y = y;
  9241. l->line_x = l->left;
  9242. l->run_x = l->left;
  9243. l->line_y = l->y;
  9244. l->line_h = 0;
  9245. l->nruns = 0;
  9246. l->space_pending = 0;
  9247. l->align = cs.align;
  9248. layout_block(l, cell[n], &cs, depth + 1, link);
  9249. if (l->y > bottom)
  9250. bottom = l->y;
  9251. }
  9252. l->left = row_left;
  9253. l->right = row_right;
  9254. l->y = bottom;
  9255. l->line_x = l->left;
  9256. l->run_x = l->left;
  9257. l->line_y = l->y;
  9258. l->line_h = 0;
  9259. l->nruns = 0;
  9260. l->space_pending = 0;
  9261. }
  9262. #define TBL_MAX_ROWS 32
  9263. #define TBL_MAX_COLS 12
  9264. #define TBL_MAX_CELLS 128
  9265. struct tbl_cell {
  9266. unsigned int node;
  9267. unsigned char row, col, rowspan, colspan;
  9268. int height;
  9269. };
  9270. static struct tbl_cell tbl_cells[TBL_MAX_CELLS];
  9271. static unsigned short tbl_at[TBL_MAX_ROWS][TBL_MAX_COLS];
  9272. static int table_active;
  9273. static int table_has_rowspan(unsigned int table)
  9274. {
  9275. unsigned int r, c;
  9276. for (r = doc.nodes[table].first; r; r = doc.nodes[r].next) {
  9277. struct br_node *rn = &doc.nodes[r];
  9278. if (rn->type != BR_NODE_ELEM || rn->tag != BR_TAG_TR)
  9279. continue;
  9280. for (c = rn->first; c; c = doc.nodes[c].next) {
  9281. struct br_node *cn = &doc.nodes[c];
  9282. if (cn->type == BR_NODE_ELEM &&
  9283. (cn->tag == BR_TAG_TD || cn->tag == BR_TAG_TH) &&
  9284. cn->rowspan > 1)
  9285. return 1;
  9286. }
  9287. }
  9288. return 0;
  9289. }
  9290. static void table_cell_style(unsigned int row, unsigned int cell,
  9291. const struct br_style *st, struct br_style *out)
  9292. {
  9293. struct br_style trs;
  9294. br_style_for(&doc, row, st, &trs);
  9295. br_style_for(&doc, cell, &trs, out);
  9296. }
  9297. /* Tables that use rowspan need row heights before anything is painted. This
  9298. * path builds a small occupancy grid, measures the natural cell heights, then
  9299. * lays every cell out at its row/column position. Tables without rowspan
  9300. * keep the lighter per-row path in layout_table_row(). */
  9301. static void layout_table(struct lay *l, unsigned int table,
  9302. const struct br_style *st, int depth,
  9303. unsigned short link)
  9304. {
  9305. unsigned int rows[TBL_MAX_ROWS];
  9306. int rowh[TBL_MAX_ROWS], rowy[TBL_MAX_ROWS];
  9307. int raw[TBL_MAX_COLS], prefix[TBL_MAX_COLS + 1], fixed[TBL_MAX_COLS];
  9308. int nrows = 0, ncells = 0, cols = 0, total = 0, fixed_sum = 0;
  9309. int free_raw = 0, free_cols = 0;
  9310. int table_left = l->left, table_right = l->right;
  9311. int top = l->y, avail = table_right - table_left;
  9312. unsigned int r, c;
  9313. int i, rr, cc;
  9314. if (depth > 48 || table_active) {
  9315. layout_children(l, table, st, depth, link);
  9316. return;
  9317. }
  9318. table_active = 1;
  9319. for (r = doc.nodes[table].first;
  9320. r && nrows < TBL_MAX_ROWS; r = doc.nodes[r].next) {
  9321. struct br_node *rn = &doc.nodes[r];
  9322. if (rn->type == BR_NODE_ELEM && rn->tag == BR_TAG_TR)
  9323. rows[nrows++] = r;
  9324. }
  9325. if (!nrows) {
  9326. table_active = 0;
  9327. layout_children(l, table, st, depth, link);
  9328. return;
  9329. }
  9330. for (rr = 0; rr < nrows; rr++)
  9331. for (cc = 0; cc < TBL_MAX_COLS; cc++)
  9332. tbl_at[rr][cc] = 0;
  9333. for (rr = 0; rr < nrows; rr++) {
  9334. int col = 0;
  9335. for (c = doc.nodes[rows[rr]].first; c;
  9336. c = doc.nodes[c].next) {
  9337. struct br_node *cn = &doc.nodes[c];
  9338. struct br_style cs;
  9339. int rs, csn;
  9340. if (cn->type != BR_NODE_ELEM ||
  9341. (cn->tag != BR_TAG_TD &&
  9342. cn->tag != BR_TAG_TH))
  9343. continue;
  9344. table_cell_style(rows[rr], c, st, &cs);
  9345. if (cs.display == BR_DISPLAY_NONE)
  9346. continue;
  9347. while (col < TBL_MAX_COLS && tbl_at[rr][col])
  9348. col++;
  9349. if (col >= TBL_MAX_COLS)
  9350. break;
  9351. rs = cn->rowspan ? cn->rowspan : 1;
  9352. csn = cn->colspan ? cn->colspan : 1;
  9353. if (rr + rs > nrows)
  9354. rs = nrows - rr;
  9355. if (col + csn > TBL_MAX_COLS)
  9356. csn = TBL_MAX_COLS - col;
  9357. if (rs < 1 || csn < 1)
  9358. continue;
  9359. if (ncells >= TBL_MAX_CELLS)
  9360. break;
  9361. tbl_cells[ncells].node = c;
  9362. tbl_cells[ncells].row = (unsigned char)rr;
  9363. tbl_cells[ncells].col = (unsigned char)col;
  9364. tbl_cells[ncells].rowspan = (unsigned char)rs;
  9365. tbl_cells[ncells].colspan = (unsigned char)csn;
  9366. tbl_cells[ncells].height = 0;
  9367. for (i = rr; i < rr + rs; i++)
  9368. for (int j = col; j < col + csn; j++)
  9369. tbl_at[i][j] =
  9370. (unsigned short)(ncells + 1);
  9371. ncells++;
  9372. col += csn;
  9373. if (col > cols)
  9374. cols = col;
  9375. }
  9376. }
  9377. if (!ncells || cols < 1) {
  9378. table_active = 0;
  9379. layout_children(l, table, st, depth, link);
  9380. return;
  9381. }
  9382. for (i = 0; i < cols; i++) {
  9383. raw[i] = 0;
  9384. fixed[i] = 0;
  9385. }
  9386. /* Intrinsic widths of single-column cells. */
  9387. for (i = 0; i < ncells; i++) {
  9388. struct br_style cs;
  9389. int w;
  9390. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9391. st, &cs);
  9392. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9393. mp_px(&cs, 7, avail) +
  9394. mp_px(&cs, 5, avail) +
  9395. mp_px(&cs, 3, avail) +
  9396. mp_px(&cs, 1, avail) +
  9397. cs.border_w[0] + cs.border_w[1] +
  9398. cs.border_w[2] + cs.border_w[3];
  9399. if (w < 24)
  9400. w = 24;
  9401. if (tbl_cells[i].colspan == 1) {
  9402. int col = tbl_cells[i].col;
  9403. if (w > raw[col])
  9404. raw[col] = w;
  9405. }
  9406. }
  9407. /* A spanning cell only needs the sum of its columns to be large
  9408. * enough; put the deficit in the last column. */
  9409. for (i = 0; i < ncells; i++) {
  9410. struct br_style cs;
  9411. int w, sum, col, span;
  9412. if (tbl_cells[i].colspan < 2)
  9413. continue;
  9414. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9415. st, &cs);
  9416. w = intrinsic_width(l->ui, tbl_cells[i].node, &cs, 0, avail) +
  9417. mp_px(&cs, 7, avail) +
  9418. mp_px(&cs, 5, avail) +
  9419. mp_px(&cs, 3, avail) +
  9420. mp_px(&cs, 1, avail) +
  9421. cs.border_w[0] + cs.border_w[1] +
  9422. cs.border_w[2] + cs.border_w[3];
  9423. col = tbl_cells[i].col;
  9424. span = tbl_cells[i].colspan;
  9425. sum = 0;
  9426. for (int j = 0; j < span; j++)
  9427. sum += raw[col + j];
  9428. if (w > sum)
  9429. raw[col + span - 1] += w - sum;
  9430. }
  9431. /* Explicit/percentage widths, as in table_columns(). */
  9432. for (i = 0; i < ncells; i++) {
  9433. struct br_style cs;
  9434. int col;
  9435. if (tbl_cells[i].colspan != 1)
  9436. continue;
  9437. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9438. st, &cs);
  9439. col = tbl_cells[i].col;
  9440. if (cs.width_kind == 1) {
  9441. raw[col] = cs.width;
  9442. fixed[col] = 1;
  9443. } else if (cs.width_kind == 2 || cs.width_kind == 3) {
  9444. raw[col] = style_width_px(&cs, avail);
  9445. fixed[col] = 1;
  9446. }
  9447. }
  9448. for (i = 0; i < cols; i++) {
  9449. if (raw[i] < 8)
  9450. raw[i] = 8;
  9451. total += raw[i];
  9452. if (fixed[i])
  9453. fixed_sum += raw[i];
  9454. else {
  9455. free_raw += raw[i];
  9456. free_cols++;
  9457. }
  9458. }
  9459. if (fixed_sum > 0 && fixed_sum < avail) {
  9460. int free_avail = avail - fixed_sum;
  9461. if (free_raw > 0) {
  9462. for (i = 0; i < cols; i++)
  9463. if (!fixed[i])
  9464. raw[i] = free_avail * raw[i] /
  9465. free_raw;
  9466. } else if (free_cols > 0) {
  9467. for (i = 0; i < cols; i++)
  9468. if (!fixed[i])
  9469. raw[i] = free_avail / free_cols;
  9470. }
  9471. } else if (total < avail && total > 0) {
  9472. for (i = 0; i < cols; i++)
  9473. raw[i] = raw[i] * avail / total;
  9474. }
  9475. prefix[0] = table_left;
  9476. for (i = 0; i < cols; i++)
  9477. prefix[i + 1] = prefix[i] + raw[i];
  9478. /* Measure natural cell heights with the column widths. */
  9479. for (i = 0; i < ncells; i++) {
  9480. struct br_style cs;
  9481. int col = tbl_cells[i].col;
  9482. int span = tbl_cells[i].colspan;
  9483. int w = prefix[col + span] - prefix[col];
  9484. int sl = l->left, sr = l->right, sy = l->y;
  9485. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9486. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9487. int sal = l->align, sdraw = l->draw;
  9488. struct ngui *sui = l->ui;
  9489. if (w < 8)
  9490. w = 8;
  9491. table_cell_style(rows[tbl_cells[i].row], tbl_cells[i].node,
  9492. st, &cs);
  9493. cs.width_kind = 0;
  9494. cs.max_width_kind = 0;
  9495. l->draw = 0;
  9496. l->ui = 0;
  9497. l->left = prefix[col];
  9498. l->right = l->left + w;
  9499. l->y = 0;
  9500. l->line_x = l->left;
  9501. l->run_x = l->left;
  9502. l->line_y = 0;
  9503. l->line_h = 0;
  9504. l->nruns = 0;
  9505. l->space_pending = 0;
  9506. l->align = cs.align;
  9507. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9508. tbl_cells[i].height = block_h[tbl_cells[i].node];
  9509. l->left = sl;
  9510. l->right = sr;
  9511. l->y = sy;
  9512. l->line_x = slx;
  9513. l->run_x = srx;
  9514. l->line_y = sly;
  9515. l->line_h = slh;
  9516. l->nruns = snr;
  9517. l->space_pending = ssp;
  9518. l->align = sal;
  9519. l->draw = sdraw;
  9520. l->ui = sui;
  9521. }
  9522. for (i = 0; i < nrows; i++)
  9523. rowh[i] = 0;
  9524. for (i = 0; i < ncells; i++) {
  9525. int row = tbl_cells[i].row;
  9526. if (tbl_cells[i].rowspan == 1) {
  9527. if (tbl_cells[i].height > rowh[row])
  9528. rowh[row] = tbl_cells[i].height;
  9529. }
  9530. }
  9531. for (i = 0; i < ncells; i++) {
  9532. int row = tbl_cells[i].row;
  9533. int span = tbl_cells[i].rowspan;
  9534. int sum = 0;
  9535. if (span < 2)
  9536. continue;
  9537. for (int j = 0; j < span; j++)
  9538. sum += rowh[row + j];
  9539. if (sum < tbl_cells[i].height)
  9540. rowh[row + span - 1] +=
  9541. tbl_cells[i].height - sum;
  9542. }
  9543. for (i = 0; i < nrows; i++)
  9544. if (rowh[i] < 8)
  9545. rowh[i] = 8;
  9546. rowy[0] = top;
  9547. for (i = 1; i < nrows; i++)
  9548. rowy[i] = rowy[i - 1] + rowh[i - 1];
  9549. if (!l->draw) {
  9550. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  9551. table_active = 0;
  9552. return;
  9553. }
  9554. for (i = 0; i < ncells; i++) {
  9555. struct br_style cs;
  9556. int col = tbl_cells[i].col;
  9557. int span = tbl_cells[i].colspan;
  9558. int row = tbl_cells[i].row;
  9559. int rspan = tbl_cells[i].rowspan;
  9560. int w = prefix[col + span] - prefix[col];
  9561. int h = 0;
  9562. int sl = l->left, sr = l->right, sy = l->y;
  9563. int slx = l->line_x, srx = l->run_x, sly = l->line_y;
  9564. int slh = l->line_h, snr = l->nruns, ssp = l->space_pending;
  9565. int sal = l->align;
  9566. int deco;
  9567. for (int j = 0; j < rspan; j++)
  9568. h += rowh[row + j];
  9569. table_cell_style(rows[row], tbl_cells[i].node, st, &cs);
  9570. cs.width_kind = 0;
  9571. cs.max_width_kind = 0;
  9572. cs.box_sizing = 0;
  9573. deco = mp_px(&cs, 4, avail) +
  9574. mp_px(&cs, 6, avail) +
  9575. cs.border_w[0] + cs.border_w[2];
  9576. cs.height_kind = 1;
  9577. cs.height = h > deco ? h - deco : 0;
  9578. /* The block painter reads block_h[] from the measure pass; make
  9579. * the table cell fill its row/rowspan, not just its content. */
  9580. if (h > 0 && h < 65536)
  9581. block_h[tbl_cells[i].node] = (unsigned short)h;
  9582. l->left = prefix[col];
  9583. l->right = l->left + w;
  9584. l->y = rowy[row];
  9585. l->line_x = l->left;
  9586. l->run_x = l->left;
  9587. l->line_y = l->y;
  9588. l->line_h = 0;
  9589. l->nruns = 0;
  9590. l->space_pending = 0;
  9591. l->align = cs.align;
  9592. layout_block(l, tbl_cells[i].node, &cs, depth + 1, link);
  9593. l->left = sl;
  9594. l->right = sr;
  9595. l->y = sy;
  9596. l->line_x = slx;
  9597. l->run_x = srx;
  9598. l->line_y = sly;
  9599. l->line_h = slh;
  9600. l->nruns = snr;
  9601. l->space_pending = ssp;
  9602. l->align = sal;
  9603. }
  9604. l->y = rowy[nrows - 1] + rowh[nrows - 1];
  9605. table_active = 0;
  9606. }
  9607. /* Positioned elements (fixed headers, overlays) are drawn after the normal
  9608. * flow so they sit above it, like CSS painting order. Their flow origin is
  9609. * saved for absolute boxes; fixed boxes only need the viewport rect. */
  9610. struct br_deferred {
  9611. unsigned int node;
  9612. int flow_y, flow_left, flow_right;
  9613. int parent_top; /* the parent box top, for sticky clamping */
  9614. unsigned short link;
  9615. signed short z_index;
  9616. unsigned char z_set;
  9617. unsigned int order;
  9618. };
  9619. /* Positioned boxes painted after the flow. News front pages have one or two
  9620. * per teaser (an absolute poster wrapper and its absolute <img>); with the
  9621. * old 16 entries the rest fell back into the flow, so a hero image landed
  9622. * below its padding-top aspect box instead of on top of it. */
  9623. #define BR_MAX_DEFERRED 256
  9624. static struct br_deferred deferred[BR_MAX_DEFERRED];
  9625. static int ndeferred;
  9626. /* ::before/::after generated text (br_pseudo()) as literal runs in the
  9627. * element's line. A block-level pseudo-element gets its own line; its box
  9628. * (margins, padding, background) is not drawn. */
  9629. static void emit_pseudo(struct lay *l, unsigned int node,
  9630. const struct br_style *st, int pe, unsigned short link)
  9631. {
  9632. char buf[160];
  9633. struct br_style ps;
  9634. unsigned int n = br_pseudo(&doc, node, pe, st, &ps, buf, sizeof(buf));
  9635. unsigned int i = 0;
  9636. int block, space_w;
  9637. if (!n)
  9638. return;
  9639. block = ps.display == BR_DISPLAY_BLOCK || ps.display == BR_DISPLAY_FLEX;
  9640. if (block)
  9641. flush_line(l);
  9642. if (ps.uppercase)
  9643. for (i = 0; i < n; i++)
  9644. if (buf[i] >= 'a' && buf[i] <= 'z')
  9645. buf[i] = (char)(buf[i] - 'a' + 'A');
  9646. space_w = (int)face_text_width(l->ui, &ps, " ", 1);
  9647. if (space_w <= 0)
  9648. space_w = 8;
  9649. i = 0;
  9650. while (i < n) {
  9651. char word[28];
  9652. unsigned int k = 0;
  9653. int w;
  9654. if (buf[i] == ' ') {
  9655. l->space_pending = 1;
  9656. i++;
  9657. continue;
  9658. }
  9659. while (i < n && buf[i] != ' ' && k + 1 < sizeof(word))
  9660. word[k++] = buf[i++];
  9661. word[k] = '\0';
  9662. if (l->space_pending &&
  9663. (l->nruns > 0 || l->line_x > l->line_left) &&
  9664. l->line_x + space_w <= l->line_right)
  9665. l->line_x += space_w;
  9666. l->space_pending = 0;
  9667. w = (int)face_text_width(l->ui, &ps, word, k);
  9668. if (l->line_x + w > l->line_right &&
  9669. (l->nruns > 0 || l->line_x > l->line_left))
  9670. flush_line(l);
  9671. add_run(l, 0, 0, &ps, link, word);
  9672. }
  9673. if (block)
  9674. flush_line(l);
  9675. }
  9676. static void layout_children(struct lay *l, unsigned int parent,
  9677. const struct br_style *pst, int depth,
  9678. unsigned short link)
  9679. {
  9680. unsigned int n;
  9681. if (depth > 48)
  9682. return;
  9683. emit_pseudo(l, parent, pst, 1, link);
  9684. n = doc.nodes[parent].first;
  9685. while (n) {
  9686. struct br_node *nd = &doc.nodes[n];
  9687. struct br_style cs;
  9688. unsigned short lk = link;
  9689. if (nd->type == BR_NODE_TEXT) {
  9690. emit_text(l, doc.text + nd->text_off, nd->text_len, pst,
  9691. link, (nd->flags & BR_NODE_PREFORMAT) != 0);
  9692. n = nd->next;
  9693. continue;
  9694. }
  9695. br_style_for(&doc, n, pst, &cs);
  9696. if (cs.display == BR_DISPLAY_NONE) {
  9697. n = nd->next;
  9698. continue;
  9699. }
  9700. if (cs.clear && l->float_active) {
  9701. flush_line(l);
  9702. if (l->y < l->float_bottom)
  9703. l->y = l->float_bottom;
  9704. l->float_active = 0;
  9705. l->line_x = l->left;
  9706. l->run_x = l->left;
  9707. l->line_left = l->left;
  9708. l->line_right = l->right;
  9709. l->line_y = l->y;
  9710. l->line_h = 0;
  9711. l->nruns = 0;
  9712. l->space_pending = 0;
  9713. }
  9714. if (nd->tag == BR_TAG_A && nd->href_off)
  9715. lk = (unsigned short)n;
  9716. if (cs.pos == 1 || cs.pos == 2 ||
  9717. ((cs.pos == 3 || cs.pos == 4) && cs.z_set)) {
  9718. if ((cs.pos == 3 || cs.pos == 4) && l->draw &&
  9719. ndeferred < BR_MAX_DEFERRED) {
  9720. /* Relative or sticky z-index (a sticky site
  9721. * header): measure and advance the flow without
  9722. * painting, then paint it in the deferred
  9723. * (stacked) pass, above the content after it. */
  9724. int fy = l->y, fl = l->left, fr = l->right;
  9725. int save_draw = l->draw;
  9726. l->draw = 0;
  9727. layout_block(l, n, &cs, depth + 1, lk);
  9728. l->draw = save_draw;
  9729. deferred[ndeferred].node = n;
  9730. deferred[ndeferred].parent_top = l->parent_top;
  9731. deferred[ndeferred].flow_y = fy;
  9732. deferred[ndeferred].flow_left = fl;
  9733. deferred[ndeferred].flow_right = fr;
  9734. deferred[ndeferred].link = lk;
  9735. deferred[ndeferred].z_index = cs.z_index;
  9736. deferred[ndeferred].z_set = cs.z_set;
  9737. deferred[ndeferred].order = (unsigned int)ndeferred;
  9738. ndeferred++;
  9739. } else if (l->draw && ndeferred < BR_MAX_DEFERRED) {
  9740. deferred[ndeferred].node = n;
  9741. deferred[ndeferred].parent_top = l->parent_top;
  9742. deferred[ndeferred].flow_y =
  9743. cs.pos == 1 ? l->cb_top : l->y;
  9744. deferred[ndeferred].flow_left =
  9745. cs.pos == 1 ? l->cb_left : l->left;
  9746. deferred[ndeferred].flow_right =
  9747. cs.pos == 1 ? l->cb_right : l->right;
  9748. deferred[ndeferred].link = lk;
  9749. deferred[ndeferred].z_index = cs.z_index;
  9750. deferred[ndeferred].z_set = cs.z_set;
  9751. deferred[ndeferred].order = (unsigned int)ndeferred;
  9752. ndeferred++;
  9753. } else if (l->draw && cs.pos == 1) {
  9754. /* Deferred list full: paint in place, but still
  9755. * against the containing block, not the flow. */
  9756. int fy = l->y, fl = l->left, fr = l->right;
  9757. l->y = l->cb_top;
  9758. l->left = l->cb_left;
  9759. l->right = l->cb_right;
  9760. layout_block(l, n, &cs, depth + 1, lk);
  9761. l->y = fy;
  9762. l->left = fl;
  9763. l->right = fr;
  9764. } else {
  9765. layout_block(l, n, &cs, depth + 1, lk);
  9766. }
  9767. if (cs.pos == 1 && block_h[n] &&
  9768. doc.nodes[n].class_off) {
  9769. const char *cl = doc.attrs +
  9770. doc.nodes[n].class_off;
  9771. if ((contains_ci(cl, "poster-wrapper") ||
  9772. contains_ci(cl, "ts-picture")) &&
  9773. !has_skeleton_sibling(n))
  9774. l->y += block_h[n];
  9775. }
  9776. n = nd->next;
  9777. continue;
  9778. }
  9779. if (nd->tag == BR_TAG_BR) {
  9780. flush_line(l);
  9781. n = nd->next;
  9782. continue;
  9783. }
  9784. if (nd->tag == BR_TAG_HR) {
  9785. flush_line(l);
  9786. if (l->draw)
  9787. ngui_fill_rect(l->ui,
  9788. (struct ngui_rect){l->left, l->y + 2,
  9789. l->right - l->left, 1}, BR_GRAY);
  9790. l->y += 8;
  9791. n = nd->next;
  9792. continue;
  9793. }
  9794. if ((nd->tag == BR_TAG_INPUT || nd->tag == BR_TAG_TEXTAREA ||
  9795. nd->tag == BR_TAG_SELECT || nd->tag == BR_TAG_BUTTON) &&
  9796. !button_has_elements(n)) {
  9797. if (!(nd->tag == BR_TAG_INPUT &&
  9798. s_eq(br_type(&doc, n), "hidden"))) {
  9799. form_fill_line = pst->display ==
  9800. BR_DISPLAY_FLEX &&
  9801. pst->flex_col;
  9802. add_form_run(l, n, &cs, lk);
  9803. form_fill_line = 0;
  9804. }
  9805. n = nd->next;
  9806. continue;
  9807. }
  9808. if (nd->tag == BR_TAG_IMG) {
  9809. add_image_run(l, n, &cs, lk);
  9810. n = nd->next;
  9811. continue;
  9812. }
  9813. if (nd->tag == BR_TAG_SVG &&
  9814. (cs.display == BR_DISPLAY_INLINE ||
  9815. cs.display == BR_DISPLAY_INLINE_BLOCK) &&
  9816. !cs.float_left) {
  9817. add_svg_run(l, n, &cs, lk);
  9818. n = nd->next;
  9819. continue;
  9820. }
  9821. if (nd->tag == BR_TAG_VIDEO) {
  9822. layout_block(l, n, &cs, depth + 1, lk);
  9823. n = nd->next;
  9824. continue;
  9825. }
  9826. if (cs.float_left) {
  9827. n = layout_float_group(l, n, pst, depth, lk);
  9828. continue;
  9829. }
  9830. if (cs.display == BR_DISPLAY_INLINE_BLOCK &&
  9831. inline_block_flows(n, &cs, 0)) {
  9832. layout_children(l, n, &cs, depth + 1, lk);
  9833. n = nd->next;
  9834. continue;
  9835. }
  9836. if (cs.display == BR_DISPLAY_INLINE_BLOCK) {
  9837. n = layout_inline_blocks(l, n, pst, depth, link);
  9838. continue;
  9839. }
  9840. /* A flex container is block-level like any block box even when
  9841. * the element is an inline tag such as <a> (a link card with
  9842. * display:flex is common on news sites). Without the block box
  9843. * its children were laid out in the parent flow with a 0x0 box
  9844. * of their own. */
  9845. /* inline-flex around inline content only ("| mehr" link
  9846. * tails, icon+label pills) stays in the text line. */
  9847. if (cs.display == BR_DISPLAY_FLEX && cs.inline_flex &&
  9848. !br_tag_is_block(nd->tag) && !cs.width_kind &&
  9849. !flex_wants_row(n, &cs)) {
  9850. layout_children(l, n, &cs, depth + 1, lk);
  9851. } else if (cs.display == BR_DISPLAY_BLOCK ||
  9852. cs.display == BR_DISPLAY_FLEX ||
  9853. br_tag_is_block(nd->tag))
  9854. layout_block(l, n, &cs, depth + 1, lk);
  9855. else {
  9856. layout_children(l, n, &cs, depth + 1, lk);
  9857. if (nd->tag == BR_TAG_TD || nd->tag == BR_TAG_TH)
  9858. l->space_pending = 1;
  9859. }
  9860. n = nd->next;
  9861. }
  9862. emit_pseudo(l, parent, pst, 2, link);
  9863. }
  9864. /* One layout state, kept out of the 8 KB user stack: it holds 96 line
  9865. * runs and a recursive page can otherwise overflow the stack. */
  9866. static struct lay layout_state;
  9867. static int measure_page(int left, int right)
  9868. {
  9869. struct lay *l = &layout_state;
  9870. struct br_style base = base_style();
  9871. unsigned int i;
  9872. for (i = 0; i < BR_MAX_NODES; i++) {
  9873. block_h[i] = 0;
  9874. img_top[i] = 0;
  9875. block_top[i] = 0;
  9876. img_h[i] = 0;
  9877. layout_boxes[i].valid = 0;
  9878. }
  9879. memset(li_marker, 0, sizeof(li_marker));
  9880. l->draw = 0;
  9881. l->ui = &ui;
  9882. l->left = left;
  9883. l->right = right;
  9884. l->y = 0;
  9885. l->line_x = left;
  9886. l->run_x = left;
  9887. l->line_left = left;
  9888. l->line_right = right;
  9889. l->line_y = 0;
  9890. l->line_h = 0;
  9891. l->align = BR_ALIGN_LEFT;
  9892. l->cb_h = layout_view_h;
  9893. l->float_active = 0;
  9894. l->parent_top = 0;
  9895. l->cb_left = left;
  9896. l->cb_right = right;
  9897. l->cb_top = 0;
  9898. l->depth = 0;
  9899. l->nruns = 0;
  9900. l->space_pending = 0;
  9901. layout_children(l, doc.root, &base, 0, 0);
  9902. return l->y + 8;
  9903. }
  9904. static int deferred_cmp(const struct br_deferred *a,
  9905. const struct br_deferred *b)
  9906. {
  9907. int az = a->z_set ? a->z_index : 0;
  9908. int bz = b->z_set ? b->z_index : 0;
  9909. if (az != bz)
  9910. return az < bz ? -1 : 1;
  9911. if (a->order != b->order)
  9912. return a->order < b->order ? -1 : 1;
  9913. return 0;
  9914. }
  9915. static void sort_deferred(void)
  9916. {
  9917. int i;
  9918. for (i = 1; i < ndeferred; i++) {
  9919. struct br_deferred key = deferred[i];
  9920. int j = i;
  9921. while (j > 0 && deferred_cmp(&deferred[j - 1], &key) > 0) {
  9922. deferred[j] = deferred[j - 1];
  9923. j--;
  9924. }
  9925. deferred[j] = key;
  9926. }
  9927. }
  9928. static void render_page(int left, int right, int y0)
  9929. {
  9930. struct lay *l = &layout_state;
  9931. struct br_style base = base_style();
  9932. l->draw = 1;
  9933. l->ui = &ui;
  9934. l->left = left;
  9935. l->right = right;
  9936. l->y = y0;
  9937. l->line_x = left;
  9938. l->run_x = left;
  9939. l->line_left = left;
  9940. l->line_right = right;
  9941. l->line_y = y0;
  9942. l->line_h = 0;
  9943. l->align = BR_ALIGN_LEFT;
  9944. l->cb_h = layout_view_h;
  9945. l->float_active = 0;
  9946. l->parent_top = 0;
  9947. l->cb_left = left;
  9948. l->cb_right = right;
  9949. l->cb_top = y0;
  9950. l->depth = 0;
  9951. l->nruns = 0;
  9952. l->space_pending = 0;
  9953. nhits = 0;
  9954. ndeferred = 0;
  9955. layout_children(l, doc.root, &base, 0, 0);
  9956. sort_deferred();
  9957. {
  9958. int i;
  9959. for (i = 0; i < ndeferred; i++) {
  9960. struct br_style st;
  9961. br_style_for(&doc, deferred[i].node, &base, &st);
  9962. if (st.display == BR_DISPLAY_NONE)
  9963. continue;
  9964. l->draw = 1;
  9965. l->left = deferred[i].flow_left;
  9966. l->right = deferred[i].flow_right;
  9967. l->y = deferred[i].flow_y;
  9968. l->parent_top = deferred[i].parent_top;
  9969. l->line_x = l->left;
  9970. l->run_x = l->left;
  9971. l->line_y = l->y;
  9972. l->line_h = 0;
  9973. l->nruns = 0;
  9974. l->space_pending = 0;
  9975. l->align = st.align;
  9976. if (st.pos == 2 && block_h[deferred[i].node]) {
  9977. struct ngui_rect clip;
  9978. int ch = block_h[deferred[i].node] + 24;
  9979. clip.x = page_rect.x;
  9980. clip.y = page_rect.y;
  9981. clip.w = page_rect.w - 12;
  9982. if (ch > page_rect.h)
  9983. ch = page_rect.h;
  9984. clip.h = ch;
  9985. ngui_push_clip(&ui, clip);
  9986. if (st.has_bg)
  9987. ngui_fill_rect(&ui, clip, st.bg);
  9988. layout_block(l, deferred[i].node, &st, 0,
  9989. deferred[i].link);
  9990. ngui_pop_clip(&ui);
  9991. } else {
  9992. layout_block(l, deferred[i].node, &st, 0,
  9993. deferred[i].link);
  9994. }
  9995. }
  9996. }
  9997. }
  9998. /* ---- UI ---- */
  9999. static int find_hit(int x, int y)
  10000. {
  10001. int i;
  10002. for (i = nhits - 1; i >= 0; i--) {
  10003. struct hit *h = &hits[i];
  10004. if (x >= h->x && y >= h->y && x < h->x + h->w &&
  10005. y < h->y + h->h)
  10006. return (int)h->node;
  10007. }
  10008. return 0;
  10009. }
  10010. static void draw_toolbar(struct ngui_rect r, unsigned int *action)
  10011. {
  10012. int x = r.x + 4, y = r.y + 4, h = 22;
  10013. int compact = r.w < 560;
  10014. int go_w = r.w < 420 ? 32 : 42;
  10015. int in_x, in_w, res;
  10016. ngui_fill_rect(&ui, r, ui.theme.panel);
  10017. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y + r.h - 1, r.w, 1},
  10018. ui.theme.border);
  10019. if (ngui_icon_button(&ui, ID_BACK, (struct ngui_rect){x, y, 28, h},
  10020. NGUI_ICON_CHEVRON_LEFT))
  10021. *action |= ACT_BACK;
  10022. x += 32;
  10023. if (!compact) {
  10024. if (ngui_icon_button(&ui, ID_FORWARD,
  10025. (struct ngui_rect){x, y, 28, h},
  10026. NGUI_ICON_CHEVRON_RIGHT))
  10027. *action |= ACT_FORWARD;
  10028. x += 32;
  10029. }
  10030. if (ngui_icon_button(&ui, ID_RELOAD, (struct ngui_rect){x, y, 28, h},
  10031. NGUI_ICON_REFRESH))
  10032. *action |= ACT_RELOAD;
  10033. x += 32;
  10034. if (!compact) {
  10035. if (ngui_icon_button(&ui, ID_HOME,
  10036. (struct ngui_rect){x, y, 28, h},
  10037. NGUI_ICON_HOME))
  10038. *action |= ACT_HOME;
  10039. x += 32;
  10040. }
  10041. in_x = x + 2;
  10042. in_w = r.x + r.w - 6 - go_w - 4 - in_x;
  10043. if (in_w < 60)
  10044. in_w = 60;
  10045. res = ngui_text_input(&ui, ID_URL,
  10046. (struct ngui_rect){in_x, y, in_w, h}, &url_in);
  10047. if (res & NGUI_INPUT_SUBMIT)
  10048. *action |= ACT_NAV;
  10049. if (res & NGUI_INPUT_CANCEL)
  10050. ngui_set_focus(&ui, 0);
  10051. if (ngui_button(&ui, ID_GO,
  10052. (struct ngui_rect){r.x + r.w - 4 - go_w, y, go_w, h},
  10053. "Go"))
  10054. *action |= ACT_NAV;
  10055. }
  10056. static int page_hover_node(void)
  10057. {
  10058. if (!ui.inside)
  10059. return 0;
  10060. if (ui.mouse_x < page_rect.x ||
  10061. ui.mouse_x >= page_rect.x + page_rect.w - 12 ||
  10062. ui.mouse_y < page_rect.y ||
  10063. ui.mouse_y >= page_rect.y + page_rect.h)
  10064. return 0;
  10065. return find_hit(ui.mouse_x, ui.mouse_y);
  10066. }
  10067. static void blit_page(struct ngui_rect page, unsigned short *src, int sw)
  10068. {
  10069. int x, y, w = page.w, h = page.h;
  10070. if (!src || w <= 0 || h <= 0)
  10071. return;
  10072. for (y = 0; y < h; y++) {
  10073. unsigned short *s = src + (page.y + y) * sw + page.x;
  10074. unsigned short *d = ui.px + (page.y + y) * ui.w + page.x;
  10075. for (x = 0; x + 1 < w; x += 2) {
  10076. *(unsigned int *)(d + x) = *(unsigned int *)(s + x);
  10077. }
  10078. if (x < w)
  10079. d[x] = s[x];
  10080. }
  10081. }
  10082. static void draw_page(struct ngui_rect page)
  10083. {
  10084. int left, right, ch;
  10085. int old_panel, old_dim;
  10086. unsigned short *saved_px;
  10087. unsigned short page_bg = ui.theme.bg;
  10088. int saved_w, saved_h, use_buf;
  10089. unsigned int t0 = u_ticks_ms();
  10090. page_rect = page;
  10091. {
  10092. unsigned int root = doc.nnode > 1 ?
  10093. br_find_tag(&doc, BR_TAG_HTML) : 0;
  10094. unsigned int body = doc.nnode > 1 ?
  10095. br_find_tag(&doc, BR_TAG_BODY) : 0;
  10096. struct br_style bs;
  10097. if (root) {
  10098. style_for_node(root - 1, &bs);
  10099. if (bs.has_bg)
  10100. page_bg = bs.bg;
  10101. }
  10102. if (body) {
  10103. style_for_node(body - 1, &bs);
  10104. if (bs.has_bg)
  10105. page_bg = bs.bg;
  10106. }
  10107. }
  10108. if (page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h &&
  10109. page_cache_valid && layout_valid &&
  10110. !ui.pressed && !(ui.buttons & 1) && !ui.released &&
  10111. !(ui.scroll_y &&
  10112. ngui_rect_contains(&page, ui.mouse_x, ui.mouse_y)) &&
  10113. page_scroll.offset == page_cache_scroll &&
  10114. page_cache_nnode == doc.nnode &&
  10115. page_cache_x == page.x && page_cache_y == page.y &&
  10116. page_cache_w == page.w && page_cache_h == page.h) {
  10117. blit_page(page, page_backbuf, pagebuf_w);
  10118. if (img_stat_n)
  10119. img_stat_paint += u_ticks_ms() - t0;
  10120. return;
  10121. }
  10122. ngui_fill_rect(&ui, page, page_bg);
  10123. if (!doc.nnode || (page_loading && doc.nnode <= 1)) {
  10124. const char *s = page_loading ? "Loading..." : "No page";
  10125. int w = (int)ngui_text_width_ui(&ui, s);
  10126. ngui_text(&ui, page.x + (page.w - w) / 2,
  10127. page.y + page.h / 2 - 8, s, ui.theme.text_dim);
  10128. page_scroll.content_h = 0;
  10129. page_scroll.view_h = page.h;
  10130. page_cache_valid = 0;
  10131. return;
  10132. }
  10133. if (page.w < 40 || page.h < 40) {
  10134. page_cache_valid = 0;
  10135. return;
  10136. }
  10137. saved_px = ui.px;
  10138. saved_w = ui.w;
  10139. saved_h = ui.h;
  10140. use_buf = page_backbuf && pagebuf_w == ui.w && pagebuf_h == ui.h;
  10141. if (use_buf) {
  10142. ui.px = page_backbuf;
  10143. ui.w = pagebuf_w;
  10144. ui.h = pagebuf_h;
  10145. ngui_fill_rect(&ui, page, page_bg);
  10146. }
  10147. left = page.x + 8;
  10148. right = page.x + page.w - 16;
  10149. if (!layout_valid || left != layout_left || right != layout_right ||
  10150. layout_nnode != doc.nnode) {
  10151. unsigned int tm = u_ticks_ms();
  10152. layout_view_h = page.h - 8;
  10153. layout_content_h = measure_page(left, right);
  10154. if (img_stat_n)
  10155. img_stat_reflow += u_ticks_ms() - tm;
  10156. layout_valid = 1;
  10157. layout_left = left;
  10158. layout_right = right;
  10159. layout_nnode = doc.nnode;
  10160. /* Scripts that measured before any layout (offsetWidth on
  10161. * mount) get a resize event once real boxes exist, and again
  10162. * whenever the page width changes. */
  10163. if (js_browser_active() && right - left != resize_sent_w)
  10164. resize_pending = 1;
  10165. }
  10166. ch = layout_content_h;
  10167. page_scroll.content_h = ch;
  10168. page_scroll.view_h = page.h;
  10169. t0 = u_ticks_ms();
  10170. ngui_scroll_begin(&ui, page, &page_scroll);
  10171. ngui_scroll_wheel(&ui, page, &page_scroll);
  10172. render_page(left, right, page.y + 4 - page_scroll.offset);
  10173. old_panel = ui.theme.panel_alt;
  10174. old_dim = ui.theme.text_dim;
  10175. ui.theme.panel_alt = 0xC618;
  10176. ui.theme.text_dim = 0x8410;
  10177. ngui_scroll_end(&ui, page, &page_scroll);
  10178. ui.theme.panel_alt = old_panel;
  10179. ui.theme.text_dim = old_dim;
  10180. if (use_buf) {
  10181. ui.px = saved_px;
  10182. ui.w = saved_w;
  10183. ui.h = saved_h;
  10184. blit_page(page, page_backbuf, pagebuf_w);
  10185. page_cache_valid = 1;
  10186. page_cache_scroll = page_scroll.offset;
  10187. page_cache_nnode = doc.nnode;
  10188. page_cache_x = page.x;
  10189. page_cache_y = page.y;
  10190. page_cache_w = page.w;
  10191. page_cache_h = page.h;
  10192. } else {
  10193. page_cache_valid = 0;
  10194. }
  10195. if (img_stat_n)
  10196. img_stat_paint += u_ticks_ms() - t0;
  10197. }
  10198. static void draw_status(struct ngui_rect r)
  10199. {
  10200. char msg[BR_URL_MAX + 32];
  10201. unsigned int n = 0;
  10202. int hover = page_hover_node();
  10203. unsigned short color;
  10204. const char *kind;
  10205. ngui_fill_rect(&ui, r, ui.theme.panel);
  10206. ngui_fill_rect(&ui, (struct ngui_rect){r.x, r.y, r.w, 1},
  10207. ui.theme.border);
  10208. if (hover) {
  10209. const char *href = br_href(&doc, (unsigned int)hover);
  10210. char url[BR_URL_MAX];
  10211. if (resolve_link(page_url, href, url, sizeof(url)) == 0) {
  10212. s_append(msg, &n, "Link: ", sizeof(msg));
  10213. s_append(msg, &n, url, sizeof(msg));
  10214. } else {
  10215. s_copy(msg, "Link", sizeof(msg));
  10216. }
  10217. color = ui.theme.accent;
  10218. } else if (status_text[0]) {
  10219. s_copy(msg, status_text, sizeof(msg));
  10220. color = status_error ? ui.theme.error : ui.theme.text;
  10221. } else if (page_title[0]) {
  10222. s_copy(msg, page_title, sizeof(msg));
  10223. color = ui.theme.text;
  10224. } else {
  10225. s_copy(msg, "Ready", sizeof(msg));
  10226. color = ui.theme.text_dim;
  10227. }
  10228. kind = s_eq(page_url, "about:home") ? "HOME" :
  10229. page_is_local ? "FILE" :
  10230. (starts_with(page_url, "https://") ? "HTTPS" : "HTTP");
  10231. ngui_text_ellipsis(&ui, r, r.x + 6, r.y + 1, msg, color);
  10232. {
  10233. int kw = (int)ngui_text_width_ui(&ui, kind);
  10234. ngui_text(&ui, r.x + r.w - 6 - kw, r.y + 1, kind,
  10235. ui.theme.text_dim);
  10236. }
  10237. }
  10238. static void draw(unsigned int *action)
  10239. {
  10240. struct ngui_rect r = {0, 0, ui.w, ui.h};
  10241. struct ngui_rect toolbar, status, page;
  10242. toolbar = ngui_cut_top(&r, BR_TOOLBAR_H);
  10243. status = ngui_cut_bottom(&r, BR_STATUS_H);
  10244. page = r;
  10245. draw_toolbar(toolbar, action);
  10246. draw_page(page);
  10247. draw_status(status);
  10248. }
  10249. static void redraw_now(void)
  10250. {
  10251. unsigned int action = 0;
  10252. ngui_begin(&ui);
  10253. draw(&action);
  10254. ngui_end(&ui);
  10255. }
  10256. static void handle_keys(unsigned int *action)
  10257. {
  10258. int k, scrolled = 0;
  10259. if (form_focus >= doc.nnode)
  10260. form_focus = 0;
  10261. if (form_focus && !ngui_focus(&ui)) {
  10262. while ((k = ngui_key(&ui)) != 0)
  10263. form_key(k);
  10264. return;
  10265. }
  10266. /* Batch queued page keys: a slow full-page render must not make a
  10267. * held Page Down advance only once every few frames. */
  10268. while (scrolled < 3 && ngui_scroll_keys(&ui, &page_scroll))
  10269. scrolled++;
  10270. if (scrolled)
  10271. ngui_invalidate(&ui);
  10272. if (ngui_focus(&ui))
  10273. return;
  10274. while ((k = ngui_key(&ui)) != 0) {
  10275. switch (k) {
  10276. case NGUI_KEY_ESC:
  10277. *action |= ACT_CLOSE;
  10278. break;
  10279. case NGUI_KEY_TAB:
  10280. case 0x0C: /* Ctrl+L */
  10281. ngui_set_focus(&ui, ID_URL);
  10282. break;
  10283. case 0x12: /* Ctrl+R */
  10284. *action |= ACT_RELOAD;
  10285. break;
  10286. case NGUI_KEY_BACKSPACE:
  10287. *action |= ACT_BACK;
  10288. break;
  10289. case NGUI_KEY_UP:
  10290. ngui_scroll_to(&page_scroll,
  10291. page_scroll.offset - 24);
  10292. ngui_invalidate(&ui);
  10293. break;
  10294. case NGUI_KEY_DOWN:
  10295. ngui_scroll_to(&page_scroll,
  10296. page_scroll.offset + 24);
  10297. ngui_invalidate(&ui);
  10298. break;
  10299. case NGUI_KEY_HOME:
  10300. ngui_scroll_to(&page_scroll, 0);
  10301. ngui_invalidate(&ui);
  10302. break;
  10303. case NGUI_KEY_END:
  10304. ngui_scroll_to(&page_scroll,
  10305. page_scroll.content_h -
  10306. page_scroll.view_h);
  10307. ngui_invalidate(&ui);
  10308. break;
  10309. default:
  10310. break;
  10311. }
  10312. }
  10313. }
  10314. static unsigned int form_ancestor(unsigned int node)
  10315. {
  10316. unsigned int p = node;
  10317. while (p && p < doc.nnode) {
  10318. if (doc.nodes[p].tag == BR_TAG_FORM &&
  10319. doc.nodes[p].type == BR_NODE_ELEM)
  10320. return p;
  10321. p = doc.nodes[p].parent;
  10322. }
  10323. return 0;
  10324. }
  10325. static int form_descendant(unsigned int node, unsigned int form)
  10326. {
  10327. unsigned int p = node;
  10328. while (p && p < doc.nnode) {
  10329. if (p == form)
  10330. return 1;
  10331. p = doc.nodes[p].parent;
  10332. }
  10333. return 0;
  10334. }
  10335. static void form_reset_form(unsigned int form)
  10336. {
  10337. unsigned int i;
  10338. for (i = 0; i < FORM_MAX; i++)
  10339. if (form_states[i].used &&
  10340. form_descendant(form_states[i].node, form))
  10341. form_states[i].used = 0;
  10342. form_focus = 0;
  10343. }
  10344. static void form_url_append(char *dst, unsigned int *n, unsigned int cap,
  10345. const char *s)
  10346. {
  10347. static const char hex[] = "0123456789ABCDEF";
  10348. while (s && *s && *n + 1 < cap) {
  10349. unsigned char c = (unsigned char)*s++;
  10350. if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z') ||
  10351. (c >= '0' && c <= '9') || c == '-' || c == '_' ||
  10352. c == '.' || c == '~') {
  10353. dst[(*n)++] = (char)c;
  10354. } else if (c == ' ') {
  10355. dst[(*n)++] = '+';
  10356. } else if (*n + 3 < cap) {
  10357. dst[(*n)++] = '%';
  10358. dst[(*n)++] = hex[c >> 4];
  10359. dst[(*n)++] = hex[c & 15];
  10360. }
  10361. }
  10362. dst[*n] = '\0';
  10363. }
  10364. static void form_add_param(char *dst, unsigned int *n, unsigned int cap,
  10365. const char *name, const char *value, int *first)
  10366. {
  10367. if (!name || !name[0])
  10368. return;
  10369. if (!*first && *n + 1 < cap)
  10370. dst[(*n)++] = '&';
  10371. *first = 0;
  10372. form_url_append(dst, n, cap, name);
  10373. if (*n + 1 < cap)
  10374. dst[(*n)++] = '=';
  10375. form_url_append(dst, n, cap, value ? value : "");
  10376. dst[*n] = '\0';
  10377. }
  10378. static int form_submit_form(unsigned int node, int fire_event)
  10379. {
  10380. unsigned int form = form_ancestor(node);
  10381. char action[BR_URL_MAX], query[2048];
  10382. unsigned int qn = 0, i;
  10383. int first = 1, is_post = 0;
  10384. const char *a, *method;
  10385. if (!form)
  10386. return 0;
  10387. if (fire_event && !js_browser_event(form, "submit", 1, 1))
  10388. return 0;
  10389. method = br_find_attr(&doc, form, "method");
  10390. if (method && (s_eq(method, "post") || s_eq(method, "POST")))
  10391. is_post = 1;
  10392. a = br_find_attr(&doc, form, "action");
  10393. if (a && a[0]) {
  10394. if (resolve_link(page_url, a, action, sizeof(action)) != 0)
  10395. return 0;
  10396. } else {
  10397. s_copy(action, page_url, sizeof(action));
  10398. }
  10399. query[0] = '\0';
  10400. for (i = 0; i < doc.nnode; i++) {
  10401. struct br_node *nd = &doc.nodes[i];
  10402. struct form_state *fs;
  10403. const char *name;
  10404. const char *value = "";
  10405. if (nd->type != BR_NODE_ELEM || i == form ||
  10406. !form_descendant(i, form))
  10407. continue;
  10408. if (nd->tag != BR_TAG_INPUT && nd->tag != BR_TAG_TEXTAREA &&
  10409. nd->tag != BR_TAG_SELECT)
  10410. continue;
  10411. if (form_disabled(i))
  10412. continue;
  10413. name = br_find_attr(&doc, i, "name");
  10414. if (!name || !name[0])
  10415. continue;
  10416. fs = form_get(i, 1);
  10417. if (!fs)
  10418. continue;
  10419. if (nd->tag == BR_TAG_SELECT) {
  10420. char opt[64];
  10421. if (!form_option_text(i, fs->selected, opt,
  10422. sizeof(opt)))
  10423. s_copy(opt, "", sizeof(opt));
  10424. value = opt;
  10425. {
  10426. unsigned int c, oi = 0;
  10427. for (c = nd->first; c;
  10428. c = doc.nodes[c].next) {
  10429. if (doc.nodes[c].type != BR_NODE_ELEM ||
  10430. doc.nodes[c].tag != BR_TAG_OPTION)
  10431. continue;
  10432. if (oi == fs->selected) {
  10433. const char *v =
  10434. br_value(&doc, c);
  10435. if (v && v[0])
  10436. value = v;
  10437. break;
  10438. }
  10439. oi++;
  10440. }
  10441. }
  10442. } else if (nd->tag == BR_TAG_INPUT) {
  10443. int kind = form_kind_of(i);
  10444. if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  10445. if (!fs->checked)
  10446. continue;
  10447. value = br_value(&doc, i);
  10448. if (!value || !value[0])
  10449. value = "on";
  10450. } else if (kind == FORM_SUBMIT || kind == FORM_RESET ||
  10451. kind == FORM_BUTTON) {
  10452. if (i != node)
  10453. continue;
  10454. value = fs->value;
  10455. } else {
  10456. value = fs->value;
  10457. }
  10458. } else {
  10459. value = fs->value;
  10460. }
  10461. form_add_param(query, &qn, sizeof(query), name, value, &first);
  10462. }
  10463. if (is_post) {
  10464. if (action[0] == '/') {
  10465. set_status("POST forms need an HTTP action URL", 1, 4000);
  10466. ngui_invalidate(&ui);
  10467. return 0;
  10468. }
  10469. if (qn >= sizeof(pending_post))
  10470. qn = sizeof(pending_post) - 1;
  10471. if (qn)
  10472. memcpy(pending_post, query, qn);
  10473. pending_post[qn] = '\0';
  10474. pending_post_len = qn;
  10475. pending_post_is = 1;
  10476. } else {
  10477. pending_post_len = 0;
  10478. pending_post_is = 0;
  10479. if (qn) {
  10480. unsigned int an = s_len(action);
  10481. if (an + qn + 2 < sizeof(action)) {
  10482. action[an++] = strchr(action, '?') ? '&' : '?';
  10483. action[an] = '\0';
  10484. s_copy(action + an, query,
  10485. sizeof(action) - an);
  10486. }
  10487. }
  10488. }
  10489. s_copy(pending_url, action, sizeof(pending_url));
  10490. pending_action |= ACT_NAV;
  10491. cancel_fetch = 1;
  10492. ngui_invalidate(&ui);
  10493. return 1;
  10494. }
  10495. static void form_reset_event(unsigned int form)
  10496. {
  10497. if (form && !js_browser_event(form, "reset", 1, 1))
  10498. return;
  10499. if (form)
  10500. form_reset_form(form);
  10501. else
  10502. form_reset_state();
  10503. form_dirty = 0;
  10504. layout_valid = 0;
  10505. ngui_invalidate(&ui);
  10506. }
  10507. static void form_blur(void)
  10508. {
  10509. unsigned int node = form_focus;
  10510. form_focus = 0;
  10511. if (node && form_dirty) {
  10512. form_dirty = 0;
  10513. js_browser_event(node, "change", 1, 0);
  10514. }
  10515. }
  10516. static void form_click(unsigned int node)
  10517. {
  10518. struct form_state *fs;
  10519. int kind, changed = 0;
  10520. if (!form_is_control(node) || form_disabled(node))
  10521. return;
  10522. if (form_focus != node)
  10523. form_blur();
  10524. if (!js_browser_event(node, "click", 1, 1))
  10525. return;
  10526. fs = form_get(node, 1);
  10527. if (!fs)
  10528. return;
  10529. kind = form_kind_of(node);
  10530. form_focus = node;
  10531. form_dirty = 0;
  10532. if (kind == FORM_CHECKBOX) {
  10533. fs->checked = !fs->checked;
  10534. changed = 1;
  10535. } else if (kind == FORM_RADIO) {
  10536. const char *name = br_find_attr(&doc, node, "name");
  10537. unsigned int i;
  10538. fs->checked = 1;
  10539. changed = 1;
  10540. if (name) {
  10541. for (i = 0; i < FORM_MAX; i++) {
  10542. struct form_state *o = &form_states[i];
  10543. if (!o->used || o->node == node)
  10544. continue;
  10545. if (form_kind_of(o->node) == FORM_RADIO) {
  10546. const char *on = br_find_attr(&doc,
  10547. o->node,
  10548. "name");
  10549. if (on && s_eq(on, name))
  10550. o->checked = 0;
  10551. }
  10552. }
  10553. }
  10554. } else if (kind == FORM_SELECT) {
  10555. unsigned int n = form_option_count(node);
  10556. if (n) {
  10557. fs->selected = (unsigned char)
  10558. ((fs->selected + 1) % n);
  10559. changed = 1;
  10560. }
  10561. } else if (kind == FORM_SUBMIT) {
  10562. form_submit_form(node, 1);
  10563. return;
  10564. } else if (kind == FORM_RESET) {
  10565. form_reset_event(form_ancestor(node));
  10566. return;
  10567. } else if (kind == FORM_TEXT || kind == FORM_PASSWORD ||
  10568. kind == FORM_TEXTAREA) {
  10569. fs->caret = fs->len;
  10570. }
  10571. if (changed) {
  10572. js_browser_event(node, "input", 1, 0);
  10573. js_browser_event(node, "change", 1, 0);
  10574. }
  10575. layout_valid = 0;
  10576. ngui_invalidate(&ui);
  10577. }
  10578. static void form_focus_next(void)
  10579. {
  10580. unsigned int start = form_focus ? form_focus + 1 : 0;
  10581. unsigned int i;
  10582. form_blur();
  10583. for (i = start; i < doc.nnode; i++) {
  10584. if (form_is_control(i) && !form_disabled(i) &&
  10585. !s_eq(br_type(&doc, i), "hidden")) {
  10586. form_focus = i;
  10587. layout_valid = 0;
  10588. ngui_invalidate(&ui);
  10589. return;
  10590. }
  10591. }
  10592. form_focus = 0;
  10593. layout_valid = 0;
  10594. ngui_invalidate(&ui);
  10595. }
  10596. static void form_key(int k)
  10597. {
  10598. struct form_state *fs;
  10599. int kind;
  10600. if (!form_focus || form_focus >= doc.nnode) {
  10601. form_focus = 0;
  10602. return;
  10603. }
  10604. fs = form_get(form_focus, 1);
  10605. if (!fs || form_disabled(form_focus))
  10606. return;
  10607. kind = form_kind_of(form_focus);
  10608. if (kind == FORM_SELECT) {
  10609. unsigned int n = form_option_count(form_focus);
  10610. int changed = 0;
  10611. if (k == NGUI_KEY_UP && n) {
  10612. fs->selected = (unsigned char)
  10613. ((fs->selected + n - 1) % n);
  10614. changed = 1;
  10615. } else if (k == NGUI_KEY_DOWN && n) {
  10616. fs->selected = (unsigned char)
  10617. ((fs->selected + 1) % n);
  10618. changed = 1;
  10619. } else if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  10620. form_blur();
  10621. layout_valid = 0;
  10622. ngui_invalidate(&ui);
  10623. return;
  10624. } else {
  10625. return;
  10626. }
  10627. if (changed) {
  10628. js_browser_event(form_focus, "input", 1, 0);
  10629. js_browser_event(form_focus, "change", 1, 0);
  10630. }
  10631. } else if (kind == FORM_CHECKBOX || kind == FORM_RADIO) {
  10632. if (k == ' ') {
  10633. form_click(form_focus);
  10634. return;
  10635. }
  10636. if (k == NGUI_KEY_ESC || k == '\r' || k == '\n') {
  10637. form_blur();
  10638. layout_valid = 0;
  10639. ngui_invalidate(&ui);
  10640. }
  10641. return;
  10642. } else if (kind == FORM_BUTTON || kind == FORM_SUBMIT ||
  10643. kind == FORM_RESET) {
  10644. if (k == NGUI_KEY_ESC) {
  10645. form_blur();
  10646. layout_valid = 0;
  10647. ngui_invalidate(&ui);
  10648. } else if (k == '\r' || k == '\n' || k == ' ') {
  10649. form_click(form_focus);
  10650. }
  10651. return;
  10652. } else if (k == NGUI_KEY_TAB) {
  10653. form_focus_next();
  10654. return;
  10655. } else if (k == NGUI_KEY_ESC) {
  10656. form_blur();
  10657. layout_valid = 0;
  10658. ngui_invalidate(&ui);
  10659. return;
  10660. } else if (k == '\r' || k == '\n') {
  10661. unsigned int node = form_focus;
  10662. form_blur();
  10663. if (form_ancestor(node))
  10664. form_submit_form(node, 1);
  10665. layout_valid = 0;
  10666. ngui_invalidate(&ui);
  10667. return;
  10668. } else if (k == NGUI_KEY_BACKSPACE) {
  10669. if (fs->caret) {
  10670. unsigned int i = --fs->caret;
  10671. for (; i < fs->len; i++)
  10672. fs->value[i] = fs->value[i + 1];
  10673. if (fs->len)
  10674. fs->len--;
  10675. form_dirty = 1;
  10676. js_browser_event(form_focus, "input", 1, 0);
  10677. }
  10678. } else if (k == NGUI_KEY_DELETE) {
  10679. if (fs->caret < fs->len) {
  10680. unsigned int i;
  10681. for (i = fs->caret; i < fs->len; i++)
  10682. fs->value[i] = fs->value[i + 1];
  10683. fs->len--;
  10684. form_dirty = 1;
  10685. js_browser_event(form_focus, "input", 1, 0);
  10686. }
  10687. } else if (k == NGUI_KEY_LEFT) {
  10688. if (fs->caret)
  10689. fs->caret--;
  10690. } else if (k == NGUI_KEY_RIGHT) {
  10691. if (fs->caret < fs->len)
  10692. fs->caret++;
  10693. } else if (k == NGUI_KEY_HOME) {
  10694. fs->caret = 0;
  10695. } else if (k == NGUI_KEY_END) {
  10696. fs->caret = fs->len;
  10697. } else if (k >= 32 && k < 127) {
  10698. if (fs->len < FORM_VALUE_MAX) {
  10699. unsigned int i;
  10700. for (i = fs->len; i > fs->caret; i--)
  10701. fs->value[i] = fs->value[i - 1];
  10702. fs->value[fs->caret++] = (char)k;
  10703. fs->len++;
  10704. form_dirty = 1;
  10705. js_browser_event(form_focus, "input", 1, 0);
  10706. }
  10707. } else {
  10708. return;
  10709. }
  10710. fs->value[fs->len] = '\0';
  10711. layout_valid = 0;
  10712. ngui_invalidate(&ui);
  10713. }
  10714. /* A link to "#..." (or to this page plus a fragment) on a scripted page is
  10715. * a same-document navigation: update the URL and fire hashchange. Returns
  10716. * 1 when handled. */
  10717. static int link_fragment_nav(unsigned int node)
  10718. {
  10719. const char *href = br_href(&doc, node);
  10720. char url[BR_URL_MAX];
  10721. unsigned int n = 0;
  10722. if (!href || !href[0] || !js_browser_active())
  10723. return 0;
  10724. if (href[0] == '#') {
  10725. while (page_url[n] && page_url[n] != '#' && n + 1 < sizeof(url)) {
  10726. url[n] = page_url[n];
  10727. n++;
  10728. }
  10729. url[n] = '\0';
  10730. s_append(url, &n, href, sizeof(url));
  10731. } else if (resolve_link(page_url, href, url, sizeof(url)) != 0) {
  10732. return 0;
  10733. }
  10734. if (!same_doc_fragment(url))
  10735. return href[0] == '#';
  10736. page_set_fragment(url, 1);
  10737. js_browser_hashchange();
  10738. return 1;
  10739. }
  10740. /* The innermost laid-out box under a screen point: the smallest valid box
  10741. * that contains it (the last one wins a tie, i.e. the later/deeper node).
  10742. * Used to deliver clicks to elements that are neither links nor controls
  10743. * (a Vue <div role="button">, a card with a click listener). */
  10744. static unsigned int find_box_hit(int x, int y)
  10745. {
  10746. unsigned int i, best = 0, best_area = 0xFFFFFFFFu;
  10747. for (i = 1; i < doc.nnode && i < BR_MAX_NODES; i++) {
  10748. const struct br_layout_box *b = &layout_boxes[i];
  10749. unsigned int area;
  10750. if (!b->valid || b->w <= 0 || b->h <= 0 ||
  10751. x < b->x || y < b->y || x >= b->x + b->w ||
  10752. y >= b->y + b->h)
  10753. continue;
  10754. area = (unsigned int)b->w * (unsigned int)b->h;
  10755. if (area <= best_area) {
  10756. best = i;
  10757. best_area = area;
  10758. }
  10759. }
  10760. return best;
  10761. }
  10762. static void handle_page_click(unsigned int *action)
  10763. {
  10764. int node;
  10765. char url[BR_URL_MAX];
  10766. if (!ui.pressed)
  10767. return;
  10768. if (ui.press_x < page_rect.x ||
  10769. ui.press_x >= page_rect.x + page_rect.w - 12 ||
  10770. ui.press_y < page_rect.y ||
  10771. ui.press_y >= page_rect.y + page_rect.h)
  10772. return;
  10773. node = find_hit(ui.press_x, ui.press_y);
  10774. if (!node) {
  10775. unsigned int box;
  10776. if (!js_browser_active())
  10777. return;
  10778. box = find_box_hit(ui.press_x, ui.press_y);
  10779. if (box) {
  10780. form_blur();
  10781. js_browser_event(box, "click", 1, 1);
  10782. }
  10783. return;
  10784. }
  10785. if (form_is_control((unsigned int)node)) {
  10786. form_click((unsigned int)node);
  10787. return;
  10788. }
  10789. form_blur();
  10790. if (!js_browser_event((unsigned int)node, "click", 1, 1))
  10791. return;
  10792. if (link_fragment_nav((unsigned int)node))
  10793. return;
  10794. if (resolve_link(page_url, br_href(&doc, (unsigned int)node), url,
  10795. sizeof(url)) != 0)
  10796. return;
  10797. s_copy(click_url, url, sizeof(click_url));
  10798. *action |= ACT_NAV;
  10799. }
  10800. void _start(const char *arg)
  10801. {
  10802. struct win_info wi;
  10803. if (u_win_create(BR_W, BR_H, "Browser", &wi) != 0 &&
  10804. u_win_create(960, 640, "Browser", &wi) != 0 &&
  10805. u_win_create(780, 540, "Browser", &wi) != 0) {
  10806. u_puts("browser: no graphics window\n");
  10807. u_exit(1);
  10808. }
  10809. ngui_init(&ui, (unsigned short *)wi.fb, (int)wi.width, (int)wi.height);
  10810. url_in.placeholder = "http://...";
  10811. br_set_theme(ui.theme.text, ui.theme.bg, ui.theme.panel,
  10812. ui.theme.accent);
  10813. br_set_viewport(wi.width);
  10814. if (u_getcwd(cwd, sizeof(cwd)) != 0 || !cwd[0])
  10815. s_copy(cwd, "/", sizeof(cwd));
  10816. heap_clear();
  10817. origin_cache_load();
  10818. css_cache_init();
  10819. script_cache_init();
  10820. persist_restore();
  10821. page_scroll.offset = 0;
  10822. page_scroll.content_h = 0;
  10823. if (arg && arg[0]) {
  10824. navigate(arg, 1);
  10825. } else {
  10826. load_home(1);
  10827. /* Start ready to type: keep the home page, but leave the address
  10828. * bar empty instead of showing "about:home". */
  10829. ngui_input_set(&url_in, "");
  10830. ngui_set_focus(&ui, ID_URL);
  10831. }
  10832. for (;;) {
  10833. unsigned int action = 0;
  10834. unsigned int now;
  10835. click_url[0] = '\0';
  10836. if (pending_action) {
  10837. action |= pending_action & ACT_WAIT_NAV;
  10838. if (pending_url[0])
  10839. s_copy(click_url, pending_url, sizeof(click_url));
  10840. pending_action = 0;
  10841. pending_url[0] = '\0';
  10842. cancel_fetch = 0;
  10843. } else if (preload_active) {
  10844. if (preload_wait)
  10845. preload_wait = 0;
  10846. else
  10847. preload_step();
  10848. } else if ((preload_pending &&
  10849. page_scroll.offset != preload_scroll) ||
  10850. (preload_rescan && layout_valid)) {
  10851. preload_scroll = page_scroll.offset;
  10852. preload_rescan = 0;
  10853. preload_pending = 0;
  10854. preload_node = 0;
  10855. preload_active = 1;
  10856. }
  10857. js_browser_tick();
  10858. if (resize_pending && !pending_action) {
  10859. resize_pending = 0;
  10860. resize_sent_w = layout_right - layout_left;
  10861. js_browser_window_event("resize");
  10862. }
  10863. persist_tick();
  10864. if (pending_action)
  10865. continue;
  10866. now = u_ticks_ms();
  10867. if (status_until && (int)(now - status_until) >= 0) {
  10868. status_text[0] = '\0';
  10869. status_until = 0;
  10870. status_error = 0;
  10871. ngui_invalidate(&ui);
  10872. }
  10873. if (!ngui_begin(&ui)) {
  10874. /* A queued navigation (e.g. Enter in the URL bar during
  10875. * a slow fetch) must be handled even when this frame
  10876. * needs no redraw. */
  10877. if (!action) {
  10878. fetch_workers_stop_if_unfocused();
  10879. u_sleep_ms(10);
  10880. continue;
  10881. }
  10882. } else {
  10883. draw(&action);
  10884. handle_keys(&action);
  10885. handle_page_click(&action);
  10886. ngui_end(&ui);
  10887. }
  10888. if (action & ACT_NAV) {
  10889. if (click_url[0]) {
  10890. navigate(click_url, 1);
  10891. click_url[0] = '\0';
  10892. } else {
  10893. navigate(url_in.text, 1);
  10894. }
  10895. }
  10896. if (action & ACT_BACK) {
  10897. if (hist_pos > 0) {
  10898. hist_pos--;
  10899. if (same_doc_fragment(history[hist_pos])) {
  10900. page_set_fragment(history[hist_pos], 0);
  10901. js_browser_hashchange();
  10902. } else {
  10903. navigate(history[hist_pos], 0);
  10904. }
  10905. }
  10906. }
  10907. if (action & ACT_FORWARD) {
  10908. if (hist_pos + 1 < hist_len) {
  10909. hist_pos++;
  10910. if (same_doc_fragment(history[hist_pos])) {
  10911. page_set_fragment(history[hist_pos], 0);
  10912. js_browser_hashchange();
  10913. } else {
  10914. navigate(history[hist_pos], 0);
  10915. }
  10916. }
  10917. }
  10918. if (action & ACT_RELOAD) {
  10919. if (s_eq(page_url, "about:home"))
  10920. load_home(0);
  10921. else
  10922. navigate(page_url, 0);
  10923. }
  10924. if (action & ACT_HOME)
  10925. load_home(1);
  10926. if (action & ACT_CLOSE)
  10927. quit = 1;
  10928. if (quit)
  10929. break;
  10930. if (pending_action)
  10931. continue;
  10932. fetch_workers_stop_if_unfocused();
  10933. u_sleep_ms(10);
  10934. }
  10935. fetch_workers_stop_all();
  10936. u_win_close();
  10937. u_exit(0);
  10938. }